Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: reset the download progress bar when a retry restarts the file (#11593)
Nilay8fb2fa34d966
diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.pyindex ae6933083b5..88360cf6e5c 100644--- a/studio/backend/hub/schemas/downloads.py+++ b/studio/backend/hub/schemas/downloads.py@@ -71,6 +71,10 @@ class DownloadJobStatus(BaseModel):0,description = "Current run generation; an adopting client stores it so a later cancel is scoped to this exact run.",)+ attempt: int = Field(+ 1,+ description = "Worker attempt within this generation; a retry that restarts the file bumps it so a client drops the old run's progress.",+ )class DownloadStartResponse(BaseModel):@@ -213,6 +217,10 @@ class DatasetDownloadJobStatus(BaseModel):0,description = "Current run generation; an adopting client stores it so a later cancel is scoped to this exact run.",)+ attempt: int = Field(+ 1,+ description = "Worker attempt within this generation; a retry that restarts the file bumps it so a client drops the old run's progress.",+ )class DatasetDownloadStartResponse(BaseModel):diff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.pyindex da856f5ba56..719da185b79 100644--- a/studio/backend/hub/services/datasets/downloads.py+++ b/studio/backend/hub/services/datasets/downloads.py@@ -236,14 +236,20 @@ async def get_dataset_download_progress_response(def _dataset_status(key: str, *, repo_id: Optional[str] = None) -> DatasetDownloadJobStatus:+ registry = _account_registry()state, error, generation = download_lifecycle.idle_status(- _account_registry(),+ registry,key,repo_type = "dataset",repo_id = repo_id,variant = None,)- return DatasetDownloadJobStatus(state = state, error = error, generation = generation)+ return DatasetDownloadJobStatus(+ state = state,+ error = error,+ generation = generation,+ attempt = registry.current_attempt(key),+ )async def download_dataset_response(diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex f86cbdddd45..5fe319ce0e2 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -82,7 +82,12 @@ def _job_status(repo_id = repo_id,variant = variant,)- return DownloadJobStatus(state = state, error = error, generation = generation)+ return DownloadJobStatus(+ state = state,+ error = error,+ generation = generation,+ attempt = _registry.current_attempt(key),+ )def _diffusion_load_in_flight(repo_id: str) -> bool:diff --git a/studio/backend/hub/tests/test_dataset_services.py b/studio/backend/hub/tests/test_dataset_services.pyindex b56a93b0f45..f630377566a 100644--- a/studio/backend/hub/tests/test_dataset_services.py+++ b/studio/backend/hub/tests/test_dataset_services.py@@ -1119,6 +1119,7 @@ def test_dataset_download_status_preserves_idle_shape():assert status.state == "idle"assert status.error is None+ assert status.attempt == 1def test_dataset_download_registry_key_is_case_insensitive():diff --git a/studio/backend/hub/tests/test_download_lifecycle.py b/studio/backend/hub/tests/test_download_lifecycle.pyindex 702b401cac4..5461cb84908 100644--- a/studio/backend/hub/tests/test_download_lifecycle.py+++ b/studio/backend/hub/tests/test_download_lifecycle.py@@ -245,6 +245,36 @@ def test_a_stalled_xet_worker_respawns_over_xet_keeping_its_claim(monkeypatch, tassert metadata.transport == download_registry.TRANSPORT_XETassert metadata.blob_hashes == frozenset({"blob"})assert registry.current_generation(key) == generation+ assert registry.current_attempt(key) == 2+++def test_reclaiming_a_run_counts_attempts_and_a_fresh_claim_resets_them():+ key, registry = _shared_setup_1()+ generation = registry.current_generation(key)+ assert registry.current_attempt(key) == 1++ for expected in (2, 3):+ registry.release_active_slot(key)+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ generation = generation,+ replace_active = True,+ )[0]+ assert registry.current_generation(key) == generation+ assert registry.current_attempt(key) == expected++ registry.set_job(key, "error", "killed")+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ )[0]+ assert registry.current_generation(key) != generation+ assert registry.current_attempt(key) == 1def test_an_unspawnable_xet_retry_falls_through_to_http(monkeypatch, tmp_path):diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 064a8af8b07..fecf589e976 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -4264,6 +4264,23 @@ def test_model_download_job_helpers_preserve_idle_shape():assert key == "org/model::"assert status.state == "idle"assert status.error is None+ assert status.attempt == 1+++def test_model_download_status_reports_the_retry_attempt(monkeypatch):+ registry = download_registry.DownloadRegistry()+ monkeypatch.setattr(downloads, "_registry", registry)+ key = downloads._download_job_key("Org/Model", "Q4_K_M")+ assert registry.claim(key, download_registry.TRANSPORT_XET)[0]+ generation = registry.current_generation(key)+ registry.release_active_slot(key)+ assert registry.claim(+ key, download_registry.TRANSPORT_XET, generation = generation, replace_active = True+ )[0]++ status = downloads._job_status(key)++ assert (status.generation, status.attempt) == (generation, 2)def test_gguf_repo_partial_treats_completed_disk_variant_as_clean(monkeypatch, tmp_path):@@ -6481,6 +6498,9 @@ def test_dataset_status_includes_generation(monkeypatch):def current_generation(self, _key):return 4+ def current_attempt(self, _key):+ return 2+monkeypatch.setattr(dataset_downloads, "_registry", _Registry())monkeypatch.setattr(dataset_downloads,@@ -6492,6 +6512,7 @@ def test_dataset_status_includes_generation(monkeypatch):assert result.state == "running"assert result.generation == 4+ assert result.attempt == 2def _write_local_model(diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex a61a5275aad..cc40fe22038 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -1222,6 +1222,7 @@ class DownloadRegistry:self._cancel_marker_transports: dict[str, str] = {}self._pending_cancel: dict[str, Optional[int]] = {}self._generations: dict[str, int] = {}+ self._attempts: dict[str, int] = {}# Monotonic across keys so an evicted then re-claimed key never reuses a prior generation, which would let a stale cancel match a new run.self._generation_seq = 0self._deleting: dict[str, set[Optional[str]]] = {}@@ -1248,6 +1249,7 @@ class DownloadRegistry:self._jobs.pop(stale_key, None)self._metadata.pop(stale_key, None)self._generations.pop(stale_key, None)+ self._attempts.pop(stale_key, None)if len(self._jobs) <= self._max_terminal:break@@ -1347,6 +1349,11 @@ class DownloadRegistry:with self._lock:return self._generations.get(key, 0)+ def current_attempt(self, key: str) -> int:+ key = normalize_job_key(key)+ with self._lock:+ return self._attempts.get(key, 1)+def get_job_metadata(self, key: str) -> Optional[DownloadMetadata]:key = normalize_job_key(key)with self._lock:@@ -1522,8 +1529,10 @@ class DownloadRegistry:if generation is None:self._generation_seq += 1self._generations[key] = self._generation_seq+ self._attempts[key] = 1else:self._generations[key] = generation+ self._attempts[key] = self._attempts.get(key, 1) + 1self._jobs[key] = DownloadState("running")self._repo_active.setdefault(repo, active).add(key)if repo_type and repo_id:diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.tsindex e023ca9dea8..2576dbe6a92 100644--- a/studio/frontend/src/features/hub/download-manager/api.ts+++ b/studio/frontend/src/features/hub/download-manager/api.ts@@ -44,6 +44,7 @@ export interface DownloadJobStatus {state: DownloadJobState;error?: string | null;generation?: number;+ attempt?: number;}// "repository_owned": a dictation model download holds this repository's cache.diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-config.ts b/studio/frontend/src/features/hub/download-manager/download-manager-config.tsindex 10662948821..9be6aae9689 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-config.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-config.ts@@ -10,6 +10,8 @@ export const HIDDEN_POLL_INTERVAL_MS = 10_000;export const POLL_JITTER_MS = 50;export const PROGRESS_POLL_INTERVAL_MS = 1_000;export const PROGRESS_POLL_BACKOFF_INTERVAL_MS = 2_000;+// Covers the retry worker's metadata fetches, which run before it purges the killed partial.+export const ATTEMPT_FLOOR_HOLD_MS = 120_000;export const POLL_REQUEST_TIMEOUT_MS = 15_000;export const POLL_DEGRADED_AFTER_MS = 30_000;export const POLL_DEGRADED_MESSAGE =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 5692fb2fbfe..f47836b6f59 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@@ -144,6 +144,9 @@ function sanitizePersistedJob(...(Number.isSafeInteger(value.serverGeneration)? { serverGeneration: Number(value.serverGeneration) }: {}),+ ...(Number.isSafeInteger(value.serverAttempt)+ ? { serverAttempt: Number(value.serverAttempt) }+ : {}),...(Array.isArray(value.scopedFiles) &&value.scopedFiles.every((f) => typeof f === "string")? { scopedFiles: value.scopedFiles as string[] }@@ -207,6 +210,9 @@ function toPersistedJob(...(job.serverGeneration !== undefined? { serverGeneration: job.serverGeneration }: {}),+ ...(job.serverAttempt !== undefined+ ? { serverAttempt: job.serverAttempt }+ : {}),...(job.scopedFiles !== undefined ? { scopedFiles: job.scopedFiles } : {}),...(job.checkpoint !== undefined ? { checkpoint: job.checkpoint } : {}),...(job.inventoryKind !== undefineddiff --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 c537c4058ea..8469c0c154f 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@@ -33,6 +33,7 @@ export interface ManagedDownload {startedAt: number;completedAt?: number;serverGeneration?: number;+ serverAttempt?: number;/** 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[];/** 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. */@@ -136,6 +137,12 @@ export interface DownloadManagerState {completedInventoryHints: InventoryHint[];}+export interface FloorHold {+ attempt: number;+ remainingBytes: number;+ until: number;+}+export interface JobRuntime {kind: DownloadKind;repoId: string;@@ -151,6 +158,8 @@ export interface JobRuntime {/*** A generation change seen on a status-only tick, held until a progress poll consumes it: status polls twice as often. */pendingGenerationChange?: boolean;+ /** Set on an attempt change: the GGUF floor stays off until the killed run's partial is purged (see floorHoldEnded). Its attempt is persisted only when the hold ends, so a reload re-detects the retry. */+ floorHold?: FloorHold | null;idleSinceMs: number | null;lastProgressPollAt: number | null;pollFailureStartedAt: number | null;diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 1c93a3740c4..54c348fe6dc 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -35,6 +35,7 @@ import {POLL_JITTER_MS,PROGRESS_POLL_BACKOFF_INTERVAL_MS,PROGRESS_POLL_INTERVAL_MS,+ ATTEMPT_FLOOR_HOLD_MS,ACTIVE_STATES,TERMINAL_DISPLAY_STATES,} from "./download-manager-config";@@ -99,8 +100,10 @@ import {setExpectedBytesForJob,} from "./download-manager-state";import {+ floorHoldEnded,hasObservedExpectedBytes,resolveProgressUpdate,+ serverRunChange,} from "./progress-reconcile";import {presentationForExpectedBytesUpdate,@@ -325,22 +328,33 @@ function syncServerGeneration(key: string,job: ManagedDownload,status: PollStatus,-): boolean {- const statusGeneration = status.generation;- const previousGeneration = job.serverGeneration;- const generationChanged =- typeof statusGeneration === "number" &&- Number.isSafeInteger(statusGeneration) &&- typeof previousGeneration === "number" &&- Number.isSafeInteger(previousGeneration) &&- statusGeneration !== previousGeneration;- if (- typeof statusGeneration === "number" &&- Number.isSafeInteger(statusGeneration)- ) {- patchJob(key, { serverGeneration: statusGeneration });+ rt: JobRuntime,+): "generation" | "attempt" | null {+ const change = serverRunChange(+ {+ generation: job.serverGeneration,+ attempt: rt.floorHold?.attempt ?? job.serverAttempt,+ },+ status,+ );+ const patch: Partial<ManagedDownload> = {};+ if (Number.isSafeInteger(status.generation)) {+ patch.serverGeneration = status.generation;}- return generationChanged;+ if (change === "attempt") {+ rt.floorHold = {+ attempt: status.attempt as number,+ remainingBytes: job.expectedBytes - job.downloadedBytes,+ until: Date.now() + ATTEMPT_FLOOR_HOLD_MS,+ };+ } else {+ if (change === "generation") rt.floorHold = null;+ if (rt.floorHold == null && Number.isSafeInteger(status.attempt)) {+ patch.serverAttempt = status.attempt;+ }+ }+ if (Object.keys(patch).length > 0) patchJob(key, patch);+ return change;}async function finalizeTerminalStatus(@@ -406,7 +420,16 @@ function reconcileProgressAndSpeed(madeProgress,} = resolveProgressUpdate(current, progressResp, {resetMonotonic: generationChanged,+ skipFloor: rt.floorHold != null,});+ let acknowledgedAttempt: number | undefined;+ if (+ rt.floorHold &&+ floorHoldEnded(rt.floorHold, expected, downloadedBytes, Date.now())+ ) {+ acknowledgedAttempt = rt.floorHold.attempt;+ rt.floorHold = null;+ }if (generationChanged) {// 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;@@ -421,6 +444,9 @@ function reconcileProgressAndSpeed(fraction,bytesPerSec: speed.bytesPerSec,etaSeconds: speed.etaSeconds,+ ...(acknowledgedAttempt !== undefined+ ? { serverAttempt: acknowledgedAttempt }+ : {}),});markPollSuccess(key, rt);return { madeProgress };@@ -496,7 +522,7 @@ async function tick(key: string): Promise<void> {if (!isCurrent(key, epoch)) return;// 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)) {+ if (syncServerGeneration(key, job, status, rt) !== null) {rt.pendingGenerationChange = true;}@@ -709,6 +735,7 @@ export async function startJob(? opts.generation: existing?.serverGeneration: undefined;+ const seedAttempt = carryOverSeed ? existing?.serverAttempt : undefined;const adopted = opts.adopt? adoptedTransports({ transport: opts.transport, cancelTransport: opts.cancelTransport },@@ -754,6 +781,9 @@ export async function startJob(...(Number.isSafeInteger(seedGeneration)? { serverGeneration: seedGeneration }: {}),+ ...(Number.isSafeInteger(seedAttempt)+ ? { serverAttempt: seedAttempt }+ : {}),...(req.files && req.files.length > 0? { scopedFiles: [...req.files] }: opts.adopt && existing?.scopedFilesdiff --git a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts b/studio/frontend/src/features/hub/download-manager/progress-reconcile.tsindex b2e97236779..7fbd27f3879 100644--- a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts+++ b/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts@@ -7,7 +7,11 @@import { DOWNLOAD_KIND } from "./constants";import { MAX_PROGRESS_FRACTION } from "./download-manager-config";-import type { ManagedDownload, ProgressLike } from "./download-manager-types";+import type {+ FloorHold,+ ManagedDownload,+ ProgressLike,+} from "./download-manager-types";export function hasObservedExpectedBytes(job: ManagedDownload): boolean {// Finalized bytes only: an `.incomplete` blob hitting expected size isn't@@ -43,7 +47,7 @@ export function isIndeterminateProgress(export function resolveProgressUpdate(job: ManagedDownload,progressResp: ProgressLike,- opts: { resetMonotonic?: boolean } = {},+ opts: { resetMonotonic?: boolean; skipFloor?: boolean } = {},): {expected: number;downloadedBytes: number;@@ -58,8 +62,8 @@ export function resolveProgressUpdate(job.kind === DOWNLOAD_KIND.MODEL && job.variant !== null;const backendOwnsGgufProgress = isGgufVariantJob && reported > 0;// GGUF totals are backend-owned (non-monotonic); snapshots stay monotonic to- // absorb jitter, but a generation bump (XET redownload, restart, re-adoption)- // must drop the stale high-water mark and snap to the new run's bytes.+ // absorb jitter, but a new generation or retry attempt must drop the stale+ // high-water mark and snap to the new run's bytes.const resetMonotonic = opts.resetMonotonic === true;const trustBackend = backendOwnsGgufProgress || resetMonotonic;const expected = trustBackend@@ -127,13 +131,13 @@ export function resolveProgressUpdate(const cappedFraction = Math.min(rawFraction, MAX_PROGRESS_FRACTION);// Keep the GGUF variant bar monotonic: backend progress is recomputed from the shared per-repo// blobs/ dir, so a sibling quant, generation bump, or no-metadata poll can dip one reading.- // Resets via startJob's seed fraction. NOT across a generation change, though. `resetMonotonic`- // is the caller saying another client restarted this job, and it already clears the byte counters- // -- carrying the old generation's high-water mark over pinned a retry that starts at 0 B to the- // previous run's 99% for its entire life, which is the stale card this whole path exists to- // remove.+ // Resets via startJob's seed fraction. NOT across a generation or attempt change, though.+ // `resetMonotonic` is the caller saying the run restarted, and it already clears the byte+ // counters -- carrying the old run's high-water mark over pinned a retry that starts at 0 B to+ // the previous run's 99% for its entire life. `skipFloor` covers the polls after that reset+ // that can still read the killed attempt's partial.const fraction =- isGgufVariantJob && !resetMonotonic+ isGgufVariantJob && !resetMonotonic && opts.skipFloor !== true? Math.max(cappedFraction, job.fraction): cappedFraction;return {@@ -146,3 +150,36 @@ export function resolveProgressUpdate(madeProgress,};}++function runCounterChanged(+ previous: number | undefined,+ current: number | undefined,+): boolean {+ return (+ Number.isSafeInteger(current) &&+ Number.isSafeInteger(previous) &&+ current !== previous+ );+}++export function serverRunChange(+ known: { generation?: number; attempt?: number },+ status: { generation?: number; attempt?: number },+): "generation" | "attempt" | null {+ if (runCounterChanged(known.generation, status.generation)) {+ return "generation";+ }+ return runCounterChanged(known.attempt, status.attempt) ? "attempt" : null;+}++// Bytes left only rise once the retry worker purges the killed partial; a re-measured baseline lowers both counters alike, so it cannot end the hold early.+export function floorHoldEnded(+ hold: FloorHold,+ expectedBytes: number,+ downloadedBytes: number,+ now: number,+): boolean {+ return (+ expectedBytes - downloadedBytes > hold.remainingBytes || now >= hold.until+ );+}diff --git a/studio/frontend/tests/download-attempt-reset.test.ts b/studio/frontend/tests/download-attempt-reset.test.tsnew file mode 100644index 00000000000..dd8ad275438--- /dev/null+++ b/studio/frontend/tests/download-attempt-reset.test.ts@@ -0,0 +1,208 @@+// 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 type {+ ManagedDownload,+ ProgressLike,+} from "../src/features/hub/download-manager/download-manager-types.ts";+import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { floorHoldEnded, resolveProgressUpdate, serverRunChange } =+ await import("../src/features/hub/download-manager/progress-reconcile.ts");++const GB = 1024 ** 3;+const EXPECTED = 5 * GB;++function job(overrides: Partial<ManagedDownload> = {}): ManagedDownload {+ return {+ key: "model:org/model-gguf#q4_k_m",+ kind: "model",+ repoId: "org/model-GGUF",+ variant: "Q4_K_M",+ state: "running",+ downloadedBytes: 2 * GB,+ completedBytes: 0,+ expectedBytes: EXPECTED,+ completeOnDisk: false,+ fraction: 0.4,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 1,+ serverGeneration: 7,+ serverAttempt: 1,+ ...overrides,+ };+}++function restartedReading(): ProgressLike {+ return {+ downloaded_bytes: 6 * 1024 * 1024,+ completed_bytes: 0,+ expected_bytes: EXPECTED,+ progress: (6 * 1024 * 1024) / EXPECTED,+ cache_measured: true,+ } as ProgressLike;+}++test("a new generation wins over an attempt change, and an unknown side is no change", () => {+ const known = { generation: 7, attempt: 1 };+ assert.equal(serverRunChange(known, { generation: 7, attempt: 1 }), null);+ assert.equal(+ serverRunChange(known, { generation: 7, attempt: 2 }),+ "attempt",+ );+ assert.equal(+ serverRunChange(known, { generation: 8, attempt: 1 }),+ "generation",+ );+ assert.equal(serverRunChange(known, { generation: 7 }), null);+ assert.equal(+ serverRunChange({ generation: 7 }, { generation: 7, attempt: 2 }),+ null,+ );+});++test("an attempt is persisted only once its hold ends, so a reload inside it re-detects the retry", () => {+ const source = readSrc("features/hub/download-manager/poll-loop.ts");+ assert.match(+ source,+ /attempt: rt\.floorHold\?\.attempt \?\? job\.serverAttempt,/,+ );+ assert.match(+ source,+ /if \(change === "attempt"\) \{\s*rt\.floorHold = \{\s*attempt: status\.attempt as number,/,+ );+ assert.match(+ source,+ /if \(rt\.floorHold == null && Number\.isSafeInteger\(status\.attempt\)\) \{\s*patch\.serverAttempt = status\.attempt;/,+ );+ assert.match(source, /acknowledgedAttempt = rt\.floorHold\.attempt;/);+ assert.match(source, /skipFloor: rt\.floorHold != null,/);+});++const MB = 1024 * 1024;++function reading(+ bytes: number,+ expected = EXPECTED,+ progress = bytes / expected,+): ProgressLike {+ return {+ downloaded_bytes: bytes,+ completed_bytes: 0,+ expected_bytes: expected,+ progress,+ cache_measured: true,+ } as ProgressLike;+}++// Replays polls after an attempt change: the first is the reset poll, and `hold` mirrors poll-loop.+function replayRetry(polls: ProgressLike[], hold: boolean): number[] {+ let current = job();+ let floorHold = hold+ ? {+ attempt: 2,+ remainingBytes: current.expectedBytes - current.downloadedBytes,+ until: 60_000,+ }+ : null;+ const fractions: number[] = [];+ polls.forEach((poll, i) => {+ const next = resolveProgressUpdate(current, poll, {+ resetMonotonic: i === 0,+ skipFloor: floorHold !== null,+ });+ if (+ floorHold &&+ floorHoldEnded(floorHold, next.expected, next.downloadedBytes, i * 2_000)+ ) {+ floorHold = null;+ }+ current = { ...current, ...next, expectedBytes: next.expected };+ fractions.push(next.fraction);+ });+ return fractions;+}++// Shape measured in a real session (Qwen3-14B-GGUF BF16, Xet worker SIGKILLed at 34%): the reclaim+// bumps the attempt before the retry worker purges the killed partial, so the reset poll reads that+// partial -- a few more bytes than the last poll but a fraction a hair lower -- and the restart only+// shows up on later polls.+test("a reset spent on the killed run's partial still lets the bar follow the restart", () => {+ const polls = [+ reading(2 * GB + 100 * MB, EXPECTED, 0.3995),+ reading(2 * GB + 100 * MB),+ reading(6 * MB),+ reading(200 * MB),+ reading(400 * MB),+ ];+ const pinned = replayRetry(polls, false);+ assert.ok(+ pinned.slice(1).every((f) => f >= 0.39),+ `without the hold the bar stays at the old run's mark: ${pinned}`,+ );++ const followed = replayRetry(polls, true);+ assert.ok(followed[2] < 0.01, `the restart should show: ${followed}`);+ assert.ok(followed[4] > followed[3] && followed[4] < 0.1, `${followed}`);+});++// A split GGUF whose first 1 GB shard finished during the killed attempt: the reclaim re-measures the+// completed baseline, so the stale reading loses 1 GB from both counters before the partial is purged.+test("a re-measured completed baseline does not end the hold before the purge", () => {+ const polls = [+ reading(1 * GB, 4 * GB),+ reading(1 * GB, 4 * GB),+ reading(6 * MB, 4 * GB),+ reading(200 * MB, 4 * GB),+ ];+ const followed = replayRetry(polls, true);+ assert.ok(followed[2] < 0.01, `the restart should show: ${followed}`);+ assert.ok(followed[3] > followed[2] && followed[3] < 0.1, `${followed}`);+});++test("the floor hold ends when the bytes left grow or at its deadline", () => {+ const hold = { attempt: 2, remainingBytes: 3 * GB, until: 10_000 };+ assert.equal(floorHoldEnded(hold, 5 * GB, 2 * GB, 0), false);+ assert.equal(floorHoldEnded(hold, 4 * GB, 1 * GB, 0), false);+ assert.equal(floorHoldEnded(hold, 5 * GB, 6 * MB, 0), true);+ assert.equal(floorHoldEnded(hold, 5 * GB, 2 * GB, 10_000), true);+});++test("a same-generation retry drops the bar to the new attempt's bytes", () => {+ const reset = resolveProgressUpdate(job(), restartedReading(), {+ resetMonotonic: true,+ });+ assert.equal(reset.downloadedBytes, 6 * 1024 * 1024);+ assert.ok(+ reset.fraction < 0.01,+ `fraction ${reset.fraction} should follow the bytes`,+ );++ const held = resolveProgressUpdate(job(), restartedReading());+ assert.equal(held.downloadedBytes, 6 * 1024 * 1024);+ assert.equal(held.fraction, 0.4);+});++test("an adopted job carries the persisted attempt so a retry while closed is detected", () => {+ const source = readSrc("features/hub/download-manager/poll-loop.ts");+ assert.match(+ source,+ /const seedAttempt = carryOverSeed \? existing\?\.serverAttempt : undefined;/,+ );+ assert.match(source, /\? \{ serverAttempt: seedAttempt \}/);+});++test("the attempt survives persistence next to the generation", () => {+ const source = readSrc(+ "features/hub/download-manager/download-manager-state.ts",+ );+ assert.match(source, /value\.serverAttempt/);+ assert.match(source, /job\.serverAttempt/);+});