Skip to content

The agent that grows with you

feat(local-runtime): live progress through runtime download/unpack + quickstart hero

emozilla70951b7e44f8
diff --git a/apps/desktop/src/app/settings/local-models-settings.tsx b/apps/desktop/src/app/settings/local-models-settings.tsx
index bc5a42b0e91..09c368b8401 100644
--- a/apps/desktop/src/app/settings/local-models-settings.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.tsx
@@ -235,54 +235,98 @@ export function LocalModelsSettings() {
// ── Quickstart: the dummy-proof front door ──
// Until something is servable (runtime + at least one model), the pane
- // leads with one button that does everything; the full pane stays one
- // 'Configure…' click away. A running quickstart pins this view so its
- // progress has a home even after a remount.
+ // leads with a hero that does everything in one click; the full pane
+ // stays one 'Configure…' click away. A running quickstart pins this
+ // view so its progress has a home even after a remount.
const qJob = jobs.find(j => j.kind === 'quickstart' && j.status === 'running') ?? null
const needsSetup = !status.runtime_installed || status.models.length === 0
const heroModel = catalog.find(c => c.recommended && c.fits) ?? catalog.find(c => c.fits) ?? null
if (qJob || (needsSetup && !configure && heroModel)) {
+ // Stage rail derived from the job phase: engine -> model -> finish.
+ const phase = qJob?.phase ?? ''
+ const stageIndex = ['starting-server', 'setting-default'].includes(phase)
+ ? 2
+ : phase === 'downloading'
+ ? 1
+ : 0
+ const stages = [copy.quickstartStageEngine, copy.quickstartStageModel, copy.quickstartStageFinish]
+
return (
<SettingsContent>
- <SettingsSection icon={Zap} title={copy.quickstartTitle}>
- {qJob ? (
- <ListRow
- below={<ProgressBar percent={qJob.percent} />}
- description={qJob.detail || copy.installing}
- title={
- <span className="inline-flex items-center gap-2">
- <Loader2 className="size-3.5 animate-spin" />
- {qJob.target}
- </span>
- }
- />
- ) : heroModel ? (
- <ListRow
- action={
- <div className="flex items-center gap-2">
+ <div className="flex min-h-[60dvh] items-center justify-center">
+ <div className="w-full max-w-md text-center">
+ <div className="mx-auto mb-5 flex size-14 items-center justify-center rounded-2xl bg-primary/10">
+ {qJob ? (
+ <Loader2 className="size-7 animate-spin text-primary" />
+ ) : (
+ <Cpu className="size-7 text-primary" />
+ )}
+ </div>
+
+ <h2 className="text-lg font-semibold text-foreground">
+ {qJob ? qJob.target : (heroModel?.display_name ?? '')}
+ </h2>
+
+ {qJob ? (
+ <>
+ <p className="mt-2 min-h-10 text-[0.8rem] leading-5 text-muted-foreground">
+ {qJob.detail || copy.installing}
+ </p>
+
+ <div className="mt-5">
+ <ProgressBar percent={qJob.percent} />
+ </div>
+
+ {/* Stage rail: engine -> model -> finish. */}
+ <div className="mt-5 flex items-center justify-center gap-5">
+ {stages.map((label, i) => (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 text-[0.72rem]',
+ i < stageIndex && 'text-(--ui-text-tertiary)',
+ i === stageIndex && 'font-medium text-foreground',
+ i > stageIndex && 'text-(--ui-text-tertiary) opacity-60'
+ )}
+ key={label}
+ >
+ {i < stageIndex ? (
+ <CheckCircle2 className="size-3.5 text-primary" />
+ ) : i === stageIndex ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <span className="size-1.5 rounded-full bg-current" />
+ )}
+ {label}
+ </span>
+ ))}
+ </div>
+ </>
+ ) : heroModel ? (
+ <>
+ <p className="mt-2 text-[0.8rem] leading-5 text-muted-foreground">
+ {heroModel.downloaded
+ ? copy.quickstartDetailReady(heroModel.display_name)
+ : copy.quickstartDetail(heroModel.display_name, heroModel.size_label)}
+ </p>
+
+ <div className="mt-6 flex items-center justify-center gap-3">
<Button onClick={() => setConfigure(true)} size="sm" variant="outline">
{copy.quickstartConfigure}
</Button>
- <Button onClick={() => void handleQuickstart()} size="sm">
+ <Button onClick={() => void handleQuickstart()} size="default">
<Zap />
{copy.quickstartAction}
</Button>
</div>
- }
- description={
- heroModel.downloaded
- ? copy.quickstartDetailReady(heroModel.display_name)
- : copy.quickstartDetail(heroModel.display_name, heroModel.size_label)
- }
- title={heroModel.display_name}
- />
- ) : null}
+ </>
+ ) : null}
- {lastError?.kind === 'quickstart' && (
- <p className="text-[0.75rem] text-destructive">{lastError.error}</p>
- )}
- </SettingsSection>
+ {lastError?.kind === 'quickstart' && !qJob && (
+ <p className="mt-4 text-[0.75rem] text-destructive">{lastError.error}</p>
+ )}
+ </div>
+ </div>
</SettingsContent>
)
}
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 637a4b49ca2..834ca545011 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -1112,6 +1112,9 @@ export const en: Translations = {
quickstartConfigure: 'Configure…',
quickstartDoneToast: model => `${model} is set up — new chats run on this machine.`,
quickstartFailed: 'Local model setup failed',
+ quickstartStageEngine: 'Engine',
+ quickstartStageModel: 'Model',
+ quickstartStageFinish: 'Finish',
useAction: 'Use',
activePill: 'Default',
updateTitle: 'Engine update available',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index d787e7ae2a0..8cc94ccd510 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -961,6 +961,9 @@ export interface Translations {
quickstartConfigure: string
quickstartDoneToast: (model: string) => string
quickstartFailed: string
+ quickstartStageEngine: string
+ quickstartStageModel: string
+ quickstartStageFinish: string
useAction: string
activePill: string
updateTitle: string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 8ea3fdedb8b..dad31515558 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1294,6 +1294,9 @@ export const zh: Translations = {
quickstartConfigure: '自定义…',
quickstartDoneToast: model => `${model} 已就绪——新会话将在本机运行。`,
quickstartFailed: '本地模型设置失败',
+ quickstartStageEngine: '引擎',
+ quickstartStageModel: '模型',
+ quickstartStageFinish: '完成',
hardwareTitle: '本机配置',
hardwareLoading: '正在检测硬件…',
vram: label => `${label} 显存`,
diff --git a/hermes_cli/local_runtime/binaries.py b/hermes_cli/local_runtime/binaries.py
index 3e8b5dc6a65..a6ce421de7c 100644
--- a/hermes_cli/local_runtime/binaries.py
+++ b/hermes_cli/local_runtime/binaries.py
@@ -23,6 +23,7 @@ import urllib.request
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
+from typing import Callable
from hermes_constants import get_hermes_home
@@ -200,22 +201,52 @@ def _sha256(path: Path) -> str:
return h.hexdigest()
-def _download(url: str, dest: Path) -> None:
+def _download(url: str, dest: Path,
+ progress: "Callable[[int, int], None] | None" = None) -> None:
+ """Stream url -> dest. ``progress(done_bytes, total_bytes)`` ticks per
+ chunk (total 0 when the server sends no Content-Length) — a several-
+ hundred-MB archive on a slow line must never look hung."""
logger.info("downloading %s", url)
tmp = dest.with_suffix(dest.suffix + ".part")
with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:
- shutil.copyfileobj(r, f, length=1 << 22)
+ total = int(r.headers.get("Content-Length") or 0)
+ done = 0
+ while True:
+ chunk = r.read(1 << 20)
+ if not chunk:
+ break
+ f.write(chunk)
+ done += len(chunk)
+ if progress is not None:
+ progress(done, total)
tmp.replace(dest)
-def _extract(archive: Path, dest: Path) -> None:
+def _extract(archive: Path, dest: Path,
+ progress: "Callable[[int, int], None] | None" = None) -> None:
+ """Extract member by member so ``progress(done, total)`` can tick in
+ uncompressed bytes — big archives take real time on laptop disks."""
if archive.name.endswith(".zip"):
with zipfile.ZipFile(archive) as z:
- z.extractall(dest)
+ members = z.infolist()
+ total = sum(m.file_size for m in members)
+ done = 0
+ for m in members:
+ z.extract(m, dest)
+ done += m.file_size
+ if progress is not None:
+ progress(done, total)
else:
import tarfile
with tarfile.open(archive) as t:
- t.extractall(dest, filter="data")
+ members = t.getmembers()
+ total = sum(m.size for m in members)
+ done = 0
+ for m in members:
+ t.extract(m, dest, filter="data")
+ done += m.size
+ if progress is not None:
+ progress(done, total)
def server_binary(install_dir: Path) -> Path:
@@ -260,12 +291,16 @@ def prune_old_tags(keep: list[str]) -> None:
def ensure_runtime_installed(tag: str, backend: str,
- expected_sha256: dict[str, str] | None = None) -> Path:
+ expected_sha256: dict[str, str] | None = None,
+ progress: "Callable[[str, int, int, str], None] | None" = None) -> Path:
"""Idempotent: resolve, download, verify, extract, version-check.
``expected_sha256`` maps asset name -> hash when the catalog pins them;
without pins the computed hash is recorded in the manifest (trust on
first download, verified on every reinstall).
+ ``progress(stage, done_bytes, total_bytes, label)`` ticks through the
+ slow parts — stage is "download" | "extract" | "verify", label is the
+ asset counter ("1/2") when the plan has several archives.
Returns the install directory containing llama-server.
"""
plan = resolve_assets(tag, backend)
@@ -284,10 +319,16 @@ def ensure_runtime_installed(tag: str, backend: str,
downloads.mkdir(parents=True, exist_ok=True)
recorded: dict[str, str] = {}
- for asset in plan.assets:
+ n_assets = len(plan.assets)
+ for i, asset in enumerate(plan.assets, 1):
+ label = f"{i}/{n_assets}" if n_assets > 1 else ""
archive = downloads / asset
if not archive.exists():
- _download(RELEASE_URL.format(tag=tag, asset=asset), archive)
+ _download(RELEASE_URL.format(tag=tag, asset=asset), archive,
+ progress=(lambda d, t, _l=label: progress("download", d, t, _l))
+ if progress is not None else None)
+ if progress is not None:
+ progress("verify", 0, 0, label)
digest = _sha256(archive)
expected = (expected_sha256 or {}).get(asset)
if expected and digest != expected:
@@ -295,8 +336,12 @@ def ensure_runtime_installed(tag: str, backend: str,
raise BinaryResolutionError(
f"sha256 mismatch for {asset}: expected {expected}, got {digest}")
recorded[asset] = digest
- _extract(archive, install_dir)
+ _extract(archive, install_dir,
+ progress=(lambda d, t, _l=label: progress("extract", d, t, _l))
+ if progress is not None else None)
+ if progress is not None:
+ progress("verify", 0, 0, "")
version = verify_install(install_dir, tag)
manifest_path.write_text(json.dumps({
"tag": tag, "backend": plan.backend, "assets": recorded,
diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.py
index 43117874374..798be3b3bda 100644
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@ -593,6 +593,41 @@ class RuntimeInstallBody(BaseModel):
backend: Optional[str] = None # None/auto -> detect
+def _runtime_progress_hook(job: Dict[str, Any]):
+ """Adapter: ensure_runtime_installed's progress stream -> job fields.
+
+ Throttled to ~4 updates/s; each stage restarts the byte counters so
+ the bar reflects the CURRENT stage (download then unpack per asset).
+ Slow lines sit in the download stage for minutes — the counters are
+ what proves liveness, so they must move on every tick."""
+ state = {"last": 0.0}
+
+ def hook(stage: str, done: int, total: int, label: str) -> None:
+ now = time.monotonic()
+ if now - state["last"] < 0.25 and done < total:
+ return
+ state["last"] = now
+ suffix = f" ({label})" if label else ""
+ if stage == "download":
+ job["phase"] = "downloading-runtime"
+ if total:
+ job["detail"] = (f"Downloading the local engine{suffix} — "
+ f"{_human_gb(done)} of {_human_gb(total)}")
+ else:
+ job["detail"] = (f"Downloading the local engine{suffix} — "
+ f"{_human_gb(done)}")
+ elif stage == "extract":
+ job["phase"] = "unpacking-runtime"
+ job["detail"] = f"Unpacking the engine{suffix}"
+ else: # verify
+ job["phase"] = "verifying-runtime"
+ job["detail"] = "Verifying the engine"
+ job["done_bytes"] = done
+ job["total_bytes"] = total or None
+
+ return hook
+
+
@router.post("/api/local-models/runtime/install")
async def local_models_runtime_install(body: RuntimeInstallBody):
from hermes_cli.local_runtime.binaries import (
@@ -626,7 +661,8 @@ async def local_models_runtime_install(body: RuntimeInstallBody):
previous = installed_tags()
job["phase"] = "downloading"
job["detail"] = f"Fetching {len(plan.assets)} package(s) for {backend}"
- ensure_runtime_installed(tag, backend)
+ ensure_runtime_installed(tag, backend,
+ progress=_runtime_progress_hook(job))
# Engine update path: a server already running on an older tag
# moves to the new one now — the click was the consent. Fresh
@@ -906,11 +942,16 @@ async def local_models_quickstart(body: QuickstartBody):
job["phase"] = "installing-runtime"
job["detail"] = "Installing the local engine"
- ensure_runtime_installed(tag, backend)
+ ensure_runtime_installed(tag, backend,
+ progress=_runtime_progress_hook(job))
if need_download:
job["phase"] = "downloading"
total = sum(p[2] for p in download_plan)
+ # The runtime leg repurposed the byte counters for its own
+ # stages — reset them to the model plan before download.
+ job["done_bytes"] = 0
+ job["total_bytes"] = total
job["detail"] = f"{entry.display_name} — {_human_gb(total)}"
done_before = 0
for url, dest, size in download_plan:
diff --git a/tests/hermes_cli/test_local_quickstart.py b/tests/hermes_cli/test_local_quickstart.py
index 15d18b047f9..c82bacdf213 100644
--- a/tests/hermes_cli/test_local_quickstart.py
+++ b/tests/hermes_cli/test_local_quickstart.py
@@ -62,7 +62,7 @@ def test_quickstart_runs_all_three_legs(client, monkeypatch, tmp_path):
"hermes_cli.local_runtime.binaries.installed_tags", lambda: [])
monkeypatch.setattr(
"hermes_cli.local_runtime.binaries.ensure_runtime_installed",
- lambda tag, backend: calls.append("install"))
+ lambda tag, backend, progress=None: calls.append("install"))
# Leg 2: nothing staged; the download writes the files the plan names.
def _fake_download(url, dest, job, *, base_done=0, keep_totals=False):
@@ -116,7 +116,7 @@ def test_quickstart_skips_satisfied_legs(client, monkeypatch):
"hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b10362"])
monkeypatch.setattr(
"hermes_cli.local_runtime.binaries.ensure_runtime_installed",
- lambda tag, backend: calls.append("install"))
+ lambda tag, backend, progress=None: calls.append("install"))
# Every catalog variant reads as staged.
from hermes_cli.local_runtime.catalog import CATALOG
diff --git a/tests/hermes_cli/test_runtime_install_progress.py b/tests/hermes_cli/test_runtime_install_progress.py
new file mode 100644
index 00000000000..da34f19b5c3
--- /dev/null
+++ b/tests/hermes_cli/test_runtime_install_progress.py
@@ -0,0 +1,124 @@
+"""Runtime install progress: the slow legs must tick, never hang silently.
+
+The incident: 'Installing runtime…' sat frozen for minutes on a slow
+line — ensure_runtime_installed downloaded and extracted with no
+progress stream, so both the quickstart hero and the pane's install row
+showed a dead bar. Contract: _download and _extract tick per chunk /
+per member, ensure_runtime_installed forwards a staged stream, and the
+router's hook translates it into live job fields."""
+
+from __future__ import annotations
+
+import io
+import zipfile
+from pathlib import Path
+
+import hermes_cli.local_runtime.binaries as binaries
+from hermes_cli.web_routers.local_models import _job, _runtime_progress_hook
+
+
+def _make_zip(path: Path, names_sizes: dict[str, int]) -> None:
+ with zipfile.ZipFile(path, "w") as z:
+ for name, size in names_sizes.items():
+ z.writestr(name, b"x" * size)
+
+
+def test_extract_ticks_per_member(tmp_path):
+ archive = tmp_path / "runtime.zip"
+ _make_zip(archive, {"a.bin": 1000, "b.bin": 3000, "c.bin": 500})
+ ticks: list[tuple[int, int]] = []
+ binaries._extract(archive, tmp_path / "out",
+ progress=lambda d, t: ticks.append((d, t)))
+ assert len(ticks) == 3
+ total = 4500
+ assert all(t == total for _, t in ticks)
+ assert [d for d, _ in ticks] == sorted(d for d, _ in ticks)
+ assert ticks[-1][0] == total
+ assert (tmp_path / "out" / "b.bin").stat().st_size == 3000
+
+
+def test_download_ticks_with_content_length(tmp_path, monkeypatch):
+ payload = b"y" * (3 << 20) # 3 MiB -> several 1 MiB chunks
+
+ class _Resp(io.BytesIO):
+ headers = {"Content-Length": str(len(payload))}
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setattr(binaries.urllib.request, "urlopen",
+ lambda url, timeout=0: _Resp(payload))
+ ticks: list[tuple[int, int]] = []
+ dest = tmp_path / "asset.zip"
+ binaries._download("http://x/asset.zip", dest,
+ progress=lambda d, t: ticks.append((d, t)))
+ assert dest.read_bytes() == payload
+ assert len(ticks) >= 3
+ assert ticks[-1] == (len(payload), len(payload))
+
+
+def test_ensure_runtime_installed_forwards_staged_progress(tmp_path, monkeypatch):
+ """The full install path emits download -> verify -> extract stages
+ (per asset) and a final verify, all through one callback."""
+ monkeypatch.setattr(binaries, "runtimes_root", lambda: tmp_path)
+
+ class _Plan:
+ assets = ["a.zip", "b.zip"]
+ backend = "cuda"
+ install_dir = tmp_path / "b1" / "cuda"
+
+ monkeypatch.setattr(binaries, "resolve_assets", lambda tag, backend: _Plan())
+ monkeypatch.setattr(binaries, "verify_install", lambda d, t: "ok")
+
+ def _fake_download(url, dest, progress=None):
+ _make_zip(dest, {"f.bin": 2048})
+ if progress is not None:
+ progress(1024, 2048)
+ progress(2048, 2048)
+
+ monkeypatch.setattr(binaries, "_download", _fake_download)
+
+ events: list[tuple[str, str]] = []
+ binaries.ensure_runtime_installed(
+ "b1", "cuda",
+ progress=lambda stage, d, t, label: events.append((stage, label)))
+
+ stages = [s for s, _ in events]
+ assert "download" in stages and "extract" in stages and "verify" in stages
+ # Two assets -> per-asset labels on the slow stages.
+ assert ("download", "1/2") in events and ("download", "2/2") in events
+ assert ("extract", "1/2") in events and ("extract", "2/2") in events
+ # Stage order per asset: download before extract.
+ assert stages.index("download") < stages.index("extract")
+
+
+def test_progress_hook_translates_stages_to_job_fields():
+ job = _job("quickstart", "Test Model")
+ hook = _runtime_progress_hook(job)
+
+ hook("download", 5 << 20, 100 << 20, "1/2")
+ assert job["phase"] == "downloading-runtime"
+ assert "1/2" in job["detail"]
+ assert job["done_bytes"] == 5 << 20
+ assert job["total_bytes"] == 100 << 20
+
+ # Rapid second tick inside the throttle window is dropped...
+ hook("download", 6 << 20, 100 << 20, "1/2")
+ assert job["done_bytes"] == 5 << 20
+ # ...but a terminal tick (done == total) always lands.
+ hook("download", 100 << 20, 100 << 20, "1/2")
+ assert job["done_bytes"] == 100 << 20
+
+ hook("extract", 10, 100, "")
+ assert job["phase"] in ("downloading-runtime", "unpacking-runtime")
+
+ job2 = _job("runtime-install", "x")
+ hook2 = _runtime_progress_hook(job2)
+ hook2("extract", 100, 100, "")
+ assert job2["phase"] == "unpacking-runtime"
+ hook2("verify", 0, 0, "")
+ assert job2["phase"] == "verifying-runtime"
+ assert job2["total_bytes"] is None # indeterminate bar, not a stuck 0%