Self-hosted AI workspace.
Python
Merge remote-tracking branch 'origin/main' into visual-pr-playground
pewdiepie-archdaemona10a81d8a555
diff --cc routes/cookbook_routes.pyindex d794aee05,f3fbc4af9..7f2157b1a--- a/routes/cookbook_routes.py+++ b/routes/cookbook_routes.py@@@ -1607,6 -1769,6 +1769,33 @@@ def setup_cookbook_routes() -> APIRoutedisk_tasks = on_disk.get("tasks") or [] if isinstance(on_disk, dict) else []incoming_tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else []++ # Anti-poisoning guard: a stale browser tab can keep POSTing a++ # download task as status='done' from before the strict-finish++ # fix landed, undoing any server-side correction. For each++ # incoming "done" download, override to "running" if the last++ # shard pattern says N<total AND no DOWNLOAD_OK/DOWNLOAD_FAILED/++ # /snapshots/ sentinel is in the output.++ import re as _re_dl++ for _it in incoming_tasks:++ if (not isinstance(_it, dict)) or _it.get("type") != "download" or _it.get("status") != "done":++ continue++ _out = _it.get("output") or ""++ if ("DOWNLOAD_OK" in _out) or ("DOWNLOAD_FAILED" in _out) or ("/snapshots/" in _out):++ continue++ _shards = _re_dl.findall(r"model-(\d+)-of-(\d+)\.safetensors", _out)++ if _shards:++ _n, _tot = _shards[-1]++ if int(_n) < int(_tot):++ logger.info(f"cookbook state POST: rejecting stale done for {_it.get('sessionId')} "++ f"(last shard {_n}/{_tot}, no DOWNLOAD_OK)")++ _it["status"] = "running"++ else:++ _completed = _out.count("Download complete")++ _starts = _out.count("Downloading '")++ if _starts > _completed:++ logger.info(f"cookbook state POST: rejecting stale done for {_it.get('sessionId')} "++ f"({_completed}/{_starts} files complete, no DOWNLOAD_OK)")++ _it["status"] = "running"incoming_ids = {t.get("sessionId") for t in incoming_tasks if isinstance(t, dict) and t.get("sessionId")}import time as _tnow_ms = int(_t.time() * 1000)diff --cc routes/hwfit_routes.pyindex e49b56e14,22995e8b3..a7af18b04--- a/routes/hwfit_routes.py+++ b/routes/hwfit_routes.py@@@ -178,9 -196,67 +196,67 @@@ def setup_hwfit_routes()if target_context is not None:target_context = max(1024, min(target_context, 1000000))- results = rank_models(system, use_case=use_case or None, limit=limit, search=search or None, sort=sort, quant=quant or None, target_context=target_context)+ results = rank_models(system, use_case=use_case or None, limit=limit, search=search or None, sort=sort, quant=quant or None, target_context=target_context, fit_only=fit_only)return {"system": system, "models": results}+ @router.get("/profiles")+ def get_serve_profiles(model: str = "", host: str = "", ssh_port: str = "", platform: str = "", fresh: bool = False, serve_weights_gb: float = 0.0, serve_quant: str = ""):+ """Compute llama.cpp serve profiles (Quality/Balanced/Speed) for `model`+ against the detected hardware on `host` (or local). Returns concrete+ flags (n_gpu_layers, n_cpu_moe, cache_type, ctx) the serve UI can apply.++ `model` is matched against the catalog by name; if it's not in the+ catalog (e.g. an ad-hoc HF repo), pass enough hints via a minimal synthetic+ entry isn't possible here, so we return [] and the UI keeps manual flags.+ """+ from services.hwfit.hardware import detect_system+ from services.hwfit.models import get_models+ from services.hwfit.profiles import compute_serve_profiles+ system = detect_system(host=host, ssh_port=ssh_port, platform=platform, fresh=fresh)+ if system.get("error"):+ return {"system": system, "profiles": [], "error": system["error"]}+ catalog = {m.get("name"): m for m in (get_models() or [])}++ def _norm(s):+ # Normalize for matching: drop org/ prefix, a trailing -GGUF/-gguf+ # marker, and any quant tag, lowercase. So "DeepSeek-Coder-V2-Lite-+ # Instruct-GGUF" (a local folder name) matches catalog entry+ # "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct".+ s = (s or "").lower().strip()+ s = s.split("/")[-1] # drop org prefix+ s = re.sub(r"[-_.]?gguf$", "", s) # drop trailing gguf marker+ s = re.sub(r"[-_.](q\d[^/]*|iq\d[^/]*|fp8|bf16|f16|awq[^/]*|gptq[^/]*)$", "", s)+ return s++ m = catalog.get(model)+ if m is None and model:+ want = _norm(model)+ for name, entry in catalog.items():+ nn = _norm(name)+ if nn and (nn == want or want.endswith(nn) or nn.endswith(want)):+ m = entry+ break+ if m is None:+ return {"system": system, "profiles": [], "error": "model not in catalog"}+ # Surface the model's trained context limit so the serve UI can clamp a+ # user-typed context down to it (asking for ctx > n_ctx_train overflows+ # and, with a quantized KV cache, can crash the GPU).+ model_ctx_max = 0+ for k in ("context_length", "max_position_embeddings", "n_ctx_train", "context"):+ v = m.get(k)+ if isinstance(v, (int, float)) and v > 0:+ model_ctx_max = int(v)+ break+ return {+ "system": system,+ "profiles": compute_serve_profiles(+ system, m,+ serve_weights_gb=(serve_weights_gb or None),+ serve_quant=(serve_quant or None),+ ),+ "model_ctx_max": model_ctx_max,+ }+@router.get("/image-models")def get_image_models(sort: str = "fit", search: str = "", host: str = "", gpu_count: str = "", ssh_port: str = "", platform: str = "", fresh: bool = False, manual_mode: str = "", manual_gpu_count: str = "", manual_vram_gb: str = "", manual_ram_gb: str = "", manual_backend: str = "", ignore_detected_gpu: bool = False, ignore_detected_ram: bool = False):"""Rank image generation models against detected hardware."""diff --cc services/hwfit/models.pyindex 41b8ddcda,b914cc8e3..75885e83f--- a/services/hwfit/models.py+++ b/services/hwfit/models.py@@@ -23,16 -27,14 +27,18 @@@ QUANT_SPEED_MULT =}QUANT_QUALITY_PENALTY = {- "F16": 0.0, "BF16": 0.0, "FP8": 0.0, "INT8": 0.0, "NVFP4": -0.5,- "Q8_0": -0.5, "Q6_K": -1.5, "Q5_K_M": -2.5,+ "F16": 0.0, "BF16": 0.0, "FP8": 0.0,+ "FP4": -3.0, "NVFP4": -3.0, "MXFP4": -3.0, "NF4": -4.0,+ "INT4": -4.0, "INT8": 0.0, "W4A16": -4.0, "W8A8": 0.0, "W8A16": 0.0,+ "Q8_0": 0.0, "Q6_K": -1.0, "Q5_K_M": -2.0,"Q4_K_M": -5.0, "Q4_0": -5.0, "Q3_K_M": -8.0, "Q2_K": -12.0,- "AWQ-4bit": -3.0, "AWQ-8bit": 0.0,- "GPTQ-Int4": -3.0, "GPTQ-Int8": 0.0,- "mlx-4bit": -4.0, "mlx-8bit": 0.0, "mlx-6bit": -1.0,+ # Bare "AWQ" and "AWQ-8bit" used to be 0.0 (tied with FP8). In practice+ # AWQ-anything is a calibrated reconstruction, not raw 8-bit weights —+ # there's a small but real quality loss vs FP8. Give them a slight+ # penalty so FP8 wins when both fit. AWQ-4bit stays heavier.+ "AWQ": -1.0, "AWQ-4bit": -4.0, "AWQ-8bit": -1.0,+ "GPTQ": -1.0, "GPTQ-Int4": -4.0, "GPTQ-Int8": -1.0,+ "mlx-4bit": -4.0, "mlx-8bit": -0.5, "mlx-6bit": -1.5,}QUANT_BYTES_PER_PARAM = {diff --cc static/js/cookbook-hwfit.jsindex 73ec1090c,99e391d11..68ba334a2--- a/static/js/cookbook-hwfit.js+++ b/static/js/cookbook-hwfit.js@@@ -205,14 -188,13 +205,16 @@@ export function _renderGpuToggles(syste} else {btn.classList.add('active');container._activeCount = count;- // Auto-set quant based on hardware selection+ // Auto-suggest a quant based on hardware selection — but ONLY when the+ // user has already picked a specific quant. When they're on "All"+ // (value === ""), leave them on All: toggling a GPU shouldn't silently+ // yank them out of the All view they wanted to see.const quantSel = document.getElementById('hwfit-quant');- if (quantSel) {+ if (quantSel && quantSel.value !== '') {if (count <= 1) {quantSel.value = 'Q4_K_M'; // RAM or 1 GPU -> Q4 sweet spot+ } else if (String(system?.backend || '').toLowerCase() === 'rocm') {+ quantSel.value = 'Q4_K_M'; // ROCm default stays GGUF/local-safe; AWQ is explicit only} else {quantSel.value = 'AWQ-4bit'; // Multi-GPU -> AWQ for vLLM}@@@ -456,7 -449,7 +472,9 @@@ export async function _hwfitFetch(fresfetch(`/api/model/cached?${_cacheParams}`, { credentials: 'same-origin' }).then(r => r.json()).then(d => {-- _cachedModelIds = new Set((d.models || []).map(m => m.repo_id));++ // Exclude stalled (download-shell) entries — a 12 KB README-only++ // folder shouldn't count as "downloaded" in the Scan/Download list.++ _cachedModelIds = new Set((d.models || []).filter(m => m.status !== 'stalled').map(m => m.repo_id));// Re-mark rows if already renderedlist.querySelectorAll('.hwfit-row[data-model]').forEach(row => {const name = row.dataset.model;diff --cc static/js/cookbook.jsindex 529d2e447,fa4b5892d..d60dd2dec--- a/static/js/cookbook.js+++ b/static/js/cookbook.js@@@ -985,6 -1116,6 +1116,7 @@@ function _wireTabEvents(body)document.getElementById('serve-bulk-cancel')?.addEventListener('click', () => {selectBtn.classList.remove('active');++ selectBtn.textContent = 'Select'; // reset label so the button doesn't stay reading "Cancel" after exitbulkBar.classList.add('hidden');document.querySelectorAll('.serve-select-cb').forEach(dot => { dot.style.display = 'none'; dot.classList.remove('selected'); });});@@@ -1003,6 -1134,6 +1135,7 @@@if (item) await _deleteCachedModel(repo, item, true);}selectBtn.classList.remove('active');++ selectBtn.textContent = 'Select'; // same reset as bulk-cancelbulkBar.classList.add('hidden');document.querySelectorAll('.serve-select-cb').forEach(dot => { dot.style.display = 'none'; dot.classList.remove('selected'); });});@@@ -1254,9 -1389,9 +1405,32 @@@// HF token — save on changeconst hfInput = document.getElementById('hwfit-hftoken');if (hfInput) {-- hfInput.addEventListener('change', () => {-- _envState.hfToken = hfInput.value.trim();-- _persistEnvState();++ hfInput.addEventListener('change', async () => {++ const val = hfInput.value.trim();++ _envState.hfToken = val;++ try { await _persistEnvState(); } catch {}++ if (val) {++ _envState.hfTokenConfigured = true;++ const masked = val.length > 6 ? val.slice(0, 3) + '…' + val.slice(-3) : '••••';++ _envState.hfTokenMasked = masked;++ hfInput.placeholder = `Stored (${masked}) - enter a new token to replace`;++ hfInput.value = '';++ let check = hfInput.parentNode.querySelector('.hwfit-hf-check');++ if (!check) {++ check = document.createElement('span');++ check.className = 'hwfit-hf-check';++ check.title = 'Token stored';++ check.textContent = '✓';++ check.style.cssText = 'font-weight:800;color:var(--green,#50fa7b);font-size:15px;line-height:1;flex-shrink:0;position:relative;top:2px;';++ hfInput.parentNode.insertBefore(check, hfInput);++ }++ const flash = document.createElement('span');++ flash.textContent = 'Saved';++ flash.style.cssText = 'margin-left:8px;font-size:11px;color:var(--green,#50fa7b);opacity:0;transition:opacity 0.18s;flex-shrink:0;position:relative;top:1px;';++ hfInput.parentNode.appendChild(flash);++ requestAnimationFrame(() => { flash.style.opacity = '1'; });++ setTimeout(() => { flash.style.opacity = '0'; setTimeout(() => flash.remove(), 220); }, 1400);++ }});}}@@@ -1419,10 -1551,9 +1593,10 @@@ function _renderRecipes()html += `</div>`;html += `<div id="cookbook-hf-latest-list" style="display:none;margin-top:4px;max-height:320px;overflow-y:auto;flex-direction:column;gap:4px;"></div>`;html += `</div>`;+ html += `</div>`; // /#cookbook-dl-tab-fold-body (whole Download card body)// Search section- html += '</div></div></div>';+ html += '</div></div></div></div>';html += '<div class="cookbook-group" data-backend-group="Search">';html += '<div class="admin-card" style="flex:1;display:flex;flex-direction:column;overflow:hidden;">';html += '<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:2px;">';@@@ -1445,13 -1573,21 +1619,21 @@@html += '<option value="Q4_K_M">Q4</option><option value="Q8_0">Q8</option>';html += '<option value="Q6_K">Q6</option><option value="Q5_K_M">Q5</option>';html += '<option value="Q3_K_M">Q3</option><option value="Q2_K">Q2</option>';- html += '<option value="AWQ-4bit">AWQ</option><option value="FP8">FP8</option></select>';- // Ctx slider — ported from origin/main. Lets you target a context length- // for fit estimates; the hwfit ranking uses _ctxValue() to factor that into- // VRAM math, so dragging this re-sorts the list toward models that fit- // your chosen ctx.- html += '<option value="AWQ-4bit">AWQ</option><option value="FP8">FP8</option><option value="FP4">FP4</option><option value="NVFP4">NVFP4</option>';- html += '<option value="">Native</option></select>';- // Engine filter: show only models whose serve engine matches. "llama.cpp"- // (GGUF) runs everywhere incl. consumer AMD/Apple; vLLM/SGLang are CUDA /- // datacenter-ROCm. Filtering is client-side via _detectBackend() in the- // hwfit renderer, so it composes with the quant/type/search filters.++ html += '<option value="AWQ-4bit">AWQ</option><option value="FP8">FP8</option><option value="FP4">FP4</option><option value="NVFP4">NVFP4</option></select>';++ // Engine filter — show only models whose serve engine matches. Composes++ // with quant / type / search filters.+ html += '<select class="cookbook-field-input hwfit-engine" id="hwfit-engine" style="height:28px;" title="Filter by serving engine">';+ html += '<option value="">Engine</option>';+ html += '<option value="llamacpp">llama.cpp</option>';+ html += '<option value="vllm">vLLM</option>';+ html += '<option value="sglang">SGLang</option>';+ html += '</select>';+ html += '<span class="hwfit-help-chip" title="Higher numbers usually mean better quality, but they need more memory. Lower numbers fit on more hardware.">?</span>';++ // Ctx slider — lets you target a context length for fit estimates; the++ // hwfit ranking uses _ctxValue() to factor that into VRAM math, so++ // dragging this re-sorts the list toward models that fit your chosen ctx.html += '<label class="hwfit-ctx-control" title="Context length for fit estimates. Lower it to find more models that could fit your hardware.">';- html += '<span>Ctx</span><input type="range" id="hwfit-context" min="0" max="5" step="1" value="3" />';+ html += '<span>Ctx</span><span class="hwfit-help-chip hwfit-help-chip-inline" title="Context length. Lower it to find more models that could fit your hardware; raise it when you need longer chats or documents.">?</span><input type="range" id="hwfit-context" min="0" max="5" step="1" value="3" />';html += '<output id="hwfit-context-label">50k</output></label>';html += '</div>';html += '<div class="hwfit-toolbar" style="margin-top:7px;">';diff --cc static/js/cookbookRunning.jsindex dc4fac722,fb1d810ff..a215c683f--- a/static/js/cookbookRunning.js+++ b/static/js/cookbookRunning.js@@@ -1475,14 -1800,12 +1800,12 @@@ export function _renderRunningTab()<div class="cookbook-task-header"><span class="cookbook-task-type${(task.status === 'done' && task.type === 'download') ? ' cookbook-task-type-done' : ''}" data-type="${esc(task.type)}">${esc((task.status === 'done' && task.type === 'download') ? 'finished' : task.type)}</span><span class="cookbook-task-name">${modelLogo(task.name)}${esc(task.name)}</span>- <span class="cookbook-task-status ${_bdg.cls}" style="display:${task.status === 'done' ? 'none' : ''}"${_bdgTitle}>${esc(_bdg.text)}</span>- ${task.type === 'serve' && task.payload?._cmd ? '<button class="cookbook-task-edit-btn" title="Edit settings & relaunch"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button>' : ''}- ${task.type === 'serve' && task.payload?._cmd ? '<button class="cookbook-task-save-btn" title="Save preset"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg></button>' : ''}- <span class="cookbook-task-indicator"><span class="cookbook-task-wave" style="display:${task.status === 'running' ? '' : 'none'}"></span><span class="cookbook-task-check" title="Clear" style="display:${(task.status === 'done' && !(task.type === 'download' && !task.payload?._dep)) ? '' : 'none'}"><svg class="cookbook-task-check-ico" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#50fa7b" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg><svg class="cookbook-task-clear-ico" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg><span class="cookbook-task-done-label">done</span><span class="cookbook-task-clear-label">clear</span></span></span>- ${task.type === 'download' && !task.payload?._dep && task.status === 'done' ? `<span class="cookbook-task-status cookbook-task-done">finished</span>` : ''}+ <span class="cookbook-task-indicator"><span class="cookbook-task-wave" style="display:${task.status === 'running' ? '' : 'none'}"></span><span class="cookbook-task-check" title="Clear" style="display:${_canClearTask(task) ? '' : 'none'}"><svg class="cookbook-task-check-ico" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#50fa7b" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg><svg class="cookbook-task-clear-ico" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg><span class="cookbook-task-done-label">${esc(_clearPillLabel(task))}</span><span class="cookbook-task-clear-label">clear</span></span></span>+ <button type="button" class="cookbook-task-start-now" title="Start this queued download now" style="display:${(task.type === 'download' && task.status === 'queued') ? '' : 'none'}"><svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><polygon points="8 5 19 12 8 19 8 5"/></svg><span>start now</span></button>+ <span class="cookbook-task-status ${_bdg.cls}"${_bdgTitle}>${esc(_bdg.text)}</span><button class="cookbook-task-menu-btn" title="Actions">⋮</button></div>-- <div class="cookbook-task-sub"><span class="cookbook-task-session">${esc(task.sessionId)}</span><span class="cookbook-task-uptime" style="display:${((task.type === 'serve' || task.type === 'download') && task.status === 'running') ? '' : 'none'}"></span></div>++ <div class="cookbook-task-sub"><span class="cookbook-task-session">${esc(task.sessionId)}</span><span class="cookbook-task-uptime" style="display:${((task.type === 'serve' || task.type === 'download') && task.status === 'running') ? '' : 'none'}"></span>${(task.type === 'download') ? `<span class="cookbook-task-dldir" title="Download destination" style="font-size:9px;color:var(--fg-muted);font-family:'Fira Code',monospace;opacity:0.4;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:40ch;">Dir: ${esc(task.payload?.local_dir || '~/.cache/huggingface/hub')}</span>` : ''}</div><div class="cookbook-output-wrap cookbook-task-collapsible${_mobileCollapseDefault ? ' cookbook-task-collapsed' : ''}"><pre class="cookbook-output-pre">${esc(task.output || '')}</pre><button type="button" class="copy-code cookbook-output-copy"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button></div>`;@@@ -1571,6 -1874,6 +1874,18 @@@if (_clearChk) {_clearChk.addEventListener('click', (e) => {e.stopPropagation();++ // Belt-and-suspenders: kill the tmux session too. For a real-finished++ // task the session is already gone and kill-session errors silently,++ // but for a task that was falsely flagged done (the strict-finish++ // bug), this guarantees the still-running download actually stops++ // rather than continuing to write to disk after the row is removed.++ try {++ fetch('/api/shell/exec', {++ method: 'POST', credentials: 'same-origin',++ headers: { 'Content-Type': 'application/json' },++ body: JSON.stringify({ command: _tmuxCmd(task, `kill-session -t ${task.sessionId}`) }),++ }).catch(() => {});++ } catch {}_animateOutThenRemove(el, task.sessionId);});}@@@ -2139,14 -2517,12 +2529,37 @@@ async function _reconnectTask(el, taskbreak;}++ // When the snapshot includes a shard-of-N marker (e.g.++ // "model-00006-of-00082.safetensors"), TRUE overall progress is++ // ((shard-1) + currentShardFraction) / totalShards. Before, _dlAgg++ // (hf_transfer's per-current-shard aggregate, e.g. 53% of shard 6)++ // was treated as overall and the row read "53%" while only 5 of++ // 82 shards were actually done.++ const _shardPat = [...snapshot.matchAll(/model-(\d+)-of-(\d+)\.(?:safetensors|bin)/g)];++ const _lastShard = _shardPat.length ? _shardPat[_shardPat.length - 1] : null;++ const _curShardNum = _lastShard ? parseInt(_lastShard[1], 10) : null;++ const _totalShards = _lastShard ? parseInt(_lastShard[2], 10) : null;++ const _useShardAgg = _curShardNum && _totalShards && _totalShards > 1;++// HF's own "Fetching N files: X%" aggregate counts ALL files,// including ones already finished in a previous session (resume) —// so on a resumed download it reflects the true overall progress,// whereas completed/totalFiles only see this session's files (→ 0%).// Take the higher of the two so resume doesn't read as 0%.- const _fetchPctMatches = [...snapshot.matchAll(/Fetching\s+\d+\s+files:\s*(\d+)%/g)];- const _fetchPct = _fetchPctMatches.length ? parseInt(_fetchPctMatches[_fetchPctMatches.length - 1][1]) : null;-- if (_dlAgg != null) {++ if (_useShardAgg) {++ // Multi-shard download: compute TRUE overall as completed shards++ // plus the current shard's fraction. _dlAgg / lastPct represent++ // *this shard's* progress, not the whole download.++ const curShardFrac = (_dlAgg != null)++ ? _dlAgg / 100++ : (lastPct ? parseInt(lastPct, 10) / 100 : 0);++ let overallPct = Math.round((((_curShardNum - 1) + curShardFrac) / _totalShards) * 100);++ if (_fetchPct != null) overallPct = Math.max(overallPct, _fetchPct);++ let text = `${overallPct}%`;++ if (lastSpeed) text += ` · ${lastSpeed}`;++ badge.textContent = text;++ badge.className = 'cookbook-task-status cookbook-task-running';++ } else if (_dlAgg != null) {// Real aggregate byte progress — most accurate; take the max of all signals.let pct = _dlAgg;if (_fetchPct != null) pct = Math.max(pct, _fetchPct);