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: stabilize download speed and ETA (#9388 + #9397) (#9593)
Daniel Han18015516ae73
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex d50cbc2c34c..905bd91038f 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -11,6 +11,11 @@ import {import { createElement, useCallback, useEffect, useRef, useState } from "react";import { toast } from "@/lib/toast";import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";+import {+ type TransferSample,+ appendSample,+ computeTransferStats,+} from "@/lib/transfer-stats";import { confirmRemoteCodeIfNeeded } from "@/features/security";import { defaultInferenceParams } from "../presets/preset-policy";import {@@ -2086,44 +2091,31 @@ export function useChatModelRuntime() {const expectedBytes =typeof selection !== "string" ? selection.expectedBytes ?? 0 : 0;- // Rolling window of byte samples for rate/ETA estimation, shared- // across download + mmap phases so it survives phase flips.- type Sample = { t: number; b: number };- const MIN_SAMPLES = 3;- const MIN_WINDOW = 3_000; // ms- const MAX_WINDOW = 15_000; // ms- const dlSamples: Sample[] = [];- const mmapSamples: Sample[] = [];+ // One buffer per phase, so a flip cannot price the new phase against+ // the old one's clock. Was a private copy of the shared estimator, so+ // fixes never reached this toast. The helper takes SECONDS, not ms.+ const dlSamples: TransferSample[] = [];+ const mmapSamples: TransferSample[] = [];function estimate(- samples: Sample[],+ samples: TransferSample[],bytes: number,total: number,): { rate: number; eta: number; stable: boolean } {- const now = Date.now();- // Drop samples if the counter reset (e.g. phase flipped).- if (samples.length > 0 && bytes < samples[samples.length - 1].b) {+ if (typeof document !== "undefined" && document.hidden) {+ // This 2s interval is clamped to about once a minute while hidden,+ // and the estimator reads gaps as the burst cadence. The hub poll+ // loop and the voice poller drop them the same way.samples.length = 0;- }- samples.push({ t: now, b: bytes });- const cutoff = now - MAX_WINDOW;- while (samples.length > 2 && samples[0].t < cutoff) {- samples.shift();- }- if (samples.length < MIN_SAMPLES) {return { rate: 0, eta: 0, stable: false };}- const first = samples[0];- const last = samples[samples.length - 1];- const dt = (last.t - first.t) / 1000;- const db = last.b - first.b;- if (dt * 1000 < MIN_WINDOW || db <= 0) {- return { rate: 0, eta: 0, stable: false };- }- const rate = db / dt;- const eta =- total > 0 && bytes < total && rate > 0 ? (total - bytes) / rate : 0;- return { rate, eta, stable: true };+ appendSample(samples, Date.now() / 1000, bytes);+ const stats = computeTransferStats(samples, total);+ return {+ rate: stats.stable ? stats.rateBytesPerSecond : 0,+ eta: stats.stable ? stats.etaSeconds : 0,+ stable: stats.stable,+ };}function composeProgressLabel(@@ -2131,7 +2123,7 @@ export function useChatModelRuntime() {totalGb: number,bytes: number,total: number,- samples: Sample[],+ samples: TransferSample[],): string {const base =totalGb > 0diff --git a/studio/frontend/src/features/chat/hooks/use-transfer-stats.ts b/studio/frontend/src/features/chat/hooks/use-transfer-stats.tsindex c94c8d586b4..2a0e9f0a856 100644--- a/studio/frontend/src/features/chat/hooks/use-transfer-stats.ts+++ b/studio/frontend/src/features/chat/hooks/use-transfer-stats.ts@@ -45,6 +45,16 @@ export function useTransferStats(? totalBytes: 0;+ if (typeof document !== "undefined" && document.hidden) {+ // Callers poll on an interval, and a hidden tab's is clamped to about+ // once a minute, so these gaps time the poller and the estimator would+ // read them as the burst cadence. Publishing nothing also stops a stale+ // reading outliving the transfer: this effect is keyed on ``bytes``, so a+ // counter that stops moving never runs it again to correct itself.+ samplesRef.current.length = 0;+ setState({ rateBytesPerSecond: 0, etaSeconds: 0, stable: false });+ return;+ }appendSample(samplesRef.current, now, cur);setState(computeTransferStats(samplesRef.current, total));}, [bytes, totalBytes]);diff --git a/studio/frontend/src/features/chat/utils/format-transfer.ts b/studio/frontend/src/features/chat/utils/format-transfer.tsindex b6e23519c7c..3ee6189db06 100644--- a/studio/frontend/src/features/chat/utils/format-transfer.ts+++ b/studio/frontend/src/features/chat/utils/format-transfer.ts@@ -15,6 +15,13 @@ export function formatRate(bytesPerSecond: number): string {return `${(bps / 1024 ** 3).toFixed(2)} GB/s`;}+/**+ * Beyond a day the number is noise. The hub formatter has clamped since #7679;+ * this one did not, so one estimate read "> 24h left" on a hub row and an+ * unbounded hour count on the model-load toast.+ */+const MAX_DISPLAYABLE_ETA_SECONDS = 24 * 60 * 60;+/*** Format an ETA in seconds as a short string (e.g. 125 → "2m 5s", 3725 →* "1h 2m"). Returns `"--"` for non-finite or non-positive inputs.@@ -22,6 +29,7 @@ export function formatRate(bytesPerSecond: number): string {export function formatEta(seconds: number): string {if (!Number.isFinite(seconds) || seconds <= 0) return "--";const s = Math.round(seconds);+ if (s >= MAX_DISPLAYABLE_ETA_SECONDS) return "> 24h";if (s < 60) return `${s}s`;if (s < 3600) {const m = Math.floor(s / 60);diff --git a/studio/frontend/src/features/hub/catalog/download-card.tsx b/studio/frontend/src/features/hub/catalog/download-card.tsxindex 1a7f317f5d2..a95354e2ac1 100644--- a/studio/frontend/src/features/hub/catalog/download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/download-card.tsx@@ -69,6 +69,7 @@ export function DownloadCard({<DownloadProgressBarprogress={progress}bytesPerSec={job.bytesPerSec}+ etaSeconds={job.etaSeconds}/></div>)}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsxindex c6dad53bc65..94d48591d57 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx@@ -172,6 +172,7 @@ function DownloadRow({ jobKey }: { jobKey: string }) {fraction: job.fraction,}}bytesPerSec={job.bytesPerSec}+ etaSeconds={job.etaSeconds}/>) : null}{terminal || job.state === "cancelling" || job.error ? (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 d2ee7dbd8e2..f1f4d0fde24 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@@ -74,6 +74,7 @@ function sanitizePersistedJob(expectedBytes: nonNegativeNumber(value.expectedBytes),fraction: Math.min(Math.max(finiteNumber(value.fraction, 0), 0), 1),bytesPerSec: 0,+ etaSeconds: 0,error: typeof value.error === "string" ? value.error : null,startedAt: nonNegativeNumber(value.startedAt, Date.now()),...(Number.isSafeInteger(value.serverGeneration)@@ -128,7 +129,7 @@ function sanitizePersistedState(function toPersistedJob(job: ManagedDownload,-): Omit<ManagedDownload, "bytesPerSec" | "completeOnDisk"> {+): Omit<ManagedDownload, "bytesPerSec" | "etaSeconds" | "completeOnDisk"> {return {key: job.key,kind: job.kind,@@ -561,6 +562,9 @@ 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.+ etaSeconds: 0,fraction:job.fraction > 0? job.fractiondiff --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 4496efee4f0..a549f4faa01 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@@ -30,6 +30,8 @@ export interface ManagedDownload {expectedBytes: number;fraction: number;bytesPerSec: number;+ /** Seconds remaining, from the same estimator as {@link bytesPerSec}; 0 hides it. */+ etaSeconds: number;error: string | null;startedAt: number;serverGeneration?: number;@@ -99,6 +101,12 @@ export interface JobRuntime {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.+ */+ pendingGenerationChange?: boolean;idleSinceMs: number | null;lastProgressPollAt: number | null;pollFailureStartedAt: number | null;diff --git a/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsx b/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsxindex 9005435aa14..6a12ba8cbe6 100644--- a/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsx+++ b/studio/frontend/src/features/hub/download-manager/download-progress-bar.tsx@@ -12,22 +12,22 @@ export interface DownloadProgress {export function DownloadProgressBar({progress,bytesPerSec,+ etaSeconds = 0,}: {progress: DownloadProgress;bytesPerSec: number;+ /**+ * Seconds remaining, from the estimator that produced ``bytesPerSec``.+ * Deriving it here gave every caller its own ETA semantics and left the+ * shared estimator's ``etaSeconds`` unused on this path.+ */+ etaSeconds?: number;}) {const exactPercent = Math.min(Math.max(progress.fraction, 0), 1) * 100;const totalLabel =progress.expectedBytes > 0 ? formatBytes(progress.expectedBytes) : null;const rateLabel = formatRate(bytesPerSec);- const remainingBytes = Math.max(- progress.expectedBytes - progress.downloadedBytes,- 0,- );- const etaLabel =- bytesPerSec > 0 && remainingBytes > 0- ? formatEta(remainingBytes / bytesPerSec)- : "";+ const etaLabel = etaSeconds > 0 ? formatEta(etaSeconds) : "";return (<div className="flex flex-col gap-1.5 pb-1"><div className="relative h-[3px] overflow-hidden rounded-full bg-foreground/[0.06] dark:bg-white/[0.06]">diff --git a/studio/frontend/src/features/hub/download-manager/external-jobs.ts b/studio/frontend/src/features/hub/download-manager/external-jobs.tsindex c4070ad66e0..0de08a0fe88 100644--- a/studio/frontend/src/features/hub/download-manager/external-jobs.ts+++ b/studio/frontend/src/features/hub/download-manager/external-jobs.ts@@ -3,6 +3,7 @@import {type TransferSample,+ type TransferStats,appendSample,computeTransferStats,} from "@/lib/transfer-stats";@@ -62,6 +63,7 @@ export function startExternalJob(init: {expectedBytes: Math.max(0, init.expectedBytes),fraction: 0,bytesPerSec: 0,+ etaSeconds: 0,error: null,startedAt: Date.now(),external: true,@@ -76,15 +78,24 @@ export function updateExternalJob(if (!job) return;const downloadedBytes = Math.max(0, progress.downloadedBytes);const expectedBytes = Math.max(0, progress.expectedBytes);- appendSample(job.samples, Date.now() / 1000, downloadedBytes);- const stats = computeTransferStats(job.samples, expectedBytes);+ // External trackers own their own timers, and a hidden tab's are clamped to+ // about once a minute, which the estimator would read as the burst cadence.+ // Guarding here rather than per tracker covers every one of them.+ let stats: TransferStats | null = null;+ if (typeof document !== "undefined" && document.hidden) {+ job.samples.length = 0;+ } else {+ appendSample(job.samples, Date.now() / 1000, downloadedBytes);+ stats = computeTransferStats(job.samples, expectedBytes);+ }patchJob(key, {downloadedBytes,expectedBytes,fraction:expectedBytes > 0 ? Math.min(1, downloadedBytes / expectedBytes) : 0,// Unstable early samples read as absurd rates; show nothing until settled.- bytesPerSec: stats.stable ? stats.rateBytesPerSecond : 0,+ bytesPerSec: stats?.stable ? stats.rateBytesPerSecond : 0,+ etaSeconds: stats?.stable ? stats.etaSeconds : 0,});}@@ -98,6 +109,7 @@ export function finishExternalJob(patchJob(key, {state: outcome,bytesPerSec: 0,+ etaSeconds: 0,error: outcome === "error" ? (error ?? "Download failed.") : null,...(outcome === "complete" ? { fraction: 1, completeOnDisk: true } : {}),});diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 83203d3bc65..81ae5a20d5f 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -181,6 +181,7 @@ function markPollFailure(key: string, rt: JobRuntime): void {patchJob(key, {error: POLL_DEGRADED_MESSAGE,bytesPerSec: 0,+ etaSeconds: 0,});}@@ -216,12 +217,18 @@ export function finalize(completedBytes: bytes,completeOnDisk: true,bytesPerSec: 0,+ etaSeconds: 0,error: null,});notify(job, "onComplete", bytes);scheduleRemoval(key, COMPLETE_LINGER_MS);} else if (outcome === "cancelled") {- patchJob(key, { state: "cancelled", bytesPerSec: 0, error: null });+ patchJob(key, {+ state: "cancelled",+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ });notify(job, "onCancelled", 0);scheduleRemoval(key, CANCELLED_LINGER_MS);} else {@@ -234,6 +241,7 @@ export function finalize(error:opts.error === null ? null : (pollAccessErrorMessage(rawError) ?? rawError),bytesPerSec: 0,+ etaSeconds: 0,});notify(job, "onError", 0);scheduleRemoval(key, ERROR_LINGER_MS);@@ -316,10 +324,13 @@ function applySpeedSample(downloadedBytes: number,expectedBytes: number,nowMs: number,-): number {+): { bytesPerSec: number; etaSeconds: number } {appendSample(rt.speedSamples, nowMs / 1000, downloadedBytes);const stats = computeTransferStats(rt.speedSamples, expectedBytes);- return stats.stable ? stats.rateBytesPerSecond : 0;+ return {+ bytesPerSec: stats.stable ? stats.rateBytesPerSecond : 0,+ etaSeconds: stats.stable ? stats.etaSeconds : 0,+ };}function reconcileProgressAndSpeed(@@ -340,7 +351,13 @@ function reconcileProgressAndSpeed(} = resolveProgressUpdate(current, progressResp, {resetMonotonic: generationChanged,});- const bytesPerSec = applySpeedSample(rt, downloadedBytes, expected, Date.now());+ 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.+ rt.speedSamples.length = 0;+ }+ const speed = applySpeedSample(rt, downloadedBytes, expected, Date.now());patchJob(key, {expectedBytes: expected,downloadedBytes,@@ -348,7 +365,8 @@ function reconcileProgressAndSpeed(completedBytes,completeOnDisk,fraction,- bytesPerSec,+ bytesPerSec: speed.bytesPerSec,+ etaSeconds: speed.etaSeconds,});markPollSuccess(key, rt);return { madeProgress };@@ -413,7 +431,12 @@ async function tick(key: string): Promise<void> {);if (!isCurrent(key, epoch)) return;- const generationChanged = syncServerGeneration(key, job, status);+ // 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.+ if (syncServerGeneration(key, job, status)) {+ rt.pendingGenerationChange = true;+ }const terminalKind = terminalKindFromState(status.state);if (terminalKind !== null) {@@ -444,6 +467,8 @@ async function tick(key: string): Promise<void> {const current = getState().jobs[key];if (!current) return;+ const generationChanged = rt.pendingGenerationChange === true;+ rt.pendingGenerationChange = false;const { madeProgress } = reconcileProgressAndSpeed(rt,key,@@ -636,6 +661,7 @@ export async function startJob(kind: req.kind,repoId: req.repoId,variant: req.variant,+ etaSeconds: 0,state: adoptingCancel ? "cancelling" : "running",downloadedBytes: seedDownloaded,completedBytes: seedCompleted,diff --git a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts b/studio/frontend/src/features/hub/download-manager/use-repo-download.tsindex 45586ebe6eb..64b09c5e8f5 100644--- a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts+++ b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts@@ -26,6 +26,7 @@ export interface DownloadJobProgress {export interface DownloadJob {progress: DownloadJobProgress | null;bytesPerSec: number;+ etaSeconds: number;/** Transport the running job resolved to, when it started on this frontend. */transport: ResolvedTransport | null;/** Its cancel marker, when a Xet run fell back to HTTP: stopping it is still@@ -185,6 +186,7 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {return {progress,bytesPerSec: active?.bytesPerSec ?? 0,+ etaSeconds: active?.etaSeconds ?? 0,transport: active?.transport ?? null,cancelTransport: active?.cancelTransport ?? null,cancelling: active?.state === "cancelling",diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsxindex 8d58fddb70e..e1197e4e8d9 100644--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx@@ -33,6 +33,11 @@ import {useExternalProvidersStore,validateSttModel,} from "@/features/chat";+import {+ type TransferSample,+ appendSample,+ computeTransferStats,+} from "@/lib/transfer-stats";import {DownloadProgressBar,hfApiToken,@@ -496,10 +501,10 @@ export function VoiceTab() {null,);const [downloadBytesPerSec, setDownloadBytesPerSec] = useState(0);- // Last observed (bytes, time) so successive polls yield a transfer rate.- const downloadRateSampleRef = useRef<{ bytes: number; at: number } | null>(- null,- );+ const [downloadEtaSeconds, setDownloadEtaSeconds] = useState(0);+ // Was a bare two-sample delta over ~800ms with no window or stability gate,+ // so one throttled timer or bursty poll set the displayed speed outright.+ const downloadSamplesRef = useRef<TransferSample[]>([]);// Model whose download this tab watched; completion auto-loads it.const watchedDownloadRef = useRef<string | null>(null);@@ -569,16 +574,30 @@ export function VoiceTab() {if (download.model && !isTrackingSttDownload(download.model)) {trackSttDownload(download.model);}- watchedDownloadRef.current = download.model;const bytes = download.bytes_done ?? 0;- const sample = downloadRateSampleRef.current;- const now = Date.now();- if (sample && bytes > sample.bytes && now > sample.at) {- setDownloadBytesPerSec(- ((bytes - sample.bytes) * 1000) / (now - sample.at),+ // Compare before adopting: assigning first made this test itself, so+ // a straight switch priced the new run over the old one's samples.+ if (download.model !== watchedDownloadRef.current) {+ // A different model's counter is a different run.+ downloadSamplesRef.current.length = 0;+ }+ watchedDownloadRef.current = download.model;+ if (typeof document !== "undefined" && document.hidden) {+ // A hidden tab's timers are clamped to about once a minute, so+ // these gaps time the poller and would read as the burst cadence.+ // The hub poll loop drops them the same way.+ downloadSamplesRef.current.length = 0;+ setDownloadBytesPerSec(0);+ setDownloadEtaSeconds(0);+ } else {+ appendSample(downloadSamplesRef.current, Date.now() / 1000, bytes);+ const stats = computeTransferStats(+ downloadSamplesRef.current,+ download.bytes_total ?? 0,);+ setDownloadBytesPerSec(stats.stable ? stats.rateBytesPerSecond : 0);+ setDownloadEtaSeconds(stats.stable ? stats.etaSeconds : 0);}- downloadRateSampleRef.current = { bytes, at: now };// Keep the download progress fresh.window.setTimeout(() => {if (!cancelled) setStatusNonce((n) => n + 1);@@ -586,8 +605,9 @@ export function VoiceTab() {} else {const finished = watchedDownloadRef.current;watchedDownloadRef.current = null;- downloadRateSampleRef.current = null;+ downloadSamplesRef.current.length = 0;setDownloadBytesPerSec(0);+ setDownloadEtaSeconds(0);if (finished === sttModel &&engineStatus.downloaded_models.includes(sttModel) &&@@ -1059,6 +1079,7 @@ export function VoiceTab() {: 0,}}bytesPerSec={downloadBytesPerSec}+ etaSeconds={downloadEtaSeconds}/></div>) : (diff --git a/studio/frontend/src/lib/transfer-stats.ts b/studio/frontend/src/lib/transfer-stats.tsindex 18631167178..b0e5c734493 100644--- a/studio/frontend/src/lib/transfer-stats.ts+++ b/studio/frontend/src/lib/transfer-stats.ts@@ -24,55 +24,188 @@ export type TransferStats = {export const MIN_SAMPLES = 3;export const MIN_WINDOW_SECONDS = 3;+/** Span the rate is averaged over once progress is dense enough to fill it. */export const MAX_WINDOW_SECONDS = 15;+/** Buffer depth by age; {@link MIN_RETAINED_INCREASES} overrides it when sparse. */+export const MAX_RETAIN_SECONDS = 60;+/**+ * Increases kept regardless of age, so a slow cadence still leaves a span. Deep+ * enough that one outlier gap cannot become the median cadence on its own.+ */+export const MIN_RETAINED_INCREASES = 8;+/** Floor on the no-progress timeout, before any cadence has been observed. */+export const STALL_WINDOW_SECONDS = 15;+/** A silence this many times the observed increase cadence reads as a stall. */+export const STALL_CADENCE_MULTIPLIER = 3;+/**+ * Gaps needed before the median is trusted as the cadence. Below this an outage+ * can be most of what you have seen, and sizing the stall window from it is+ * circular: the outage would set the window meant to catch it.+ */+export const MIN_CADENCE_GAPS = 3;/**- * Mutate ``samples`` in place: append the sample, drop any out of the rolling- * window, and clear the buffer if the counter went backwards (cancel + restart).- * Returns the same array for chaining.+ * Mutate ``samples`` in place: append the sample, drop those out of the rolling+ * window while {@link MIN_RETAINED_INCREASES} survive, and clear the buffer if+ * the counter went backwards (cancel + restart). Returns it for chaining.*/export function appendSample(samples: TransferSample[],t: number,b: number,- maxWindowSeconds: number = MAX_WINDOW_SECONDS,+ maxWindowSeconds: number = MAX_RETAIN_SECONDS,): TransferSample[] {if (samples.length > 0 && b < samples[samples.length - 1].b) {samples.length = 0;}- samples.push({ t, b });+ const n = samples.length;+ // Collapse a plateau to its first and latest reading. Nothing here reads the+ // ones between, and the trim below cannot drop them (too few increases left+ // to protect), so a stopped transfer would grow the buffer without bound.+ if (n >= 2 && !(b > samples[n - 1].b) && !(samples[n - 1].b > samples[n - 2].b)) {+ samples[n - 1] = { t, b };+ } else {+ samples.push({ t, b });+ }const cutoff = t - maxWindowSeconds;- while (samples.length > 2 && samples[0].t < cutoff) {+ // Age alone cannot decide this: on a slow link one blob takes minutes, so+ // trimming by seconds drops the older increase measurableSpan needs.+ while (+ samples.length > 2 &&+ samples[0].t < cutoff &&+ countIncreases(samples, 1) >= MIN_RETAINED_INCREASES+ ) {samples.shift();}return samples;}+/** Byte increases in ``samples`` at or after ``from``. */+function countIncreases(samples: readonly TransferSample[], from: number): number {+ let n = 0;+ for (let i = Math.max(from, 1); i < samples.length; i += 1) {+ if (samples[i].b > samples[i - 1].b) n += 1;+ }+ return n;+}++/**+ * How long a silence runs before it is a stall rather than a gap between jumps.+ * A fixed 15s calls a 60s blob cadence stalled every time, blanking 95% of+ * ticks at 3 MB/s, so track the observed cadence. Uncapped: any cap is a cliff+ * for a repo slower than it.+ */+function stallWindowSeconds(samples: readonly TransferSample[]): number {+ const gaps: number[] = [];+ let previous = -1;+ for (let i = 1; i < samples.length; i += 1) {+ if (samples[i].b <= samples[i - 1].b) continue;+ if (previous >= 0) gaps.push(samples[i].t - samples[previous].t);+ previous = i;+ }+ if (gaps.length < MIN_CADENCE_GAPS) return STALL_WINDOW_SECONDS;+ gaps.sort((a, b) => a - b);+ // Lower median: on an even count take the shorter of the middle pair, so a+ // long gap needs a majority behind it before it can stretch the window.+ const median = gaps[Math.floor((gaps.length - 1) / 2)];+ return Math.max(STALL_WINDOW_SECONDS, median * STALL_CADENCE_MULTIPLIER);+}++function hasRecentProgress(+ samples: readonly TransferSample[],+ last: TransferSample,+): boolean {+ const cutoff = last.t - stallWindowSeconds(samples);+ for (let index = samples.length - 2; index >= 0; index -= 1) {+ const sample = samples[index];+ if (sample.t < cutoff) break;+ if (sample.b < last.b) return true;+ }+ return false;+}++/**+ * The pair to price the transfer from: newest byte increase, and the tightest+ * earlier increase ≥ {@link MAX_WINDOW_SECONDS} back (else the oldest held).+ *+ * Hub progress is read off disk, where sparse allocation makes a steady transfer+ * look like plateaus and jumps (#9378). Increase-to-increase spans a whole number+ * of jumps, so the partial plateau at each end stops tilting the rate; a dense+ * feed increases every sample and so still averages over the full span.+ *+ * ``null`` below two increases: one jump alone carries no timing to measure.+ */+function measurableSpan(+ samples: readonly TransferSample[],+): [number, number] | null {+ let to = -1;+ for (let i = samples.length - 1; i > 0; i -= 1) {+ if (samples[i].b > samples[i - 1].b) {+ to = i;+ break;+ }+ }+ if (to < 1) return null;+ const stall = stallWindowSeconds(samples);+ let from = -1;+ let newer = to;+ let resumed = false;+ for (let i = to - 1; i > 0; i -= 1) {+ if (samples[i].b <= samples[i - 1].b) continue;+ // A silence past the stall window is a break, not a slow burst. Reaching+ // across it averages the dead time in: 20 MB/s resuming after a 30 minute+ // drop published 0.64 MB/s.+ if (samples[newer].t - samples[i].t > stall) {+ resumed = true;+ break;+ }+ from = i;+ newer = i;+ if (samples[to].t - samples[i].t >= MAX_WINDOW_SECONDS) break;+ }+ if (from < 1) return null;+ // Increases clumped inside the smoothing span are spaced by arrival jitter, not+ // by the rate. Price the whole buffer instead, and stay silent while even that is+ // too short to divide by, so no single clump is ever published as the speed.+ if (samples[to].t - samples[from].t < MAX_WINDOW_SECONDS) {+ // Unless that would reach back over a break: stay silent until the resumed+ // transfer has a span of its own.+ if (resumed) return null;+ from = 0;+ }+ return samples[to].t - samples[from].t < MIN_WINDOW_SECONDS ? null : [from, to];+}+/*** Derive {@link TransferStats} from a window of cumulative-byte samples plus the* known total.* * Needs ≥ {@link MIN_SAMPLES} samples spanning ≥ {@link MIN_WINDOW_SECONDS}* seconds before reporting ``stable: true``.+ * * Prices bursty cumulative-byte observations increase-to-increase.+ * * Reports unstable once a silence outruns the observed increase cadence.* * ETA clamps to 0 when there's no progress, no total, or total is hit.*/export function computeTransferStats(samples: readonly TransferSample[],total: number,): TransferStats {- if (samples.length < MIN_SAMPLES) {- return { rateBytesPerSecond: 0, etaSeconds: 0, stable: false };- }+ const unstable = { rateBytesPerSecond: 0, etaSeconds: 0, stable: false };+ if (samples.length < MIN_SAMPLES) return unstable;const first = samples[0];const last = samples[samples.length - 1];- const dt = last.t - first.t;- const db = last.b - first.b;- if (dt < MIN_WINDOW_SECONDS || db <= 0) {- return { rateBytesPerSecond: 0, etaSeconds: 0, stable: false };+ if (last.t - first.t < MIN_WINDOW_SECONDS || last.b <= first.b) {+ return unstable;}- const rate = db / dt;+ if (!hasRecentProgress(samples, last)) return unstable;+ const span = measurableSpan(samples);+ if (!span) return unstable;+ const dt = samples[span[1]].t - samples[span[0]].t;+ const db = samples[span[1]].b - samples[span[0]].b;+ const rate = dt > 0 ? db / dt : 0;+ if (!(Number.isFinite(rate) && rate > 0)) return unstable;const safeTotal = Number.isFinite(total) && total > 0 ? total : 0;const eta =- safeTotal > 0 && last.b < safeTotal && rate > 0+ safeTotal > 0 && last.b < safeTotal? (safeTotal - last.b) / rate: 0;return { rateBytesPerSecond: rate, etaSeconds: eta, stable: true };diff --git a/studio/frontend/tests/chat-format-transfer.test.ts b/studio/frontend/tests/chat-format-transfer.test.tsnew file mode 100644index 00000000000..caf2132b0fa--- /dev/null+++ b/studio/frontend/tests/chat-format-transfer.test.ts@@ -0,0 +1,51 @@+// 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 chat/model-load/training-overlay formatters. The 24h ETA clamp mirrors+// the hub formatter's, which has had one since #7679 (see hub-format.test.ts).++import assert from "node:assert/strict";+import test from "node:test";++import {+ formatEta,+ formatRate,+} from "../src/features/chat/utils/format-transfer.ts";++const DAY = 24 * 60 * 60;++test("formatEta renders the usual units", () => {+ assert.equal(formatEta(5), "5s");+ assert.equal(formatEta(65), "1m 5s");+ assert.equal(formatEta(120), "2m");+ assert.equal(formatEta(3725), "1h 2m");+ assert.equal(formatEta(7200), "2h");+});++test("formatEta clamps at 24h", () => {+ assert.equal(formatEta(DAY), "> 24h");+ assert.equal(formatEta(DAY * 40), "> 24h");+ // #7667's "753d 5h left" must be unreachable through this formatter.+ assert.equal(formatEta(753 * DAY), "> 24h");+});++test("formatEta clamps on the rounded value, as the hub formatter does", () => {+ assert.equal(formatEta(DAY - 0.5), "> 24h");+ assert.equal(formatEta(DAY - 1), "23h 59m");+});++test("formatEta rejects non-finite and non-positive input", () => {+ for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {+ assert.equal(formatEta(bad), "--");+ }+});++test("formatRate scales and rejects non-finite input", () => {+ assert.equal(formatRate(500), "500 B/s");+ assert.equal(formatRate(1024 * 10), "10.0 KB/s");+ assert.equal(formatRate(1024 ** 2 * 20), "20.0 MB/s");+ assert.equal(formatRate(1024 ** 3 * 2), "2.00 GB/s");+ for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) {+ assert.equal(formatRate(bad), "--");+ }+});diff --git a/studio/frontend/tests/chat-transfer-hidden-tab.test.ts b/studio/frontend/tests/chat-transfer-hidden-tab.test.tsnew file mode 100644index 00000000000..2bb7a4c0636--- /dev/null+++ b/studio/frontend/tests/chat-transfer-hidden-tab.test.ts@@ -0,0 +1,84 @@+// 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 model-load toast polls on a 2s interval, clamped to about once a minute+// while hidden. Those gaps time the poller, not the transfer, and the estimator+// reads gaps as the burst cadence, so progress stopping near the moment the user+// returns left a stale rate on screen for a minute. The hub and voice pollers+// already drop hidden samples; this pins that the chat one does too.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ type TransferSample,+ appendSample,+ computeTransferStats,+} from "../src/lib/transfer-stats.ts";++const MB = 1e6;++test("the chat estimator drops samples taken while the tab is hidden", () => {+ const source = readFileSync(+ new URL(+ "../src/features/chat/hooks/use-chat-model-runtime.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const guard = source.indexOf("document.hidden");+ assert.ok(guard > 0, "the chat poller should skip a hidden tab");+ const clear = source.indexOf("samples.length = 0", guard);+ const sample = source.indexOf("appendSample(samples,", guard);+ assert.ok(+ clear > 0 && clear < sample,+ "the hidden branch must clear, not sample",+ );+});++test("throttled hidden samples do not hold a stale rate once progress stops", () => {+ const heldSeconds = (dropWhileHidden: boolean) => {+ const samples: TransferSample[] = [];+ let rate = 0;+ const poll = (t: number, b: number, hidden: boolean) => {+ if (dropWhileHidden && hidden) {+ samples.length = 0;+ rate = 0;+ return;+ }+ appendSample(samples, t, b);+ const stats = computeTransferStats(samples, 100_000 * MB);+ rate = stats.stable ? stats.rateBytesPerSecond : 0;+ };++ let bytes = 0;+ let t = 0;+ for (; t <= 60; t += 2) {+ bytes = t * 50 * MB;+ poll(t, bytes, false);+ }+ // Hidden: the 2s interval is clamped to a minute, still downloading.+ for (; t <= 660; t += 60) {+ bytes = t * 50 * MB;+ poll(t, bytes, true);+ }+ // Progress stops just as the tab is shown again.+ let held = 0;+ for (const end = t + 300; t <= end; t += 2) {+ poll(t, bytes, false);+ if (rate > 0) held += 2;+ }+ return held;+ };++ assert.ok(+ heldSeconds(false) > 30,+ "without the guard the throttled cadence should still hold a stale rate",+ );+ assert.equal(+ heldSeconds(true),+ 0,+ "with the guard nothing survives the hidden stretch",+ );+});diff --git a/studio/frontend/tests/download-eta-invalidation.test.ts b/studio/frontend/tests/download-eta-invalidation.test.tsnew file mode 100644index 00000000000..bf9a039a53a--- /dev/null+++ b/studio/frontend/tests/download-eta-invalidation.test.ts@@ -0,0 +1,79 @@+// 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 bar renders the stored etaSeconds rather than deriving one, so a total+// that grows underneath it leaves an ETA measured against the old, smaller one.+// GGUF metadata arriving after a job was adopted does exactly that. Hiding the+// ETA for one poll beats showing one for a size that is no longer the target.+//+// Also pins that the voice poller ignores a hidden tab's throttled callbacks,+// the way the hub poll loop already does.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+installLocalStorageFake();+Object.assign(globalThis.window, { addEventListener: () => {} });++const { getState, putJob, jobKeyOf, setExpectedBytesForJob } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);++const KEY = jobKeyOf("model", "org/gguf-repo", null);++test("a total that grows drops the ETA measured against the old one", () => {+ putJob({+ key: KEY,+ kind: "model",+ repoId: "org/gguf-repo",+ variant: null,+ state: "running",+ downloadedBytes: 900_000_000,+ completedBytes: 0,+ completeOnDisk: false,+ expectedBytes: 1_000_000_000,+ fraction: 0.9,+ bytesPerSec: 10_000_000,+ // 10s left, against a 1 GB total.+ etaSeconds: 10,+ error: null,+ startedAt: 1,+ });++ // GGUF metadata lands: the job is really 8 GB, not 1 GB.+ setExpectedBytesForJob("model", "org/gguf-repo", null, 8_000_000_000);++ const job = getState().jobs[KEY];+ assert.equal(job.expectedBytes, 8_000_000_000);+ assert.equal(+ job.etaSeconds,+ 0,+ "the ETA for the old total must not survive the total changing",+ );+});++test("the voice poller drops a hidden tab's throttled samples", () => {+ const source = readFileSync(+ new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),+ "utf8",+ );+ const guard = source.indexOf("document.hidden");+ assert.ok(guard > 0, "the voice poller should skip a hidden tab");+ const clear = source.indexOf("downloadSamplesRef.current.length = 0", guard);+ const sample = source.indexOf(+ "appendSample(downloadSamplesRef.current",+ guard,+ );+ assert.ok(clear > 0, "a hidden tab should clear the samples");+ assert.ok(+ sample < 0 || clear < sample,+ "the hidden-tab branch must clear rather than sample",+ );+});diff --git a/studio/frontend/tests/download-eta-persist-compat.test.ts b/studio/frontend/tests/download-eta-persist-compat.test.tsnew file mode 100644index 00000000000..cc6773f4346--- /dev/null+++ b/studio/frontend/tests/download-eta-persist-compat.test.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// `etaSeconds` is a new required field on ManagedDownload, so an install that+// upgrades into it has records without one, and one that downgrades away must+// still read what this version wrote. It is injected on the way in and omitted+// on the way out, leaving the persisted shape unchanged in both directions.++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";+let flushPersistedState: (() => void) | undefined;+Object.assign(globalThis.window, {+ addEventListener: (type: string, listener: () => void) => {+ if (type === "pagehide") flushPersistedState = listener;+ },+});++/** Exactly what a Studio from before this change wrote: no `etaSeconds` key. */+function legacyJob(repoId: string, extra: Record<string, unknown> = {}) {+ return {+ key: `model:${repoId}`,+ kind: "model",+ repoId,+ variant: null,+ state: "running",+ downloadedBytes: 4_000_000_000,+ completedBytes: 0,+ expectedBytes: 8_000_000_000,+ fraction: 0.5,+ error: null,+ startedAt: 1,+ ...extra,+ };+}++store.set(+ PERSIST_KEY,+ JSON.stringify({+ state: {+ jobs: {+ legacy: legacyJob("org/legacy"),+ // A record whose eta survived some other route, or was hand-edited.+ poisoned: legacyJob("org/poisoned", { etaSeconds: "not a number" }),+ infinite: legacyJob("org/infinite", {+ etaSeconds: Number.POSITIVE_INFINITY,+ }),+ negative: legacyJob("org/negative", { etaSeconds: -1 }),+ },+ conflicts: {},+ },+ version: 1,+ }),+);++const { getState, jobKeyOf, patchJob } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);++const keyOf = (repoId: string) => jobKeyOf("model", repoId, null);++test("a record written before etaSeconds existed still hydrates", () => {+ const job = getState().jobs[keyOf("org/legacy")];+ assert.ok(job, "the legacy job should hydrate");+ assert.equal(job.etaSeconds, 0);+ assert.equal(job.downloadedBytes, 4_000_000_000);+ assert.equal(job.fraction, 0.5);+ assert.equal(job.state, "running");+});++test("a hostile persisted etaSeconds cannot reach the UI", () => {+ for (const repoId of ["org/poisoned", "org/infinite", "org/negative"]) {+ const job = getState().jobs[keyOf(repoId)];+ assert.ok(job, `${repoId} should hydrate`);+ assert.equal(job.etaSeconds, 0, `${repoId} kept ${job.etaSeconds}`);+ assert.ok(Number.isFinite(job.etaSeconds));+ }+});++test("what this version writes back carries no etaSeconds, so an older Studio reads it unchanged", () => {+ patchJob(keyOf("org/legacy"), { etaSeconds: 1234, bytesPerSec: 5_000_000 });+ assert.equal(getState().jobs[keyOf("org/legacy")].etaSeconds, 1234);++ assert.ok(flushPersistedState, "the store should register a pagehide flush");+ flushPersistedState?.();++ const written = JSON.parse(store.get(PERSIST_KEY) as string);+ const job = written.state.jobs[keyOf("org/legacy")];+ assert.ok(job, "the job should be persisted");+ assert.ok(+ !("etaSeconds" in job),+ `persisted record leaked etaSeconds: ${JSON.stringify(job)}`,+ );+ // The rate has never been persisted either; the ETA follows the same rule.+ assert.ok(!("bytesPerSec" in job), "persisted record leaked bytesPerSec");+ // Everything an older Studio does read is still there and unchanged.+ assert.equal(job.downloadedBytes, 4_000_000_000);+ assert.equal(job.expectedBytes, 8_000_000_000);+ assert.equal(job.state, "running");+});diff --git a/studio/frontend/tests/download-generation-pending.test.ts b/studio/frontend/tests/download-generation-pending.test.tsnew file mode 100644index 00000000000..3f72032cc9b--- /dev/null+++ b/studio/frontend/tests/download-generation-pending.test.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// syncServerGeneration persists the new generation before the tick decides+// whether to poll progress, and status is polled twice as often as progress+// (500ms against 1000ms). A generation observed on a status-only tick was+// therefore already stored by the next one, so generationChanged read false and+// the samples from the previous server were never dropped. Holding the change+// until a progress poll consumes it is what makes the reset reliable.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ POLL_INTERVAL_MS,+ PROGRESS_POLL_INTERVAL_MS,+} from "../src/features/hub/download-manager/download-manager-config.ts";++const source = readFileSync(+ new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),+ "utf8",+);++test("status ticks outnumber progress polls, so the race is the normal case", () => {+ assert.ok(+ PROGRESS_POLL_INTERVAL_MS > POLL_INTERVAL_MS,+ "the race only exists because progress is polled less often than status",+ );+});++test("a generation change is held until a progress poll consumes it", () => {+ const set = source.indexOf("rt.pendingGenerationChange = true");+ const read = source.indexOf("rt.pendingGenerationChange === true");+ const clear = source.indexOf("rt.pendingGenerationChange = false");+ assert.ok(set > 0, "a generation change should be recorded on the runtime");+ assert.ok(read > 0, "the progress path should read the held change");+ assert.ok(clear > read, "it should be cleared only after it is read");+ // It must not be read straight out of syncServerGeneration's return value+ // again, or the early return swallows it exactly as before.+ assert.doesNotMatch(+ source,+ /const generationChanged = syncServerGeneration\(/,+ "reading the return value directly reintroduces the swallow",+ );+});++// The behaviour the flag buys, modelled on the real cadence: a change seen on a+// status-only tick still reaches the progress path.+test("a change seen between progress polls still reaches reconcile", () => {+ const consumed: boolean[] = [];+ const rt: { pendingGenerationChange?: boolean } = {};+ let storedGeneration = 1;+ let lastProgressAt = 0;++ const tick = (now: number, serverGeneration: number, sticky: boolean) => {+ // syncServerGeneration: persists immediately, reports the change once.+ const changed = serverGeneration !== storedGeneration;+ storedGeneration = serverGeneration;+ if (sticky && changed) rt.pendingGenerationChange = true;+ // shouldPollProgress: the early return that drops the signal.+ if (now - lastProgressAt < PROGRESS_POLL_INTERVAL_MS) return;+ lastProgressAt = now;+ if (sticky) {+ consumed.push(rt.pendingGenerationChange === true);+ rt.pendingGenerationChange = false;+ } else {+ consumed.push(changed);+ }+ };++ const run = (sticky: boolean) => {+ consumed.length = 0;+ rt.pendingGenerationChange = false;+ storedGeneration = 1;+ lastProgressAt = 0;+ // The backend restarts at t=500ms, which is a status-only tick.+ for (let now = 0; now <= 3_000; now += POLL_INTERVAL_MS) {+ tick(now, now >= 500 ? 2 : 1, sticky);+ }+ return consumed.some(Boolean);+ };++ assert.equal(run(false), false, "without the flag the change is swallowed");+ assert.equal(run(true), true, "with it the progress path still sees it");+});diff --git a/studio/frontend/tests/download-generation-rate-reset.test.ts b/studio/frontend/tests/download-generation-rate-reset.test.tsnew file mode 100644index 00000000000..e35d04aad39--- /dev/null+++ b/studio/frontend/tests/download-generation-rate-reset.test.ts@@ -0,0 +1,79 @@+// 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 generation change means another backend owns the transfer, so the previous+// one's samples describe a different run. Nothing else catches it: a restart+// resumes from the same cache so the counter never goes backwards, and the+// runtime holding the buffer is not recreated. The poll gap across the restart+// then lands inside the measured span: 100 MB/s published 13 MB/s.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ type TransferSample,+ appendSample,+ computeTransferStats,+} from "../src/lib/transfer-stats.ts";++const MB = 1e6;++test("a generation change clears the rate samples before the next one is taken", () => {+ const source = readFileSync(+ new URL(+ "../src/features/hub/download-manager/poll-loop.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const clear = source.indexOf(+ "rt.speedSamples.length = 0",+ source.indexOf("generationChanged) {"),+ );+ const sample = source.indexOf("applySpeedSample(rt,");+ assert.ok(clear > 0, "a generation change should clear the samples");+ assert.ok(sample > 0, "the speed sample should still be taken");+ assert.ok(+ clear < sample,+ "clearing after sampling would price the new run on the old buffer",+ );+});++test("a restart does not make the resumed transfer look slow", () => {+ const rates = (clearOnGeneration: boolean) => {+ const samples: TransferSample[] = [];+ const out: number[] = [];+ let bytes = 0;+ const poll = (t: number, b: number, generationChanged: boolean) => {+ if (generationChanged && clearOnGeneration) samples.length = 0;+ appendSample(samples, t, b);+ const stats = computeTransferStats(samples, 100_000 * MB);+ out.push(stats.stable ? stats.rateBytesPerSecond : 0);+ };+ for (let t = 0; t <= 60; t += 1) {+ bytes = t * 100 * MB;+ poll(t, bytes, false);+ }+ // The backend restarts. 12s without a successful poll, which is inside the+ // 30s degraded-poll reset, so nothing else clears the buffer. It resumes at+ // the same byte count and the same speed.+ const after: number[] = [];+ for (let t = 73; t <= 84; t += 1) {+ poll(t, bytes + (t - 73) * 100 * MB, t === 73);+ after.push(out[out.length - 1]);+ }+ return after;+ };++ const stale = rates(false).filter((r) => r > 0);+ const cleared = rates(true).filter((r) => r > 0);+ assert.ok(+ Math.min(...stale) < 20 * MB,+ "without the reset the restart gap should still drag the rate down",+ );+ assert.ok(+ Math.min(...cleared) > 95 * MB,+ `after the reset the resumed transfer should read ~100 MB/s, got ${(Math.min(...cleared) / MB).toFixed(1)}`,+ );+});diff --git a/studio/frontend/tests/download-held-transfer-persistence.test.ts b/studio/frontend/tests/download-held-transfer-persistence.test.tsindex d9f48714f69..bf705018449 100644--- a/studio/frontend/tests/download-held-transfer-persistence.test.ts+++ b/studio/frontend/tests/download-held-transfer-persistence.test.ts@@ -105,6 +105,7 @@ test("the held marker is written out with the job", () => {expectedBytes: 500_000_000,fraction: 0.1,bytesPerSec: 0,+ etaSeconds: 0,error: null,startedAt: 2,measuredTransfer: false,diff --git a/studio/frontend/tests/download-progress-reconcile.test.ts b/studio/frontend/tests/download-progress-reconcile.test.tsindex 565ddb95982..7335fe3c29d 100644--- a/studio/frontend/tests/download-progress-reconcile.test.ts+++ b/studio/frontend/tests/download-progress-reconcile.test.ts@@ -45,6 +45,7 @@ function job(overrides: Partial<ManagedDownload> = {}): ManagedDownload {completeOnDisk: false,fraction: 0.99,bytesPerSec: 0,+ etaSeconds: 0,error: null,startedAt: 1,};diff --git a/studio/frontend/tests/download-rate-not-restored.test.ts b/studio/frontend/tests/download-rate-not-restored.test.tsnew file mode 100644index 00000000000..bb5f101d8bb--- /dev/null+++ b/studio/frontend/tests/download-rate-not-restored.test.ts@@ -0,0 +1,63 @@+// 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 persisted rate or ETA must never come back: the wall-clock gap while the+// app was closed is not transfer time. The estimator restarts cold instead.++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";+Object.assign(globalThis.window, {+ addEventListener: () => {},+});++store.set(+ PERSIST_KEY,+ JSON.stringify({+ state: {+ jobs: {+ "model:org/mid-transfer": {+ key: "model:org/mid-transfer",+ kind: "model",+ repoId: "org/mid-transfer",+ variant: null,+ state: "running",+ downloadedBytes: 4_000_000_000,+ completedBytes: 0,+ expectedBytes: 8_000_000_000,+ fraction: 0.5,+ error: null,+ startedAt: 1,+ // Whatever a previous session happened to leave behind.+ bytesPerSec: 50_000_000,+ etaSeconds: 900,+ },+ },+ conflicts: {},+ },+ version: 1,+ }),+);++const { getState, jobKeyOf } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);++test("a persisted rate and ETA are both dropped on hydration", () => {+ const job = getState().jobs[jobKeyOf("model", "org/mid-transfer", null)];+ assert.ok(job, "the job itself should still hydrate");+ assert.equal(job.bytesPerSec, 0);+ assert.equal(job.etaSeconds, 0);+ // The progress itself is still worth restoring; only the timing is not.+ assert.equal(job.downloadedBytes, 4_000_000_000);+ assert.equal(job.fraction, 0.5);+});diff --git a/studio/frontend/tests/download-transport-persistence.test.ts b/studio/frontend/tests/download-transport-persistence.test.tsindex afd1cf638a5..c8b1c6dd961 100644--- a/studio/frontend/tests/download-transport-persistence.test.ts+++ b/studio/frontend/tests/download-transport-persistence.test.ts@@ -89,6 +89,7 @@ test("the active transport is written with the persisted job", () => {expectedBytes: 100,fraction: 0.5,bytesPerSec: 10,+ etaSeconds: 0,error: null,startedAt: 2,transport: "xet",@@ -133,6 +134,7 @@ test("the cancel marker is written with the persisted job", () => {expectedBytes: 100,fraction: 0.1,bytesPerSec: 0,+ etaSeconds: 0,error: null,startedAt: 3,transport: "http",@@ -167,6 +169,7 @@ test("an external job counts too, since a quit kills its transfer as well", () =expectedBytes: 0,fraction: 0,bytesPerSec: 0,+ etaSeconds: 0,error: null,startedAt: 4,external: true,@@ -189,6 +192,7 @@ test("an external job counts too, since a quit kills its transfer as well", () =expectedBytes: 0,fraction: 1,bytesPerSec: 0,+ etaSeconds: 0,error: null,startedAt: 4,},diff --git a/studio/frontend/tests/external-job-hidden-tab.test.ts b/studio/frontend/tests/external-job-hidden-tab.test.tsnew file mode 100644index 00000000000..50276f5e636--- /dev/null+++ b/studio/frontend/tests/external-job-hidden-tab.test.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// External trackers own their own timers: the STT mirror runs a 750ms interval,+// and a hidden tab's are clamped to about once a minute. The estimator reads+// gaps between increases as the burst cadence, so those gaps stretch the stall+// window and leave a stale rate on the Downloads row. The guard lives in+// updateExternalJob so every external tracker inherits it.++import assert from "node:assert/strict";+import test from "node:test";++import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";++registerBundlerResolver();+installLocalStorageFake();+Object.assign(globalThis.window, { addEventListener: () => {} });++const visibility = { hidden: false };+Object.defineProperty(globalThis, "document", {+ configurable: true,+ value: {+ get hidden() {+ return visibility.hidden;+ },+ },+});++const { startExternalJob, updateExternalJob } = await import(+ "../src/features/hub/download-manager/external-jobs.ts"+);+const { getState } = await import(+ "../src/features/hub/download-manager/download-manager-state.ts"+);++const KEY = "model:org/stt-mirror";+const MB = 1e6;++test("a hidden tab's throttled samples never become a published rate", () => {+ // updateExternalJob reads the wall clock itself, so drive it: without real+ // spacing the estimator would be unstable anyway and the test would pass for+ // the wrong reason.+ const realNow = Date.now;+ let now = realNow();+ Date.now = () => now;+ try {+ startExternalJob({+ key: KEY,+ repoId: "org/stt-mirror",+ variant: null,+ expectedBytes: 8_000 * MB,+ cancel: () => {},+ });++ // Visible and healthy first, at the tracker's own 750ms cadence.+ visibility.hidden = false;+ let bytes = 0;+ for (let i = 0; i <= 60; i += 1) {+ now += 750;+ bytes += 37.5 * MB; // 50 MB/s at 750ms+ updateExternalJob(KEY, {+ downloadedBytes: bytes,+ expectedBytes: 8_000 * MB,+ });+ }+ assert.ok(+ getState().jobs[KEY].bytesPerSec > 0,+ "the visible phase should publish a rate, or this test proves nothing",+ );++ // Backgrounded: browsers clamp the interval to about once a minute.+ visibility.hidden = true;+ for (let i = 0; i < 10; i += 1) {+ now += 60_000;+ bytes += 3_000 * MB;+ updateExternalJob(KEY, {+ downloadedBytes: bytes,+ expectedBytes: 8_000 * MB,+ });+ }++ const job = getState().jobs[KEY];+ assert.ok(job, "the external job should still exist");+ assert.equal(job.bytesPerSec, 0, "a hidden tab must publish no rate");+ assert.equal(job.etaSeconds, 0, "a hidden tab must publish no ETA");+ // Progress itself is still worth recording; only the timing is not.+ assert.equal(job.downloadedBytes, bytes);+ } finally {+ Date.now = realNow;+ }+});diff --git a/studio/frontend/tests/hub-download-rate.test.ts b/studio/frontend/tests/hub-download-rate.test.tsindex 5a3661d4c61..babadc4ebc5 100644--- a/studio/frontend/tests/hub-download-rate.test.ts+++ b/studio/frontend/tests/hub-download-rate.test.ts@@ -1,10 +1,9 @@// 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 hub download manager now derives its rate from the shared rolling-window-// estimator instead of an EMA seeded by the first sample (#7667). These pin the-// gating the progress bar relies on: no rate (and so no ETA) until the window is-// trustworthy, and no tiny positive rate while a transfer is stalled.+// The hub download manager rates its progress bar through the shared estimator,+// not an EMA seeded by the first sample (#7667). These pin the gating it relies+// on, and the smoothing for byte counts arriving in disk bursts (#9378).import assert from "node:assert/strict";import test from "node:test";@@ -45,14 +44,263 @@ test("a steady transfer reports its true rate", () => {assert.ok(Math.abs(rate - 20 * MB) < 1);});-test("a stall reports no rate instead of decaying toward zero", () => {+/** Steady ``rate`` whose observed counter only advances every ``burst`` seconds. */+function burstyRates(burst: number, rate: number, until = 300): number[] {+ const samples: TransferSample[] = [];+ const published: number[] = [];+ for (let t = 0; t <= until; t++) {+ const observed = Math.floor(t / burst) * burst * rate;+ const seen = publishedRate(samples, t, observed);+ if (t >= 3 * burst && seen > 0) published.push(seen);+ }+ return published;+}++// Sparse allocation turns a steady transfer into plateaus and jumps, so pricing+// the window endpoints swung between "very slow, hours left" and hundreds of MB/s.+test("bursty byte observations report the underlying transfer rate", () => {+ for (const burst of [2, 5, 10, 15, 20, 30, 45]) {+ const rates = burstyRates(burst, 100 * MB);+ assert.ok(rates.length > 0, `no rate published for ${burst}s bursts`);+ for (const rate of rates) {+ assert.ok(+ Math.abs(rate - 100 * MB) < 5 * MB,+ `${burst}s bursts published ${(rate / MB).toFixed(1)} MB/s`,+ );+ }+ }+});++// Two jumps are the minimum that carries timing; below that the honest answer is+// no rate, not a number set by where the window happened to cut.+test("bursts far apart still report their rate once the cadence is known", () => {+ // Silence used to be the answer here, because a fixed stall window shorter+ // than the burst period reads every healthy gap as a stall. The rate is+ // exactly recoverable though: increase-to-increase over a 90s cadence is+ // 100 MB/s on the nose, and showing it beats blanking the bar for minutes.+ const rates = burstyRates(90, 100 * MB, 600);+ assert.ok(rates.length > 0, "a 90s cadence should still publish");+ for (const rate of rates) {+ assert.ok(+ Math.abs(rate - 100 * MB) < 1 * MB,+ `published ${(rate / 1e6).toFixed(1)} MB/s, want 100`,+ );+ }+});++// External job callbacks can fire back to back, so the first two increases may be+// milliseconds apart while the buffer is still short. Dividing by that gap is how+// the gate used to leak a "123 GB/s" first tick.+test("increases arriving together during warm-up are not a rate", () => {+ const samples: TransferSample[] = [];+ publishedRate(samples, 0, 0);+ publishedRate(samples, 3, 0);+ publishedRate(samples, 3.01, 1_000 * MB);+ const rate = publishedRate(samples, 3.02, 2_000 * MB);+ // 2 GB over the 3.02s actually observed, not 1 GB over the 10ms between them.+ assert.ok(rate < 1_000 * MB, `published ${(rate / MB).toFixed(0)} MB/s`);+});++// Recovering from a stall longer than the buffer leaves only the clump that just+// landed. Its samples are a second apart, so measuring across them alone would+// turn one xorb into the transfer speed.+test("a clump landing after a long stall does not become the speed", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ let peak = 0;+ for (let t = 0; t <= 95; t++) {+ if (t <= 20) bytes = t * 100 * MB;+ else if (t === 82 || t === 83) bytes += 1_000 * MB;+ peak = Math.max(peak, publishedRate(samples, t, bytes));+ }+ assert.ok(peak <= 100 * MB, `published ${(peak / MB).toFixed(0)} MB/s`);+});++test("a stall reports no rate instead of carrying an old window forward", () => {const samples: TransferSample[] = [];for (let t = 0; t <= 10; t++) publishedRate(samples, t, t * 20 * MB);let rate = 0;- for (let t = 11; t <= 40; t++) rate = publishedRate(samples, t, 10 * 20 * MB);+ for (let t = 11; t <= 26; t++) rate = publishedRate(samples, t, 10 * 20 * MB);assert.equal(rate, 0);});+// The chat toast, model-load UI and training overlay share this on dense feeds,+// so the burst handling must not slow their reaction down.+test("a dense feed still tracks a rate change within the smoothing span", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ let rate = 0;+ for (let t = 0; t <= 40; t++) {+ bytes += (t < 20 ? 200 : 50) * MB;+ rate = publishedRate(samples, t, bytes);+ }+ assert.ok(Math.abs(rate - 50 * MB) < 1);+});++// The trim protects a floor of increases and a stopped transfer has none, so+// nothing was eligible to drop and a wedged download grew the buffer forever.+// 16 is what the age-only trim this replaced held.+test("a transfer that stops does not grow the sample buffer without bound", () => {+ const samples: TransferSample[] = [];+ for (let t = 0; t <= 6 * 60 * 60; t += 1) publishedRate(samples, t, 1_000);+ assert.ok(+ samples.length <= 16,+ `buffer held ${samples.length} samples after 6h`,+ );+});++test("a long plateau keeps the span it is measured over", () => {+ // Collapsing the plateau must not lose when it began.+ const samples: TransferSample[] = [];+ publishedRate(samples, 0, 0);+ for (let t = 1; t <= 300; t += 1) publishedRate(samples, t, 500 * MB);+ assert.equal(samples[samples.length - 1].t, 300);+ assert.equal(samples[samples.length - 1].b, 500 * MB);+});++// One outlier gap (a suspend, or a browser-clamped background timer) used to be+// the only gap left in the buffer, so it became the median cadence, the stall+// window stretched to hours, and a dead transfer kept showing its last speed.+test("one outlier gap does not disable stall detection", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ for (let t = 0; t <= 600; t += 1) {+ if (t % 5 === 0) bytes += 5 * MB;+ publishedRate(samples, t, bytes);+ }+ // 30 minutes asleep, then one burst lands, then the transfer dies.+ for (let t = 601; t <= 2_400; t += 60) publishedRate(samples, t, bytes);+ bytes += 5 * MB;+ publishedRate(samples, 2_401, bytes);+ let rate = 0;+ for (let t = 2_402; t <= 3_000; t += 1)+ rate = publishedRate(samples, t, bytes);+ assert.equal(rate, 0, "a dead transfer should stop reporting a rate");+});++// A resume keeps its byte counter, so nothing resets. Reaching back past the+// break averaged the dead time in: 20 MB/s resuming after a 30 minute drop+// published 0.64 MB/s for a full burst period. Silence is the honest answer.+test("a resume after a long stall is not priced across the stall", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ let t = 0;+ for (; t <= 600; t += 1) {+ if (t % 60 === 0 && t > 0) bytes += 60 * 20 * MB;+ publishedRate(samples, t, bytes);+ }+ // 30 minutes with no progress and no counter reset.+ for (; t <= 600 + 1_800; t += 1) publishedRate(samples, t, bytes);+ // Then the same 20 MB/s in the same 60s bursts.+ const resumeAt = t;+ const published: number[] = [];+ for (; t <= resumeAt + 300; t += 1) {+ if ((t - resumeAt) % 60 === 0 && t > resumeAt) bytes += 60 * 20 * MB;+ const rate = publishedRate(samples, t, bytes);+ if (rate > 0) published.push(rate);+ }+ assert.ok(published.length > 0, "the resumed transfer should publish again");+ for (const rate of published) {+ assert.ok(+ Math.abs(rate - 20 * MB) < 1 * MB,+ `published ${(rate / MB).toFixed(2)} MB/s after a resume, want 20`,+ );+ }+});++// One gap is not a rhythm. When the only two increases seen straddle an outage,+// that gap used to become the cadence and size the stall window from itself, so+// the window meant to catch the outage was three times its length: a dead+// transfer published 0.28 MB/s with a 98h ETA for 90 minutes.+test("a lone outage gap is not mistaken for the burst cadence", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ let t = 0;+ for (; t <= 5; t += 1) publishedRate(samples, t, bytes);+ bytes += 500 * MB;+ publishedRate(samples, ++t, bytes);+ for (; t <= 1_800; t += 1) publishedRate(samples, t, bytes);+ bytes += 500 * MB;+ publishedRate(samples, ++t, bytes);+ // Two increases, one gap. Progress now stops for good.+ let published = 0;+ for (const end = t + 5_400; t <= end; t += 1) {+ if (publishedRate(samples, t, bytes) > 0) published += 1;+ }+ assert.equal(+ published,+ 0,+ `published a rate on ${published} ticks after death`,+ );+});++// The same trap one increase later: a normal gap followed by an outage leaves+// gaps of [5, 1800], and taking the upper of two picks the outage, so the stall+// window became 90 minutes and a dead transfer published 0.03 MB/s with a 999h+// ETA on every tick of it. Two defences: the median is not trusted below+// MIN_CADENCE_GAPS, and on an even count it takes the shorter of the middle+// pair, so an outlier needs a majority behind it.+test("a normal gap followed by an outage does not set the cadence", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ for (let t = 0; t <= 3; t += 1) publishedRate(samples, t, bytes);+ bytes += 50 * MB;+ publishedRate(samples, 4, bytes);+ for (let t = 5; t <= 8; t += 1) publishedRate(samples, t, bytes);+ bytes += 50 * MB;+ publishedRate(samples, 9, bytes);+ for (let t = 10; t <= 1_809; t += 1) publishedRate(samples, t, bytes);+ bytes += 50 * MB;+ publishedRate(samples, 1_810, bytes);+ // Three increases, gaps of 5s and 1800s. Progress now stops for good.+ let published = 0;+ for (let t = 1_811; t <= 1_810 + 5_400; t += 1) {+ if (publishedRate(samples, t, bytes) > 0) published += 1;+ }+ assert.equal(+ published,+ 0,+ `published a rate on ${published} ticks after death`,+ );+});++// Half the gaps being outages is still a minority reading of the transfer, not+// a rhythm. Four increases with gaps [5, 5, 1800, 1800] pass the count gate, so+// only the choice of middle value keeps the window off the outage.+test("outages tying with real gaps do not win the median", () => {+ const samples: TransferSample[] = [];+ let bytes = 0;+ let t = 0;+ const burst = () => {+ bytes += 50 * MB;+ publishedRate(samples, t, bytes);+ };+ for (; t <= 3; t += 1) publishedRate(samples, t, bytes);+ burst();+ for (t = 5; t <= 8; t += 1) publishedRate(samples, t, bytes);+ t = 9;+ burst();+ for (t = 10; t <= 13; t += 1) publishedRate(samples, t, bytes);+ t = 14;+ burst();+ for (t = 15; t <= 1_813; t += 1) publishedRate(samples, t, bytes);+ t = 1_814;+ burst();+ for (t = 1_815; t <= 3_613; t += 1) publishedRate(samples, t, bytes);+ t = 3_614;+ burst();+ // gaps: 5, 5, 1800, 1800. Progress now stops for good.+ let published = 0;+ for (t = 3_615; t <= 3_614 + 5_400; t += 1) {+ if (publishedRate(samples, t, bytes) > 0) published += 1;+ }+ assert.equal(+ published,+ 0,+ `published a rate on ${published} ticks after death`,+ );+});+test("a restart drops the samples from the previous run", () => {const samples: TransferSample[] = [];for (let t = 0; t <= 10; t++) publishedRate(samples, t, t * 20 * MB);diff --git a/studio/frontend/tests/transfer-stats-hook-hidden.test.ts b/studio/frontend/tests/transfer-stats-hook-hidden.test.tsnew file mode 100644index 00000000000..330a0982aea--- /dev/null+++ b/studio/frontend/tests/transfer-stats-hook-hidden.test.ts@@ -0,0 +1,87 @@+// 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 training-start overlay reaches the estimator through useTransferStats,+// the fifth caller and the last one without a visibility guard. It polls on a+// 1.5s interval, which a hidden tab clamps to about once a minute, and the+// estimator reads gaps between increases as the burst cadence.+//+// This one bites harder than the other callers because the hook's effect is+// keyed on ``bytes``: a counter that stops moving never runs it again, so+// whatever was last computed stays on screen indefinitely. Measured at 50 MB/s+// with 22 minutes left, still displayed after the transfer was dead and the tab+// visible again.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ type TransferSample,+ appendSample,+ computeTransferStats,+} from "../src/lib/transfer-stats.ts";++const MB = 1e6;++const hookSource = readFileSync(+ new URL("../src/features/chat/hooks/use-transfer-stats.ts", import.meta.url),+ "utf8",+);++test("the shared hook skips sampling while the tab is hidden", () => {+ const guard = hookSource.indexOf("document.hidden");+ assert.ok(guard > 0, "the hook should skip a hidden tab");+ const clear = hookSource.indexOf("samplesRef.current.length = 0", guard);+ const sample = hookSource.indexOf("appendSample(samplesRef.current", guard);+ assert.ok(+ clear > 0 && clear < sample,+ "the hidden branch must clear, not sample",+ );+});++// The effect only runs when bytes change, so model that rather than a timer.+test("a stale estimate does not outlive the transfer that produced it", () => {+ const displayed = (guardHidden: boolean) => {+ const samples: TransferSample[] = [];+ let shown = { rate: 0, stable: false };+ let lastBytes = -1;+ const render = (t: number, bytes: number, hidden: boolean) => {+ if (bytes === lastBytes) return;+ lastBytes = bytes;+ if (guardHidden && hidden) {+ samples.length = 0;+ shown = { rate: 0, stable: false };+ return;+ }+ appendSample(samples, t, bytes);+ const s = computeTransferStats(samples, 100_000 * MB);+ shown = { rate: s.stable ? s.rateBytesPerSecond : 0, stable: s.stable };+ };++ let bytes = 0;+ let t = 0;+ for (; t <= 60; t += 1.5) {+ bytes += 75 * MB;+ render(t, bytes, false);+ }+ // Hidden: the 1.5s interval is clamped to about a minute.+ for (; t <= 660; t += 60) {+ bytes += 3_000 * MB;+ render(t, bytes, true);+ }+ // The transfer stops and the tab comes back. Bytes never change again.+ for (; t <= 660 + 1_800; t += 1.5) render(t, bytes, false);+ return shown;+ };++ assert.ok(+ displayed(false).stable,+ "without the guard the dead transfer should still be showing a rate",+ );+ assert.equal(+ displayed(true).rate,+ 0,+ "with the guard nothing survives the hidden stretch",+ );+});diff --git a/studio/frontend/tests/voice-download-model-switch.test.ts b/studio/frontend/tests/voice-download-model-switch.test.tsnew file mode 100644index 00000000000..0907abf2bbd--- /dev/null+++ b/studio/frontend/tests/voice-download-model-switch.test.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Switching straight from one dictation download to another must restart the+// estimator. The guard once sat AFTER the ref it compares against was assigned,+// so it never fired and the new run was priced over the old one's samples: a+// 5 MB/s download read as 200 MB/s with 20s left. appendSample cannot save it+// either, since a resumed model can start above where the last one stopped.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import {+ type TransferSample,+ appendSample,+ computeTransferStats,+} from "../src/lib/transfer-stats.ts";++const MB = 1e6;++const voiceTabSource = readFileSync(+ new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),+ "utf8",+);++test("the watched model is compared before it is adopted", () => {+ const compare = voiceTabSource.indexOf(+ "download.model !== watchedDownloadRef.current",+ );+ const assign = voiceTabSource.indexOf(+ "watchedDownloadRef.current = download.model",+ );+ assert.ok(compare > 0, "the model-change guard should still exist");+ assert.ok(assign > 0, "the watched model should still be recorded");+ assert.ok(+ compare < assign,+ "comparing after assigning makes the guard unreachable",+ );+});++// What that guard is worth: the same two downloads, with and without the reset.+test("a new model's rate is not priced over the previous model's samples", () => {+ const published = (reset: boolean) => {+ const samples: TransferSample[] = [];+ let watched: string | null = null;+ let rate = 0;+ const poll = (model: string, bytes: number, total: number, t: number) => {+ if (reset && model !== watched) samples.length = 0;+ watched = model;+ appendSample(samples, t, bytes);+ const stats = computeTransferStats(samples, total);+ rate = stats.stable ? stats.rateBytesPerSecond : 0;+ };+ // A fast model finishes 4 GB at 200 MB/s.+ for (let t = 0; t <= 20; t += 1) poll("A", t * 200 * MB, 4_000 * MB, t);+ // Then a slow one resumes from its own 4 GB partial at 5 MB/s. Its counter+ // starts at or above where the last one stopped, so nothing regresses.+ let worst = 0;+ for (let t = 21; t <= 30; t += 1) {+ poll("B", 4_000 * MB + (t - 21) * 5 * MB, 8_000 * MB, t);+ worst = Math.max(worst, rate);+ }+ return worst;+ };++ assert.ok(+ published(true) <= 6 * MB,+ `with the reset, published ${(published(true) / MB).toFixed(1)} MB/s for a 5 MB/s transfer`,+ );+ assert.ok(+ published(false) > 50 * MB,+ "without the reset the old model's samples should still poison the rate",+ );+});