Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(brain): read sub-gigabyte sizes and never cache the installed state
rubenluetke10-beep3a3c9a8c9320
diff --git a/jarvis/brain/ollama_library.py b/jarvis/brain/ollama_library.pyindex f126220e1d..59eba1ccc2 100644--- a/jarvis/brain/ollama_library.py+++ b/jarvis/brain/ollama_library.py@@ -71,14 +71,46 @@ _NAME_RE = re.compile(r"[A-Za-z0-9._-]+")#: handled separately: it is a hosting fact, not a model capability._CAPABILITY_BADGES = ("vision", "tools", "thinking", "embedding")-_search_cache: dict[str, tuple[float, dict[str, Any]]] = {}-_tags_cache: dict[str, tuple[float, dict[str, Any]]] = {}---def _cache_get(cache: dict[str, tuple[float, dict[str, Any]]], key: str) -> dict[str, Any] | None:+#: Download sizes as the tags page writes them. The unit is NOT always GB — a+#: sub-gigabyte tag reads "398MB", and matching only GB dropped the size of+#: exactly the small models a weak machine depends on, leaving them with no fit+#: verdict at all. Decimal units, matching the catalog's own arithmetic.+_SIZE_RE = re.compile(r"([\d.]+)\s*(TB|GB|MB|KB)\b")+_SIZE_FACTOR_GB = {"TB": 1000.0, "GB": 1.0, "MB": 1e-3, "KB": 1e-6}++#: Caches hold the CATALOG half only — what ollama.com said, never what this+#: machine holds. Caching the enriched answer froze `installed` too, so a tag+#: downloaded from this very panel kept offering "Download" for the rest of the+#: TTL. The catalog drifts in days; the inventory changes while the user+#: watches, so it is re-read on every call.+_search_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}+_tags_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}+++def _size_to_gb(match: re.Match[str]) -> float | None:+ """A matched ``398MB`` / ``6.6GB`` as gigabytes, or ``None`` if unreadable."""+ try:+ value = float(match.group(1))+ except ValueError:+ return None+ gb = value * _SIZE_FACTOR_GB[match.group(2)]+ # Two decimals keeps a 398 MB model at 0.4 rather than collapsing to 0.0,+ # which would read as "free" next to the fit verdict.+ return round(gb, 2) if gb > 0 else None+++def _cache_get(+ cache: dict[str, tuple[float, list[dict[str, Any]]]], key: str+) -> list[dict[str, Any]] | None:+ """Cached catalog entries for ``key``, or ``None`` when stale or absent.++ Copies are returned: the caller enriches each entry with this machine's+ state, and mutating the cached dicts would bake that state into every+ later reader.+ """hit = cache.get(key)if hit and (time.monotonic() - hit[0]) < _CACHE_TTL_SECONDS:- return hit[1]+ return [dict(entry) for entry in hit[1]]return None@@ -181,31 +213,28 @@ async def search_library(query: str) -> dict[str, Any]:already pulled (any tag of it) reads as such directly in the results."""q = (query or "").strip()- if cached := _cache_get(_search_cache, q):- return cached-- page, error = await _fetch_page("/search", params={"q": q} if q else None)- if page is None:- return {"query": q, "models": [], "error": error}-- models = parse_search_html(page)- if not models:- # An empty answer for a nonsense query is correct; empty for a page- # that no longer parses would silently kill the feature. Only the- # latter is an error, and only the live guard can tell them apart —- # here both honestly say "nothing found".- log.info("ollama-library: search %r parsed 0 entries", q)+ models = _cache_get(_search_cache, q)+ if models is None:+ page, error = await _fetch_page("/search", params={"q": q} if q else None)+ if page is None:+ return {"query": q, "models": [], "error": error}++ models = parse_search_html(page)+ if not models:+ # An empty answer for a nonsense query is correct; empty for a page+ # that no longer parses would silently kill the feature. Only the+ # latter is an error, and only the live guard can tell them apart —+ # here both honestly say "nothing found".+ log.info("ollama-library: search %r parsed 0 entries", q)+ _search_cache[q] = (time.monotonic(), [dict(entry) for entry in models])installed, _inventory_error = await installed_models()+ families = {i.partition(":")[0] for i in installed}for model in models:name = model["name"]- model["installed"] = name in {i.partition(":")[0] for i in installed} or _is_installed(- name, installed- )+ model["installed"] = name in families or _is_installed(name, installed)- result = {"query": q, "models": models, "error": None}- _search_cache[q] = (time.monotonic(), result)- return result+ return {"query": q, "models": models, "error": None}# ── tags ────────────────────────────────────────────────────────────────────@@ -235,7 +264,7 @@ def parse_tags_html(page: str, name: str) -> list[dict[str, Any]]:end = first_seen[index + 1][1] if index + 1 < len(first_seen) else len(page)window = page[start:end]- size_match = re.search(r"([\d.]+)\s*GB", window)+ size_match = _SIZE_RE.search(window)context_match = re.search(r"([\d.]+[KM])\s+context window", window)inputs_match = re.search(r"([A-Za-z][A-Za-z, ]*?)\s+input\b", window)updated_match = re.search(r"(\d+ \w+ ago|yesterday)", window)@@ -244,7 +273,7 @@ def parse_tags_html(page: str, name: str) -> list[dict[str, Any]]:{"tag": tag,"id": f"{name}:{tag}",- "size_gb": float(size_match.group(1)) if size_match else None,+ "size_gb": _size_to_gb(size_match) if size_match else None,"context": context_match.group(1) if context_match else "","inputs": _text(inputs_match.group(1)) if inputs_match else "","updated": updated_match.group(1) if updated_match else "",@@ -267,20 +296,20 @@ async def library_tags(model: str) -> dict[str, Any]:name = (model or "").strip()if not name or not _NAME_RE.fullmatch(name):return {"model": name, "tags": [], "error": "Not a valid library model name."}- if cached := _cache_get(_tags_cache, name):- return cached-- page, error = await _fetch_page(f"/library/{name}/tags")- if page is None:- return {"model": name, "tags": [], "error": error}-- tags = parse_tags_html(page, name)- if not tags:- return {- "model": name,- "tags": [],- "error": f"No tags could be read for '{name}' — check it on ollama.com/library.",- }+ tags = _cache_get(_tags_cache, name)+ if tags is None:+ page, error = await _fetch_page(f"/library/{name}/tags")+ if page is None:+ return {"model": name, "tags": [], "error": error}++ tags = parse_tags_html(page, name)+ if not tags:+ return {+ "model": name,+ "tags": [],+ "error": f"No tags could be read for '{name}' — check it on ollama.com/library.",+ }+ _tags_cache[name] = (time.monotonic(), [dict(entry) for entry in tags])installed, _inventory_error = await installed_models()memory_gb = total_memory_gb()@@ -292,6 +321,4 @@ async def library_tags(model: str) -> dict[str, Any]:else:entry["fit"], entry["fit_note"] = fit_verdict(entry["size_gb"], memory_gb, accel)- result = {"model": name, "tags": tags, "error": None}- _tags_cache[name] = (time.monotonic(), result)- return result+ return {"model": name, "tags": tags, "error": None}diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 1b04ccef38..c6a7b90def 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -2730,7 +2730,10 @@ function LibraryBrowser({</button>{openModel === model.name && (- <div className="space-y-1 border-t border-border/40 px-2 py-1.5">+ // A popular family publishes well over a hundred tags+ // (qwen2.5: 133). Un-capped, one opened model would push the+ // whole settings page down by several screens.+ <div className="max-h-56 space-y-1 overflow-y-auto border-t border-border/40 px-2 py-1.5">{loadingTags && !tags[model.name] && (<p className="text-[11px] text-muted-foreground">{t("apikeys_model_pull.library_loading_versions")}diff --git a/tests/fixtures/brain/ollama_tags.html b/tests/fixtures/brain/ollama_tags.htmlindex a253d7c3e9..f9d35b611c 100644--- a/tests/fixtures/brain/ollama_tags.html+++ b/tests/fixtures/brain/ollama_tags.html@@ -78,4 +78,31 @@</div></div></div>+ <!-- A sub-gigabyte tag: the page switches units to MB here, which is why the+ size parser cannot anchor on "GB". These are exactly the tags a weak+ machine depends on, so losing their size loses their fit verdict too. -->+ <div class="group px-4 py-3">+ <a href="/library/qwen3.5:0.3b" class="md:hidden flex flex-col space-y-[6px] group">+ <div class="flex items-center font-medium">+ <span class="group-hover:underline">qwen3.5:0.3b</span>+ </div>+ <div class="flex flex-col text-neutral-500 text-[13px]">+ <span>+ <span class="font-mono">a8b0c5157701</span> • 398MB • 32K context window •+ <span class="hidden sm:inline">Text input • 5 months ago</span>+ </span>+ </div>+ </a>+ <div class="hidden md:flex flex-col space-y-[6px]">+ <div class="grid grid-cols-12 items-center">+ <span class="flex items-center font-medium col-span-6 group text-sm">+ <a href="/library/qwen3.5:0.3b" class="group-hover:underline">qwen3.5:0.3b</a>+ <input class="command hidden" value="qwen3.5:0.3b" />+ </span>+ <p class="col-span-2 text-neutral-500 text-[13px]">398MB</p>+ <p class="col-span-2 text-neutral-500 text-[13px]">32K</p>+ <div class="col-span-2 text-neutral-500 text-[13px] ">Text</div>+ </div>+ </div>+ </div></main>diff --git a/tests/unit/brain/test_ollama_library.py b/tests/unit/brain/test_ollama_library.pyindex fef1eb7402..47b694717f 100644--- a/tests/unit/brain/test_ollama_library.py+++ b/tests/unit/brain/test_ollama_library.py@@ -82,7 +82,30 @@ def test_search_parser_answers_empty_on_garbage() -> None:def test_tags_parser_dedupes_the_mobile_and_desktop_blocks(tags_page: str) -> None:tags = library.parse_tags_html(tags_page, "qwen3.5")- assert [t["tag"] for t in tags] == ["latest", "cloud", "0.8b"]+ assert [t["tag"] for t in tags] == ["latest", "cloud", "0.8b", "0.3b"]+++def test_tags_parser_reads_sub_gigabyte_sizes(tags_page: str) -> None:+ """The page writes "398MB", not "0.4GB". A GB-only parser dropped the size+ of exactly the tags a weak machine depends on, leaving them fit-unknown."""+ small = next(t for t in library.parse_tags_html(tags_page, "qwen3.5") if t["tag"] == "0.3b")+ assert small["size_gb"] == 0.4+++ ("markup", "expected"),+ [+ ('<a href="/library/x:a">x</a> 6.6GB', 6.6),+ ('<a href="/library/x:a">x</a> 398MB', 0.4),+ ('<a href="/library/x:a">x</a> 1.2TB', 1200.0),+ # "256K context window" must never be read as a size.+ ('<a href="/library/x:a">x</a> 256K context window', None),+ ],+)+def test_size_units_are_read_the_way_the_catalog_writes_them(+ markup: str, expected: float | None+) -> None:+ assert library.parse_tags_html(markup, "x")[0]["size_gb"] == expecteddef test_tags_parser_reads_size_context_and_inputs(tags_page: str) -> None:@@ -178,6 +201,61 @@ async def test_tags_enrich_with_fit_and_installed(monkeypatch, tags_page: str, _assert by_tag["cloud"]["fit_note"] == ""+async def test_a_freshly_pulled_tag_stops_offering_download_immediately(+ monkeypatch, tags_page: str+) -> None:+ """The cache must hold the CATALOG, never this machine's inventory.++ Caching the enriched answer meant a tag downloaded from this very panel+ kept its "Download" button for the rest of the TTL — the one moment the+ panel is guaranteed to be wrong is right after it did its job.+ """+ inventory: set[str] = set()++ async def _installed() -> tuple[set[str], str | None]:+ return set(inventory), None++ monkeypatch.setattr(library, "installed_models", _installed)+ monkeypatch.setattr(library, "total_memory_gb", lambda: 32.0)+ monkeypatch.setattr(library, "accelerator_gb", lambda: (0.0, "none"))+ fetches: list[str] = []+ monkeypatch.setattr(library, "_fetch_page", _fake_fetch(tags_page, None, fetches))++ first = await library.library_tags("qwen3.5")+ assert next(t for t in first["tags"] if t["tag"] == "0.8b")["installed"] is False++ inventory.add("qwen3.5:0.8b") # the pull completes++ second = await library.library_tags("qwen3.5")+ assert next(t for t in second["tags"] if t["tag"] == "0.8b")["installed"] is True+ # …and the catalog half still came from the cache, not a second fetch.+ assert len(fetches) == 1+++async def test_search_installed_state_is_never_cached(+ monkeypatch, search_page: str+) -> None:+ inventory: set[str] = set()++ async def _installed() -> tuple[set[str], str | None]:+ return set(inventory), None++ monkeypatch.setattr(library, "installed_models", _installed)+ fetches: list[str] = []+ monkeypatch.setattr(library, "_fetch_page", _fake_fetch(search_page, None, fetches))++ first = await library.search_library("qwen")+ assert first["models"][0]["installed"] is False++ inventory.add("qwen3.5:9b")++ second = await library.search_library("qwen")+ assert second["models"][0]["installed"] is True+ assert len(fetches) == 1++@pytest.mark.asyncioasync def test_tags_reject_a_name_that_is_not_a_library_name(_machine) -> None:"""The name doubles as a URL segment — a path-shaped one must never reach