The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): real model-load progress in chat and the model picker
emozillabbe0b9fdc9ef
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex e63e28f3bd3..466d2b6eccd 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -1051,6 +1051,43 @@ def should_use_direct_api_call(agent) -> bool:_DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS = 15.0+def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":+ """'⏳ loading <model> into memory — N%' when the managed local server is+ loading this request's model right now; None otherwise.++ A cold local model spends ~tens of seconds streaming weights off disk+ before the first token can exist. Without this, that window renders as+ the generic "no output yet (provider may be slow or overloaded)" stall+ warning — alarming copy for a healthy, expected phase. The progress+ snapshot is fed by the router's SSE stream (per-tensor load callback),+ so the percent is real, not inferred.+ """+ try:+ base = str(getattr(agent, "base_url", "") or "")+ if not base:+ return None+ import json as _json+ from urllib.parse import urlparse++ from hermes_cli.local_runtime.load_progress import get_loading_progress+ from hermes_cli.local_runtime.supervisor import state_path++ state = _json.loads(state_path().read_text(encoding="utf-8"))+ managed = urlparse(str(state.get("base_url", ""))).netloc.lower()+ if not managed or urlparse(base).netloc.lower() != managed:+ return None+ model = str(api_kwargs.get("model", ""))+ progress = get_loading_progress().get(model)+ if progress is None:+ return None+ return (+ f"⏳ loading {model} into memory — {progress['percent']}% "+ "(responses start once the model is loaded)"+ )+ except Exception: # noqa: BLE001 — a status nicety must never break a call+ return None++def _resolve_direct_stale_timeout(agent, api_kwargs: dict) -> float:"""Stale budget for the inline non-streaming call.@@ -5144,9 +5181,43 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=t.start()_last_heartbeat = time.time()_HEARTBEAT_INTERVAL = 30.0 # seconds between gateway activity touches+ # Managed local server: a cold model streams weights off disk for tens+ # of seconds before the first token can exist. Surface THAT immediately+ # (real per-tensor percent from the router's SSE stream) instead of+ # letting the wait fall through to the 30s "provider may be slow or+ # overloaded" copy. Checked on a ~1s cadence only while no chunks have+ # arrived; the probe is an in-memory snapshot read, not a network call.+ _last_load_poll = 0.0+ _load_notice_shown = False+ _is_local_base = bool(agent.base_url) and is_local_endpoint(agent.base_url)+ _wait_loop_started = time.time()while t.is_alive():t.join(timeout=0.3)+ _hb_now = time.time()+ # last_chunk_time only moves past loop start when a real chunk lands,+ # so this gate is exactly "first token hasn't arrived yet".+ if (+ _is_local_base+ and last_chunk_time["t"] <= _wait_loop_started+ and _hb_now - _last_load_poll >= 1.0+ ):+ _last_load_poll = _hb_now+ _load_notice = _managed_local_load_notice(agent, api_kwargs)+ if _load_notice is not None:+ agent._emit_wait_notice(_load_notice)+ agent._touch_activity("local model loading")+ _load_notice_shown = True+ # Loading IS liveness for the heartbeat; the stale detector+ # needs no help — the local floor (900s) dwarfs any load.+ _last_heartbeat = _hb_now+ continue+ if _load_notice_shown:+ # Load finished (entry left the snapshot): clear the line so+ # the UI returns to the normal spinner while prefill runs.+ _load_notice_shown = False+ agent._emit_wait_notice("")+# Periodic heartbeat: touch the agent's activity tracker so the# gateway's inactivity monitor knows we're alive while waiting# for stream chunks. Without this, long thinking pauses (e.g.@@ -5155,7 +5226,6 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=# activity on each chunk, but the gap between API call start# and first chunk can exceed the gateway timeout — especially# when the stale-stream timeout is disabled (local providers).- _hb_now = time.time()if _hb_now - _last_heartbeat >= _HEARTBEAT_INTERVAL:_last_heartbeat = _hb_now_waiting_secs = int(_hb_now - last_chunk_time["t"])diff --git a/apps/desktop/src/components/assistant-ui/thread/status.tsx b/apps/desktop/src/components/assistant-ui/thread/status.tsxindex d7ee789ba16..835fff41007 100644--- a/apps/desktop/src/components/assistant-ui/thread/status.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/status.tsx@@ -16,7 +16,7 @@ import { cn } from '@/lib/utils'import { $backgroundResume } from '@/store/background-delegation'import { sessionCompacting } from '@/store/compaction'import { sessionAwaitingInput } from '@/store/prompts'-import { sessionProviderWait } from '@/store/provider-wait'+import { parseModelLoadWait, sessionProviderWait } from '@/store/provider-wait'import { type DraftingTool, sessionDraftingTool } from '@/store/tool-drafting'// A status line is scaffolding like any other — "Editing" while the model@@ -51,6 +51,34 @@ const HintText: FC<{ children: ReactNode }> = ({ children }) => (<span className={cn(SCAFFOLD_LABEL_CLASS, 'shimmer min-w-0 flex-1 truncate')}>{children}</span>)+/** Wait hint with a real progress bar for managed-local model loads. The+ * percent comes from llama-server's per-tensor load callback (via the+ * gateway's wait frames), so a determinate bar is honest — and a 40s cold+ * load reads as visible progress instead of an alarming stall. */+const WaitHint: FC<{ hint: string }> = ({ hint }) => {+ const { t } = useI18n()+ const load = parseModelLoadWait(hint)++ if (!load) {+ return <HintText>{hint}</HintText>+ }++ return (+ <span className="flex min-w-0 flex-1 items-center gap-2">+ <span className={cn(SCAFFOLD_LABEL_CLASS, 'shimmer min-w-0 shrink truncate')}>+ {t.assistant.thread.loadingLocalModel(load.model)}+ </span>+ <span className="h-1 w-24 shrink-0 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">+ <span+ className="block h-full rounded-full bg-primary transition-[width] duration-500"+ style={{ width: `${Math.max(2, load.percent)}%` }}+ />+ </span>+ <span className={cn(SCAFFOLD_LABEL_CLASS, 'shrink-0 tabular-nums')}>{load.percent}%</span>+ </span>+ )+}+/** These indicators render inside whichever transcript mounted them, so every* session-scoped signal comes from that surface's view — a tile must never* show the primary chat's compaction, prompt-wait, or turn timer. */@@ -155,7 +183,7 @@ export const ResponseLoadingIndicator: FC = () => {className="dither inline-block size-3 rounded-[2px] text-midground/80"kind="opacity"/>- {hint && <HintText>{hint}</HintText>}+ {hint && <WaitHint hint={hint} />}<ActivityTimerText seconds={elapsed} /></StatusRow>)@@ -263,7 +291,7 @@ export const TurnActivityIndicator: FC = () => {className="dither inline-block size-3 rounded-[2px] text-midground/80"kind="opacity"/>- {hint && <HintText>{hint}</HintText>}+ {hint && <WaitHint hint={hint} />}<ActivityTimerText seconds={elapsed} /></StatusRow>)diff --git a/apps/desktop/src/components/model-picker.tsx b/apps/desktop/src/components/model-picker.tsxindex 4f5415f9205..717301c10b6 100644--- a/apps/desktop/src/components/model-picker.tsx+++ b/apps/desktop/src/components/model-picker.tsx@@ -1,12 +1,13 @@import { useQuery } from '@tanstack/react-query'import { useState } from 'react'+import { getLocalModelsStatus } from '@/hermes'import { useI18n } from '@/i18n'import { modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'import { modelSearchText } from '@/lib/model-search-text'import { currentPickerSelection } from '@/lib/model-status-label'import { normalize } from '@/lib/text'-import type { ModelOptionProvider, ModelPricing } from '@/types/hermes'+import type { LocalModelLoadProgress, ModelOptionProvider, ModelPricing } from '@/types/hermes'import type { HermesGateway } from '../hermes'import { cn } from '../lib/utils'@@ -63,6 +64,20 @@ export function ModelPickerDialog({enabled: open})+ // Live load state for the managed local server: which model is loading+ // into memory right now, with a REAL percent (per-tensor callback relayed+ // over the router's SSE stream). Polled only while the picker is open —+ // 2s idle cadence is enough for a bar under a ~40s load. Errors read as+ // "nothing loading" (remote-only installs have no local-models routes).+ const localStatus = useQuery({+ queryKey: ['local-models-loading', profile],+ queryFn: () => getLocalModelsStatus(),+ enabled: open,+ refetchInterval: 2_000,+ retry: false+ })+ const loadingModels: Record<string, LocalModelLoadProgress> = localStatus.data?.loading ?? {}+const providers = modelOptions.data?.providers ?? []const { model: optionsModel, provider: optionsProvider } = currentPickerSelection(@@ -115,6 +130,7 @@ export function ModelPickerDialog({currentProvider={optionsProvider || currentProvider}error={error}loading={loading}+ loadingModels={loadingModels}onSelectModel={selectModel}providers={providers}search={search}@@ -141,6 +157,7 @@ function ModelResults({providers,currentModel,currentProvider,+ loadingModels,onSelectModel,search}: {@@ -149,6 +166,7 @@ function ModelResults({providers: ModelOptionProvider[]currentModel: stringcurrentProvider: string+ loadingModels: Record<string, LocalModelLoadProgress>onSelectModel: (provider: ModelOptionProvider, model: string) => voidsearch: string}) {@@ -211,6 +229,10 @@ function ModelResults({const isCurrent = model === currentModel && provider.slug === currentProviderconst price = provider.pricing?.[model]const locked = unavailable.has(model)+ // Managed local model loading into memory right now: show the+ // real load percent inline (keyed by exact model id — remote+ // providers never match).+ const loadProgress = loadingModels[model]return (<CommandItem@@ -232,6 +254,19 @@ function ModelResults({<span className="min-w-0 flex-1 truncate"><HighlightMatches query={search} text={model} /></span>+ {loadProgress && (+ <span className="flex shrink-0 items-center gap-1.5" title={copy.loadingIntoMemory}>+ <span className="h-1 w-16 overflow-hidden rounded-full bg-(--ui-bg-tertiary)">+ <span+ className="block h-full rounded-full bg-primary transition-[width] duration-500"+ style={{ width: `${Math.max(2, loadProgress.percent)}%` }}+ />+ </span>+ <span className="text-[0.62rem] tabular-nums text-muted-foreground">+ {loadProgress.percent}%+ </span>+ </span>+ )}{locked && (<span className="shrink-0 text-[0.62rem] uppercase tracking-wide opacity-80">{copy.pro}</span>)}diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex ec5385e1cc0..01e92a905df 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -2883,6 +2883,7 @@ export const en: Translations = {noModels: 'No models found.',addProvider: 'Add provider',loadFailed: 'Could not load models',+ loadingIntoMemory: 'Loading into memory',noAuthenticatedProviders: 'No authenticated providers.',pro: 'Pro',proNeedsSubscription: 'Pro models need a paid Nous subscription.',@@ -3264,6 +3265,7 @@ export const en: Translations = {loadingSession: 'Loading session',showEarlier: 'Show earlier messages',loadingResponse: 'Hermes is loading a response',+ loadingLocalModel: model => `Loading ${model} into memory`,resumeWhenBackgroundDone: count =>count === 1? 'Will resume when the background task finishes'diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 2ba566cd017..8e0e295f3f7 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2444,6 +2444,7 @@ export interface Translations {noModels: stringaddProvider: stringloadFailed: string+ loadingIntoMemory: stringnoAuthenticatedProviders: stringpro: stringproNeedsSubscription: string@@ -2820,6 +2821,7 @@ export interface Translations {loadingSession: stringshowEarlier: stringloadingResponse: string+ loadingLocalModel: (model: string) => stringresumeWhenBackgroundDone: (count: number) => stringthinking: stringthought: stringdiff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 2f90e432db0..700f8db4b6d 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3044,6 +3044,7 @@ export const zh: Translations = {noModels: '未找到模型。',addProvider: '添加提供方',loadFailed: '无法加载模型',+ loadingIntoMemory: '正在载入内存',noAuthenticatedProviders: '没有已认证的提供方。',pro: 'Pro',proNeedsSubscription: 'Pro 模型需要付费 Nous 订阅。',@@ -3422,6 +3423,7 @@ export const zh: Translations = {loadingSession: '正在加载会话',showEarlier: '显示更早的消息',loadingResponse: 'Hermes 正在加载回复',+ loadingLocalModel: model => `正在将 ${model} 载入内存`,resumeWhenBackgroundDone: count =>count === 1 ? '后台任务完成后将自动继续' : `${count} 个后台任务完成后将自动继续`,thinking: '思考中',diff --git a/apps/desktop/src/store/provider-wait.test.ts b/apps/desktop/src/store/provider-wait.test.tsnew file mode 100644index 00000000000..c4d3da3f79c--- /dev/null+++ b/apps/desktop/src/store/provider-wait.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'++import { parseModelLoadWait, providerWaitText } from './provider-wait'++// The load-notice string is minted by the backend+// (agent/chat_completion_helpers._managed_local_load_notice) and parsed+// here — these tests pin the desktop side of that cross-language contract+// (the backend pins its side in tests/hermes_cli/test_load_progress.py).+describe('providerWaitText', () => {+ it('accepts the managed-local load frame', () => {+ const frame = '⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 42% (responses start once the model is loaded)'++ expect(providerWaitText(frame)).toBe(frame)+ })++ it('still accepts classic wait frames and rejects spinner noise', () => {+ expect(providerWaitText('⏳ waiting on local-model — 30s with no output yet')).not.toBe('')+ expect(providerWaitText('◉_◉ cogitating...')).toBe('')+ })+})++describe('parseModelLoadWait', () => {+ it('extracts model and percent from a load frame', () => {+ expect(+ parseModelLoadWait('⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 42% (responses start once the model is loaded)')+ ).toEqual({ model: 'Qwen3.6-35B-A3B-UD-Q4_K_M', percent: 42 })+ })++ it('returns null for every other wait frame', () => {+ expect(parseModelLoadWait('⏳ waiting on qwen — 30s with no output yet')).toBeNull()+ expect(parseModelLoadWait('⚠ no output from provider for 900s — reconnecting...')).toBeNull()+ expect(parseModelLoadWait('')).toBeNull()+ })++ it('clamps out-of-range percents', () => {+ expect(parseModelLoadWait('⏳ loading m into memory — 999%')?.percent).toBe(100)+ })+})diff --git a/apps/desktop/src/store/provider-wait.ts b/apps/desktop/src/store/provider-wait.tsindex 696c07bb49e..95737ebf0a7 100644--- a/apps/desktop/src/store/provider-wait.ts+++ b/apps/desktop/src/store/provider-wait.ts@@ -45,5 +45,19 @@ export function clearAllProviderWaits(): void {export function providerWaitText(text: string): string {const value = text.trim()- return /^(?:⏳|⚠|↻)\s*(?:waiting on|no (?:output|response)|model returned)/i.test(value) ? value : ''+ return /^(?:⏳|⚠|↻)\s*(?:waiting on|loading|no (?:output|response)|model returned)/i.test(value) ? value : ''+}++/** Parse a managed-local model-load frame ("⏳ loading <model> into memory —+ * 43% …") into its parts, or null for every other wait frame. The percent is+ * real (per-tensor load callback relayed by the server), so surfaces can+ * render an honest determinate bar instead of prose. */+export function parseModelLoadWait(text: string): null | { model: string; percent: number } {+ const m = /^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%/i.exec(text.trim())++ if (!m) {+ return null+ }++ return { model: m[1], percent: Math.max(0, Math.min(100, Number(m[2]))) }}diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 68d983110b8..c4d0c374890 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -1230,6 +1230,12 @@ export interface LocalModelPlacement {granted_window_label?: string}+export interface LocalModelLoadProgress {+ stage: string+ value: number+ percent: number+}+export interface LocalModelsStatus {enabled: booleantag: string@@ -1241,6 +1247,8 @@ export interface LocalModelsStatus {server_base_url: string | nullactive_model_id: string | nullloaded_models: Record<string, string>+ /** Models loading into memory right now: real per-tensor load percent. */+ loading?: Record<string, LocalModelLoadProgress>placement?: Record<string, LocalModelPlacement>models: { id: string; size_bytes: number; size_label: string }[]models_dir: stringdiff --git a/hermes_cli/local_runtime/load_progress.py b/hermes_cli/local_runtime/load_progress.pynew file mode 100644index 00000000000..fb0597000f3--- /dev/null+++ b/hermes_cli/local_runtime/load_progress.py@@ -0,0 +1,151 @@+"""Live model-load progress from the managed llama-server router.++llama-server's child processes emit per-tensor load progress+({stages, current, value}, throttled upstream to ~200ms) which the+router relays ONLY over its /models/sse stream — GET /models carries+just the coarse status string. This module owns one lazy background+watcher on that stream and keeps an in-memory snapshot other code can+poll cheaply:++ get_loading_progress() -> {model_id: {"stage", "value", "percent"}}++"percent" is a composite across stages so a bar doesn't sprint 0->100+once per stage: the text model dominates load time (its weights dwarf+the mmproj/spec extras), so it gets the lion's share of the range and+the extras split the remainder.++The watcher starts on first call, reconnects with backoff (the router+bounces on model download/eject), and never raises into callers — no+router, no state file, or no SSE support (older engines) all read as+"nothing loading". Safe from any process on the machine: the endpoint+comes from the supervisor's machine-scoped state file.+"""++from __future__ import annotations++import json+import logging+import threading+import time+import urllib.request++logger = logging.getLogger(__name__)++_TEXT_STAGE_SHARE = 0.85 # composite range share for the text model+_RECONNECT_DELAY_S = 3.0+_STALE_ENTRY_TTL_S = 120.0 # a loading entry with no events this long is dead++_lock = threading.Lock()+_watcher: threading.Thread | None = None+_snapshot: dict[str, dict] = {}+++def _composite_percent(stages: list[str], current: str, value: float) -> int:+ """Map (stage, in-stage value) onto one 0-100 range, text-heavy."""+ if not stages or current not in stages or len(stages) == 1:+ return max(0, min(100, round(value * 100)))+ extras = [s for s in stages if s != "text_model"]+ extra_share = (1.0 - _TEXT_STAGE_SHARE) / len(extras) if extras else 0.0+ offset = 0.0+ for stage in stages:+ share = _TEXT_STAGE_SHARE if stage == "text_model" else extra_share+ if stage == current:+ return max(0, min(100, round((offset + share * value) * 100)))+ offset += share+ return max(0, min(100, round(value * 100)))+++def _endpoint() -> "tuple[str, str] | None":+ """(base_root, api_key) of the managed router, or None."""+ try:+ from hermes_cli.local_runtime.supervisor import state_path++ state = json.loads(state_path().read_text(encoding="utf-8"))+ base = str(state.get("base_url", "")).rsplit("/v1", 1)[0]+ return (base, str(state.get("api_key", ""))) if base else None+ except Exception: # noqa: BLE001+ return None+++def _apply_event(model: str, event: str, data: dict) -> None:+ with _lock:+ status = str(data.get("status", ""))+ if event in ("status_change", "model_status") and status == "loading":+ progress = data.get("progress") or {}+ stages = [str(s) for s in (progress.get("stages") or [])]+ current = str(progress.get("current", ""))+ value = progress.get("value")+ entry = _snapshot.setdefault(model, {"stage": "", "value": 0.0,+ "percent": 0, "ts": 0.0})+ entry["ts"] = time.monotonic()+ if current and isinstance(value, (int, float)):+ entry["stage"] = current+ entry["value"] = float(value)+ entry["percent"] = _composite_percent(stages, current, float(value))+ elif event in ("status_change", "model_status", "model_remove"):+ # Any terminal status (loaded/unloaded/failed) ends the load.+ if status != "loading":+ _snapshot.pop(model, None)+++def _watch() -> None:+ while True:+ endpoint = _endpoint()+ if endpoint is None:+ with _lock:+ _snapshot.clear()+ time.sleep(_RECONNECT_DELAY_S)+ continue+ base, key = endpoint+ try:+ req = urllib.request.Request(+ f"{base}/models/sse",+ headers={"Authorization": f"Bearer {key}",+ "Accept": "text/event-stream"})+ with urllib.request.urlopen(req, timeout=60) as r:+ buf = b""+ while True:+ chunk = r.read1(4096) if hasattr(r, "read1") else r.read(4096)+ if not chunk:+ break+ buf += chunk+ while b"\n" in buf:+ line, buf = buf.split(b"\n", 1)+ text = line.decode("utf-8", "replace").strip()+ if not text.startswith("data:"):+ continue+ try:+ msg = json.loads(text[5:].strip())+ _apply_event(str(msg.get("model", "")),+ str(msg.get("event", "")),+ msg.get("data") or {})+ except (json.JSONDecodeError, TypeError):+ continue+ except Exception as exc: # noqa: BLE001 — watcher must never die loud+ logger.debug("load-progress SSE reconnecting: %s", exc)+ # Stream ended (router bounce, timeout, error): loading entries from+ # the dead connection are unverifiable — drop rather than freeze.+ with _lock:+ _snapshot.clear()+ time.sleep(_RECONNECT_DELAY_S)+++def _ensure_watcher() -> None:+ global _watcher+ with _lock:+ if _watcher is None or not _watcher.is_alive():+ _watcher = threading.Thread(target=_watch, daemon=True,+ name="llamacpp-load-progress")+ _watcher.start()+++def get_loading_progress() -> dict[str, dict]:+ """{model_id: {"stage", "value", "percent"}} for models loading right+ now. Empty when nothing is loading (or nothing is knowable)."""+ _ensure_watcher()+ now = time.monotonic()+ with _lock:+ return {m: {"stage": e["stage"], "value": e["value"],+ "percent": e["percent"]}+ for m, e in _snapshot.items()+ if now - e["ts"] < _STALE_ENTRY_TTL_S}diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex 798be3b3bda..14f71d61aac 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -410,12 +410,24 @@ async def local_models_status():"server_base_url": (running or {}).get("base_url"),"active_model_id": active_model_id,"loaded_models": loaded,+ # Live load progress per model (SSE-fed): {model_id: {stage, value,+ # percent}}. The chat's loading bar and the picker rows poll this.+ "loading": _loading_progress(),"placement": placement,"models": staged,"models_dir": str(mdir),}+def _loading_progress() -> Dict[str, Any]:+ try:+ from hermes_cli.local_runtime.load_progress import get_loading_progress++ return get_loading_progress()+ except Exception: # noqa: BLE001 — progress is garnish, never a 500+ return {}++# ── hardware: what this machine can do ───────────────────────diff --git a/tests/hermes_cli/test_load_progress.py b/tests/hermes_cli/test_load_progress.pynew file mode 100644index 00000000000..d65540cdc49--- /dev/null+++ b/tests/hermes_cli/test_load_progress.py@@ -0,0 +1,137 @@+"""Model-load progress: SSE events -> composite percent -> wait notices.++The 40-second problem: a cold local model streams 16-21 GB of weights+before the first token, and the chat rendered that as the generic+"provider may be slow or overloaded" stall warning. llama-server's child+emits real per-tensor progress which the router relays over /models/sse+ONLY — these tests pin the consumer that turns that stream into the+status route's `loading` field and the chat's load notice."""++from __future__ import annotations++import json+import time++import hermes_cli.local_runtime.load_progress as lp+++def setup_function(_fn):+ with lp._lock:+ lp._snapshot.clear()+++# ── composite percent ────────────────────────────────────────+++def test_composite_percent_text_stage_dominates():+ stages = ["text_model", "spec_model", "mmproj_model"]+ # Text model owns [0, 85): halfway through it reads ~42%.+ assert lp._composite_percent(stages, "text_model", 0.5) == 42 # 0.5*85+ # Extras start where text ends and never regress below it.+ assert lp._composite_percent(stages, "spec_model", 0.0) == 85+ assert lp._composite_percent(stages, "mmproj_model", 1.0) == 100+++def test_composite_percent_monotone_across_stage_walk():+ """Walking the stages in llama-server's real order never moves the+ bar backwards — the property that makes the bar trustworthy."""+ stages = ["text_model", "spec_model", "mmproj_model"]+ walk = [("text_model", v / 10) for v in range(11)] + \+ [("spec_model", v / 10) for v in range(11)] + \+ [("mmproj_model", v / 10) for v in range(11)]+ seen = [lp._composite_percent(stages, s, v) for s, v in walk]+ assert seen == sorted(seen)+ assert seen[0] == 0 and seen[-1] == 100+++def test_composite_percent_single_stage_is_plain():+ assert lp._composite_percent(["text_model"], "text_model", 0.4) == 40+++# ── event application ────────────────────────────────────────+++def _loading_event(value: float, current: str = "text_model") -> dict:+ return {"status": "loading",+ "progress": {"stages": ["text_model", "mmproj_model"],+ "current": current, "value": value}}+++def test_loading_events_build_snapshot_and_terminal_clears():+ lp._apply_event("m1", "status_change", _loading_event(0.5))+ snap = lp.get_loading_progress()+ assert "m1" in snap+ assert snap["m1"]["percent"] == 42 # 0.5 * 85 within text stage+ assert snap["m1"]["stage"] == "text_model"++ lp._apply_event("m1", "status_change", {"status": "loaded", "info": {}})+ assert lp.get_loading_progress() == {}+++def test_unload_and_failure_clear_too():+ lp._apply_event("m1", "status_change", _loading_event(0.2))+ lp._apply_event("m1", "status_change", {"status": "unloaded", "exit_code": 1})+ assert lp.get_loading_progress() == {}++ lp._apply_event("m2", "status_change", _loading_event(0.9))+ lp._apply_event("m2", "model_remove", {})+ assert lp.get_loading_progress() == {}+++def test_progressless_loading_event_keeps_entry_alive():+ """The router's first model_status event says just {status: loading} —+ it must register the load (indeterminate) without inventing a percent."""+ lp._apply_event("m1", "model_status", {"status": "loading"})+ snap = lp.get_loading_progress()+ assert snap["m1"]["percent"] == 0+++def test_stale_entries_expire():+ lp._apply_event("m1", "status_change", _loading_event(0.5))+ with lp._lock:+ lp._snapshot["m1"]["ts"] -= lp._STALE_ENTRY_TTL_S + 1+ assert lp.get_loading_progress() == {}+++# ── chat wait-notice ─────────────────────────────────────────+++def test_load_notice_for_managed_model(tmp_path, monkeypatch):+ from agent.chat_completion_helpers import _managed_local_load_notice++ state = tmp_path / "server.json"+ state.write_text(json.dumps({"base_url": "http://127.0.0.1:18434/v1",+ "api_key": "k"}), encoding="utf-8")+ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.state_path",+ lambda: state)+ lp._apply_event("Qwen-Test", "status_change", _loading_event(0.5))+ monkeypatch.setattr(lp, "_ensure_watcher", lambda: None)++ class _Agent:+ base_url = "http://127.0.0.1:18434/v1"++ notice = _managed_local_load_notice(_Agent(), {"model": "Qwen-Test"})+ assert notice is not None+ assert notice.startswith("⏳ loading Qwen-Test into memory — 42%")++ # Different endpoint (user's own server): never claim its loads.+ class _Other:+ base_url = "http://127.0.0.1:9999/v1"++ assert _managed_local_load_notice(_Other(), {"model": "Qwen-Test"}) is None+ # Managed endpoint but a model that isn't loading: no notice.+ assert _managed_local_load_notice(_Agent(), {"model": "Elsewhere"}) is None+++def test_load_notice_matches_desktop_wait_filter():+ """The notice must pass the desktop's providerWaitText regex (anchored+ '⏳ loading') and parse under parseModelLoadWait's shape — pinned here+ as a plain string contract so the two sides can't drift silently."""+ import re++ sample = "⏳ loading Qwen3.6-35B-A3B-UD-Q4_K_M into memory — 43% (responses start once the model is loaded)"+ # providerWaitText's accept set (mirrored from provider-wait.ts):+ assert re.match(r"^(?:⏳|⚠|↻)\s*(?:waiting on|loading|no (?:output|response)|model returned)", sample)+ # parseModelLoadWait's shape (mirrored):+ m = re.match(r"^⏳\s*loading\s+(.+?)\s+into memory\s+—\s+(\d{1,3})%", sample)+ assert m and m.group(1) == "Qwen3.6-35B-A3B-UD-Q4_K_M" and m.group(2) == "43"