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
Fix Hub On Device Selection Across Refresh and Download Changes (#9922)
Eyera3574e20c6615
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 5b91a71e126..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@@ -28,6 +28,8 @@ import {type DownloadManagerState,type JobListeners,type ManagedDownload,+ downloadInventoryHintKind,+ scopedDownloadInventoryKind,} from "./download-manager-types";import {clearRuntimeTimer,@@ -37,8 +39,7 @@ import {} from "./runtime-registry";const PERSIST_KEY = "unsloth.studio.downloads";-// 2 is the first version whose records can say whether their byte counters were measured.-// Below it, an absent marker is not evidence of anything, so the migration decides.+// Below version 2 an absent measuredTransfer marker is not evidence of anything, so the migration decides.const PERSIST_VERSION = 2;const MEASURED_TRANSFER_VERSION = 2;const PERSIST_THROTTLE_MS = 1_000;@@ -55,6 +56,33 @@ function nonNegativeNumber(value: unknown, fallback = 0): number {return Math.max(0, finiteNumber(value, fallback));}+/**+ * Inventory kind of a persisted job. Records written before the field carry `scopedFiles`, the same evidence+ * `startJob` classifies a fresh scoped request from: without it a scoped GGUF download comes back as a model+ * download, so its row changes format until backend adoption repairs it.+ */+function inventoryKindOfPersisted(+ value: Record<string, unknown>,+ variant: string | null,+): { inventoryKind?: Exclude<InventoryHint["kind"], "dataset"> } {+ if (+ value.inventoryKind === INVENTORY_HINT_KIND.MODEL ||+ value.inventoryKind === INVENTORY_HINT_KIND.GGUF+ ) {+ return { inventoryKind: value.inventoryKind };+ }+ if (+ variant?.startsWith("@") &&+ Array.isArray(value.scopedFiles) &&+ value.scopedFiles.every((file) => typeof file === "string")+ ) {+ return {+ inventoryKind: scopedDownloadInventoryKind(value.scopedFiles as string[]),+ };+ }+ return {};+}+function sanitizePersistedJob(value: unknown,legacy = false,@@ -92,14 +120,9 @@ function sanitizePersistedJob(...(typeof value.checkpoint === "boolean"? { checkpoint: value.checkpoint }: {}),- // A held reading survives the reload that carried it: dropping the flag restores the stale- // downloadedBytes with the guard reading undefined (so, measured), which is the "0 B left"- // the guard exists to stop.- //- // Absent means "never polled" only for a record written since the field existed. Below that- // version a job that HAD polled says nothing either way, so a legacy record already carrying- // counters is read as held. It costs one poll of an untightened remainder; believing it- // costs the "0 B left" this whole marker is for.+ ...inventoryKindOfPersisted(value, variant),+ // A held reading must survive the reload: dropping the flag restores the stale downloadedBytes reading as measured, the "0 B left" the guard exists to stop.+ // Absent means "never polled" only since the field existed, so a legacy record already carrying counters is read as held....(typeof value.measuredTransfer === "boolean"? { measuredTransfer: value.measuredTransfer }: legacy && nonNegativeNumber(value.downloadedBytes) > 0@@ -152,22 +175,21 @@ function toPersistedJob(: {}),...(job.scopedFiles !== undefined ? { scopedFiles: job.scopedFiles } : {}),...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),+ ...(job.inventoryKind !== undefined+ ? { inventoryKind: job.inventoryKind }+ : {}),...(job.measuredTransfer !== undefined? { measuredTransfer: job.measuredTransfer }: {}),...(job.transport !== undefined ? { transport: job.transport } : {}),- // Alongside the transport, never instead of it: a fallback run reads as- // plain HTTP without this and the reloaded card offers Pause for a stop- // that leaves a restart-only partial.+ // Alongside the transport, never instead of it: a fallback run reads as plain HTTP and the reloaded card offers Pause for a restart-only stop....(job.cancelTransport !== undefined? { cancelTransport: job.cancelTransport }: {}),};}-// Mirrors the backend's normalize_repo_key (strip().lower()) so two casings of-// one repo share a key (else duplicate jobs / mismatched listeners). Keys only;-// `repoId` keeps original casing for display and API calls.+// Mirrors the backend's normalize_repo_key (strip().lower()) for keys only; `repoId` keeps its casing for display and API calls.function normalizeRepoIdentity(repoId: string): string {return repoId.trim().toLowerCase();}@@ -190,24 +212,17 @@ export function jobKeyOf(return variantKey ? `${base}#${variantKey}` : base;}-function completedInventoryHintKind(- kind: DownloadKind,- variant: string | null,-): InventoryHint["kind"] {- return kind === DOWNLOAD_KIND.DATASET- ? INVENTORY_HINT_KIND.DATASET- : variant- ? INVENTORY_HINT_KIND.GGUF- : INVENTORY_HINT_KIND.MODEL;-}-function liveCompletedInventoryHintKeys(): Set<string> {const keys = new Set<string>();for (const job of Object.values(getState().jobs)) {if (job.state !== "complete") continue;keys.add(inventoryHintKey(- completedInventoryHintKind(job.kind, job.variant),+ downloadInventoryHintKind(+ job.kind,+ job.variant,+ job.inventoryKind,+ ),job.repoId,),);@@ -220,11 +235,13 @@ function collectCompletedInventoryHints(): InventoryHint[] {return Object.values(jobs).flatMap((job) => {if (job.state !== "complete") return [];- // A dictation download is not a chat model arriving. A custom Whisper repo- // is only hidden once the backend has scanned its config, so an optimistic- // hint would surface it in the chat inventory for the hint's whole TTL.+ // A dictation download is not a chat model arriving: a custom Whisper repo stays visible in chat for the hint's whole TTL until the backend scans its config.if (job.external) return [];- const kind = completedInventoryHintKind(job.kind, job.variant);+ const kind = downloadInventoryHintKind(+ job.kind,+ job.variant,+ job.inventoryKind,+ );if (runtimeRegistry.suppressedCompletedInventoryHints.has(inventoryHintKey(kind, job.repoId),@@ -282,7 +299,6 @@ 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..filter(([, job]) => !job.external && ACTIVE_STATES.has(job.state)).map(([key, job]) => [key, toPersistedJob(job)] as const),),@@ -295,14 +311,11 @@ export const setState = useDownloadManagerStore.setState;export const getState = useDownloadManagerStore.getState;/**- * Downloads run in the backend, which the quit path reaps, but only this store knows they- * are in flight. A Tauri quit never fires beforeunload, so mirror it to Rust to ask first.- */+ * A Tauri quit never fires beforeunload, and only this store knows a backend download is in flight. */export function hasActiveDownloadJob(jobs: Record<string, ManagedDownload>,): boolean {- // External jobs count too, unlike in `partialize`: their STT sidecars are reached- // through the backend, so a quit kills those transfers as well.+ // External jobs count too, unlike in `partialize`: their STT sidecars go through the backend, so a quit kills those transfers.return Object.values(jobs).some((job) => ACTIVE_STATES.has(job.state));}@@ -315,7 +328,6 @@ function publishDownloadsActive(active: boolean): void {.catch(() => {});}-// Transitions only: the poll loop patches progress several times a second.let lastPublishedDownloadsActive: boolean | null = null;function syncDownloadsActivity(state: DownloadManagerState): void {@@ -325,7 +337,6 @@ function syncDownloadsActivity(state: DownloadManagerState): void {publishDownloadsActive(active);}-// Once for whatever the persisted state restored, then on every change.syncDownloadsActivity(getState());useDownloadManagerStore.subscribe(syncDownloadsActivity);@@ -383,9 +394,6 @@ function hasRuntimePeerForRepo(return false;}-// Shared rule for what blocks a fresh GGUF variant start. Peer guard passes-// includeOwnRuntime:false (runs after this start made its own runtime);-// requestStart passes both true (runs before any runtime or job exists).export function hasVariantRepoActivity(kind: DownloadKind,repoId: string,@@ -436,7 +444,11 @@ export function patchJob(key: string, patch: Partial<ManagedDownload>): void {) {runtimeRegistry.suppressedCompletedInventoryHints.delete(inventoryHintKey(- completedInventoryHintKind(previousJob.kind, previousJob.variant),+ downloadInventoryHintKind(+ previousJob.kind,+ previousJob.variant,+ previousJob.inventoryKind,+ ),previousJob.repoId,),);@@ -476,14 +488,18 @@ export function putJob(job: ManagedDownload): void {runtimeRegistry.clearRemovalTimer(job.key);if (!job.external) {forgetObservedInventoryHint(- completedInventoryHintKind(job.kind, job.variant),+ downloadInventoryHintKind(job.kind, job.variant, job.inventoryKind),job.repoId,);}const suppressionChanged =runtimeRegistry.suppressedCompletedInventoryHints.delete(inventoryHintKey(- completedInventoryHintKind(job.kind, job.variant),+ downloadInventoryHintKind(+ job.kind,+ job.variant,+ job.inventoryKind,+ ),job.repoId,),);@@ -580,7 +596,9 @@ export function discardDeletedInventoryHints(if (job.state === "complete" &&normalizeRepoIdentity(job.repoId) === repoIdentity &&- kinds.includes(completedInventoryHintKind(job.kind, job.variant))+ kinds.includes(+ downloadInventoryHintKind(job.kind, job.variant, job.inventoryKind),+ )) {removeJob(job.key);}@@ -595,9 +613,15 @@ export function discardDeletedModelInventoryHints(discardDeletedInventoryHints(repoId, ["model", "gguf"]);return;}- discardPendingInventoryHint("gguf", repoId);- clearCompletedInventoryHint({ kind: "gguf", repoId });const job = getState().jobs[jobKeyOf(DOWNLOAD_KIND.MODEL, repoId, variant)];+ // Every other hint site classifies a scoped `@variant` as a model download; hardcoding "gguf" leaves a scoped model download's hint behind, so the deleted row returns until it expires.+ const kind = downloadInventoryHintKind(+ DOWNLOAD_KIND.MODEL,+ variant,+ job?.inventoryKind,+ );+ discardPendingInventoryHint(kind, repoId);+ clearCompletedInventoryHint({ kind, repoId });if (job?.state === "complete") {removeJob(job.key);}@@ -633,8 +657,7 @@ export function setExpectedBytesForJob(if (!job || job.state !== "running" || bytes <= job.expectedBytes) return;patchJob(job.key, {expectedBytes: bytes,- // Measured against the old, smaller total, so it is wrong the moment the- // total grows. The bar hides it until the next poll measures one.+ // Measured against the old, smaller total, so wrong the moment the total grows.etaSeconds: 0,fraction:job.fraction > 0diff --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 1190a442b25..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@@ -12,47 +12,30 @@ export interface ManagedDownload {kind: DownloadKind;repoId: string;variant: string | null;+ inventoryKind?: Exclude<InventoryHint["kind"], "dataset">;state: DownloadJobState;downloadedBytes: number;- /** False when the last poll HELD `downloadedBytes` rather than measuring it- * (see `resolveProgressUpdate`). A held figure belongs to the previous- * reading's total, so a surface that subtracts it from the current- * `expectedBytes` is mixing two plans and should fall back to the backend's- * own remainder. Undefined on a job that has not polled yet, which has no held- * bytes to forward. */+ /** False when the last poll HELD `downloadedBytes` instead of measuring it (see `resolveProgressUpdate`): a held+ * figure belongs to the previous reading's total, so subtracting it from the current `expectedBytes` mixes two plans. */measuredTransfer?: boolean;- // Finalized bytes on disk (excludes the in-progress `.incomplete` portion in- // `downloadedBytes`). The completion fallback keys off this so a partial can't- // be marked complete.+ // Finalized bytes on disk, excluding the in-progress `.incomplete` portion; the completion fallback keys off this so a partial cannot be marked complete.completedBytes: number;- // Server-verified completion; not trusted across reloads (hydration re-probes).completeOnDisk: boolean;expectedBytes: number;fraction: number;bytesPerSec: number;- /** Seconds remaining, from the same estimator as {@link bytesPerSec}; 0 hides it. */etaSeconds: number;error: string | null;- /** epoch milliseconds from Date.now(). */startedAt: number;- /** epoch milliseconds captured once when the job completes. */completedAt?: number;serverGeneration?: number;- /** Files a scoped job is fetching, when known. Every file set of one repo rides the same scope slot (see `scopedVariant`), so this separates "my transfer is already running" from "a different quant of this repo is running": adopting the latter would report ready for files nobody fetched. Unknown stays adoptable only for an UNSCOPED job. */+ /** Files a scoped job is fetching. Every file set of one repo rides the same scope slot, so this separates "my transfer is running" from "a different quant of this repo is running": adopting the latter reports ready for files nobody fetched. Unknown stays adoptable only for an UNSCOPED job. */scopedFiles?: string[];- /** Set by the page that staged a multi-repo plan: true for the entry that IS the model the user picked, false for the companion repos it needs. Only the stager can tell them apart, since a checkpoint may be a single `.safetensors` and companions carry `.safetensors` too. Undefined on a job persisted before this field existed. */+ /** True for the entry that IS the model the user picked, false for companion repos. Only the stager can tell them apart, since a checkpoint may be a single `.safetensors` and companions carry `.safetensors` too. */checkpoint?: boolean;- // The transport this run resolved to, so a surface can say whether stopping- // keeps a resumable partial. Absent only when neither the backend nor- // persisted state identifies an adopted job's transport.transport?: ResolvedTransport;- /** A Xet run that fell back to HTTP keeps its original cancel marker, so- * stopping it still leaves a restart-only partial. Set only in that case,- * and it, not `transport`, decides the stop control. */+ /** A Xet run that fell back to HTTP keeps its original cancel marker, so it, not `transport`, decides the stop control. */cancelTransport?: ResolvedTransport;- // Driven by another subsystem (see external-jobs.ts), not the poll loop. Such- // a job is never persisted, probed against the hub API, or published as a- // chat-inventory hint when it completes.external?: boolean;}@@ -60,37 +43,65 @@ export interface DownloadRequest {kind: DownloadKind;repoId: string;variant: string | null;+ inventoryKind?: Exclude<InventoryHint["kind"], "dataset">;expectedBytes: number;- /** Marks a partial-by-design download of `files` only, for a consumer that reads a deliberate subset of a repo (the diffusion loader skips the packaged root single, transformer/ shards and fp16 twins). Set `variant` to `scopedVariant(scopeId)` so this surface keys the job the way the backend does. */scopeId?: string | null;files?: string[];- /** See `ManagedDownload.checkpoint`. Carried on the request so the job records the role its stager already knew, rather than a surface re-deriving it from filenames. */checkpoint?: boolean;- /** What this surface wants said about the start, for the download manager to raise.- * Chat used to toast this itself while startJob raised the Xet notice, stacking two.- * Suppressing one loses information, so the manager folds this into the notice, or- * shows it alone when the notice does not fire. One start, one toast. */callerToast?: CallerToast;}export interface CallerToast {title: string;description: string;- /** Fold into a granted Xet notice, never raise alone. #9663 removed chat's- * auto-load toast as a duplicate of the download panel: the sentence is still worth- * carrying inside the notice, but alone it would put that toast back. */+ /** Fold into a granted Xet notice, never raise alone: #9663 removed chat's auto-load toast as a duplicate of the download panel. */noticeOnly?: boolean;- /** Asked again just before the raise, several round trips after the request. False- * drops this line and keeps the notice: chat moved to another thread so nothing- * auto-loads, but the transfer is still running. Absent means always valid. */+ /** Re-asked just before the raise: false drops this line but keeps the notice, since chat may have moved on while the transfer runs. Absent means always valid. */stillValid?: () => boolean;}-/** The variant slot a scoped job occupies. Mirrors the backend's `_scope_variant`: no GGUF quant label starts with "@", so a scope collides with neither a real variant nor the repo's full snapshot. */+/** Mirrors the backend's `_scope_variant`: no GGUF quant label starts with "@", so a scope collides with neither a real variant nor the repo's full snapshot. */export function scopedVariant(scopeId: string): string {return `@${scopeId}`;}+export function downloadInventoryHintKind(+ kind: DownloadKind,+ variant: string | null,+ inventoryKind?: Exclude<InventoryHint["kind"], "dataset">,+): InventoryHint["kind"] {+ if (kind === "dataset") return "dataset";+ if (inventoryKind) return inventoryKind;+ return variant && !variant.startsWith("@") ? "gguf" : "model";+}++export function scopedDownloadInventoryKind(+ files: readonly string[] | null | undefined,+): Exclude<InventoryHint["kind"], "dataset"> {+ return files?.some((file) => file.trim().toLowerCase().endsWith(".gguf"))+ ? "gguf"+ : "model";+}++export function downloadRequestInventoryKind(+ request: Pick<+ DownloadRequest,+ "kind" | "variant" | "inventoryKind" | "files"+ >,+): DownloadRequest["inventoryKind"] {+ if (request.inventoryKind) {+ return request.inventoryKind;+ }+ if (+ request.kind !== "model" ||+ !request.variant?.startsWith("@") ||+ !request.files?.length+ ) {+ return undefined;+ }+ return scopedDownloadInventoryKind(request.files);+}+export interface JobListeners {onComplete?: (variant: string | null, bytes: number) => unknown;onCancelled?: (variant: string | null) => unknown;@@ -120,13 +131,9 @@ export interface JobRuntime {inFlight: boolean;cancelRequested: boolean;watchdog: number | null;- /** Rolling byte samples behind the stability-gated rate/ETA. */speedSamples: TransferSample[];/**- * A generation change seen on a status-only tick, held until a progress poll- * consumes it. Status polls twice as often as progress, so the change is- * usually observed on a tick that returns before reaching the progress path.- */+ * A generation change seen on a status-only tick, held until a progress poll consumes it: status polls twice as often. */pendingGenerationChange?: boolean;idleSinceMs: number | null;lastProgressPollAt: number | null;@@ -140,15 +147,11 @@ export interface ProgressLike {complete_on_disk?: boolean;expected_bytes: number;progress: number;- /** The scanned cache dir, or null when no cache for this repo exists at all. Optional so an- * older backend's response still satisfies this shape; hydration treats absent as unknown. */+ /** The scanned cache dir, or null when no cache for this repo exists. Absent from an older backend, which hydration treats as unknown. */cache_path?: string | null;- /** Whether the backend found anything for THIS target (variant) rather than the shared repo- * cache dir. Null where it cannot say, absent from an older backend; both leave the- * repo-level cache_path rule in charge. */+ /** Whether the backend found anything for THIS target rather than the shared repo cache dir. Null or absent leaves the repo-level cache_path rule in charge. */target_present?: boolean | null;- /** False when the cache could not be scanned at all: unknown, not empty. Absent from an- * older backend, which is also unknown. */+ /** False when the cache could not be scanned at all: unknown, not empty. Absent from an older backend is also unknown. */cache_measured?: boolean;}diff --git a/studio/frontend/src/features/hub/download-manager/hydration.ts b/studio/frontend/src/features/hub/download-manager/hydration.tsindex b7340344a79..e1c363088ce 100644--- a/studio/frontend/src/features/hub/download-manager/hydration.ts+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts@@ -15,9 +15,10 @@ import {apiGetStatus,isRequestTimeout,} from "./download-api-adapter";-import type {- DownloadRequest,- ManagedDownload,+import {+ downloadRequestInventoryKind,+ type DownloadRequest,+ type ManagedDownload,} from "./download-manager-types";import {getState,@@ -85,23 +86,27 @@ async function adoptActiveModelDownloads(): Promise<void> {for (const download of downloads) {const repoId = download.repo_id?.trim();if (!repoId || !ACTIVE_STATES.has(download.state)) continue;- removeLocalActivePeers(- DOWNLOAD_KIND.MODEL,- repoId,- download.variant ?? null,- );+ const variant = download.variant ?? null;+ const files = download.files?.length ? [...download.files] : undefined;+ const inventoryKind = downloadRequestInventoryKind({+ kind: DOWNLOAD_KIND.MODEL,+ variant,+ files,+ });+ removeLocalActivePeers(DOWNLOAD_KIND.MODEL, repoId, variant);adoptJob({kind: DOWNLOAD_KIND.MODEL,repoId,- variant: download.variant ?? null,+ variant,+ ...(inventoryKind ? { inventoryKind } : {}),+ ...(files ? { files } : {}),expectedBytes: 0,},safeGeneration(download.generation),download.state,isResolvedTransport(download.transport) ? download.transport : undefined,- // null, not undefined: this endpoint always reports the marker, so "no- // marker" has to clear one a previous run left in storage.+ // null, not undefined: this endpoint always reports the marker, so "no marker" must clear one left in storage.isResolvedTransport(download.cancel_transport)? download.cancel_transport: null,@@ -127,8 +132,7 @@ async function adoptActiveDatasetDownloads(): Promise<void> {safeGeneration(download.generation),download.state,isResolvedTransport(download.transport) ? download.transport : undefined,- // null, not undefined: this endpoint always reports the marker, so "no- // marker" has to clear one a previous run left in storage.+ // null, not undefined: this endpoint always reports the marker, so "no marker" must clear one left in storage.isResolvedTransport(download.cancel_transport)? download.cancel_transport: null,@@ -143,8 +147,6 @@ const BACKEND_ADOPTERS: Record<BackendAdoptionSide, () => Promise<void>> = {dataset: adoptActiveDatasetDownloads,};-// Adopt backend-running downloads this client doesn't know about. Retry only-// the failed side(s) so backend readiness settles without duplicating jobs.async function hydrateBackendActiveDownloads(attempt = 0,sides: readonly BackendAdoptionSide[] = ["model", "dataset"],@@ -187,21 +189,8 @@ async function probeHydratedIdleProgress(finalize(key, "complete", { bytes: updated.downloadedBytes });return "settled";}- // The raw reading decides this one, not the figure the card keeps. Whether- // anything is on disk is a question about the cache, and a persisted job- // whose cache was wiped has to read "gone" here rather than adopt and sit- // in the panel as a phantom download until the idle-evict grace expires- // sixty seconds later, blocking a fresh start for the same repo meanwhile.- // The reason the resolved figure holds a zero over -- an unresolvable- // variant file set -- is answered on the backend now, so a finished- // download does not reach this line reading zero in the first place.- //- // A zero alone is still not proof, though: a transient measurement failure comes back as a- // perfectly successful all-zero response, and calling that "gone" drops a job whose partial- // cache is sitting right there. cache_path is the discriminator -- the backend only answers- // null when no cache dir for this repo exists at all, and a dir it scanned and measured at- // zero still names itself. So the cache being absent is what retires the card, not the- // counter being zero.+ // A persisted job whose cache was wiped must read "gone" here, not sit as a phantom download blocking a fresh start until the idle-evict grace expires.+ // A zero alone is not proof, since a transient measurement failure returns a successful all-zero response; cache_path is null only when no cache dir exists.return idleProbeVerdict(progressResp.downloaded_bytes,progressResp.cache_path,@@ -306,6 +295,9 @@ export function hydrateDownloadManager(): void {kind: job.kind,repoId: job.repoId,variant: job.variant,+ ...(job.inventoryKind ? { inventoryKind: job.inventoryKind } : {}),+ ...(job.scopedFiles ? { files: job.scopedFiles } : {}),+ ...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),expectedBytes: job.expectedBytes,};void probeHydratedJob(job.key, req, 0);diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.tsindex e6ab9fccdf8..6068632a0fb 100644--- a/studio/frontend/src/features/hub/download-manager/index.ts+++ b/studio/frontend/src/features/hub/download-manager/index.ts@@ -48,7 +48,10 @@ export {useStagedDownload,type StagedDownloadEntry,} from "./use-staged-download";-export { scopedVariant } from "./download-manager-types";+export {+ downloadInventoryHintKind,+ scopedVariant,+} from "./download-manager-types";export { dismissStartToast, dismissStartToasts } from "./start-toast";export {TRANSPORT_MODE_STORAGE_KEY,diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex c8ebb4be1fd..32937b88c35 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -56,13 +56,14 @@ import {pollAccessErrorMessage,withPollRequestTimeout,} from "./download-api-adapter";-import type {- DownloadRequest,- JobListeners,- JobRuntime,- ManagedDownload,- ProgressLike,- Terminal,+import {+ downloadRequestInventoryKind,+ type DownloadRequest,+ type JobListeners,+ type JobRuntime,+ type ManagedDownload,+ type ProgressLike,+ type Terminal,} from "./download-manager-types";import {XET_NOTICE_TITLE,@@ -205,9 +206,6 @@ export function finalize(): void {const job = getState().jobs[key];teardownRuntime(key);- // The 8s duration is a cap, not a description of the transfer: a finished download- // left the toast still claiming it was running. Before the early returns below, so- // a job already in a terminal display state still clears it.dismissStartToast(key);if (!job) return;if (TERMINAL_DISPLAY_STATES.has(job.state)) return;@@ -218,9 +216,7 @@ export function finalize(notify(job, "onCancelled", 0);removeJob(key);} else if (outcome === "complete") {- // A terminal "complete" arriving before the final progress poll must not- // leave a stale sub-total. Reconcile to the largest known figure so- // downloaded == completed >= expected, fraction 1, and report that.+ // A terminal "complete" before the final progress poll must not leave a stale sub-total, so reconcile to the largest known figure.const bytes = Math.max(opts.bytes ?? 0,job.downloadedBytes,@@ -322,7 +318,6 @@ async function finalizeTerminalStatus(finalBytes = downloadedBytes;}} catch {- // Terminal status is authoritative; progress reconciliation is best-effort.}finalize(key, "complete", { bytes: finalBytes });} else if (terminalKind === "error") {@@ -332,10 +327,7 @@ async function finalizeTerminalStatus(}}-// Rolling-window rate, withheld until the window is trustworthy. The old EMA-// published its first sample verbatim and decayed toward -- never reaching ---// zero while stalled, so ramp-up and idle ticks produced "753d 5h left" (#7667).-// 0 hides both labels, as the training-start overlay already does.+ // Rolling-window rate, withheld until the window is trustworthy: an EMA publishing its first sample verbatim gave "753d 5h left" (#7667). 0 hides both labels.function applySpeedSample(rt: JobRuntime,downloadedBytes: number,@@ -369,9 +361,7 @@ function reconcileProgressAndSpeed(resetMonotonic: generationChanged,});if (generationChanged) {- // Another server owns this transfer now, so the old samples describe a- // different run. The counter cannot say so: a restart resumes from the- // same cache and never goes backwards for appendSample to catch.+ // Another server owns this transfer, so the old samples describe a different run; the counter cannot say so, since a restart resumes from the same cache.rt.speedSamples.length = 0;}const speed = applySpeedSample(rt, downloadedBytes, expected, Date.now());@@ -448,9 +438,7 @@ async function tick(key: string): Promise<void> {);if (!isCurrent(key, epoch)) return;- // syncServerGeneration persists the new generation immediately, so a change- // seen on a tick that returns before the progress path would look unchanged- // on the next one. Hold it until a progress poll actually consumes it.+ // syncServerGeneration persists immediately, so a change seen before the progress path would look unchanged next tick; hold it until a progress poll consumes it.if (syncServerGeneration(key, job, status)) {rt.pendingGenerationChange = true;}@@ -581,17 +569,13 @@ export async function startJob(state?: DownloadJobState;transport?: ResolvedTransport;cancelTransport?: ResolvedTransport | null;- /** The surface this start was asked for, to hold its toast against. Passed by- * `requestStart`, whose preflight is itself navigable; else taken here. */originRoute?: string;} = {},): Promise<void> {const key = jobKeyOf(req.kind, req.repoId, req.variant);const startRoute = opts.originRoute ?? currentRoute();- // Peer guard stops a FRESH start from double-starting a variant already- // downloading (or colliding with a no-variant snapshot). Skipped when ADOPTING:- // the restored own entry would look like a peer and freeze the bar; adoptJob's- // `pollingStarted` guard already prevents double-polling the same key.+ // Peer guard stops a FRESH start from double-starting a variant already downloading. Skipped when ADOPTING:+ // the restored own entry would look like a peer and freeze the bar, and adoptJob already guards double-polling.if (!opts.adopt && hasActiveRepoPeer(req.kind, req.repoId, key, req.variant)) {return;}@@ -624,13 +608,8 @@ export async function startJob(const expected = Math.max(existing?.expectedBytes ?? 0, req.expectedBytes);const hfToken = getHfToken() || null;- // An explicit opts.useXet (a retry pinning a transport) wins; otherwise carry the stored- // preference UNRESOLVED so "auto" survives to effectiveTransportMode(). Collapsing it to a- // boolean here would read "auto" as "not xet" and send every download over HTTP.- // Never for an adopted job: that branch ignores requestedMode, and resolving it is now a- // settings round trip. Suspending here left pollingStarted=false long enough for the other- // concurrent adoptJob caller to replace this runtime, and both continuations then reached- // beginPolling, leaving duplicate timers and a leaked visibility listener.+ // Carry the stored preference UNRESOLVED so "auto" survives to effectiveTransportMode(); collapsing it to a boolean sends every download over HTTP.+ // Never awaited for an adopted job: suspending here let a concurrent adoptJob replace this runtime, leaving duplicate timers and a leaked listener.const requestedMode: TransportMode = opts.adopt? TRANSPORT.HTTP: opts.useXet === undefined@@ -655,22 +634,17 @@ export async function startJob(const seedDownloaded = carryOverSeed ? (existing?.downloadedBytes ?? 0) : 0;const seedCompleted = carryOverSeed ? (existing?.completedBytes ?? 0) : 0;const seedFraction = carryOverSeed ? (existing?.fraction ?? 0) : 0;- // Whatever the counters mean, they keep meaning it. Seeding the bytes without- // this said "measured" for a figure the poll only held, which is the- // "0 B left" the guard exists to stop.+ // Seeding the bytes without carrying the flag said "measured" for a figure the poll only held, which is the "0 B left" the guard exists to stop.const seedMeasuredTransfer = seededMeasuredTransfer(carryOverSeed,existing?.measuredTransfer,);- // An adopted job never called apiStart, so it learns the run's generation from- // the probe (or persisted value) to scope a later cancel to this exact run.+ // An adopted job never called apiStart, so it learns the run's generation from the probe to scope a later cancel to this exact run.const seedGeneration = opts.adopt? Number.isSafeInteger(opts.generation)? opts.generation: existing?.serverGeneration: undefined;- // An adopted job prefers what the backend just reported and falls back to- // the persisted value, for the transport and its cancel marker alike.const adopted = opts.adopt? adoptedTransports({ transport: opts.transport, cancelTransport: opts.cancelTransport },@@ -678,6 +652,7 @@ export async function startJob(): { transport: mode, cancelTransport: undefined };const activeTransport = adopted.transport;+ const inventoryKind = downloadRequestInventoryKind(req);if (!opts.adopt && hasActiveRepoPeer(req.kind, req.repoId, key, req.variant)) {teardownRuntime(key);return;@@ -697,11 +672,8 @@ export async function startJob(bytesPerSec: 0,error: null,startedAt: opts.adopt ? (existing?.startedAt ?? Date.now()) : Date.now(),- // An adopted job prefers the backend's live transport, then a persisted- // value. It never claims the HTTP placeholder used to skip resolution.+ // An adopted job prefers the backend's live transport, then the persisted value; never the HTTP placeholder used to skip resolution....(activeTransport ? { transport: activeTransport } : {}),- // A fallback run's cancel marker. Only an adopted job can have one: the- // fallback happens long after a start....(adopted.cancelTransport? { cancelTransport: adopted.cancelTransport }: {}),@@ -711,18 +683,21 @@ export async function startJob(...(Number.isSafeInteger(seedGeneration)? { serverGeneration: seedGeneration }: {}),- // Recorded so a later start for the same scope slot can tell whether this running job is fetching its files or a different quant's. An adopted job keeps the existing record....(req.files && req.files.length > 0? { scopedFiles: [...req.files] }: opts.adopt && existing?.scopedFiles? { scopedFiles: existing.scopedFiles }: {}),- // The staged plan's own verdict on which entry is the picked model, so the panel labels it without guessing from file extensions. An adopted job keeps the existing record, since only the stager can supply it....(req.checkpoint !== undefined? { checkpoint: req.checkpoint }: opts.adopt && existing?.checkpoint !== undefined? { checkpoint: existing.checkpoint }: {}),+ ...(inventoryKind !== undefined+ ? { inventoryKind }+ : opts.adopt && existing?.inventoryKind !== undefined+ ? { inventoryKind: existing.inventoryKind }+ : {}),});if (!opts.adopt) {@@ -736,8 +711,7 @@ export async function startJob(});return;}- // A cancel during this apiStart round-trip can land before the job is- // claimable; re-issue against the accepted generation.+ // A cancel during this apiStart round trip can land before the job is claimable, so re-issue against the accepted generation.if (rt.cancelRequested && result.accepted) {reissueDroppedStartCancel(req, result.generation);}@@ -751,14 +725,9 @@ export async function startJob(}const started = transportAfterStart(mode, result.transport);if (started !== activeTransport) patchJob(key, { transport: started });- // One start, one toast: the only place a start is announced. A cancel can land- // mid-flight (the reissue above is the giveaway), and neither message is true- // of a start that is already stopping.+ // One start, one toast: a cancel can land mid-flight, and neither message is true of a start that is already stopping.const stopping = rt.cancelRequested;- // Everything above was round trips the user could navigate during. Checked BEFORE- // reserving, since a reservation is one of three for the life of the install:- // spending one on a toast that will be discarded on arrival is how starting a- // download and going to watch it burns all three unseen.+ // Checked BEFORE reserving: a reservation is one of three for the life of the install, and spending one on a toast discarded on arrival burns all three unseen.const onOriginRoute = currentRoute() === startRoute;if (onOriginRoute &&@@ -769,15 +738,10 @@ export async function startJob(live: result.state === "running" && !stopping,})) {- // Async (it asks the backend for one of the three) and nothing below waits on- // a toast. A lost reservation still leaves the caller owed its message.void reserveXetNoticeFromServer().then(({ granted }) => {- // This round trip can outlive the transfer: finalize() dismisses by id before- // it resolves, so raising here would leave a finished or cancelled job claiming- // to run for another 8s, or hand a restart on the same key a stale message.+ // This round trip can outlive the transfer: finalize() dismisses by id before it resolves, so raising here would leave a finished or cancelled job claiming to run.if (!isCurrent(key, epoch) || rt.cancelRequested) return;- // The caller's line can go stale while the notice stays true: chat moved- // thread, so nothing auto-loads, but the 0% still needs explaining.+ // The caller's line can go stale while the notice stays true: chat moved thread, but the 0% still needs explaining.const caller = liveCallerToast(req.callerToast);if (granted) {showStartToast(@@ -795,8 +759,7 @@ export async function startJob(} else if (!stopping && onOriginRoute) {showCallerToast(key, liveCallerToast(req.callerToast), startRoute);}- // An adopted job can already have fallen back from Xet to HTTP, which- // keeps its original cancel marker and so its stop control.+ // An adopted job may already have fallen back from Xet to HTTP, which keeps its original cancel marker and so its stop control.if (isResolvedTransport(result.cancel_transport)) {patchJob(key, { cancelTransport: result.cancel_transport });}@@ -934,7 +897,6 @@ async function probeCancelOutcome(export async function cancelJob(key: string): Promise<void> {const job = getState().jobs[key];if (!job) return;- // Another subsystem owns this transfer; it does the cancelling.if (isExternalJob(key)) {await cancelExternalJob(key);return;@@ -953,8 +915,7 @@ export async function cancelJob(key: string): Promise<void> {} catch (err) {const liveAtError = runtimeRegistry.runtimes.get(key);if (rt && liveAtError && liveAtError.epoch !== cancelEpoch) return;- // apiCancel failed; the probe below is authoritative. Disarm the watchdog so- // it can't finalize "cancelled" mid-probe and tear down a still-running worker.+ // apiCancel failed and the probe below is authoritative: disarm the watchdog so it cannot finalize "cancelled" mid-probe and tear down a running worker.clearWatchdog(liveAtError);const probe = await probeCancelOutcome(key, job, rt, cancelEpoch);@@ -989,24 +950,23 @@ export function adoptJob(generation?: number,state?: DownloadJobState,transport?: ResolvedTransport,- // null is the backend reporting no marker, which must clear a stored one;- // undefined is a caller that cannot report one at all.+ // null is the backend reporting no marker, which must clear a stored one; undefined is a caller that cannot report one at all.cancelTransport?: ResolvedTransport | null,): void {const key = jobKeyOf(req.kind, req.repoId, req.variant);if (runtimeRegistry.runtimes.get(key)?.pollingStarted) {- // Persistence hydration and the backend-active probe run concurrently, so a- // late backend response must still replace a missing or stale stored value.- // Only for the run it described, though: a cancel and restart in between- // makes this a different job, possibly on the other transport.+ // A late backend response must still replace a stale stored value, but only for the run it described: a cancel and restart in between makes this a different job.const known = getState().jobs[key]?.serverGeneration;- if (transport && probeDescribesCurrentRun(known, generation)) {+ if (probeDescribesCurrentRun(known, generation)) {+ const inventoryKind = downloadRequestInventoryKind(req);patchJob(key, {- transport,- ...(cancelTransport === undefined- ? {}- : { cancelTransport: cancelTransport ?? undefined }),+ ...(transport ? { transport } : {}),+ ...(transport && cancelTransport !== undefined+ ? { cancelTransport: cancelTransport ?? undefined }+ : {}),...(Number.isSafeInteger(known) ? {} : { serverGeneration: generation }),+ ...(req.files?.length ? { scopedFiles: [...req.files] } : {}),+ ...(inventoryKind ? { inventoryKind } : {}),});}return;@@ -1051,8 +1011,7 @@ export async function probeAndAdopt(repoId,variant: active.variant,expectedBytes: 0,- // Carry the live job's own file list so the adopted record can be matched against a later start for the same slot.- // Without it the adopted job had an unknown set and any sibling checkpoint's request read as "already started".+ // Carry the live job's file list so the adopted record can be matched against a later start for the same slot; without it any sibling checkpoint's request read as "already started"....(active.files && active.files.length > 0 ? { files: [...active.files] } : {}),},active.generation,@@ -1066,14 +1025,10 @@ export async function probeAndAdopt(return;}- // The active-downloads list, not download-status: only the list reports the- // transport, without which an adopted HTTP dataset shows Cancel for a- // transfer that would have resumed.+ // The active-downloads list, not download-status: only the list reports the transport, without which an adopted HTTP dataset shows Cancel for a transfer that would have resumed.const datasets = await getActiveDatasetDownloads(signal, repoId);if (signal.aborted) return;- // No repo compare here: the endpoint resolves the cached casing before it- // filters, so an exact match against the card's spelling would drop the- // very row it just asked for.+ // No repo compare here: the endpoint resolves the cached casing before it filters, so an exact match against the card's spelling would drop the row it just asked for.for (const active of datasets) {if (active.state !== "running" && active.state !== "cancelling") continue;adoptJob(diff --git a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts b/studio/frontend/src/features/hub/download-manager/use-staged-download.tsindex 69201a6c3a7..f2ccdf3f067 100644--- a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts+++ b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts@@ -7,17 +7,17 @@ import { toast } from "@/lib/toast";import { DOWNLOAD_KIND } from "./constants";import { downloadManager } from "./download-manager-controller";-import { scopedVariant } from "./download-manager-types";+import {+ scopedDownloadInventoryKind,+ scopedVariant,+} from "./download-manager-types";import { useRepoDownload } from "./use-repo-download";-/** One repo of a staged plan: the exact files to fetch and their declared size. */export interface StagedDownloadEntry {repoId: string;files: string[];bytes: number;- /** Set when this entry is a single-file GGUF checkpoint. Informational: it is fetched as a scoped job like every other entry. */ggufFilename?: string | null;- /** True for the entry whose repo is the one the user picked; the rest of the plan is companion repos it needs. The stager is the only place that knows this, so it travels with the job for surfaces that label the two differently. */checkpoint?: boolean;}@@ -25,25 +25,21 @@ function entryKey(entry: StagedDownloadEntry): string {return `${entry.repoId}|${[...entry.files].sort().join(",")}`;}-/** Runs a multi-repo download plan through the shared download manager, then calls `onReady` once every entry is on disk. Chat stages a single repo inline; the diffusion pages need two (a GGUF checkpoint plus its companion base) and read only part of each, so the entries go out as scoped jobs. Staging here rather than inside the load is what puts image and video downloads in the same panel, with the same progress, cancel, resume, disk preflight and manifest verification. */+/** Runs a multi-repo download plan through the shared download manager, then calls `onReady` once every entry is on disk. Staging here rather than inside the load is what puts image and video downloads in the same panel, with the same progress, cancel, resume, disk preflight and manifest verification. */export function useStagedDownload({scopeId,onReady,onCancelled,}: {- /** Scope label for entries that fetch a file subset (e.g. "diffusion"). */scopeId: string;onReady: () => void;- /** Clears the consumer's pending auto-load whenever the plan ends without every entry on disk:- * cancelled, failed, or never started. A pick is only an intent until then, and leaving it- * behind lets a later completion or a deferred page activation load a model nobody asked for. */+ /** Clears the consumer's pending auto-load when the plan ends without every entry on disk: leaving it behind lets a later completion load a model nobody asked for. */onCancelled?: () => void;}) {const [queue, setQueue] = useState<StagedDownloadEntry[] | null>(null);const current = queue?.[0] ?? null;- // Every entry is scoped, including a GGUF checkpoint: the Hub's snapshot ignore list drops *.gguf, so a plain snapshot job- // would finish at once having fetched everything EXCEPT the weights, leaving the repo on device unloadable.+ // Every entry is scoped, including a GGUF checkpoint: the Hub's snapshot ignore list drops *.gguf, so a plain snapshot job would finish having fetched everything EXCEPT the weights.const activeVariant = current ? scopedVariant(scopeId) : null;const advance = useCallback(() => {@@ -54,8 +50,7 @@ export function useStagedDownload({});}, []);- // The job this hook waits on, keyed by the entry it started (repo + exact file set) AND the staging generation: every scoped pick in a repo- // shares the "@diffusion" variant, so restaging while the first job finishes would let its completion pass for the new pick.+ // Keyed by entry AND staging generation: every scoped pick in a repo shares the "@scope" variant, so restaging would let the first job's completion pass for the new pick.const inFlight = useRef<{ key: string; generation: number } | null>(null);const generation = useRef(0);const isOurs = (variant: string | null | undefined) =>@@ -69,14 +64,12 @@ export function useStagedDownload({kind: DOWNLOAD_KIND.MODEL,repoId: current?.repoId ?? "__staged_download_idle__",activeVariant,- // The listener subscription is per REPO, not per job, and one repo can have several jobs in flight. Each callback carries the variant it fired- // for, so drop the ones that are not this staged entry: a sibling's completion would advance the queue and its failure would wipe a live job.+ // The listener subscription is per REPO and each callback carries its variant, so drop the ones that are not this entry: a sibling's completion would advance the queue.onComplete: (variant) => {if (!isOurs(variant)) return;inFlight.current = null;const remaining = (queue ?? []).slice(1);advance();- // Every entry is on disk, so the load will find its cache warm.if (remaining.length === 0) onReady();},onError: (variant) => {@@ -93,23 +86,20 @@ export function useStagedDownload({},});- // Read through a ref so a consumer's inline callback cannot re-run the start effect and- // restart a live download.const onCancelledRef = useRef(onCancelled);onCancelledRef.current = onCancelled;useEffect(() => {if (!current) return;let active = true;const started = { key: entryKey(current), generation: generation.current };- // Register ownership before the start request. The global panel can expose the job as soon as- // the controller updates its store, before this await resumes; a very fast cancel/completion in- // that window must still belong to this plan.+ // Register ownership before the start request: the panel can expose the job before this await resumes, and a very fast cancel in that window must still belong to this plan.inFlight.current = started;void (async () => {const outcome = await downloadManager.requestStart({kind: DOWNLOAD_KIND.MODEL,repoId: current.repoId,variant: activeVariant,+ inventoryKind: scopedDownloadInventoryKind(current.files),expectedBytes: current.bytes,scopeId,files: current.files,@@ -118,9 +108,7 @@ export function useStagedDownload({if (!active) return;if (outcome === "started") return;if (inFlight.current === started) inFlight.current = null;- // A start that never got off the ground (network failure, rejected scoped request, worker refused) will never complete, so- // clear the queue instead of leaving the head in place, where the effect never re-runs and onReady never fires.- // The pick dies with it, so the consumer's pending auto-load has to go too.+ // A start that never got off the ground will never complete, so clear the queue instead of leaving the head in place where the effect never re-runs. The pick dies with it.if (outcome === "error") {toast.error("Could not start the download", {description: "Check the connection, then select the model again.",@@ -142,16 +130,11 @@ export function useStagedDownload({return () => {active = false;};- // Only the head of the queue drives a start; advancing re-runs this with the next one.}, [current, activeVariant, scopeId]);const stage = useCallback((entries: StagedDownloadEntry[]) => {- // A fresh plan supersedes whatever was staged, so bump the generation: a callback for the previous plan's job is no longer ours.generation.current += 1;inFlight.current = null;- // The Downloads panel is the sole download surface. A second toast duplicated its- // progress and exposed another X that looked like cancellation but only dismissed copy.- // `onReady` owns the later GPU-load toast, after every queued entry is complete.setQueue(entries.length > 0 ? entries : null);}, []);diff --git a/studio/frontend/src/features/hub/hooks/use-models-selection.ts b/studio/frontend/src/features/hub/hooks/use-models-selection.tsindex ebbd8baae1d..8af79e67519 100644--- a/studio/frontend/src/features/hub/hooks/use-models-selection.ts+++ b/studio/frontend/src/features/hub/hooks/use-models-selection.ts@@ -30,6 +30,7 @@ import { useSelectedModelView } from "./use-selected-model-view";export interface ModelsSelection {selectedId: string | null;+ selectionInputId: string | null;setSelected: (id: string | null) => void;selectedModel: SelectedModelView | null;metadataUnavailable: boolean;@@ -69,6 +70,7 @@ export function useModelsSelection({filteredDiscoverRows,filteredCachedRows,filteredLocalRows,+ downloadedReady,results,accessToken,online,@@ -81,11 +83,11 @@ export function useModelsSelection({filteredDiscoverRows: DiscoverRow[];filteredCachedRows: CachedInventoryRow[];filteredLocalRows: LocalInventoryRow[];+ downloadedReady: boolean;results: HfModelResult[];accessToken: string | undefined;online: boolean;}): ModelsSelection {- // Per-tab selection so switching keeps each list's highlighted row.const [discoverSelectedId, setDiscoverSelectedId] = useState<string | null>(null,);@@ -154,6 +156,7 @@ export function useModelsSelection({() =>resolveDownloadedSelection({selectedId: downloadedSelectedId,+ inventoryReady: downloadedReady,cachedRows,localRows,filteredCachedRows,@@ -161,6 +164,7 @@ export function useModelsSelection({}),[cachedRows,+ downloadedReady,downloadedSelectedId,filteredCachedRows,filteredLocalRows,@@ -170,10 +174,14 @@ export function useModelsSelection({const selectedId = isDiscoverTab? discoverResolution.selectedId: downloadedResolution.selectedId;+ const selectionInputId = isDiscoverTab+ ? discoverSelectedId+ : downloadedSelectedId;const selectionHiddenByFilters = isDiscoverTab? discoverResolution.hiddenByFilters: downloadedResolution.hiddenByFilters;- const detailSelectedId = useDeferredValue(selectedId);+ const deferredSelectedId = useDeferredValue(selectedId);+ const detailSelectedId = isDiscoverTab ? deferredSelectedId : selectedId;const setSelected = useCallback((id: string | null) => {if (isDiscoverTab) {@@ -315,6 +323,7 @@ export function useModelsSelection({return {selectedId,+ selectionInputId,setSelected,selectedModel,metadataUnavailable,diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex 286e2fa57cf..87cb729f62b 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -79,6 +79,7 @@ import type {} from "./hooks/use-hub-model-search";import { useHubModelVram } from "./hooks/use-hub-model-vram";import { useModelsSelection } from "./hooks/use-models-selection";+import { resolveSelectionUrlSync } from "./lib/selection-resolution";import { useHubInventory } from "./inventory";import { LOCAL_MODEL_SOURCE } from "./inventory/constants";import { settingsGgufVariantForRow } from "./inventory/settings-identity";@@ -1162,6 +1163,7 @@ export function ModelsPage() {const {selectedId,+ selectionInputId,setSelected,selectedModel,metadataUnavailable,@@ -1175,6 +1177,7 @@ export function ModelsPage() {filteredDiscoverRows: selectionFilteredDiscoverRows,filteredCachedRows,filteredLocalRows,+ downloadedReady,results: selectionResults,accessToken: apiHfToken,online,@@ -1182,13 +1185,12 @@ export function ModelsPage() {const handleSelect = useCallback((id: string) => {- setSelected(id);void navigate({to: "/hub",search: (prev) => ({ ...prev, model: id, file: undefined }),});},- [setSelected, navigate],+ [navigate],);const handleCloseDetail = useCallback(() => {// From split view, "Back to Hub" returns to the main hub feed (not the filtered list): leave@@ -1244,10 +1246,35 @@ export function ModelsPage() {);useEffect(() => {- if (urlModel !== selectedId) {- setSelected(urlModel);+ const sync = resolveSelectionUrlSync({+ isDiscoverTab,+ urlModel,+ selectionInputId,+ resolvedSelectedId: selectedId,+ resolvedModelFormat: selectedModel?.modelFormat ?? null,+ });+ if (sync?.action === "select") {+ setSelected(sync.selectedId);+ } else if (sync?.action === "replace") {+ void navigate({+ to: "/hub",+ search: (prev) => ({+ ...prev,+ model: sync.selectedId,+ file: sync.preserveGgufFile ? prev.file : undefined,+ }),+ replace: true,+ });}- }, [urlModel, selectedId, setSelected]);+ }, [+ isDiscoverTab,+ navigate,+ selectedId,+ selectedModel?.modelFormat,+ selectionInputId,+ setSelected,+ urlModel,+ ]);// Track the last non-split layout so leaving split mode restores it.useEffect(() => {@@ -1265,7 +1292,6 @@ export function ModelsPage() {? listRows[0]?.id: (filteredCachedRows[0]?.id ?? filteredLocalRows[0]?.id);if (!firstId) return;- setSelected(firstId);void navigate({to: "/hub",search: (prev) => ({ ...prev, model: firstId, file: undefined }),@@ -1278,7 +1304,6 @@ export function ModelsPage() {listRows,filteredCachedRows,filteredLocalRows,- setSelected,navigate,]);diff --git a/studio/frontend/src/features/hub/inventory/inventory-dedupe.ts b/studio/frontend/src/features/hub/inventory/inventory-dedupe.tsindex 138f83fadb4..c110f2d4ca8 100644--- a/studio/frontend/src/features/hub/inventory/inventory-dedupe.ts+++ b/studio/frontend/src/features/hub/inventory/inventory-dedupe.ts@@ -18,6 +18,51 @@ function repoKey(repoId: string | null | undefined): string | null {return repoId?.trim().toLowerCase() || null;}+export type PartialFormatFamily = "gguf" | "model";++function partialFormatFamily(+ modelFormat: CachedInventoryRow["modelFormat"],+): PartialFormatFamily | null {+ if (modelFormat === "unknown") return null;+ return modelFormat === "gguf" ? "gguf" : "model";+}++/**+ * The family an unclassified PARTIAL row can be PROVEN to belong to, or null. The backend writes a transport+ * only for snapshot partials and hardcodes none for a GGUF (`services/models/common.py`, `cache_inventory.py`).+ * The converse is WRONG: a snapshot partial with neither a cancel marker nor a manifest also reports none+ * (`utils/inventory_scan.py`), so an absent transport must not be read as "GGUF". Null for a complete row.+ */+export function provenUnknownPartialFamily(+ row: Pick<CachedInventoryRow | LocalInventoryRow, "partialTransport">,+): PartialFormatFamily | null {+ return row.partialTransport ? "model" : null;+}++function addPartialFormatFamily(+ familiesByRepo: Map<string, Set<PartialFormatFamily>>,+ repoId: string | null | undefined,+ modelFormat: CachedInventoryRow["modelFormat"],+): void {+ const repo = repoKey(repoId);+ const family = partialFormatFamily(modelFormat);+ if (!repo || !family) return;+ const families = familiesByRepo.get(repo) ?? new Set<PartialFormatFamily>();+ families.add(family);+ familiesByRepo.set(repo, families);+}++function knownFamiliesMatchUnknownRow(+ row: Pick<CachedInventoryRow | LocalInventoryRow, "partialTransport" | "partial">,+ families: ReadonlySet<PartialFormatFamily> | undefined,+): boolean {+ if (!families?.size) return false;+ if (families.size > 1) return true;+ // A complete row has no transport, so the test below would always say "gguf" and keep it beside a safetensors row; any known family shadows it instead.+ if (!row.partial) return true;+ return families.has(row.partialTransport ? "model" : "gguf");+}+export function findCompleteHfCacheLocalRow(cachedRow: CachedInventoryRow,localRows: readonly LocalInventoryRow[],@@ -101,27 +146,37 @@ export function dedupeSameSourceHubCacheRows({localRows: LocalInventoryRow[];} {const uniqueCachedRows = dedupeCachedRows(cachedRows);- const completeCachedRepos = new Set<string>();- const partialGgufRepos = new Set<string>();+ const completeCachedFormatFamilies = new Map<+ string,+ Set<PartialFormatFamily>+ >();+ const partialFormatFamilies = new Map<string, Set<PartialFormatFamily>>();for (const row of uniqueCachedRows) {- if (row.partial && row.modelFormat === "gguf") {- const repo = repoKey(row.repoId);- if (repo) partialGgufRepos.add(repo);+ if (row.partial && row.modelFormat !== "unknown") {+ addPartialFormatFamily(+ partialFormatFamilies,+ row.repoId,+ row.modelFormat,+ );}if (row.partial) {continue;}- const repo = repoKey(row.repoId);- if (repo) {- completeCachedRepos.add(repo);- }+ addPartialFormatFamily(+ completeCachedFormatFamilies,+ row.repoId,+ row.modelFormat,+ );}const completeHfCacheLocalKeys = new Set<string>();for (const row of localRows) {- if (row.partial && row.modelFormat === "gguf") {- const repo = repoKey(row.repoId);- if (repo) partialGgufRepos.add(repo);+ if (row.partial && row.modelFormat !== "unknown") {+ addPartialFormatFamily(+ partialFormatFamilies,+ row.repoId,+ row.modelFormat,+ );}if (row.source !== "hf_cache" || row.partial) {continue;@@ -139,7 +194,7 @@ export function dedupeSameSourceHubCacheRows({!row.liveDownload &&row.modelFormat === "unknown" &&repo &&- partialGgufRepos.has(repo)+ knownFamiliesMatchUnknownRow(row, partialFormatFamilies.get(repo))) {return false;}@@ -168,14 +223,17 @@ export function dedupeSameSourceHubCacheRows({row.partial &&row.modelFormat === "unknown" &&repo &&- partialGgufRepos.has(repo)+ knownFamiliesMatchUnknownRow(row, partialFormatFamilies.get(repo))) {return false;}if (row.modelFormat === "unknown" &&repo &&- completeCachedRepos.has(repo)+ knownFamiliesMatchUnknownRow(+ row,+ completeCachedFormatFamilies.get(repo),+ )) {return false;}diff --git a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts b/studio/frontend/src/features/hub/inventory/use-hub-inventory.tsindex 71208ea3b67..6bbdc09fcdb 100644--- a/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts+++ b/studio/frontend/src/features/hub/inventory/use-hub-inventory.ts@@ -4,6 +4,7 @@import {type ManagedDownload,clearCompletedInventoryHint,+ downloadInventoryHintKind,useDownloadManagerStore,} from "@/features/hub/download-manager";import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";@@ -23,6 +24,7 @@ import {} from "./inventory-hint-store";import {type PendingInventoryHints,+ inventoryHintKey,nextInventoryHintExpiryDelay,repoKey,} from "./inventory-hints";@@ -39,6 +41,7 @@ import {import {buildCachedInventoryRow,buildLocalInventoryRows,+ cachedInventoryId,defaultCapabilities,} from "./view-models";import { normalizeTimestamp } from "./inventory-timestamps";@@ -87,7 +90,12 @@ const LOCAL_DATASET_INVENTORY_SOURCE = [type LiveInventoryJob = Pick<ManagedDownload,- "kind" | "repoId" | "variant" | "state" | "startedAt"+ | "kind"+ | "repoId"+ | "variant"+ | "inventoryKind"+ | "state"+ | "startedAt"> & {displayBytes: number;};@@ -135,11 +143,16 @@ function liveInventoryRank(job: ManagedDownload): number {return 0;}-function inventoryHintKindForJob(job: ManagedDownload): InventoryHint["kind"] {- return job.kind === "dataset" ? "dataset" : job.variant ? "gguf" : "model";+export function liveInventorySelectionKey(+ job: Pick<ManagedDownload, "kind" | "repoId" | "variant" | "inventoryKind">,+): string {+ return inventoryHintKey(+ downloadInventoryHintKind(job.kind, job.variant, job.inventoryKind),+ job.repoId,+ );}-function observedKeyProtections(+export function observedKeyProtections(jobs: Record<string, ManagedDownload>,): Record<InventoryHint["kind"], Set<string>> {const keys: Record<InventoryHint["kind"], Set<string>> = {@@ -156,7 +169,9 @@ function observedKeyProtections() {continue;}- keys[inventoryHintKindForJob(job)].add(repoKey(job.repoId));+ keys[+ downloadInventoryHintKind(job.kind, job.variant, job.inventoryKind)+ ].add(repoKey(job.repoId));}return keys;}@@ -177,7 +192,7 @@ function liveJobDisplayBytes(job: ManagedDownload): number {return Math.max(job.downloadedBytes, job.completedBytes, 0);}-function createLiveInventoryJobsSelector(isDatasetMode: boolean): (state: {+export function createLiveInventoryJobsSelector(isDatasetMode: boolean): (state: {jobs: Record<string, ManagedDownload>;}) => LiveInventoryJob[] {let cache: { signature: string; jobs: LiveInventoryJob[] } = {@@ -185,35 +200,42 @@ function createLiveInventoryJobsSelector(isDatasetMode: boolean): (state: {jobs: [],};return (state) => {- const selectedByRepo = new Map<string, ManagedDownload>();+ const selectedByRepoAndKind = new Map<string, ManagedDownload>();for (const job of Object.values(state.jobs)) {if (!shouldSurfaceLiveJob(job, isDatasetMode)) continue;- const repoKey = job.repoId.trim().toLowerCase();- if (!repoKey) continue;- const current = selectedByRepo.get(repoKey);+ if (!repoKey(job.repoId)) continue;+ const selectionKey = liveInventorySelectionKey(job);+ const current = selectedByRepoAndKind.get(selectionKey);if (!current ||liveInventoryRank(job) > liveInventoryRank(current) ||(liveInventoryRank(job) === liveInventoryRank(current) &&job.startedAt > current.startedAt)) {- selectedByRepo.set(repoKey, job);+ selectedByRepoAndKind.set(selectionKey, job);}}- const jobs = [...selectedByRepo.values()]+ const jobs = [...selectedByRepoAndKind.values()].map((job) => ({kind: job.kind,repoId: job.repoId,variant: job.variant,+ inventoryKind: job.inventoryKind,state: job.state,startedAt: job.startedAt,displayBytes: liveJobDisplayBytes(job),}))- .sort((a, b) => a.repoId.localeCompare(b.repoId));+ .sort(+ (a, b) =>+ repoKey(a.repoId).localeCompare(repoKey(b.repoId)) ||+ liveInventorySelectionKey(a).localeCompare(+ liveInventorySelectionKey(b),+ ),+ );const signature = jobs.map((job) =>- `${job.kind}\u0001${job.repoId.toLowerCase()}\u0001${job.variant ?? ""}\u0001${job.state}\u0001${job.startedAt}\u0001${job.displayBytes}`,+ `${job.kind}\u0001${job.repoId.toLowerCase()}\u0001${job.variant ?? ""}\u0001${job.inventoryKind ?? ""}\u0001${job.state}\u0001${job.startedAt}\u0001${job.displayBytes}`,).join("\u0002");if (signature === cache.signature) return cache.jobs;@@ -227,16 +249,21 @@ function liveDownloadInventoryRows(isDatasetMode: boolean,): CachedInventoryRow[] {return jobs.map((job) => {+ const inventoryKind = downloadInventoryHintKind(+ job.kind,+ job.variant,+ job.inventoryKind,+ );const modelFormat = isDatasetMode? "unknown"- : job.variant+ : inventoryKind === "gguf"? "gguf": "safetensors";return {...buildCachedInventoryRow({repo_id: job.repoId,- inventory_id: `cache:${modelFormat}:${job.repoId}`,+ inventory_id: cachedInventoryId(modelFormat, job.repoId),load_id: job.repoId,model_format: modelFormat,runtime:diff --git a/studio/frontend/src/features/hub/inventory/view-models.ts b/studio/frontend/src/features/hub/inventory/view-models.tsindex 15545cb1c5d..2951a8a4306 100644--- a/studio/frontend/src/features/hub/inventory/view-models.ts+++ b/studio/frontend/src/features/hub/inventory/view-models.ts@@ -153,6 +153,20 @@ export function normalizeCapabilities(};}+export function cachedInventoryId(+ modelFormat: ModelInventoryFormat,+ repoId: string,+): string {+ return `cache:${modelFormat}:${encodeURIComponent(repoId)}`;+}++export function optimisticInventoryId(+ modelFormat: ModelInventoryFormat,+ repoId: string,+): string {+ return `download:${modelFormat}:${encodeURIComponent(repoId)}`;+}+export function buildCachedInventoryRow(row: {repo_id: string;@@ -200,9 +214,11 @@ export function buildCachedInventoryRow(return {kind: "cache",id:- !inferredFromEndpoint && row.inventory_id- ? row.inventory_id- : `cache:${modelFormat}:${row.repo_id}`,+ row.optimistic+ ? optimisticInventoryId(modelFormat, row.repo_id)+ : !inferredFromEndpoint && row.inventory_id+ ? row.inventory_id+ : cachedInventoryId(modelFormat, row.repo_id),loadId: row.load_id ?? row.repo_id,repoId: row.repo_id,owner: row.repo_id.includes("/") ? ownerOf(row.repo_id) : "Hub",diff --git a/studio/frontend/src/features/hub/lib/selection-resolution.ts b/studio/frontend/src/features/hub/lib/selection-resolution.tsindex 642fb68f1d8..804ad32f939 100644--- a/studio/frontend/src/features/hub/lib/selection-resolution.ts+++ b/studio/frontend/src/features/hub/lib/selection-resolution.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 { findCompleteHfCacheLocalRow } from "../inventory/inventory-dedupe";+import {+ findCompleteHfCacheLocalRow,+ provenUnknownPartialFamily,+} from "../inventory/inventory-dedupe";+import { cachedInventoryId } from "../inventory/view-models";import type {CachedInventoryRow,DiscoverRow,@@ -13,6 +17,48 @@ export type SelectionResolution = {hiddenByFilters: boolean;};+export type SelectionUrlSync =+ | { action: "select"; selectedId: string | null }+ | { action: "replace"; selectedId: string; preserveGgufFile: boolean }+ | null;++export function resolveSelectionUrlSync({+ isDiscoverTab,+ urlModel,+ selectionInputId,+ resolvedSelectedId,+ resolvedModelFormat,+}: {+ isDiscoverTab: boolean;+ urlModel: string | null;+ selectionInputId: string | null;+ resolvedSelectedId: string | null;+ resolvedModelFormat: CachedInventoryRow["modelFormat"] | null;+}): SelectionUrlSync {+ if (urlModel !== selectionInputId) {+ return { action: "select", selectedId: urlModel };+ }+ if (+ !isDiscoverTab &&+ resolvedSelectedId &&+ resolvedSelectedId !== urlModel+ ) {+ const resolvedFormat =+ resolvedModelFormat ??+ parseCacheSelectionIdentity(resolvedSelectedId)?.modelFormat ??+ null;+ return {+ action: "replace",+ selectedId: resolvedSelectedId,+ preserveGgufFile:+ resolvedFormat === "gguf" ||+ (resolvedFormat === "unknown" &&+ parseCacheSelectionIdentity(urlModel ?? "")?.modelFormat === "gguf"),+ };+ }+ return null;+}+function idSet(rows: readonly { id: string }[]): Set<string> {return new Set(rows.map((row) => row.id));}@@ -21,6 +67,115 @@ function idMap<T extends { id: string }>(rows: readonly T[]): Map<string, T> {return new Map(rows.map((row) => [row.id, row]));}+type CacheSelectionIdentity = {+ source: "cache" | "download" | "hf_cache";+ modelFormat: CachedInventoryRow["modelFormat"];+ repoKey: string;+};++const MODEL_FORMATS = new Set<CachedInventoryRow["modelFormat"]>([+ "gguf",+ "safetensors",+ "adapter",+ "checkpoint",+ "unknown",+]);++function parseCacheSelectionIdentity(+ id: string,+): CacheSelectionIdentity | null {+ const firstSeparator = id.indexOf(":");+ const secondSeparator = id.indexOf(":", firstSeparator + 1);+ if (firstSeparator <= 0 || secondSeparator <= firstSeparator + 1) {+ return null;+ }+ const source = id.slice(0, firstSeparator);+ const modelFormat = id.slice(firstSeparator + 1, secondSeparator);+ const encodedRepoId = id.slice(secondSeparator + 1);+ if (+ (source !== "cache" && source !== "download" && source !== "hf_cache") ||+ !MODEL_FORMATS.has(modelFormat as CachedInventoryRow["modelFormat"]) ||+ !encodedRepoId ||+ encodedRepoId.includes(":")+ ) {+ return null;+ }+ try {+ const repoKey = decodeURIComponent(encodedRepoId).trim().toLowerCase();+ return repoKey+ ? {+ source,+ modelFormat: modelFormat as CachedInventoryRow["modelFormat"],+ repoKey,+ }+ : null;+ } catch {+ return null;+ }+}++function inventoryRepoKey(+ row: Pick<CachedInventoryRow | LocalInventoryRow, "repoId">,+): string {+ return row.repoId?.trim().toLowerCase() ?? "";+}++function hfCacheInventoryId(+ row: Pick<LocalInventoryRow, "modelFormat" | "repoId">,+): string | null {+ if (!row.repoId) {+ return null;+ }+ const canonicalId = cachedInventoryId(row.modelFormat, row.repoId);+ return `hf_cache:${canonicalId.slice("cache:".length)}`;+}++function cachedIdMap(+ rows: readonly CachedInventoryRow[],+): Map<string, CachedInventoryRow> {+ const map = idMap(rows);+ for (const row of rows) {+ const canonicalId = cachedInventoryId(row.modelFormat, row.repoId);+ if (!map.has(canonicalId)) {+ map.set(canonicalId, row);+ }+ const legacyId = `cache:${row.modelFormat}:${row.repoId}`;+ if (!map.has(legacyId)) {+ map.set(legacyId, row);+ }+ if (row.modelFormat !== "unknown") {+ const localId = hfCacheInventoryId(row);+ if (localId && !map.has(localId)) {+ map.set(localId, row);+ }+ }+ }+ return map;+}++function localIdMap(+ rows: readonly LocalInventoryRow[],+): Map<string, LocalInventoryRow> {+ const map = idMap(rows);+ for (const row of rows) {+ if (row.source !== "hf_cache" || !row.repoId) {+ continue;+ }+ if (row.modelFormat === "unknown") {+ continue;+ }+ const canonicalId = cachedInventoryId(row.modelFormat, row.repoId);+ if (!map.has(canonicalId)) {+ map.set(canonicalId, row);+ }+ const legacyId = `cache:${row.modelFormat}:${row.repoId}`;+ if (!map.has(legacyId)) {+ map.set(legacyId, row);+ }+ }+ return map;+}+function resolveCachedSelection(cached: CachedInventoryRow,filteredCachedIds: ReadonlySet<string>,@@ -42,6 +197,196 @@ function resolveCachedSelection(};}+function resolveCurrentSelection(+ cachedRows: readonly CachedInventoryRow[],+ localRows: readonly LocalInventoryRow[],+ filteredCachedIds: ReadonlySet<string>,+ filteredLocalIds: ReadonlySet<string>,+ allLocalRows: readonly LocalInventoryRow[],+): SelectionResolution | null {+ const formats = new Set([+ ...cachedRows.map((row) => row.modelFormat),+ ...localRows.map((row) => row.modelFormat),+ ]);+ if (formats.size !== 1) {+ return null;+ }+ const cached = cachedRows[0];+ if (cached) {+ return resolveCachedSelection(+ cached,+ filteredCachedIds,+ filteredLocalIds,+ allLocalRows,+ );+ }+ const local = localRows[0];+ return local+ ? {+ selectedId: local.id,+ hiddenByFilters: !filteredLocalIds.has(local.id),+ }+ : null;+}++function formatFamilyOf(+ modelFormat: CachedInventoryRow["modelFormat"],+): "gguf" | "model" {+ return modelFormat === "gguf" ? "gguf" : "model";+}++/**+ * Whether `row` can carry a selection currently identified as `provisional`. An unclassified row stays a+ * candidate unless its family can be PROVEN to differ: reading `unknown` as "compatible with anything" let a+ * cancelled GGUF download land on a safetensors fragment deduplication had deliberately kept apart.+ */+function isProvisionalFormatCompatible(+ provisional: CachedInventoryRow["modelFormat"],+ row: Pick<+ CachedInventoryRow | LocalInventoryRow,+ "modelFormat" | "partial" | "partialTransport"+ >,+): boolean {+ const current = row.modelFormat;+ if (current === "unknown") {+ // A complete row carries no transport, so there is nothing to disagree with.+ if (!row.partial) {+ return true;+ }+ const proven = provenUnknownPartialFamily(row);+ return proven === null || proven === formatFamilyOf(provisional);+ }+ if (provisional === "safetensors") {+ return (+ current === "safetensors" ||+ current === "adapter" ||+ current === "checkpoint"+ );+ }+ return current === provisional;+}++function resolveFormatTransition(+ id: string | null,+ cachedRows: readonly CachedInventoryRow[],+ localRows: readonly LocalInventoryRow[],+ filteredCachedIds: ReadonlySet<string>,+ filteredLocalIds: ReadonlySet<string>,+): SelectionResolution | null {+ if (!id) {+ return null;+ }+ const identity = parseCacheSelectionIdentity(id);+ if (!identity) {+ return null;+ }+ const matchingCached = cachedRows.filter(+ (row) => inventoryRepoKey(row) === identity.repoKey,+ );+ const matchingLocal = localRows.filter(+ (row) =>+ row.source === "hf_cache" && inventoryRepoKey(row) === identity.repoKey,+ );+ if (identity.source === "download") {+ return resolveCurrentSelection(+ matchingCached.filter((row) =>+ isProvisionalFormatCompatible(identity.modelFormat, row),+ ),+ matchingLocal.filter((row) =>+ isProvisionalFormatCompatible(identity.modelFormat, row),+ ),+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+ }+ if (identity.modelFormat === "unknown") {+ if (identity.source === "cache") {+ return resolveCurrentSelection(+ matchingCached.filter((row) => row.modelFormat === "unknown"),+ [],+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+ }+ const exactLocal = resolveCurrentSelection(+ [],+ matchingLocal.filter((row) => row.modelFormat === "unknown"),+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+ if (exactLocal) {+ return exactLocal;+ }+ return resolveCurrentSelection(+ matchingCached.filter((row) => row.modelFormat !== "unknown"),+ matchingLocal.filter((row) => row.modelFormat !== "unknown"),+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+ }+ const exact = resolveCurrentSelection(+ matchingCached.filter((row) => row.modelFormat === identity.modelFormat),+ matchingLocal.filter((row) => row.modelFormat === identity.modelFormat),+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+ if (exact) {+ return exact;+ }+ if (+ matchingCached.some((row) => row.modelFormat !== "unknown") ||+ matchingLocal.some((row) => row.modelFormat !== "unknown")+ ) {+ return null;+ }+ // Cancel and resume land here: only an unclassified partial is left, and it is the right row only if it is the same family dedup used to keep it.+ return resolveCurrentSelection(+ [],+ matchingLocal.filter(+ (row) =>+ row.modelFormat === "unknown" &&+ isProvisionalFormatCompatible(identity.modelFormat, row),+ ),+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+}++function resolveRawRepoTransition(+ id: string | null,+ cachedRows: readonly CachedInventoryRow[],+ localRows: readonly LocalInventoryRow[],+ filteredCachedIds: ReadonlySet<string>,+ filteredLocalIds: ReadonlySet<string>,+): SelectionResolution | null {+ const segments = id?.trim().split("/") ?? [];+ if (+ segments.length !== 2 ||+ segments.some((segment) => !segment) ||+ id?.includes(":") ||+ id?.includes("\\")+ ) {+ return null;+ }+ const repoKey = segments.join("/").toLowerCase();+ return resolveCurrentSelection(+ cachedRows.filter((row) => inventoryRepoKey(row) === repoKey),+ localRows.filter(+ (row) =>+ row.source === "hf_cache" && inventoryRepoKey(row) === repoKey,+ ),+ filteredCachedIds,+ filteredLocalIds,+ localRows,+ );+}+function resolveDownloadedId(id: string | null,cachedById: ReadonlyMap<string, CachedInventoryRow>,@@ -62,10 +407,11 @@ function resolveDownloadedId(localRows,);}- if (localById.has(id)) {+ const local = localById.get(id);+ if (local) {return {- selectedId: id,- hiddenByFilters: !filteredLocalIds.has(id),+ selectedId: local.id,+ hiddenByFilters: !filteredLocalIds.has(local.id),};}return null;@@ -101,19 +447,24 @@ export function resolveDiscoverSelection({export function resolveDownloadedSelection({selectedId,+ inventoryReady = true,cachedRows,localRows,filteredCachedRows,filteredLocalRows,}: {selectedId: string | null;+ inventoryReady?: boolean;cachedRows: readonly CachedInventoryRow[];localRows: readonly LocalInventoryRow[];filteredCachedRows: readonly CachedInventoryRow[];filteredLocalRows: readonly LocalInventoryRow[];}): SelectionResolution {- const cachedById = idMap(cachedRows);- const localById = idMap(localRows);+ if (!inventoryReady) {+ return { selectedId, hiddenByFilters: false };+ }+ const cachedById = cachedIdMap(cachedRows);+ const localById = localIdMap(localRows);const filteredCachedIds = idSet(filteredCachedRows);const filteredLocalIds = idSet(filteredLocalRows);return (@@ -124,6 +475,20 @@ export function resolveDownloadedSelection({filteredCachedIds,filteredLocalIds,localRows,+ ) ??+ resolveFormatTransition(+ selectedId,+ cachedRows,+ localRows,+ filteredCachedIds,+ filteredLocalIds,+ ) ??+ resolveRawRepoTransition(+ selectedId,+ cachedRows,+ localRows,+ filteredCachedIds,+ filteredLocalIds,) ?? { selectedId: null, hiddenByFilters: false });}diff --git a/studio/frontend/src/features/settings/components/documents-rag-section.tsx b/studio/frontend/src/features/settings/components/documents-rag-section.tsxindex e3343dcac9d..60bfdfe946d 100644--- a/studio/frontend/src/features/settings/components/documents-rag-section.tsx+++ b/studio/frontend/src/features/settings/components/documents-rag-section.tsx@@ -29,20 +29,14 @@ import { EmbeddingModelPicker } from "./embedding-model-picker";import { SettingsRow } from "./settings-row";import { SettingsSection } from "./settings-section";-/** One slot per repo for the embedder's GGUF, so re-picking adopts the running- * transfer and a full-repo Hub download keeps its own. */+/** One slot per repo for the embedder's GGUF, so re-picking adopts the running transfer and a full-repo Hub download keeps its own. */const EMBEDDING_DOWNLOAD_SCOPE = "rag-embedding";/**- * Which model indexes uploaded documents. Rendered in both General and Data,- * off one shared store, so a save on one is what the other reads.- *- * Picking applies immediately, as dictation does; a model that is not on disk- * is marked pending by the server and offered as a download. Its loader remains- * cache-only, so closing or cancelling cannot turn into a first-index transfer.+ * Which model indexes uploaded documents, rendered in both General and Data off one shared store.+ * A model not on disk is marked pending and offered as a download, and its loader stays cache-only,+ * so closing or cancelling cannot turn into a first-index transfer.*/-// Residency is not a function of anything this component does, so it is polled-// rather than read only on a settings mutation.const RESIDENCY_POLL_MS = 5000;export function DocumentsRagSection(): ReactElement {@@ -53,28 +47,21 @@ export function DocumentsRagSection(): ReactElement {const beginSave = useEmbeddingModelStore((s) => s.beginSave);const isSaveCurrent = useEmbeddingModelStore((s) => s.isSaveCurrent);const save = useEmbeddingModelStore((s) => s.save);- // Unloading releases residency and leaves the selection alone, so it must not- // take a place in save order and retire an in-flight selection's reservation.+ // Unloading leaves the selection alone, so it must not take a place in save order and retire an in-flight selection's reservation.const applyResidency = useEmbeddingModelStore((s) => s.applyResidency);const [saveError, setSaveError] = useState<string | null>(null);- // The store carries the backend's reason; an unreadable failure has none.const loadFailure =loadError === null? null: loadError || t("settings.general.rag.loadError");const embeddingModelError = saveError ?? loadFailure;- // Set after a 409 (unverifiable model); "Save anyway" applies to that pick only.const [forceCandidate, setForceCandidate] = useState<string | null>(null);- /** Bumped when a save leaves the model string unchanged, which the effect- * below keys on and would otherwise not re-run for. */+ /** Bumped when a save leaves the model string unchanged, which the effect below keys on. */const [resolveNonce, setResolveNonce] = useState(0);const [isSavingEmbeddingModel, setIsSavingEmbeddingModel] = useState(false);- // What /resolve last said about the saved model: drives the status line and- // whether the action row offers Download.const [resolution, setResolution] = useState<EmbeddingModelResolution | null>(null,);- // Repo ids with a complete cache, for the picker's on-device dot.const [cachedRepos, setCachedRepos] = useState<ReadonlySet<string>>(() => new Set(),);@@ -83,10 +70,7 @@ export function DocumentsRagSection(): ReactElement {void useEmbeddingModelStore.getState().load();}, []);- // Residency changes with no settings mutation: a running job reaching its- // first encode makes a backend resident, and the store loads only on mount.- // No lifecycle event to subscribe to, so re-read while visible; a hidden tab- // does not poll and catches up when it returns.+ // Residency changes with no settings mutation and there is no lifecycle event to subscribe to, so re-read while visible; a hidden tab catches up when it returns.useEffect(() => {const refresh = () => {if (document.hidden) return;@@ -114,7 +98,6 @@ export function DocumentsRagSection(): ReactElement {),);} catch {- // Advisory: without it rows just lose their dot.}}, [hfToken]);@@ -122,12 +105,8 @@ export function DocumentsRagSection(): ReactElement {void refreshCachedRepos();}, [refreshCachedRepos]);- // Resolve the model already saved, so the row reports its state on open- // rather than only after a pick.const savedModel = embeddingModel?.embeddingModel;useEffect(() => {- // Another mounted settings surface may have saved a different model. Its- // model-scoped actions and errors say nothing about this new selection.setResolution(null);setForceCandidate(null);setSaveError(null);@@ -138,15 +117,13 @@ export function DocumentsRagSection(): ReactElement {if (live && next.embeddingModel === savedModel) setResolution(next);}).catch(() => {- // Offline: the row simply says nothing about disk state.});return () => {live = false;};}, [savedModel, hfToken, resolveNonce]);- /** Persist the pick, recording the GGUF repo /resolve named so the loader- * opens what was downloaded rather than re-deriving a name. */+ /** Persist the pick, recording the GGUF repo /resolve named so the loader opens what was downloaded rather than re-deriving a name. */const persist = async (model: string,plan: EmbeddingModelResolution | null,@@ -165,7 +142,6 @@ export function DocumentsRagSection(): ReactElement {}),reservation,);- // A later save owns the setting now, so this answer says nothing current.if (!stood) return false;setForceCandidate(null);toast.success(t("settings.general.rag.saved"), {@@ -188,27 +164,22 @@ export function DocumentsRagSection(): ReactElement {}};- /** Resolve first, so a model that needs fetching is offered as a download- * rather than saved and quietly fetched at the first index. */+ /** Resolve first, so a model that needs fetching is offered as a download rather than saved and quietly fetched at the first index. */const applyEmbeddingModel = async (model: string, force: boolean) => {- // A force affordance belongs only to the request that produced its 409.setForceCandidate(null);const trimmed = model.trim();if (!trimmed) {setSaveError(t("settings.general.rag.emptyError"));return;}- // Claim cross-surface ordering before the resolver await. Otherwise a- // slower older selection can call save last and overwrite a newer pick.+ // Claim cross-surface ordering before the resolver await, else a slower older selection saves last and overwrites a newer pick.const reservation = beginSave();setIsSavingEmbeddingModel(true);setSaveError(null);setResolution(null);try {if (force) {- // A force save can leave the model string unchanged, so the savedModel- // effect does not re-run and nothing restores the plan this call cleared,- // leaving no Download offered while the loader refuses to index.+ // A force save can leave the model string unchanged, so the savedModel effect does not re-run and nothing restores the plan this call cleared.if (await persist(trimmed, null, true, reservation)) {setResolveNonce((n) => n + 1);}@@ -221,20 +192,17 @@ export function DocumentsRagSection(): ReactElement {});} catch {if (!isSaveCurrent(reservation)) return;- // Offline or the probe failed: let the save decide, as it did before.await persist(trimmed, null, false, reservation);return;}if (!isSaveCurrent(reservation)) return;if (resolution.error) {- // Forceable: the user may know something the probe cannot see.setResolution(resolution);setForceCandidate(trimmed);setSaveError(resolution.error);return;}- // Retain the plan only after the server accepted the matching setting.- // A rejected save must not expose a Download action for an unsaved repo.+ // Retain the plan only after the server accepted the matching setting: a rejected save must not expose Download for an unsaved repo.if (await persist(trimmed, resolution, false, reservation)) {setResolution(resolution);}@@ -246,8 +214,7 @@ export function DocumentsRagSection(): ReactElement {const startDownload = async (resolution: EmbeddingModelResolution) => {const repoId = resolution.downloadRepo;if (!repoId) return;- // Scoped when the backend named a file: the companion repo carries every- // quant, and the embedder opens one.+ // Scoped when the backend named a file: the companion repo carries every quant, and the embedder opens one.const scoped = resolution.files !== null && resolution.files.length > 0;try {const outcome = await downloadManager.requestStart({@@ -256,6 +223,7 @@ export function DocumentsRagSection(): ReactElement {variant: scoped ? scopedVariant(EMBEDDING_DOWNLOAD_SCOPE) : null,scopeId: scoped ? EMBEDDING_DOWNLOAD_SCOPE : null,files: scoped ? (resolution.files ?? undefined) : undefined,+ inventoryKind: scoped ? "gguf" : undefined,expectedBytes: resolution.sizeBytes ?? 0,});if (outcome === "started") {@@ -266,17 +234,12 @@ export function DocumentsRagSection(): ReactElement {{ description: t("settings.general.rag.downloadingDescription") },);} else if (outcome === "conflict") {- // Not a failure: an earlier partial used a different transport and the- // Hub's own card is where it resumes. "Couldn't start" would send the- // user looking for a problem instead of for that row.+ // Not a failure: an earlier partial used a different transport and the Hub's own card is where it resumes.toast.info(t("settings.general.rag.downloadConflict"));} else if (outcome === "busy") {- // The repo is occupied by a sibling transfer, which the downloads panel- // is already showing. Reselect once it lands.toast.info(t("settings.general.rag.downloadBusy"));} else {- // requestStart turns refused starts into outcomes rather than throws, so- // every remaining non-start still needs feedback from this caller.+ // requestStart turns refused starts into outcomes rather than throws, so every remaining non-start needs feedback here.toast.error(t("settings.general.rag.downloadFailed"));}} catch (error) {@@ -286,8 +249,6 @@ export function DocumentsRagSection(): ReactElement {}};- // The live job for the repo this model needs, so the button reflects a- // transfer started here or from anywhere else.const downloadJobKey =resolution?.downloadRepo && !resolution.cached? jobKeyOf(@@ -314,8 +275,6 @@ export function DocumentsRagSection(): ReactElement {fullSnapshotDownloadState === "running" ||fullSnapshotDownloadState === "cancelling";- // The original resolve correctly said uncached. Once the shared manager- // completes, ask again so the status/button and picker dots reflect disk.useEffect(() => {if ((downloadState !== "complete" &&@@ -332,8 +291,6 @@ export function DocumentsRagSection(): ReactElement {if (live && next.embeddingModel === savedModel) setResolution(next);}).catch(() => {- // The completed transfer remains in the shared panel; a later open- // retries the advisory resolve/cache inventory.});return () => {live = false;@@ -450,9 +407,7 @@ export function DocumentsRagSection(): ReactElement {{t("settings.general.rag.download")}</Button>) : null}- {/* Outside the chain above: saving a new model does not release the- old one, so while Download shows for an uncached pick the previous- model can still be resident. backendLoaded asks about any. */}+ {/* Outside the chain above: saving a new model does not release the old one, so while Download shows the previous model can still be resident. */}{embeddingModel?.backendLoaded ? (<Buttonvariant="outline"diff --git a/studio/frontend/tests/download-inventory-kind.test.ts b/studio/frontend/tests/download-inventory-kind.test.tsnew file mode 100644index 00000000000..dd2627f011a--- /dev/null+++ b/studio/frontend/tests/download-inventory-kind.test.ts@@ -0,0 +1,188 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { registerStoreStubResolver } from "./helpers/kit.ts";++import {+ downloadInventoryHintKind,+ downloadRequestInventoryKind,+ scopedDownloadInventoryKind,+} from "../src/features/hub/download-manager/download-manager-types.ts";++registerStoreStubResolver();++const {+ createLiveInventoryJobsSelector,+ liveInventorySelectionKey,+ observedKeyProtections,+} = await import("../src/features/hub/inventory/use-hub-inventory.ts");++function liveJob(over: Record<string, unknown>) {+ return {+ kind: "model",+ repoId: "Org/Repo",+ variant: null,+ state: "running",+ startedAt: 1,+ downloadedBytes: 0,+ completedBytes: 0,+ expectedBytes: 0,+ fraction: 0,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ completeOnDisk: false,+ ...over,+ } as never;+}++test("classifies quant variants as GGUF", () => {+ assert.equal(downloadInventoryHintKind("model", "Q4_K_M"), "gguf");+});++test("classifies legacy scoped variants as model downloads", () => {+ assert.equal(downloadInventoryHintKind("model", "@diffusion"), "model");+});++test("uses the caller's format for scoped downloads", () => {+ assert.equal(+ downloadInventoryHintKind("model", "@diffusion", "gguf"),+ "gguf",+ );+ assert.equal(+ downloadInventoryHintKind("model", "@diffusion", "model"),+ "model",+ );+});++test("keeps dataset jobs out of model inventory", () => {+ assert.equal(downloadInventoryHintKind("dataset", null), "dataset");+});++test("recovers scoped inventory format from backend files", () => {+ assert.equal(+ scopedDownloadInventoryKind(["transformer/model-Q4_K_M.gguf"]),+ "gguf",+ );+ assert.equal(+ scopedDownloadInventoryKind(["transformer/model.safetensors"]),+ "model",+ );+ assert.equal(scopedDownloadInventoryKind(undefined), "model");+});++test("classifies staged single-file checkpoints from their file set", () => {+ // A `.safetensors` checkpoint can sit in the field named gguf_filename, so that field is not evidence of GGUF.+ assert.equal(+ downloadRequestInventoryKind({+ kind: "model",+ variant: "@diffusion",+ files: ["flux1-dev.safetensors"],+ }),+ "model",+ );+ assert.equal(+ downloadRequestInventoryKind({+ kind: "model",+ variant: "@diffusion",+ files: ["flux1-dev-Q8_0.gguf"],+ }),+ "gguf",+ );+ assert.equal(scopedDownloadInventoryKind(["flux1-dev.safetensors"]), "model");+});++test("infers missing scoped request formats during adoption", () => {+ assert.equal(+ downloadRequestInventoryKind({+ kind: "model",+ variant: "@rag-embedding",+ files: ["model-Q4_K_M.gguf"],+ }),+ "gguf",+ );+ assert.equal(+ downloadRequestInventoryKind({+ kind: "model",+ variant: "@diffusion",+ files: ["transformer/model.safetensors"],+ }),+ "model",+ );+ assert.equal(+ downloadRequestInventoryKind({+ kind: "model",+ variant: "@rag-embedding",+ inventoryKind: "model",+ files: ["model-Q4_K_M.gguf"],+ }),+ "model",+ );+ assert.equal(+ downloadRequestInventoryKind({+ kind: "model",+ variant: "@rag-embedding",+ }),+ undefined,+ );++});++test("separates live inventory rows for hybrid repository formats", () => {+ // Two scoped jobs on one repo share the variant SHAPE, so only the resolved inventory kind separates them; keying on the variant collapses both rows onto one.+ const selector = createLiveInventoryJobsSelector(false);+ const rows = selector({+ jobs: {+ a: liveJob({+ key: "a",+ variant: "@rag-embedding",+ inventoryKind: "gguf",+ }),+ b: liveJob({ key: "b", variant: "@diffusion", inventoryKind: "model" }),+ },+ });++ assert.equal(rows.length, 2);+ assert.deepEqual(+ rows.map((row) => row.inventoryKind).sort(),+ ["gguf", "model"],+ );+ assert.equal(+ liveInventorySelectionKey(rows[0]!) === liveInventorySelectionKey(rows[1]!),+ false,+ "two formats of one repo collapsed onto a single live row",+ );+});++test("same-format live jobs for one repository still collapse", () => {+ const selector = createLiveInventoryJobsSelector(false);+ const rows = selector({+ jobs: {+ a: liveJob({ key: "a", variant: "Q4_K_M", inventoryKind: "gguf" }),+ b: liveJob({ key: "b", variant: "Q8_0", inventoryKind: "gguf" }),+ },+ });+ assert.equal(rows.length, 1);+});++test("protects observed keys with the job's explicit inventory kind", () => {+ // A scoped job classified as gguf must protect the gguf key, not the key its `@variant` shape alone implies.+ const keys = observedKeyProtections({+ scoped: liveJob({+ key: "scoped",+ variant: "@rag-embedding",+ inventoryKind: "gguf",+ }),+ });+ assert.equal(keys.gguf.has("org/repo"), true);+ assert.equal(keys.model.has("org/repo"), false);++ const unclassified = observedKeyProtections({+ scoped: liveJob({ key: "scoped", variant: "@diffusion" }),+ });+ assert.equal(unclassified.model.has("org/repo"), true);+ assert.equal(unclassified.gguf.has("org/repo"), false);+});diff --git a/studio/frontend/tests/download-scoped-delete-hint.test.ts b/studio/frontend/tests/download-scoped-delete-hint.test.tsnew file mode 100644index 00000000000..5bb87c0bd75--- /dev/null+++ b/studio/frontend/tests/download-scoped-delete-hint.test.ts@@ -0,0 +1,74 @@+// 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 scoped `@variant` download publishes a `model` hint, so deleting one while clearing only `gguf` leaves the row to come back until the hint expires.++import assert from "node:assert/strict";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const {+ discardPendingInventoryHint,+ rememberCompletedInventoryHints,+ useInventoryHintStore,+} = await import("../src/features/hub/inventory/inventory-hint-store.ts");+const { discardDeletedModelInventoryHints } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);++function pendingHas(kind: "model" | "gguf", repoId: string): boolean {+ return useInventoryHintStore+ .getState()+ .pending[kind].has(repoId.toLowerCase());+}++function seed(kind: "model" | "gguf", repoId: string) {+ rememberCompletedInventoryHints([{ kind, repoId }]);+ assert.equal(pendingHas(kind, repoId), true, "precondition: hint was stored");+}++test("deleting a scoped model download clears its model hint", () => {+ const repoId = "org/diffusion-model";+ seed("model", repoId);++ discardDeletedModelInventoryHints(repoId, "@diffusion");++ assert.equal(+ pendingHas("model", repoId),+ false,+ "the deleted scoped row keeps its hint and reappears until it expires",+ );+});++test("deleting a quant download still clears its gguf hint", () => {+ const repoId = "org/quant-model";+ seed("gguf", repoId);++ discardDeletedModelInventoryHints(repoId, "Q4_K_M");++ assert.equal(pendingHas("gguf", repoId), false);+});++test("deleting a whole repo clears both hint kinds", () => {+ const repoId = "org/both-model";+ seed("gguf", repoId);+ seed("model", repoId);++ discardDeletedModelInventoryHints(repoId);++ assert.equal(pendingHas("gguf", repoId), false);+ assert.equal(pendingHas("model", repoId), false);+});++test("deleting one variant leaves an unrelated repo's hint alone", () => {+ const kept = "org/untouched";+ seed("model", kept);+ discardPendingInventoryHint("model", "org/somewhere-else");++ discardDeletedModelInventoryHints("org/other-model", "@diffusion");++ assert.equal(pendingHas("model", kept), true);+});diff --git a/studio/frontend/tests/download-scoped-kind-upgrade.test.ts b/studio/frontend/tests/download-scoped-kind-upgrade.test.tsnew file mode 100644index 00000000000..caea8c38f96--- /dev/null+++ b/studio/frontend/tests/download-scoped-kind-upgrade.test.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Jobs persisted before `inventoryKind` still carry `scopedFiles`, so hydration recovers the kind rather than giving a scoped GGUF a safetensors row after an update.++import assert from "node:assert/strict";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+const { store } = installLocalStorageFake();++const PERSIST_KEY = "unsloth.studio.downloads";++function persistedJob(+ repoId: string,+ variant: string | null,+ extra: Record<string, unknown> = {},+) {+ return {+ key: `model:${repoId}:${variant ?? ""}`,+ kind: "model",+ repoId,+ variant,+ state: "running",+ downloadedBytes: 25,+ completedBytes: 0,+ expectedBytes: 100,+ fraction: 0.25,+ error: null,+ startedAt: 1,+ ...extra,+ };+}++store.set(+ PERSIST_KEY,+ JSON.stringify({+ state: {+ jobs: {+ // Written before `inventoryKind` existed: a scoped GGUF embedding download.+ legacyGguf: persistedJob("org/embedder", "@rag-embedding", {+ scopedFiles: ["nomic-embed-text-v1.5.Q8_0.gguf"],+ }),+ legacyModel: persistedJob("org/diffusion", "@diffusion", {+ scopedFiles: ["transformer/diffusion_pytorch_model.safetensors"],+ }),+ explicit: persistedJob("org/explicit", "@diffusion", {+ scopedFiles: ["model.safetensors"],+ inventoryKind: "gguf",+ }),+ noEvidence: persistedJob("org/unknown-scope", "@diffusion"),+ quant: persistedJob("org/quant", "Q4_K_M"),+ },+ conflicts: {},+ },+ version: 2,+ }),+);++const { getState, jobKeyOf } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);+const { downloadInventoryHintKind } = await import(+ "../src/features/hub/download-manager/download-manager-types.ts"+);++function job(repoId: string, variant: string | null) {+ return getState().jobs[jobKeyOf("model", repoId, variant)];+}++test("a scoped GGUF job persisted before inventoryKind is recovered", () => {+ const recovered = job("org/embedder", "@rag-embedding");+ assert.ok(recovered, "the legacy job did not survive hydration");+ assert.equal(recovered.inventoryKind, "gguf");+ assert.equal(+ downloadInventoryHintKind(+ recovered.kind,+ recovered.variant,+ recovered.inventoryKind,+ ),+ "gguf",+ "a scoped GGUF download came back as a model download after a reload",+ );+});++test("a scoped safetensors job keeps the model classification", () => {+ const recovered = job("org/diffusion", "@diffusion");+ assert.ok(recovered);+ assert.equal(recovered.inventoryKind, "model");+});++test("an explicitly stored kind still wins over the file list", () => {+ assert.equal(job("org/explicit", "@diffusion")?.inventoryKind, "gguf");+});++test("a scoped job with no files stays unclassified", () => {+ // Guessing here would publish a wrong row; backend adoption resolves it.+ assert.equal(+ job("org/unknown-scope", "@diffusion")?.inventoryKind,+ undefined,+ );+});++test("an unscoped quant download is untouched", () => {+ const quant = job("org/quant", "Q4_K_M");+ assert.ok(quant);+ assert.equal(quant.inventoryKind, undefined);+ assert.equal(+ downloadInventoryHintKind(quant.kind, quant.variant, quant.inventoryKind),+ "gguf",+ );+});diff --git a/studio/frontend/tests/embedding-model-picker.test.ts b/studio/frontend/tests/embedding-model-picker.test.tsindex 82ec1dca8d6..3ad13c6909b 100644--- a/studio/frontend/tests/embedding-model-picker.test.ts+++ b/studio/frontend/tests/embedding-model-picker.test.ts@@ -12,8 +12,7 @@ function read(path: string): string {return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf-8");}-// These reach the hub and chat barrels and cannot be imported here, so this-// asserts on source, like ~50 sibling tests.+// These reach the hub and chat barrels and cannot be imported here, so this asserts on source, like ~50 sibling tests.const PICKER = read("../src/features/settings/components/embedding-model-picker.tsx",);@@ -36,20 +35,15 @@ test("the field says it reaches the whole Hub", () => {});test("an empty query lists unsloth, a typed one searches everything", () => {- // The global top-downloads page holds no unsloth mirrors to float, so an- // unscoped empty query buries the models this install actually ships with.assert.match(PICKER, /ownerScope: debouncedQuery \? "all" : "unsloth"/);assert.match(PICKER, /useDebouncedValue\(query\.trim\(\)\)/);});test("only the query searches; the saved model never becomes one", () => {- // The old combobox searched for whatever was in the field, so opening it on a- // saved model returned that one row and hid every other embedder.assert.ok(!PICKER.includes("useDebouncedValue(value)"),"the controlled value is not the query",);- // It is still reachable as a row, just not as a search term.assert.match(PICKER, /rows\.push\(\{ id: selected, sizeBytes: null \}\)/);});@@ -62,23 +56,17 @@ test("picking applies straight away, with no Save button", () => {!SECTION.includes('t("common.save")'),"selection is the apply action, as it is for dictation models",);- // "Save anyway" survives: a 409 is still forceable, per model.assert.match(SECTION, /applyEmbeddingModel\(forceCandidate, true\)/);});test("a model that is not on disk is offered as a real download", () => {- // The whole point of the change: before this, saving only wrote the setting- // and the weights arrived invisibly at the first index.assert.match(SECTION, /resolveEmbeddingModel\(trimmed, \{/);assert.match(SECTION, /setResolution\(resolution\)/);- // Same manager the Hub cards use, so progress, cancel and transport are shared.assert.match(SECTION, /downloadManager\.requestStart\(\{/);assert.match(SECTION, /kind: DOWNLOAD_KIND\.MODEL/);});test("the resolve runs before the save, not after it", () => {- // Saving first meant a model with no same-owner GGUF 409'd and the user saw a- // wall of red text instead of a download.const fn = SECTION.slice(SECTION.indexOf("const applyEmbeddingModel"),SECTION.indexOf("const startDownload"),@@ -88,7 +76,6 @@ test("the resolve runs before the save, not after it", () => {fn.indexOf("persist(trimmed, resolution"),"resolve decides, then the save records what it found",);- // Only the explicit override skips it, and it persists no plan.assert.match(fn,/if \(force\) \{[\s\S]*persist\(trimmed, null, true, reservation\)/,@@ -114,9 +101,7 @@ test("cross-surface save order is claimed before model resolution", () => {});test("the repo the resolve picked is what gets stored", () => {- // A GGUF repo need not follow a naming rule, so the loader has to be told- // rather than left to re-derive it. The backend rides along: a model with no- // GGUF runs on safetensors, and llama-server would have nothing to open.+ // A GGUF repo need not follow a naming rule, and a model with no GGUF runs on safetensors, so the loader has to be told the filename.assert.match(SECTION,/plan\?\.backend === "llama" \? \(plan\.downloadRepo \?\? null\) : null/,@@ -127,7 +112,6 @@ test("the repo the resolve picked is what gets stored", () => {});test("a missing model gets a Download button, not a popup", () => {- // A modal for a one-click action was noise, and voice already had the shape.assert.ok(!SECTION.includes("AlertDialog"), "no confirmation modal");assert.match(SECTION, /const canDownload = Boolean\(/);assert.match(@@ -142,9 +126,6 @@ test("the action slot offers Download or Unload, not Reset to default", () => {"reset is reachable by picking the default in the list",);assert.match(SECTION, /settings\.general\.rag\.unload/);- // Gated on backendLoaded, not loaded, and outside the Download chain: saving a- // new model does not release the old one, so the control that frees the- // previous model was unreachable while Download showed.assert.match(SECTION, /embeddingModel\?\.backendLoaded \? \(/);assert.ok(!SECTION.includes("): embeddingModel?.loaded ? ("),@@ -153,7 +134,6 @@ test("the action slot offers Download or Unload, not Reset to default", () => {});test("the button follows a transfer started anywhere", () => {- // Keyed off the shared manager, so a download begun from the Hub disables it too.assert.match(SECTION, /useDownloadManagerStore\(\(state\) =>/);assert.match(SECTION, /jobKeyOf\(/);assert.match(SECTION, /const fullSnapshotJobKey =/);@@ -211,12 +191,6 @@ test("a rejected save cannot retain its download plan", () => {});test("every download-manager non-start outcome gets feedback", () => {- // requestStart refuses by returning an outcome rather than throwing, so a- // non-start is silent unless this caller speaks. Every branch must, and the- // three do not mean the same thing: "conflict" is resumable from the Hub and- // "busy" is a sibling transfer already running, so reporting either as- // "couldn't start the download" sends the user hunting for a fault that the- // downloads panel is, at that moment, showing them the answer to.assert.match(SECTION, /if \(outcome === "started"\)[\s\S]*else \{/);assert.match(SECTION,@@ -238,6 +212,7 @@ test("only the embedder's own GGUF is fetched, not every quant", () => {SECTION,/variant: scoped \? scopedVariant\(EMBEDDING_DOWNLOAD_SCOPE\) : null/,);+ assert.match(SECTION, /inventoryKind: scoped \? "gguf" : undefined/);});test("the current row can be retried and arbitrary relative paths submit", () => {@@ -259,8 +234,6 @@ test("a gated-repo token never rides in the URL", () => {test("on-device rows carry the Hub's green dot", () => {assert.match(PICKER, /rounded-full bg-status-success/);- // The membership test moved off the raw id and onto the resolved repo; see- // "the on-device dot follows the resolved repo, not the displayed id".assert.match(PICKER, /isOnDevice\(cachedModels, item\.id\)/);assert.match(PICKER, /cached\.has\(repo\)/);});@@ -272,7 +245,6 @@ test("General and Data show the same section, not two copies of it", () => {["data", DATA_TAB],] as const) {assert.ok(tab.includes("<DocumentsRagSection />"), `${name} renders it`);- // A second copy of the load and save logic would let the two tabs disagree.assert.ok(!tab.includes("loadEmbeddingModelSettings"),`${name} has no embedding logic of its own`,@@ -283,8 +255,6 @@ test("General and Data show the same section, not two copies of it", () => {const VOICE_TAB = read("../src/features/settings/tabs/voice-tab.tsx");test("a dictation download is reported once, not twice", () => {- // Settings drew its own bar and Cancel beside the shared downloads panel,- // so one transfer showed two identical progress readouts.assert.ok(!VOICE_TAB.includes("DownloadProgressBar"),"no second progress bar",@@ -293,7 +263,6 @@ test("a dictation download is reported once, not twice", () => {!VOICE_TAB.includes("sttCancelDownload"),"cancelling belongs to the panel",);- // The status line still names the state; only the duplicate readout went.assert.match(VOICE_TAB, /\{sttModelStatusText\}/);assert.match(VOICE_TAB, /sttDownloading/);});@@ -310,10 +279,6 @@ test("the rate estimator went with the bar it fed", () => {});test("a force save re-resolves even though the model string did not change", () => {- // Save anyway on the model already saved leaves savedModel identical, so the- // effect keyed on it never re-runs and nothing restores the plan the apply- // cleared. The backend still marks an uncached model pending, so the row would- // sit with no Download while the loader refuses to index.assert.match(SECTION,/if \(await persist\(trimmed, null, true, reservation\)\) \{\s*setResolveNonce\(\(n\) => n \+ 1\);/,@@ -322,23 +287,17 @@ test("a force save re-resolves even though the model string did not change", ()});test("the configured default stays reachable when the listing drops it", () => {- // The empty query is scoped to `unsloth`, so a private, other-owner or local- // default had no row, and "Reset to default" is gone.+ // The empty query is scoped to `unsloth`, so a private, other-owner or local default has no row.assert.match(PICKER, /rows\.push\(\{ id: fallback, sizeBytes: null \}\)/);assert.match(PICKER, /const fallback = defaultModel\?\.trim\(\)/);- // A stale memo would pin the row to whatever the default was on first render.assert.match(PICKER, /\}, \[results, value, defaultModel\]\)/);- // And the section still hands the default down for it to be found.assert.match(SECTION, /defaultModel=\{embeddingModel\?\.defaultEmbeddingModel\}/);});test("backend residency is re-read, not just loaded once on mount", () => {- // A running job reaching its first encode makes a backend resident with no- // settings mutation, and the store loads only on mount. No lifecycle event to- // subscribe to, so this re-reads.+ // A running job's first encode makes a backend resident with no settings mutation, and there is no lifecycle event to subscribe to.assert.match(SECTION, /const RESIDENCY_POLL_MS = \d+;/);assert.match(SECTION, /window\.setInterval\(refresh, RESIDENCY_POLL_MS\)/);- // A hidden tab must not poll, and must catch up the moment it is shown.assert.match(SECTION, /if \(document\.hidden\) return;/);assert.match(SECTION, /addEventListener\("visibilitychange", refresh\)/);assert.match(SECTION, /removeEventListener\("visibilitychange", refresh\)/);@@ -346,8 +305,7 @@ test("backend residency is re-read, not just loaded once on mount", () => {});test("the on-device dot follows the resolved repo, not the displayed id", () => {- // The inventory records what was fetched, not what was picked, so an exact-id- // lookup left the dot off a fully downloaded model.+ // The inventory records what was fetched, not what was picked, so an exact-id lookup left the dot off a downloaded model.assert.match(PICKER, /export function cachedRepoCandidates\(model: string\): string\[\]/);assert.match(PICKER, /`\$\{id\}-GGUF`/);assert.match(PICKER, /`sentence-transformers\/\$\{id\}`/);@@ -360,13 +318,9 @@ test("the on-device dot follows the resolved repo, not the displayed id", () =>});test("an unquantized re-upload's GGUF companion counts as on device", () => {- // The backend strips the quant suffix, so- // unsloth/embeddinggemma-300m-qat-q8_0-unquantized resolves under- // unsloth/embeddinggemma-300m-GGUF; checking only <literal>-GGUF left the dot- // off a fully downloaded companion.+ // The backend strips the quant suffix, so unsloth/embeddinggemma-300m-qat-q8_0-unquantized resolves under unsloth/embeddinggemma-300m-GGUF.assert.match(PICKER, /\(\?:-qat\)\?\(\?:-q\\d\+_\\d\+\[a-z\]\*\)\?-unquantized\$/i);assert.match(PICKER, /if \(base !== name\) candidates\.push\(`\$\{owner\}\$\{base\}-GGUF`\)/);- // No lookbehind: this build target ships regex verbatim, so anything Safari 16- // cannot parse would break the bundle rather than fail a test.+ // No lookbehind: this build target ships regex verbatim, so anything Safari 16 cannot parse breaks the bundle rather than failing a test.assert.ok(!PICKER.includes("(?<="), "no lookbehind in shipped regex");});diff --git a/studio/frontend/tests/helpers/store-stubs/download-manager.ts b/studio/frontend/tests/helpers/store-stubs/download-manager.tsnew file mode 100644index 00000000000..2f48d796375--- /dev/null+++ b/studio/frontend/tests/helpers/store-stubs/download-manager.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Only the barrel needs stubbing: it also exports the React panel, which bare Node cannot resolve. The helpers under test stay real.+export type { ManagedDownload } from "../../../src/features/hub/download-manager/download-manager-types.ts";+export {+ downloadInventoryHintKind,+ downloadRequestInventoryKind,+ scopedDownloadInventoryKind,+} from "../../../src/features/hub/download-manager/download-manager-types.ts";++export function clearCompletedInventoryHint(): void {+}++export const useDownloadManagerStore = Object.assign(+ () => ({ jobs: {} }),+ {+ getState: () => ({ jobs: {} }),+ subscribe: () => () => {},+ },+);diff --git a/studio/frontend/tests/hub-selection-compat.test.ts b/studio/frontend/tests/hub-selection-compat.test.tsnew file mode 100644index 00000000000..47f73b44914--- /dev/null+++ b/studio/frontend/tests/hub-selection-compat.test.ts@@ -0,0 +1,477 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The selection ID outlives the process in the URL, and the download manager's jobs outlive it in+// localStorage, so every case below is an upgrade path a bookmark or an older Studio can walk into.++import assert from "node:assert/strict";+import test from "node:test";++import { registerStoreStubResolver } from "./helpers/kit.ts";++registerStoreStubResolver();++const { dedupeSameSourceHubCacheRows } = await import(+ "../src/features/hub/inventory/inventory-dedupe.ts"+);+const {+ buildCachedInventoryRow,+ buildLocalInventoryRows,+ cachedInventoryId,+ optimisticInventoryId,+} = await import("../src/features/hub/inventory/view-models.ts");+const { resolveDownloadedSelection, resolveSelectionUrlSync } = await import(+ "../src/features/hub/lib/selection-resolution.ts"+);+const { scopedDownloadInventoryKind, downloadInventoryHintKind } = await import(+ "../src/features/hub/download-manager/download-manager-types.ts"+);++function cachedRow(+ repoId: string,+ modelFormat: "gguf" | "safetensors" | "adapter" | "checkpoint" | "unknown",+ over: Record<string, unknown> = {},+) {+ return buildCachedInventoryRow(+ {+ repo_id: repoId,+ inventory_id: cachedInventoryId(modelFormat, repoId),+ model_format: modelFormat,+ size_bytes: 100,+ ...over,+ },+ modelFormat,+ );+}++function localRow(over: Record<string, unknown>) {+ return buildLocalInventoryRows([+ {+ source: "hf_cache",+ model_format: "unknown",+ ...over,+ } as never,+ ])[0];+}++function resolve(+ selectedId: string | null,+ cachedRows: readonly unknown[],+ localRows: readonly unknown[],+) {+ return resolveDownloadedSelection({+ selectedId,+ cachedRows: cachedRows as never,+ localRows: localRows as never,+ filteredCachedRows: cachedRows as never,+ filteredLocalRows: localRows as never,+ });+}+++test("a pre-encoding deep link still selects its row", () => {+ const repoId = "unsloth/gemma-3-270m-it";+ const row = cachedRow(repoId, "gguf");++ assert.equal(row.id, "cache:gguf:unsloth%2Fgemma-3-270m-it");+ assert.equal(resolve(`cache:gguf:${repoId}`, [row], []).selectedId, row.id);+});++test("a raw Org/Repo deep link still selects its row", () => {+ const row = cachedRow("unsloth/gemma-3-270m-it", "safetensors");+ assert.equal(+ resolve("unsloth/gemma-3-270m-it", [row], []).selectedId,+ row.id,+ );+});++test("percent escapes resolve regardless of hex case", () => {+ const row = cachedRow("unsloth/gemma-3-270m-it", "gguf");+ assert.equal(+ resolve("cache:gguf:unsloth%2fgemma-3-270m-it", [row], []).selectedId,+ row.id,+ );+ assert.equal(+ resolve("cache:gguf:unsloth%2Fgemma-3-270m-it", [row], []).selectedId,+ row.id,+ );+});++test("repo IDs survive characters encodeURIComponent leaves alone", () => {+ for (const repoId of [+ "unsloth/model-v1.5",+ "unsloth/model_v2",+ "unsloth/model.gguf-test",+ "org/repo!name",+ "org/repo~name",+ "org/repo'name",+ "org/repo(1)",+ ]) {+ const row = cachedRow(repoId, "gguf");+ assert.equal(+ resolve(row.id, [row], []).selectedId,+ row.id,+ `canonical ID did not round-trip for ${repoId}`,+ );+ }+});++test("non-ASCII repo IDs round-trip through the canonical ID", () => {+ for (const repoId of [+ "组织/模型",+ "org/модель",+ "org/modèle-café",+ "org/モデル",+ "org/emoji-\u{1F600}",+ ]) {+ const row = cachedRow(repoId, "safetensors");+ assert.equal(+ resolve(row.id, [row], []).selectedId,+ row.id,+ `non-ASCII repo ID did not round-trip for ${repoId}`,+ );+ }+});+++test("malformed selection IDs fail safely instead of throwing", () => {+ // decodeURIComponent throws URIError on all of these, and this runs inside a render, so an uncaught throw is a blank Hub.+ const malformed = [+ "cache:gguf:%",+ "cache:gguf:%2",+ "cache:gguf:%ZZ",+ "cache:gguf:%E0%A4%A",+ "cache:gguf:%C3%28",+ "cache:gguf:%ED%A0%80",+ "cache:gguf:org%2F%",+ ];+ for (const id of malformed) {+ assert.doesNotThrow(+ () => resolve(id, [cachedRow("org/repo", "gguf")], []),+ `threw on ${id}`,+ );+ assert.equal(+ resolve(id, [cachedRow("org/repo", "gguf")], []).selectedId,+ null,+ `${id} should not select a row`,+ );+ }+});++test("structurally invalid selection IDs are rejected", () => {+ const row = cachedRow("org/repo", "gguf");+ for (const id of [+ "",+ ":",+ "::",+ "cache:",+ "cache::org%2Frepo",+ ":gguf:org%2Frepo",+ "cache:nosuchformat:org%2Frepo",+ "bogus:gguf:org%2Frepo",+ "cache:gguf:org%2Frepo:extra",+ "ollama:gguf:llama3",+ ]) {+ assert.doesNotThrow(() => resolve(id, [row], []), `threw on ${id}`);+ }+});+++test("a Windows path is never mistaken for a raw repo ID", () => {+ const gguf = cachedRow("org/repo", "gguf");+ for (const id of [+ "C:\\Users\\me\\models\\model.gguf",+ "D:\\models\\org\\repo",+ "\\\\server\\share\\model",+ "models\\org\\repo",+ ]) {+ assert.equal(+ resolve(id, [gguf], []).selectedId,+ null,+ `${id} was resolved onto an unrelated row`,+ );+ }+});++test("a POSIX path is never mistaken for a raw repo ID", () => {+ const gguf = cachedRow("home/me", "gguf");+ for (const id of [+ "/home/me/models/model.gguf",+ "/home/me",+ "./models/foo",+ "../models/foo",+ "/",+ "//",+ ]) {+ assert.equal(+ resolve(id, [gguf], []).selectedId,+ null,+ `${id} was resolved onto an unrelated row`,+ );+ }+});++test("a locally selected path row keeps its exact selection", () => {+ const row = localRow({+ id: "C:\\Users\\me\\models\\mymodel",+ load_id: "C:\\Users\\me\\models\\mymodel",+ display_name: "mymodel",+ path: "C:\\Users\\me\\models\\mymodel",+ source: "models_dir",+ model_format: "safetensors",+ });+ assert.equal(resolve(row.id, [], [row]).selectedId, row.id);+});++// inventory-dedupe reads a truthy partialTransport as model family and a missing one as gguf; the resolver must not contradict it.++test("a gguf download does not adopt a snapshot partial the deduper kept apart", () => {+ const repoId = "unsloth/hybrid-repo";+ const snapshot = localRow({+ id: repoId,+ inventory_id: `hf_cache:unknown:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "hybrid-repo",+ path: `/cache/models--unsloth--hybrid-repo`,+ model_id: repoId,+ model_format: "unknown",+ partial: true,+ partial_transport: "xet",+ partial_resumable: true,+ });++ const gguf = cachedRow(repoId, "gguf", { partial: true });+ const deduped = dedupeSameSourceHubCacheRows({+ cachedRows: [gguf],+ localRows: [snapshot],+ });+ assert.equal(+ deduped.localRows.length,+ 1,+ "precondition: the deduper keeps the unrelated snapshot partial",+ );++ assert.equal(+ resolve(+ optimisticInventoryId("gguf", repoId),+ [],+ deduped.localRows,+ ).selectedId,+ null,+ "a gguf download adopted a model-family snapshot partial",+ );+});++test("a gguf download still adopts an unclassified gguf partial", () => {+ const repoId = "unsloth/gguf-repo";+ const partial = localRow({+ id: repoId,+ inventory_id: `hf_cache:unknown:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "gguf-repo",+ path: `/cache/models--unsloth--gguf-repo`,+ model_id: repoId,+ model_format: "unknown",+ partial: true,+ partial_transport: null,+ });++ assert.equal(+ resolve(optimisticInventoryId("gguf", repoId), [], [partial]).selectedId,+ partial.id,+ "cancelling a gguf download lost its own unclassified partial",+ );+});++test("a transport-less partial is still adopted, in either direction", () => {+ // Only the positive direction is provable: the backend never writes a transport for a GGUF partial, but a+ // snapshot partial with no cancel marker and no manifest also reports none, so an absent transport is not evidence.+ const repoId = "unsloth/gguf-repo";+ const partial = localRow({+ id: repoId,+ inventory_id: `hf_cache:unknown:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "gguf-repo",+ path: `/cache/models--unsloth--gguf-repo`,+ model_id: repoId,+ model_format: "unknown",+ partial: true,+ partial_transport: null,+ });++ for (const format of ["gguf", "safetensors"] as const) {+ assert.equal(+ resolve(optimisticInventoryId(format, repoId), [], [partial]).selectedId,+ partial.id,+ `a ${format} download lost a transport-less partial`,+ );+ }+});++test("a known-format selection does not fall back onto a proven other family", () => {+ const repoId = "unsloth/hybrid-repo";+ const snapshot = localRow({+ id: repoId,+ inventory_id: `hf_cache:unknown:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "hybrid-repo",+ path: `/cache/models--unsloth--hybrid-repo`,+ model_id: repoId,+ model_format: "unknown",+ partial: true,+ partial_transport: "xet",+ });++ assert.equal(+ resolve(cachedInventoryId("gguf", repoId), [], [snapshot]).selectedId,+ null,+ "a gguf cache selection fell back onto a model-family partial",+ );+ assert.equal(+ resolve(cachedInventoryId("safetensors", repoId), [], [snapshot])+ .selectedId,+ snapshot.id,+ "a safetensors selection lost its own model-family partial",+ );+});+++test("a complete unclassified local row is suppressed by any complete cache row", () => {+ // partialTransport is null on every complete row, so reading it as "gguf family" would retain the duplicate beside safetensors and drop it beside gguf.+ for (const format of ["gguf", "safetensors"] as const) {+ const repoId = "unsloth/complete-repo";+ const complete = cachedRow(repoId, format);+ const unknownLocal = localRow({+ id: repoId,+ inventory_id: `hf_cache:unknown:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "complete-repo",+ path: `/cache/models--unsloth--complete-repo`,+ model_id: repoId,+ model_format: "unknown",+ partial: false,+ partial_transport: null,+ });++ const deduped = dedupeSameSourceHubCacheRows({+ cachedRows: [complete],+ localRows: [unknownLocal],+ });+ assert.equal(+ deduped.localRows.length,+ 0,+ `a complete unclassified row survived beside a complete ${format} row`,+ );+ }+});+++test("scoped file sets classify by extension, case-insensitively", () => {+ assert.equal(scopedDownloadInventoryKind(["model.gguf"]), "gguf");+ assert.equal(scopedDownloadInventoryKind(["MODEL.GGUF"]), "gguf");+ assert.equal(scopedDownloadInventoryKind(["model.safetensors"]), "model");+ assert.equal(scopedDownloadInventoryKind(["gguf/model.safetensors"]), "model");+ assert.equal(scopedDownloadInventoryKind([]), "model");+ assert.equal(scopedDownloadInventoryKind(null), "model");+ assert.equal(scopedDownloadInventoryKind(undefined), "model");+});++test("an explicit inventory kind wins over the variant shape", () => {+ assert.equal(downloadInventoryHintKind("model", "@rag-embedding", "gguf"), "gguf");+ assert.equal(downloadInventoryHintKind("model", "Q4_K_M", "model"), "model");+ assert.equal(downloadInventoryHintKind("dataset", "@anything", "gguf"), "dataset");+});++test("an unscoped quant variant is still gguf without an explicit kind", () => {+ assert.equal(downloadInventoryHintKind("model", "Q4_K_M", undefined), "gguf");+ assert.equal(downloadInventoryHintKind("model", null, undefined), "model");+});+++test("the gguf file query survives canonicalization but a stale one is dropped", () => {+ const gguf = resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: "cache:gguf:org/repo",+ selectionInputId: "cache:gguf:org/repo",+ resolvedSelectedId: "cache:gguf:org%2Frepo",+ resolvedModelFormat: "gguf",+ });+ assert.equal(gguf?.action, "replace");+ assert.equal(gguf?.preserveGgufFile, true);++ const safetensors = resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: "hf_cache:unknown:org%2Frepo",+ selectionInputId: "hf_cache:unknown:org%2Frepo",+ resolvedSelectedId: "cache:safetensors:org%2Frepo",+ resolvedModelFormat: "safetensors",+ });+ assert.equal(safetensors?.action, "replace");+ assert.equal(safetensors?.preserveGgufFile, false);+});++test("a null selection never invents a row", () => {+ assert.equal(resolve(null, [cachedRow("org/repo", "gguf")], []).selectedId, null);+ assert.equal(+ resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: null,+ selectionInputId: null,+ resolvedSelectedId: null,+ resolvedModelFormat: null,+ }),+ null,+ );+});++// The resolver must be idempotent, or the URL sync effect loops.++test("resolution is idempotent across every row shape combination", () => {+ const repoId = "org/repo";+ const formats = ["gguf", "safetensors", "adapter", "checkpoint", "unknown"] as const;+ const sources = ["cache", "download", "hf_cache"] as const;+ let checked = 0;++ for (const rowFormat of formats) {+ for (const partial of [false, true]) {+ for (const transport of [null, "xet"]) {+ const cached = [+ cachedRow(repoId, rowFormat, { partial, partial_transport: transport }),+ ];+ const locals = [+ localRow({+ id: repoId,+ inventory_id: `hf_cache:${rowFormat}:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "repo",+ path: "/cache/models--org--repo",+ model_id: repoId,+ model_format: rowFormat,+ partial,+ partial_transport: transport,+ }),+ ];+ for (const source of sources) {+ for (const selFormat of formats) {+ const id = `${source}:${selFormat}:${encodeURIComponent(repoId)}`;+ for (const [c, l] of [+ [cached, []],+ [[], locals],+ [cached, locals],+ ] as const) {+ const once = resolve(id, c, l).selectedId;+ const twice = resolve(once, c, l).selectedId;+ assert.equal(+ twice,+ once,+ `not idempotent for ${id}: ${once} -> ${twice}`,+ );+ checked += 1;+ }+ }+ }+ }+ }+ }+ assert.ok(checked >= 900, `expected a wide sweep, only checked ${checked}`);+});diff --git a/studio/frontend/tests/hub-selection-resolution.test.ts b/studio/frontend/tests/hub-selection-resolution.test.tsnew file mode 100644index 00000000000..4fa58d0541f--- /dev/null+++ b/studio/frontend/tests/hub-selection-resolution.test.ts@@ -0,0 +1,897 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { registerStoreStubResolver } from "./helpers/kit.ts";++registerStoreStubResolver();++const { dedupeSameSourceHubCacheRows } = await import(+ "../src/features/hub/inventory/inventory-dedupe.ts"+);+const {+ buildCachedInventoryRow,+ buildLocalInventoryRows,+ cachedInventoryId,+ optimisticInventoryId,+} = await import("../src/features/hub/inventory/view-models.ts");+const { resolveDownloadedSelection, resolveSelectionUrlSync } = await import(+ "../src/features/hub/lib/selection-resolution.ts"+);++const REPO_ID = "Org/Model";++for (const modelFormat of ["gguf", "safetensors"] as const) {+ const transition =+ modelFormat === "gguf"+ ? "across resume, cancel, and sibling partial deletion transitions"+ : "across download transitions";++ test(`keeps a selected ${modelFormat} row stable ${transition}`, () => {+ const selectedId = cachedInventoryId(modelFormat, REPO_ID);+ const observed = buildCachedInventoryRow(+ {+ repo_id: REPO_ID,+ inventory_id: selectedId,+ model_format: modelFormat,+ size_bytes: 100,+ partial: true,+ },+ modelFormat,+ );+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: REPO_ID,+ model_format: modelFormat,+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ modelFormat,+ ),+ liveDownload: true,+ };++ assert.equal(selectedId, `cache:${modelFormat}:Org%2FModel`);++ const transitions = [+ { input: [observed], selectionId: selectedId, expectedId: selectedId },+ {+ input: [observed, live],+ selectionId: selectedId,+ expectedId: live.id,+ },+ {+ input: [observed],+ selectionId: `cache:${modelFormat}:${REPO_ID}`,+ expectedId: selectedId,+ },+ ];++ for (const { input, selectionId, expectedId } of transitions) {+ const cachedRows = dedupeSameSourceHubCacheRows({+ cachedRows: input,+ localRows: [],+ }).cachedRows;++ assert.equal(cachedRows.length, 1);+ assert.equal(cachedRows[0]?.id, expectedId);+ assert.equal(cachedRows[0]?.liveDownload, input.includes(live) || undefined);+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: selectionId,+ cachedRows,+ localRows: [],+ filteredCachedRows: cachedRows,+ filteredLocalRows: [],+ }),+ { selectedId: expectedId, hiddenByFilters: false },+ );+ }+ });+}++function resolveInventorySelection(+ inventory: ReturnType<typeof dedupeSameSourceHubCacheRows>,+ selectedId: string,+) {+ return resolveDownloadedSelection({+ selectedId,+ cachedRows: inventory.cachedRows,+ localRows: inventory.localRows,+ filteredCachedRows: inventory.cachedRows,+ filteredLocalRows: inventory.localRows,+ });+}++function buildUnknownHfCacheRow(+ repoId: string,+ partialTransport: string | null = null,+) {+ return buildLocalInventoryRows([+ {+ id: repoId,+ inventory_id: `hf_cache:unknown:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: repoId.split("/").at(-1) ?? repoId,+ path: `/cache/models--${repoId.replace("/", "--")}`,+ source: "hf_cache",+ model_id: repoId,+ model_format: "unknown",+ partial: true,+ partial_transport: partialTransport,+ partial_resumable: partialTransport !== null,+ },+ ])[0];+}++for (const modelFormat of ["gguf", "safetensors"] as const) {+ test(`keeps a selected local HF-cache ${modelFormat} partial stable across resume and cancel`, () => {+ const repoId =+ modelFormat === "safetensors"+ ? "unsloth/gemma-3-270m-it"+ : "unsloth/gemma-3-270m-it-GGUF";+ const localId = `hf_cache:${modelFormat}:${encodeURIComponent(repoId)}`;+ const liveId = optimisticInventoryId(modelFormat, repoId);+ const local = buildLocalInventoryRows([+ {+ id: repoId,+ inventory_id: localId,+ load_id: repoId,+ display_name: repoId.split("/").at(-1) ?? repoId,+ path: `/cache/models--${repoId.replace("/", "--")}`,+ source: "hf_cache",+ model_id: repoId,+ model_format: modelFormat,+ partial: true,+ partial_resumable: true,+ },+ ])[0];+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: repoId,+ inventory_id: liveId,+ load_id: repoId,+ model_format: modelFormat,+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ modelFormat,+ ),+ liveDownload: true,+ };++ assert.ok(local);++ const atRest = dedupeSameSourceHubCacheRows({+ cachedRows: [],+ localRows: [local],+ });+ assert.deepEqual(resolveInventorySelection(atRest, localId), {+ selectedId: localId,+ hiddenByFilters: false,+ });++ const resumed = dedupeSameSourceHubCacheRows({+ cachedRows: [live],+ localRows: [local],+ });+ assert.deepEqual(resumed.localRows, []);+ assert.deepEqual(resolveInventorySelection(resumed, localId), {+ selectedId: liveId,+ hiddenByFilters: false,+ });++ const cancelled = dedupeSameSourceHubCacheRows({+ cachedRows: [],+ localRows: [local],+ });+ assert.deepEqual(resolveInventorySelection(cancelled, liveId), {+ selectedId: localId,+ hiddenByFilters: false,+ });+ });+}++test("keeps an unclassified local HF-cache partial selected across GGUF resume and cancel", () => {+ const repoId = "Org/Partial-GGUF";+ const local = buildUnknownHfCacheRow(repoId);+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "gguf",+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ "gguf",+ ),+ liveDownload: true,+ };++ assert.ok(local);++ const resumed = dedupeSameSourceHubCacheRows({+ cachedRows: [live],+ localRows: [local],+ });+ assert.deepEqual(resumed.localRows, []);+ for (const selectedId of [+ local.id,+ `hf_cache:unknown:${repoId}`,+ "hf_cache:unknown:org%2fpartial-gguf",+ ]) {+ assert.deepEqual(resolveInventorySelection(resumed, selectedId), {+ selectedId: live.id,+ hiddenByFilters: false,+ });+ }++ const cancelled = dedupeSameSourceHubCacheRows({+ cachedRows: [],+ localRows: [local],+ });+ for (const selectedId of [+ live.id,+ `cache:gguf:${repoId}`,+ "cache:gguf:org/partial-gguf",+ ]) {+ assert.deepEqual(resolveInventorySelection(cancelled, selectedId), {+ selectedId: local.id,+ hiddenByFilters: false,+ });+ }+});++test("keeps an unclassified local HF-cache partial selected across safetensors resume and cancel", () => {+ const repoId = "Org/Partial-Model";+ const local = buildUnknownHfCacheRow(repoId, "http");+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ "safetensors",+ ),+ liveDownload: true,+ };++ assert.ok(local);+ const resumed = dedupeSameSourceHubCacheRows({+ cachedRows: [live],+ localRows: [local],+ });+ assert.deepEqual(resumed.localRows, []);+ assert.deepEqual(resolveInventorySelection(resumed, local.id), {+ selectedId: live.id,+ hiddenByFilters: false,+ });++ const cancelled = dedupeSameSourceHubCacheRows({+ cachedRows: [],+ localRows: [local],+ });+ assert.deepEqual(resolveInventorySelection(cancelled, live.id), {+ selectedId: local.id,+ hiddenByFilters: false,+ });+});++for (const { partialTransport, unrelatedFormat } of [+ { partialTransport: null, unrelatedFormat: "safetensors" as const },+ { partialTransport: "http", unrelatedFormat: "gguf" as const },+]) {+ test(`keeps an unclassified partial beside an unrelated ${unrelatedFormat} job`, () => {+ const repoId = "Org/Hybrid-Partial";+ const local = buildUnknownHfCacheRow(repoId, partialTransport);+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: unrelatedFormat,+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ unrelatedFormat,+ ),+ liveDownload: true,+ };++ assert.ok(local);+ const inventory = dedupeSameSourceHubCacheRows({+ cachedRows: [live],+ localRows: [local],+ });+ assert.deepEqual(inventory.cachedRows, [live]);+ assert.deepEqual(inventory.localRows, [local]);+ assert.deepEqual(resolveInventorySelection(inventory, local.id), {+ selectedId: local.id,+ hiddenByFilters: false,+ });+ });+}++test("keeps an unclassified local HF-cache partial selected when safetensors completes", () => {+ const repoId = "Org/Partial-Model";+ const local = buildUnknownHfCacheRow(repoId, "http");+ const complete = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 100,+ partial: false,+ },+ "safetensors",+ );++ assert.ok(local);++ const completed = dedupeSameSourceHubCacheRows({+ cachedRows: [complete],+ localRows: [local],+ });+ assert.deepEqual(completed.localRows, []);+ assert.deepEqual(resolveInventorySelection(completed, local.id), {+ selectedId: complete.id,+ hiddenByFilters: false,+ });+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: local.id,+ cachedRows: completed.cachedRows,+ localRows: completed.localRows,+ filteredCachedRows: [],+ filteredLocalRows: [],+ }),+ { selectedId: complete.id, hiddenByFilters: true },+ );++ const reverted = dedupeSameSourceHubCacheRows({+ cachedRows: [],+ localRows: [local],+ });+ assert.deepEqual(resolveInventorySelection(reverted, complete.id), {+ selectedId: local.id,+ hiddenByFilters: false,+ });+});++test("keeps an unclassified GGUF partial when an unrelated safetensors job completes", () => {+ const repoId = "Org/Hybrid-Complete";+ const local = buildUnknownHfCacheRow(repoId);+ const complete = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 100,+ partial: false,+ },+ "safetensors",+ );++ assert.ok(local);+ const inventory = dedupeSameSourceHubCacheRows({+ cachedRows: [complete],+ localRows: [local],+ });+ assert.deepEqual(inventory.cachedRows, [complete]);+ assert.deepEqual(inventory.localRows, [local]);+ assert.deepEqual(resolveInventorySelection(inventory, local.id), {+ selectedId: local.id,+ hiddenByFilters: false,+ });+});++test("waits for local inventory before resolving an unknown selection", () => {+ const repoId = "Org/Refresh-Race";+ const selectedId = `hf_cache:unknown:${encodeURIComponent(repoId)}`;+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ "safetensors",+ ),+ liveDownload: true,+ };++ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId,+ inventoryReady: false,+ cachedRows: [live],+ localRows: [],+ filteredCachedRows: [live],+ filteredLocalRows: [],+ }),+ { selectedId, hiddenByFilters: false },+ );++ const local = buildUnknownHfCacheRow(repoId);+ assert.ok(local);+ const settled = dedupeSameSourceHubCacheRows({+ cachedRows: [live],+ localRows: [local],+ });+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId,+ inventoryReady: true,+ cachedRows: settled.cachedRows,+ localRows: settled.localRows,+ filteredCachedRows: settled.cachedRows,+ filteredLocalRows: settled.localRows,+ }),+ { selectedId: local.id, hiddenByFilters: false },+ );+});++for (const modelFormat of ["adapter", "checkpoint"] as const) {+ test(`keeps a provisional download selected when it becomes ${modelFormat}`, () => {+ const repoId = `Org/${modelFormat}`;+ const live = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ "safetensors",+ );+ const complete = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: modelFormat,+ size_bytes: 100,+ },+ "safetensors",+ );++ assert.equal(live.id, optimisticInventoryId("safetensors", repoId));+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: live.id,+ cachedRows: [complete],+ localRows: [],+ filteredCachedRows: [complete],+ filteredLocalRows: [],+ }),+ { selectedId: complete.id, hiddenByFilters: false },+ );+ });+}++test("keeps an HF-cache selection when a local row becomes classified", () => {+ const repoId = "Org/Locally-Classified";+ const unknown = buildUnknownHfCacheRow(repoId);+ const known = buildLocalInventoryRows([+ {+ id: repoId,+ inventory_id: `hf_cache:safetensors:${encodeURIComponent(repoId)}`,+ load_id: repoId,+ display_name: "Locally-Classified",+ path: "/cache/models--Org--Locally-Classified",+ source: "hf_cache",+ model_id: repoId,+ model_format: "safetensors",+ partial: true,+ },+ ])[0];++ assert.ok(unknown);+ assert.ok(known);++ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: unknown.id,+ cachedRows: [],+ localRows: [known],+ filteredCachedRows: [],+ filteredLocalRows: [known],+ }),+ { selectedId: known.id, hiddenByFilters: false },+ );+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: known.id,+ cachedRows: [],+ localRows: [unknown],+ filteredCachedRows: [],+ filteredLocalRows: [unknown],+ }),+ { selectedId: unknown.id, hiddenByFilters: false },+ );+});++test("does not resolve an unclassified HF-cache selection across ambiguous formats", () => {+ const repoId = "Org/Hybrid-Unknown";+ const local = buildUnknownHfCacheRow(repoId);+ const gguf = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "gguf",+ size_bytes: 50,+ partial: true,+ },+ "gguf",+ );+ const safetensors = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 50,+ partial: true,+ },+ "safetensors",+ );++ assert.ok(local);++ const ambiguousKnown = dedupeSameSourceHubCacheRows({+ cachedRows: [gguf, safetensors],+ localRows: [local],+ });+ assert.deepEqual(resolveInventorySelection(ambiguousKnown, local.id), {+ selectedId: null,+ hiddenByFilters: false,+ });++ const ambiguousUnknown = dedupeSameSourceHubCacheRows({+ cachedRows: [safetensors],+ localRows: [local],+ });+ assert.deepEqual(resolveInventorySelection(ambiguousUnknown, gguf.id), {+ selectedId: null,+ hiddenByFilters: false,+ });+});++test("ignores malformed unclassified HF-cache selection IDs", () => {+ const cached = buildCachedInventoryRow(+ {+ repo_id: "Org/Model",+ model_format: "gguf",+ size_bytes: 50,+ partial: true,+ },+ "gguf",+ );++ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: "hf_cache:unknown:Org%2",+ cachedRows: [cached],+ localRows: [],+ filteredCachedRows: [cached],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+});++test("keeps a raw legacy HF-cache ID attached after deduplication", () => {+ const repoId = "Org/Legacy-Model";+ const local = buildLocalInventoryRows([+ {+ id: repoId,+ load_id: repoId,+ display_name: "Legacy-Model",+ path: "/cache/models--Org--Legacy-Model",+ source: "hf_cache",+ model_id: repoId,+ model_format: "safetensors",+ partial: true,+ },+ ])[0];+ const live = {+ ...buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 50,+ partial: true,+ optimistic: true,+ },+ "safetensors",+ ),+ liveDownload: true,+ };++ assert.ok(local);+ assert.equal(local.id, repoId);+ const resumed = dedupeSameSourceHubCacheRows({+ cachedRows: [live],+ localRows: [local],+ });+ assert.deepEqual(resumed.localRows, []);+ assert.deepEqual(resolveInventorySelection(resumed, local.id), {+ selectedId: live.id,+ hiddenByFilters: false,+ });+});++test("does not bridge unclassified identities across cache source kinds", () => {+ const repoId = "Org/Shared-Identity";+ const local = buildUnknownHfCacheRow(repoId);+ const cached = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "unknown",+ size_bytes: 50,+ partial: true,+ },+ "unknown",+ );+ const known = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "gguf",+ size_bytes: 50,+ partial: true,+ },+ "gguf",+ );++ assert.ok(local);++ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: local.id,+ cachedRows: [cached],+ localRows: [],+ filteredCachedRows: [cached],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: cached.id,+ cachedRows: [],+ localRows: [local],+ filteredCachedRows: [],+ filteredLocalRows: [local],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: cached.id,+ cachedRows: [known],+ localRows: [],+ filteredCachedRows: [known],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: known.id,+ cachedRows: [cached],+ localRows: [],+ filteredCachedRows: [cached],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+});++test("does not carry HF-cache selection across model formats", () => {+ const repoId = "Org/Hybrid";+ const localId = `hf_cache:safetensors:${encodeURIComponent(repoId)}`;+ const local = buildLocalInventoryRows([+ {+ id: repoId,+ inventory_id: localId,+ display_name: "Hybrid",+ path: "/cache/models--Org--Hybrid",+ source: "hf_cache",+ model_id: repoId,+ model_format: "safetensors",+ partial: true,+ },+ ])[0];+ const cached = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "gguf",+ size_bytes: 50,+ partial: true,+ },+ "gguf",+ );++ assert.ok(local);+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: localId,+ cachedRows: [cached],+ localRows: [],+ filteredCachedRows: [cached],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: cached.id,+ cachedRows: [],+ localRows: [local],+ filteredCachedRows: [],+ filteredLocalRows: [local],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+});++test("commits a resolved identity before another format appears", () => {+ const repoId = "Org/Hybrid-After-Completion";+ const unknownId = `hf_cache:unknown:${encodeURIComponent(repoId)}`;+ const safetensors = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 100,+ },+ "safetensors",+ );+ const gguf = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "gguf",+ size_bytes: 100,+ },+ "gguf",+ );++ const firstResolution = resolveDownloadedSelection({+ selectedId: unknownId,+ cachedRows: [safetensors],+ localRows: [],+ filteredCachedRows: [safetensors],+ filteredLocalRows: [],+ });+ assert.equal(firstResolution.selectedId, safetensors.id);+ assert.deepEqual(+ resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: unknownId,+ selectionInputId: unknownId,+ resolvedSelectedId: firstResolution.selectedId,+ resolvedModelFormat: safetensors.modelFormat,+ }),+ {+ action: "replace",+ selectedId: safetensors.id,+ preserveGgufFile: false,+ },+ );++ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: safetensors.id,+ cachedRows: [safetensors, gguf],+ localRows: [],+ filteredCachedRows: [safetensors, gguf],+ filteredLocalRows: [],+ }),+ { selectedId: safetensors.id, hiddenByFilters: false },+ );+});++test("preserves a GGUF file while canonicalizing its selection ID", () => {+ const repoId = "Org/GGUF-Model";++ assert.deepEqual(+ resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: optimisticInventoryId("gguf", repoId),+ selectionInputId: optimisticInventoryId("gguf", repoId),+ resolvedSelectedId: cachedInventoryId("gguf", repoId),+ resolvedModelFormat: "gguf",+ }),+ {+ action: "replace",+ selectedId: cachedInventoryId("gguf", repoId),+ preserveGgufFile: true,+ },+ );++ assert.deepEqual(+ resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: optimisticInventoryId("gguf", repoId),+ selectionInputId: optimisticInventoryId("gguf", repoId),+ resolvedSelectedId: repoId,+ resolvedModelFormat: "unknown",+ }),+ {+ action: "replace",+ selectedId: repoId,+ preserveGgufFile: true,+ },+ );+});++test("does not move a provisional selection to an incompatible format", () => {+ const repoId = "Org/Hybrid-Provisional";+ const gguf = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "gguf",+ size_bytes: 100,+ },+ "gguf",+ );+ const safetensors = buildCachedInventoryRow(+ {+ repo_id: repoId,+ model_format: "safetensors",+ size_bytes: 100,+ },+ "safetensors",+ );++ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: optimisticInventoryId("gguf", repoId),+ cachedRows: [safetensors],+ localRows: [],+ filteredCachedRows: [safetensors],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+ assert.deepEqual(+ resolveDownloadedSelection({+ selectedId: optimisticInventoryId("safetensors", repoId),+ cachedRows: [gguf],+ localRows: [],+ filteredCachedRows: [gguf],+ filteredLocalRows: [],+ }),+ { selectedId: null, hiddenByFilters: false },+ );+});++test("applies URL navigation before rewriting a resolved selection", () => {+ assert.deepEqual(+ resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: "cache:gguf:Org%2FNext",+ selectionInputId: "cache:gguf:Org%2FPrevious",+ resolvedSelectedId: "cache:gguf:Org%2FPrevious",+ resolvedModelFormat: "gguf",+ }),+ { action: "select", selectedId: "cache:gguf:Org%2FNext" },+ );+});++test("adopts a raw selection after its URL navigation lands", () => {+ assert.deepEqual(+ resolveSelectionUrlSync({+ isDiscoverTab: false,+ urlModel: "Org/Legacy-Model",+ selectionInputId: null,+ resolvedSelectedId: null,+ resolvedModelFormat: null,+ }),+ { action: "select", selectedId: "Org/Legacy-Model" },+ );+});diff --git a/studio/frontend/tests/store-stub-resolver.mjs b/studio/frontend/tests/store-stub-resolver.mjsindex bac6b479b55..96a81167df3 100644--- a/studio/frontend/tests/store-stub-resolver.mjs+++ b/studio/frontend/tests/store-stub-resolver.mjs@@ -7,6 +7,10 @@ import { resolve as resolveBundler } from "./bundler-resolver.mjs";const STUBS = new Map([["@/features/auth", "./helpers/store-stubs/auth.ts"],["@/features/hub", "./helpers/store-stubs/hub.ts"],+ [+ "@/features/hub/download-manager",+ "./helpers/store-stubs/download-manager.ts",+ ],["@/config/env", "./helpers/store-stubs/env.ts"],["@/lib/toast", "./helpers/store-stubs/toast.ts"],]);