Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: show byte progress so a single-file HuggingFace download no longer sits at 100%
[._.]/ Adam Eivy2004e28309d9
diff --git a/.changelog/next/fixed-main.md b/.changelog/next/fixed-main.mdindex 63696c4425..11af3a0e1c 100644--- a/.changelog/next/fixed-main.md+++ b/.changelog/next/fixed-main.md@@ -2,3 +2,4 @@- Windows: git worktree add for CoS agents timed out at 30s on a full checkout, blocking tasks with worktree-failed while git actually completed the worktree- Windows: orphaned and merged CoS worktrees were never cleaned up, because git reports POSIX paths while PortOS built Windows ones- Series Autopilot retires a queued gap task when a new run starts, so CoS stops dispatching agents against findings the resumed run has already repaired+- Single-file HuggingFace downloads no longer sit at 100% for the whole transfer — the badge now tracks bytes.diff --git a/client/src/components/media/ModelDownloadBadge.jsx b/client/src/components/media/ModelDownloadBadge.jsxindex 3a5d8a6e67..eabd8f1f5d 100644--- a/client/src/components/media/ModelDownloadBadge.jsx+++ b/client/src/components/media/ModelDownloadBadge.jsx@@ -17,6 +17,7 @@ const STAGE_LABELS = {starting: 'Starting…',list: 'Fetching file list…',download: 'Downloading…',+ verify: 'Verifying…',};export default function ModelDownloadBadge({@@ -40,9 +41,19 @@ export default function ModelDownloadBadge({if (status.downloading) {const frame = status.progress || {};+ const hasBytes = Number.isFinite(frame.downloaded);const pct = typeof frame.progress === 'number' ? Math.round(frame.progress * 100) : null;+ // A 1-file pull used to report 100% the moment the file started. Hide a+ // bare 0% (file just started, no bytes yet) so we don't flash a number+ // that is not a transfer percentage.+ const showPct = pct != null && (hasBytes || pct > 0 || frame.stage === 'verify');const stage = STAGE_LABELS[frame.stage] || (frame.type === 'log' ? 'Downloading…' : (STAGE_LABELS[frame.type] || 'Downloading…'));const fileLine = frame.file ? `${frame.step}/${frame.total} · ${frame.file}` : '';+ const byteLine = hasBytes+ ? (Number.isFinite(frame.totalBytes) && frame.totalBytes > 0+ ? `${formatBytes(frame.downloaded)} / ${formatBytes(frame.totalBytes)}`+ : formatBytes(frame.downloaded))+ : '';return (<div className="mt-1 flex items-center gap-2 text-[11px]"><Loader2 className="w-3.5 h-3.5 animate-spin text-port-accent" />@@ -50,7 +61,7 @@ export default function ModelDownloadBadge({<div className="flex items-center justify-between gap-2 text-port-accent"><span className="truncate">{stage}- {pct != null ? ` ${pct}%` : ''}+ {showPct ? ` ${pct}%` : ''}</span>{onCancel && (<button@@ -65,7 +76,10 @@ export default function ModelDownloadBadge({{fileLine && (<div className="text-[10px] text-gray-500 truncate" title={fileLine}>{fileLine}</div>)}- {pct != null && (+ {byteLine && (+ <div className="text-[10px] text-gray-500 truncate" title={byteLine}>{byteLine}</div>+ )}+ {showPct && (<div className="mt-0.5 h-1 bg-port-border rounded overflow-hidden"><div className="h-full bg-port-accent" style={{ width: `${pct}%` }} /></div>diff --git a/client/src/components/media/ModelDownloadBadge.test.jsx b/client/src/components/media/ModelDownloadBadge.test.jsxindex 6f21414b63..ac094de03a 100644--- a/client/src/components/media/ModelDownloadBadge.test.jsx+++ b/client/src/components/media/ModelDownloadBadge.test.jsx@@ -31,4 +31,66 @@ describe('ModelDownloadBadge', () => {fireEvent.click(button);expect(onDownload).not.toHaveBeenCalled();});++ it('does not treat a 1-file start as 100%', () => {+ render(<ModelDownloadBadge+ status={{+ repo: 'example/encoder',+ cached: false,+ downloading: true,+ progress: {+ type: 'progress',+ stage: 'download',+ progress: 0,+ step: 1,+ total: 1,+ file: 'qwen3vl_32b.safetensors',+ },+ }}+ />);+ expect(screen.getByText('Downloading…')).toBeInTheDocument();+ expect(screen.queryByText(/100%/)).not.toBeInTheDocument();+ expect(screen.getByText('1/1 · qwen3vl_32b.safetensors')).toBeInTheDocument();+ });++ it('shows byte progress for a large single-file pull', () => {+ render(<ModelDownloadBadge+ status={{+ repo: 'example/encoder',+ cached: false,+ downloading: true,+ progress: {+ type: 'progress',+ stage: 'download',+ progress: 0.5,+ step: 1,+ total: 1,+ downloaded: 24 * 1024 * 1024 * 1024,+ totalBytes: 48 * 1024 * 1024 * 1024,+ file: 'qwen3vl_32b.safetensors',+ },+ }}+ />);+ expect(screen.getByText('Downloading… 50%')).toBeInTheDocument();+ expect(screen.getByText('24 GB / 48 GB')).toBeInTheDocument();+ });++ it('labels the post-transfer commit as verifying', () => {+ render(<ModelDownloadBadge+ status={{+ repo: 'example/encoder',+ cached: false,+ downloading: true,+ progress: {+ type: 'progress',+ stage: 'verify',+ progress: 1,+ step: 1,+ total: 1,+ file: 'qwen3vl_32b.safetensors',+ },+ }}+ />);+ expect(screen.getByText('Verifying… 100%')).toBeInTheDocument();+ });});diff --git a/scripts/hf_download_repo.py b/scripts/hf_download_repo.pyindex a8082b9d87..8625986fcd 100755--- a/scripts/hf_download_repo.py+++ b/scripts/hf_download_repo.py@@ -21,6 +21,9 @@ image-gen runners use, so the existing SSE bridge picks it up unchanged):STAGE:list — fetching file listSTAGE:download:<n>/<total>:<filename> — starting file <n> of <total>+ STAGE:bytes:<n>/<total>:<got>/<size>:<filename>+ — byte progress for the current file+ STAGE:verify:<n>/<total>:<filename> — transfer done; committing/hashingDOWNLOAD:<n>/<total>:<filename> — same; redundant for the regexSTAGE:complete:<bytes> — done, with total resident bytesUSER_ERROR:<kind>:<repo> — typed error (gated_repo, …)@@ -33,33 +36,162 @@ import argparseimport inspectimport osimport sys+import threadingfrom pathlib import Path-# `huggingface_hub` is installed in the FLUX.2 venv (and any mflux venv) —-# the caller picks the python binary that has it. Import errors surface as-# a USER_ERROR with a clear "runtime missing huggingface_hub" message so the-# UI can route the user to the applicable model setup panel.-try:- from huggingface_hub import HfApi, hf_hub_download- from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError-except Exception as err: # noqa: BLE001- print(f"USER_ERROR:venv_missing_hf_hub:{err}", file=sys.stderr, flush=True)- print("❌ The selected model runtime is missing huggingface_hub. Use Install / Repair in the Media Generation UI.", file=sys.stderr, flush=True)- sys.exit(2)---# `hf_hub_download(..., local_dir=...)` defaulted to populating `local_dir`-# via symlinks into the HF cache on huggingface_hub < 0.23, which would-# break BYOV installers (HiDream-O1) that need real on-disk files. Force-# real copies with `local_dir_use_symlinks=False`. Newer huggingface_hub-# (>= 0.23) deprecated the kwarg and always copies, eventually removing-# it — probe the signature so we only pass it where it's still accepted.-_HF_DOWNLOAD_ACCEPTS_SYMLINK_KWARG = (- "local_dir_use_symlinks" in inspect.signature(hf_hub_download).parameters-)++# --- Pure helpers (importable without huggingface_hub; covered by the JS suite+# that loads this file via importlib). Keep them above the hub import so a+# missing hub package cannot prevent the tests from reaching them.++def repo_cache_dir(repo_id, cache_root):+ """HF hub folder for a repo: `<cache_root>/models--org--name`."""+ return Path(cache_root) / f"models--{str(repo_id).replace('/', '--')}"+++def incomplete_bytes(cache_dir):+ """Sum of `*.incomplete` sizes under a repo cache dir (0 if none)."""+ root = Path(cache_dir)+ if not root.is_dir():+ return 0+ total = 0+ for path in root.rglob("*.incomplete"):+ try:+ total += path.stat().st_size+ except OSError:+ pass+ return total+++def format_bytes_stage(step, total_files, downloaded, total_bytes, filename):+ return (+ f"STAGE:bytes:{int(step)}/{int(total_files)}:"+ f"{int(downloaded)}/{int(total_bytes)}:{filename}"+ )+++def format_verify_stage(step, total_files, filename):+ return f"STAGE:verify:{int(step)}/{int(total_files)}:{filename}"+++class ByteProgressWatcher:+ """Poll the HF incomplete blob and emit STAGE:bytes / STAGE:verify.++ huggingface_hub (HTTP and xet) writes the in-flight weight to+ `*.incomplete` under the repo cache. File-count progress is 1/1 the moment+ a single-file pull starts, which made a 50 GB conditioner look "done" for+ the entire transfer. This watcher is the byte signal the badge needs.++ When the incomplete file disappears after having grown, the hub is+ committing/hashing — emit STAGE:verify so the UI does not sit on a stale+ "Downloading… 100%" with no further movement.+ """++ def __init__(self, cache_dir, filename, step, total_files, expected, interval=0.5):+ self.cache_dir = Path(cache_dir)+ self.filename = filename+ self.step = step+ self.total_files = total_files+ self.expected = int(expected or 0)+ self.interval = interval+ self._stop = threading.Event()+ self._thread = None+ self._last_n = 0+ self._saw_bytes = False++ def _emit_bytes(self, n):+ print(+ format_bytes_stage(self.step, self.total_files, n, self.expected, self.filename),+ file=sys.stderr,+ flush=True,+ )++ def _run(self):+ n = incomplete_bytes(self.cache_dir)+ self._last_n = n+ if n > 0:+ self._saw_bytes = True+ self._emit_bytes(n)+ while not self._stop.wait(self.interval):+ n = incomplete_bytes(self.cache_dir)+ if n > 0:+ self._saw_bytes = True+ if n == 0 and self._saw_bytes:+ # Transfer finished; hub is renaming + hashing the blob.+ self._emit_bytes(self.expected or self._last_n)+ print(+ format_verify_stage(self.step, self.total_files, self.filename),+ file=sys.stderr,+ flush=True,+ )+ self._stop.wait()+ return+ if n != self._last_n:+ self._last_n = n+ self._emit_bytes(n)++ def start(self):+ self._thread = threading.Thread(target=self._run, name="hf-byte-progress", daemon=True)+ self._thread.start()++ def stop(self):+ self._stop.set()+ if self._thread is not None:+ self._thread.join(timeout=2)++ def __enter__(self):+ self.start()+ return self++ def __exit__(self, *exc):+ self.stop()+ return False+++def _hub_cache_root():+ # huggingface_hub.constants.HF_HUB_CACHE already honors HF_HUB_CACHE /+ # HF_HOME. Importing here (not at module load) keeps the helpers above+ # testable without the package.+ from huggingface_hub.constants import HF_HUB_CACHE+ return HF_HUB_CACHE+++def _expected_file_size(repo, filename, revision, token):+ try:+ from huggingface_hub import get_hf_file_metadata, hf_hub_url+ meta = get_hf_file_metadata(+ hf_hub_url(repo_id=repo, filename=filename, revision=revision),+ token=token,+ )+ size = getattr(meta, "size", None)+ return int(size) if size else 0+ except Exception: # noqa: BLE001+ return 0def main() -> int:+ # `huggingface_hub` is installed in the FLUX.2 venv (and any mflux venv) —+ # the caller picks the python binary that has it. Import errors surface as+ # a USER_ERROR with a clear "runtime missing huggingface_hub" message so the+ # UI can route the user to the applicable model setup panel.+ try:+ from huggingface_hub import HfApi, hf_hub_download+ from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError+ except Exception as err: # noqa: BLE001+ print(f"USER_ERROR:venv_missing_hf_hub:{err}", file=sys.stderr, flush=True)+ print("❌ The selected model runtime is missing huggingface_hub. Use Install / Repair in the Media Generation UI.", file=sys.stderr, flush=True)+ return 2++ # `hf_hub_download(..., local_dir=...)` defaulted to populating `local_dir`+ # via symlinks into the HF cache on huggingface_hub < 0.23, which would+ # break BYOV installers (HiDream-O1) that need real on-disk files. Force+ # real copies with `local_dir_use_symlinks=False`. Newer huggingface_hub+ # (>= 0.23) deprecated the kwarg and always copies, eventually removing+ # it — probe the signature so we only pass it where it's still accepted.+ accepts_symlink_kwarg = (+ "local_dir_use_symlinks" in inspect.signature(hf_hub_download).parameters+ )+parser = argparse.ArgumentParser(description="Pre-fetch a HuggingFace repo snapshot.")parser.add_argument("--repo", required=True, help="HF repo id, e.g. 'org/name'.")parser.add_argument("--revision", default=None, help="Optional revision (branch / tag / sha).")@@ -129,6 +261,7 @@ def main() -> int:print(f"❌ Repository {args.repo} reports zero downloadable files.", file=sys.stderr, flush=True)return 2+ cache_dir = repo_cache_dir(args.repo, _hub_cache_root())total_bytes = 0for i, filename in enumerate(files, start=1):# Stage marker (UI-friendly) + DOWNLOAD: marker (matches the existing@@ -146,10 +279,12 @@ def main() -> int:# Only force copies when the caller actually asked for a flat# on-disk layout — without `--local-dir`, hf_hub_download writes# into the standard HF cache where symlinks are the contract.- if args.local_dir and _HF_DOWNLOAD_ACCEPTS_SYMLINK_KWARG:+ if args.local_dir and accepts_symlink_kwarg:download_kwargs["local_dir_use_symlinks"] = False+ expected = _expected_file_size(args.repo, filename, args.revision, token)try:- resolved = hf_hub_download(**download_kwargs)+ with ByteProgressWatcher(cache_dir, filename, i, total, expected):+ resolved = hf_hub_download(**download_kwargs)except GatedRepoError:print(f"USER_ERROR:gated_repo:{args.repo}", file=sys.stderr, flush=True)print(f"❌ {args.repo} is gated. Accept its license, save your Hugging Face token in Media Generation settings, then retry.", file=sys.stderr, flush=True)diff --git a/scripts/hf_download_repo.test.js b/scripts/hf_download_repo.test.jsnew file mode 100644index 0000000000..f607380106--- /dev/null+++ b/scripts/hf_download_repo.test.js@@ -0,0 +1,61 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const script = join(dirname(fileURLToPath(import.meta.url)), 'hf_download_repo.py');+const pyBin = resolveTestPython();+const runPython = (source) => execFileSync(pyBin, ['-c', source, script], {+ encoding: 'utf8',+});++const importHelper = [+ 'import importlib.util, sys',+ 'from pathlib import Path',+ 'script = Path(sys.argv[1])',+ 'spec = importlib.util.spec_from_file_location("hf_download_repo", script)',+ 'helper = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(helper)',+].join('\n');++describe.skipIf(!pyBin)('hf_download_repo.py helpers', () => {+ it('maps a repo id onto the HF hub cache folder name', () => {+ const output = runPython(`${importHelper}+print(helper.repo_cache_dir("ethanfel/Qwen3-VL-32B", "/tmp/hf-hub"))+`);+ expect(output.trim()).toMatch(/models--ethanfel--Qwen3-VL-32B$/);+ });++ it('sums only incomplete blobs under the repo cache', () => {+ const output = runPython(`${importHelper}+import tempfile+with tempfile.TemporaryDirectory() as temp:+ root = Path(temp)+ blobs = root / "blobs"+ blobs.mkdir()+ (blobs / "aaa.incomplete").write_bytes(b"x" * 100)+ (blobs / "bbb.incomplete").write_bytes(b"y" * 50)+ (blobs / "done").write_bytes(b"z" * 999)+ print(helper.incomplete_bytes(root))+`);+ expect(output.trim()).toBe('150');+ });++ it('returns 0 when the cache dir does not exist yet', () => {+ const output = runPython(`${importHelper}+print(helper.incomplete_bytes("/tmp/portos-hf-cache-does-not-exist"))+`);+ expect(output.trim()).toBe('0');+ });++ it('formats the STAGE:bytes / STAGE:verify wire lines the JS parser expects', () => {+ const output = runPython(`${importHelper}+print(helper.format_bytes_stage(1, 1, 26843545600, 51506295440, "qwen3vl.safetensors"))+print(helper.format_verify_stage(1, 1, "qwen3vl.safetensors"))+`);+ const [bytes, verify] = output.trim().split('\n');+ expect(bytes).toBe('STAGE:bytes:1/1:26843545600/51506295440:qwen3vl.safetensors');+ expect(verify).toBe('STAGE:verify:1/1:qwen3vl.safetensors');+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex b84a1abd46..6f42e2dd02 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -142,7 +142,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `hfToken.js` | HuggingFace token resolution (settings > env > CLI): `getHfToken` / `getHfTokenInfo` / `hfTokenEnv`, plus `hfChildEnv(extra?)` for a complete Malloc-stripped child environment that preserves inherited variables while injecting the resolved token. || `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. || `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId,{revision?})` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep,revision?})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep,revision?})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoSnapshot(repoId,revision)` resolves an immutable local snapshot; `findCachedRepoFile(repoId,filename,{revision?})` resolves ONE known file without walking it; `isSafeHfRepoRelativePath` rejects traversal/absolute dependency filenames; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that revision-aware exact-file contract to pinned adapter pairs; and `repairCachedFile(path,{snapshotPath?})` is the containment-checked matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |-| `hfDownload.js` | `downloadHfRepo({repo,revision?,only?,onEvent,pythonPath?})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in a caller-preferred runtime or the shared fallback venvs and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. |+| `hfDownload.js` | `downloadHfRepo({repo,revision?,only?,onEvent,pythonPath?})` returning `{promise,kill}` — spawns `scripts/hf_download_repo.py` in a caller-preferred runtime or the shared fallback venvs and emits SSE-friendly stage/progress/complete events. Powers the inline "Download" button next to the model picker. `parseHfDownloadLine(line)` is the wire decoder (`STAGE:download` / `STAGE:bytes` / `STAGE:verify` / `STAGE:complete` / `USER_ERROR`) so a single-file multi-GB pull reports byte progress instead of sitting at 100% for the whole transfer. || `icLoraWeights.js` | IC-LoRA weight registry for the local LTX-2 remix modes (`IC_LORA_MODES`, `IC_LORA_MODE_VALUES`, `listIcLoraWeights()`, `isIcLoraMode(mode)`, `icLoraSpecForMode(mode)`, `icLoraRepos()`, `icLoraWeightCandidates(spec)`, `findCachedIcLoraWeight(spec)`, `resolveIcLoraWeight(mode)` → `{path,cached,spec}`). Single source of truth mapping each remix mode (`ic-control`, `ic-colorize`, `ic-ingredients`) → its HF repo/filename, reference-count rule, per-weight `referenceDownscaleFactor` (read from the weight's safetensors metadata, never assumed), and input surface (`referenceKind: 'video' | 'image'`). A `requiresPreDownload` spec (Ingredients) suppresses `resolveIcLoraWeight`'s bare-repo-id fallback — the pipeline would `snapshot_download` it, and its candidates are a gated first-party repo plus a ~708 GB aggregate mirror, so the weight must be pre-fetched single-file instead. Also owns the two rules derived from that data: `assertIcReferenceCount(spec,count,fail)` / `describeIcReferenceRange(spec)` and `icResolutionIssue(spec,w,h)` (the output-resolution divisibility its reference encoder imposes). Mirrored to `client/src/lib/videoGenParams.js`; `icLoraWeights.parity.test.js` diffs the two. || `sseHeaders.js` | `SSE_HEADERS` — the canonical SSE response headers (incl. `X-Accel-Buffering:no`) in a dependency-free module so any producer (`sseDownload.js`, `sseUtils.js`) can share them without pulling in a heavier module's transitive imports. || `sseDownload.js` | `startHfDownloadStream({req,res,repo|repos|fallbacks,alreadyDownloadedMessage,pythonPath?})`, `openSseStream(res)` — shared SSE driver for model downloads. Required targets may name an immutable `revision` and exact `only` files, fallback chains are first-success, and the cross-route in-flight Map deduplicates pulls. |diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.jsindex ee27f93e22..77a6a3f378 100644--- a/server/lib/hfDownload.js+++ b/server/lib/hfDownload.js@@ -9,7 +9,9 @@//// Wire protocol parses the stdout/stderr lines from scripts/hf_download_repo.py:// STAGE:list -> { type: 'stage', stage: 'list' }-// STAGE:download:<n>/<total>:<file> -> stage + progress n/total+// STAGE:download:<n>/<total>:<file> -> progress at the START of file n+// STAGE:bytes:<n>/<total>:<got>/<size>:<file> -> byte progress for file n+// STAGE:verify:<n>/<total>:<file> -> transfer done; committing/hashing// STAGE:complete:<bytes> -> { type: 'complete', sizeBytes }// USER_ERROR:<kind>:<detail> -> typed-error capture; <detail>// is the repo id for list/auth@@ -17,6 +19,9 @@// for per-file download errors// ❌ <prose> -> errorMessage// Unknown lines fall through as raw `{ type: 'log', message }`.+//+// parseHfDownloadLine is the single decoder — downloadHfRepo and the tests+// share it so a wire-shape change cannot drift between them.import { spawn } from 'node:child_process';import { join } from 'node:path';@@ -32,6 +37,116 @@ import { getSettings } from '../services/settings.js';const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'hf_download_repo.py');+/**+ * Decode one helper stdout/stderr line into a typed action.+ *+ * { type: 'event', event } — emit via onEvent+ * { type: 'complete', sizeBytes } — record resident bytes; do not emit yet+ * { type: 'user_error', errorKind }+ * { type: 'error_message', message }+ * { type: 'ignore' }+ */+export function parseHfDownloadLine(raw) {+ const line = String(raw).trim();+ if (!line) return { type: 'ignore' };++ if (line.startsWith('STAGE:')) {+ const body = line.slice('STAGE:'.length);+ const colon = body.indexOf(':');+ const stage = colon === -1 ? body : body.slice(0, colon);+ const detail = colon === -1 ? '' : body.slice(colon + 1);++ if (stage === 'download') {+ // `3/47:model-00003-of-00047.safetensors` — this fires when a file+ // STARTS, so the bar sits at the beginning of that file. Using+ // step/total here made a 1-file 50 GB pull report 100% for the entire+ // transfer.+ const m = detail.match(/^(\d+)\/(\d+):(.+)$/);+ if (m) {+ const step = parseInt(m[1], 10);+ const total = parseInt(m[2], 10);+ return {+ type: 'event',+ event: {+ type: 'progress',+ stage: 'download',+ progress: total > 0 ? (step - 1) / total : 0,+ step,+ total,+ file: m[3],+ },+ };+ }+ }++ if (stage === 'bytes') {+ // `1/1:26843545600/51506295440:qwen3vl_….safetensors`+ const m = detail.match(/^(\d+)\/(\d+):(\d+)\/(\d+):(.+)$/);+ if (m) {+ const step = parseInt(m[1], 10);+ const files = parseInt(m[2], 10);+ const downloaded = parseInt(m[3], 10);+ const totalBytes = parseInt(m[4], 10);+ const fileFrac = totalBytes > 0 ? Math.min(1, downloaded / totalBytes) : 0;+ return {+ type: 'event',+ event: {+ type: 'progress',+ stage: 'download',+ progress: files > 0 ? ((step - 1) + fileFrac) / files : fileFrac,+ step,+ total: files,+ downloaded,+ totalBytes,+ file: m[5],+ },+ };+ }+ }++ if (stage === 'verify') {+ const m = detail.match(/^(\d+)\/(\d+):(.+)$/);+ if (m) {+ const step = parseInt(m[1], 10);+ const total = parseInt(m[2], 10);+ return {+ type: 'event',+ event: {+ type: 'progress',+ stage: 'verify',+ progress: total > 0 ? step / total : 1,+ step,+ total,+ file: m[3],+ },+ };+ }+ }++ if (stage === 'complete') {+ const bytes = parseInt(detail, 10);+ return { type: 'complete', sizeBytes: Number.isFinite(bytes) ? bytes : 0 };+ }++ return { type: 'event', event: { type: 'stage', stage, detail } };+ }++ if (line.startsWith('USER_ERROR:')) {+ const body = line.slice('USER_ERROR:'.length);+ const colon = body.indexOf(':');+ return { type: 'user_error', errorKind: colon === -1 ? body : body.slice(0, colon) };+ }++ if (line.startsWith('❌')) {+ return { type: 'error_message', message: line.replace(/^❌\s*/, '') };+ }++ // Mirrored by STAGE:download — the helper prints both so older regexes still match.+ if (line.startsWith('DOWNLOAD:')) return { type: 'ignore' };++ return { type: 'event', event: { type: 'log', message: line } };+}+// Resolve a Python interpreter with huggingface_hub installed. Order: FLUX.2// venv (the modern path; always has hf_hub via diffusers), then the// settings.imageGen.local.pythonPath (mflux installs), then any provisioned@@ -114,54 +229,23 @@ export function downloadHfRepo({ repo, revision = null, only = null, pythonPath:if (killed) proc.kill('SIGTERM');const handleLine = (raw) => {- const line = raw.trim();- if (!line) return;- if (line.startsWith('STAGE:')) {- // STAGE:<name>[:rest]. Special-case the file-progress + complete- // shapes so the UI can render a real progress bar; everything- // else falls through as a generic stage event.- const body = line.slice('STAGE:'.length);- const colon = body.indexOf(':');- const stage = colon === -1 ? body : body.slice(0, colon);- const detail = colon === -1 ? '' : body.slice(colon + 1);- if (stage === 'download') {- // detail looks like `3/47:model-00003-of-00047.safetensors`- const m = detail.match(/^(\d+)\/(\d+):(.+)$/);- if (m) {- const step = parseInt(m[1], 10);- const total = parseInt(m[2], 10);- onEvent({- type: 'progress',- progress: total > 0 ? step / total : 0,- step,- total,- file: m[3],- });- return;- }- }- if (stage === 'complete') {- const bytes = parseInt(detail, 10);- if (Number.isFinite(bytes)) sizeBytes = bytes;- // Don't emit a `complete` event here — wait for the close- // handler so a successful exit code is required.- return;- }- onEvent({ type: 'stage', stage, detail });+ const parsed = parseHfDownloadLine(raw);+ if (parsed.type === 'ignore') return;+ if (parsed.type === 'complete') {+ sizeBytes = parsed.sizeBytes;+ // Don't emit a `complete` event here — wait for the close+ // handler so a successful exit code is required.return;}- if (line.startsWith('USER_ERROR:')) {- const body = line.slice('USER_ERROR:'.length);- const colon = body.indexOf(':');- errorKind = colon === -1 ? body : body.slice(0, colon);+ if (parsed.type === 'user_error') {+ errorKind = parsed.errorKind;return;}- if (line.startsWith('❌')) {- errorMessage = line.replace(/^❌\s*/, '');+ if (parsed.type === 'error_message') {+ errorMessage = parsed.message;return;}- if (line.startsWith('DOWNLOAD:')) return; // mirrored by STAGE:download- onEvent({ type: 'log', message: line });+ onEvent(parsed.event);};// Line-buffer across chunks so a STAGE:/USER_ERROR: marker split acrossdiff --git a/server/lib/hfDownload.test.js b/server/lib/hfDownload.test.jsnew file mode 100644index 0000000000..415132b785--- /dev/null+++ b/server/lib/hfDownload.test.js@@ -0,0 +1,103 @@+import { describe, expect, it } from 'vitest';+import { parseHfDownloadLine } from './hfDownload.js';++describe('parseHfDownloadLine', () => {+ it('treats an empty line as ignore', () => {+ expect(parseHfDownloadLine('')).toEqual({ type: 'ignore' });+ expect(parseHfDownloadLine(' \n')).toEqual({ type: 'ignore' });+ });++ it('places file-start progress at the beginning of that file, not 100% of 1/1', () => {+ expect(parseHfDownloadLine(+ 'STAGE:download:1/1:qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors',+ )).toEqual({+ type: 'event',+ event: {+ type: 'progress',+ stage: 'download',+ progress: 0,+ step: 1,+ total: 1,+ file: 'qwen3vl_32b_h3_ultra_uncensored_heretic_bf16.safetensors',+ },+ });+ });++ it('places a mid-repo file start at (n-1)/total', () => {+ expect(parseHfDownloadLine('STAGE:download:3/47:model-00003-of-00047.safetensors').event)+ .toMatchObject({ progress: 2 / 47, step: 3, total: 47 });+ });++ it('decodes byte progress for a single-file pull', () => {+ const downloaded = 26843545600;+ const totalBytes = 51506295440;+ const parsed = parseHfDownloadLine(+ `STAGE:bytes:1/1:${downloaded}/${totalBytes}:qwen3vl_32b.safetensors`,+ );+ expect(parsed.type).toBe('event');+ expect(parsed.event).toMatchObject({+ type: 'progress',+ stage: 'download',+ step: 1,+ total: 1,+ downloaded,+ totalBytes,+ file: 'qwen3vl_32b.safetensors',+ });+ expect(parsed.event.progress).toBeCloseTo(downloaded / totalBytes);+ });++ it('folds the current file\'s byte fraction into a multi-file bar', () => {+ const parsed = parseHfDownloadLine('STAGE:bytes:2/4:50/100:shard-00002.safetensors');+ expect(parsed.event.progress).toBeCloseTo((1 + 0.5) / 4);+ });++ it('treats a zero-size total as no file fraction (still reports downloaded)', () => {+ expect(parseHfDownloadLine('STAGE:bytes:1/1:4096/0:weights.safetensors').event)+ .toMatchObject({ progress: 0, downloaded: 4096, totalBytes: 0 });+ });++ it('decodes the post-transfer verify stage as a completed-file bar', () => {+ expect(parseHfDownloadLine('STAGE:verify:1/1:weights.safetensors')).toEqual({+ type: 'event',+ event: {+ type: 'progress',+ stage: 'verify',+ progress: 1,+ step: 1,+ total: 1,+ file: 'weights.safetensors',+ },+ });+ });++ it('records STAGE:complete bytes without emitting an event', () => {+ expect(parseHfDownloadLine('STAGE:complete:51506295440'))+ .toEqual({ type: 'complete', sizeBytes: 51506295440 });+ });++ it('falls through unknown stages as a generic stage event', () => {+ expect(parseHfDownloadLine('STAGE:list')).toEqual({+ type: 'event',+ event: { type: 'stage', stage: 'list', detail: '' },+ });+ });++ it('captures USER_ERROR kind and prose error messages', () => {+ expect(parseHfDownloadLine('USER_ERROR:gated_repo:org/model'))+ .toEqual({ type: 'user_error', errorKind: 'gated_repo' });+ expect(parseHfDownloadLine('❌ Access to org/model is gated.'))+ .toEqual({ type: 'error_message', message: 'Access to org/model is gated.' });+ });++ it('ignores the redundant DOWNLOAD: mirror line', () => {+ expect(parseHfDownloadLine('DOWNLOAD:1/1:weights.safetensors')).toEqual({ type: 'ignore' });+ });++ it('passes unknown prose through as a log event', () => {+ expect(parseHfDownloadLine('still going')).toEqual({+ type: 'event',+ event: { type: 'log', message: 'still going' },+ });+ });+});diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.jsindex b501f2885d..428f101938 100644--- a/server/lib/sseDownload.js+++ b/server/lib/sseDownload.js@@ -158,7 +158,9 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,only: singleFile ? onlyFiles : null,pythonPath,onEvent: (ev) => {- if (ev.type === 'progress' && ev.file) {+ // File-start frames only. Byte ticks arrive several times a second on+ // a large single-file pull and would drown the PM2 log.+ if (ev.type === 'progress' && ev.file && ev.downloaded == null && ev.stage !== 'verify') {console.log(`⬇️ ${r}: ${ev.file} (${ev.step}/${ev.total})`);}// A failure that we're about to retry against the next candidate isn't adiff --git a/server/lib/sseDownload.test.js b/server/lib/sseDownload.test.jsindex 4d0be8333b..5584abadca 100644--- a/server/lib/sseDownload.test.js+++ b/server/lib/sseDownload.test.js@@ -134,6 +134,34 @@ describe('startHfDownloadStream server-side logging', () => {expect(errorSpy).not.toHaveBeenCalled();});+ it('does not log every byte-progress tick', async () => {+ inspectModelCache.mockResolvedValue({ cached: false });+ downloadHfRepo.mockImplementation(({ onEvent }) => ({+ promise: (async () => {+ onEvent({+ type: 'progress', stage: 'download', step: 1, total: 1,+ file: 'weights.safetensors',+ });+ onEvent({+ type: 'progress', stage: 'download', step: 1, total: 1,+ file: 'weights.safetensors', downloaded: 1024, totalBytes: 4096,+ });+ onEvent({+ type: 'progress', stage: 'download', step: 1, total: 1,+ file: 'weights.safetensors', downloaded: 2048, totalBytes: 4096,+ });+ return { ok: true, sizeBytes: 4096 };+ })(),+ kill: vi.fn(),+ }));++ const { req, res } = makeLoggingReqRes();+ await startHfDownloadStream({ req, res, repo: 'org/big-file' });++ const fileLines = logged(logSpy).filter((l) => l.includes('org/big-file: weights.safetensors'));+ expect(fileLines).toHaveLength(1);+ });+it('logs the forced re-fetch marker', async () => {inspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 10 });downloadHfRepo.mockImplementation(() => ({