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
feat(brain): browse the full public Ollama library from inside the app
rubenluetke10-beep0862ddf53e9e
diff --git a/jarvis/brain/ollama_library.py b/jarvis/brain/ollama_library.pynew file mode 100644index 0000000000..f126220e1d--- /dev/null+++ b/jarvis/brain/ollama_library.py@@ -0,0 +1,297 @@+"""Browse the FULL public Ollama library from inside the app.++The curated shortlist in :mod:`jarvis.brain.ollama_pull` answers "what should+I run?". This module answers "what else exists?" — the user picks any model+from the public library without leaving the app or knowing the exact tag name+in advance.++Ollama publishes no JSON search API, and the registry does NOT expose the+Docker ``tags/list`` endpoint (404, verified 2026-08-09). Both surfaces here+therefore parse the public web pages:++- search: ``https://ollama.com/search?q=…`` (name, blurb, badges)+- tag list: ``https://ollama.com/library/{name}/tags`` (tag, size, context)++Scraping is a liability, so the contract is honest degradation: any fetch or+parse failure answers ``{"models"/"tags": [], "error": "<English sentence>"}``+and the panel keeps its free-text pull field, which needs no ollama.com at+all. The pull itself never depends on this module — the local server's+``/api/pull`` remains the authority on whether a name exists, so a stale or+wrong search result still ends in a clear "not in the library" message rather+than a broken install.++Parsers are deliberately structure-light: they anchor on ``/library/{name}``+hrefs and plain-text markers ("GB", "context window", "Pulls"), not on the+page's CSS classes, so a Tailwind reshuffle upstream does not blank the panel.+Guard: ``tests/integration/test_ollama_library_live.py`` parses the LIVE pages+and fails loudly when ollama.com changes shape for real.+"""++from __future__ import annotations++import html as html_lib+import logging+import re+import time+from typing import Any++import httpx++from jarvis.brain.ollama_pull import (+ _is_installed,+ accelerator_gb,+ fit_verdict,+ installed_models,+ total_memory_gb,+)++log = logging.getLogger(__name__)++_LIBRARY_ROOT = "https://ollama.com"++#: Short enough that a dead network fails the panel fast, long enough for the+#: ~250 KB tags page of a large model family on a slow line.+_FETCH_TIMEOUT = httpx.Timeout(connect=3.0, read=10.0, write=10.0, pool=10.0)++#: The library moves slowly (new models land daily, not per-second), and the+#: panel re-queries on every keystroke burst. Ten minutes keeps browsing snappy+#: without ever showing a week-old catalog.+_CACHE_TTL_SECONDS = 600.0++#: Search answers at most this many models. The page itself shows about this+#: many above the fold, and a narrower query beats scrolling page two.+_SEARCH_LIMIT = 25++#: Library model names as they appear in ``/library/{name}`` URLs. No slash on+#: purpose: community-namespaced models (``/{user}/{model}``) are out of scope+#: here, and the pattern doubles as the URL-injection guard for the tags fetch.+_NAME_RE = re.compile(r"[A-Za-z0-9._-]+")++#: Capability badges the search page renders, in display order. "cloud" is+#: 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:+ hit = cache.get(key)+ if hit and (time.monotonic() - hit[0]) < _CACHE_TTL_SECONDS:+ return hit[1]+ return None+++def _text(fragment: str) -> str:+ """Visible text of an HTML fragment: tags out, entities decoded, one space."""+ plain = re.sub(r"<[^>]+>", " ", fragment)+ return re.sub(r"\s+", " ", html_lib.unescape(plain)).strip()+++async def _fetch_page(+ path: str, params: dict[str, str] | None = None+) -> tuple[str | None, str | None]:+ """``(html, error)`` for one ollama.com page — exactly one is non-None."""+ url = f"{_LIBRARY_ROOT}{path}"+ try:+ async with httpx.AsyncClient(+ timeout=_FETCH_TIMEOUT,+ follow_redirects=True,+ headers={"User-Agent": "Jarvis-Agents local model browser"},+ ) as client:+ resp = await client.get(url, params=params or {})+ except Exception as exc: # noqa: BLE001 — offline is a normal state here+ log.info("ollama-library: %s unreachable (%s)", url, type(exc).__name__)+ return None, (+ "ollama.com did not answer, so the library cannot be browsed right "+ "now. Downloads by exact name still work."+ )+ if resp.status_code == 404:+ return None, "The Ollama library does not know this model."+ if resp.status_code != 200:+ return None, (+ f"ollama.com answered {resp.status_code}, so the library cannot be "+ "browsed right now. Downloads by exact name still work."+ )+ return resp.text, None+++# ── search ──────────────────────────────────────────────────────────────────+++def parse_search_html(page: str) -> list[dict[str, Any]]:+ """Model entries from a ``/search`` (or ``/library``) page, page order kept.++ Pure and offline-testable. Anchors on ``<li`` blocks that link to+ ``/library/{name}``; everything else about the markup is treated as noise.+ An entry that lost its blurb or badges upstream still lists with what could+ be read — a partial row beats a vanished model.+ """+ entries: list[dict[str, Any]] = []+ seen: set[str] = set()+ for block_match in re.finditer(r"<li\b(.*?)</li>", page, re.DOTALL):+ block = block_match.group(1)+ name_match = re.search(r'href="/library/([^"/:?#]+)"', block)+ if not name_match:+ continue+ name = name_match.group(1)+ if name in seen:+ continue+ seen.add(name)++ description = ""+ for para in re.finditer(r"<p\b[^>]*>(.*?)</p>", block, re.DOTALL):+ text = _text(para.group(1))+ # The stats line ("17.2M Pulls · 64 Tags · Updated …") is also a+ # <p>; the blurb is the first paragraph that is not it.+ if text and "Pulls" not in text and "Updated" not in text:+ description = text+ break++ spans = [_text(m.group(1)) for m in re.finditer(r"<span\b[^>]*>([^<]*)</span>", block)]+ spans = [s for s in spans if s]+ capabilities = [badge for badge in _CAPABILITY_BADGES if badge in spans]+ sizes = [s for s in spans if re.fullmatch(r"\d+(?:\.\d+)?[bm]", s)]++ pulls_match = re.search(+ r">\s*([\d.,]+[KMB]?)\s*</span>\s*<span[^>]*>(?: |\s)*Pulls", block+ )+ updated = next((s for s in spans if s.endswith(" ago") or s == "yesterday"), "")++ entries.append(+ {+ "name": name,+ "description": description,+ "capabilities": capabilities,+ "cloud": "cloud" in spans,+ "sizes": sizes,+ "pulls": pulls_match.group(1) if pulls_match else "",+ "updated": updated,+ }+ )+ if len(entries) >= _SEARCH_LIMIT:+ break+ return entries+++async def search_library(query: str) -> dict[str, Any]:+ """Search the public library; an empty query lists the popular models.++ ``installed`` is judged against the LOCAL server's inventory, so a model+ 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)++ installed, _inventory_error = await installed_models()+ for model in models:+ name = model["name"]+ model["installed"] = name in {i.partition(":")[0] for i in installed} or _is_installed(+ name, installed+ )++ result = {"query": q, "models": models, "error": None}+ _search_cache[q] = (time.monotonic(), result)+ return result+++# ── tags ────────────────────────────────────────────────────────────────────+++def parse_tags_html(page: str, name: str) -> list[dict[str, Any]]:+ """Tag entries from a ``/library/{name}/tags`` page, page order kept.++ The page renders each tag twice (a mobile and a desktop block). Instead of+ depending on either block's classes, this walks the FIRST occurrence of+ each distinct ``/library/{name}:{tag}`` href and reads the plain-text facts+ ("6.6GB", "256K context window", "Text, Image input", "5 months ago") from+ the window up to the next distinct tag.+ """+ href_re = re.compile(rf'href="/library/{re.escape(name)}:([^"?#]+)"')+ matches = list(href_re.finditer(page))+ first_seen: list[tuple[str, int]] = []+ seen: set[str] = set()+ for match in matches:+ tag = match.group(1)+ if tag not in seen:+ seen.add(tag)+ first_seen.append((tag, match.start()))++ entries: list[dict[str, Any]] = []+ for index, (tag, start) in enumerate(first_seen):+ 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)+ 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)++ entries.append(+ {+ "tag": tag,+ "id": f"{name}:{tag}",+ "size_gb": float(size_match.group(1)) 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 "",+ # A hosting fact from the tag NAME, never inferred from a+ # missing size: parse drift must degrade to "size unknown",+ # not to hiding a local tag as cloud-only.+ "cloud": tag == "cloud" or tag.endswith("-cloud"),+ }+ )+ return entries+++async def library_tags(model: str) -> dict[str, Any]:+ """Every tag of ``model`` with size, fit verdict and installed state.++ The fit verdict reuses the SAME rule the curated shortlist applies+ (:func:`jarvis.brain.ollama_pull.fit_verdict`), so "tight" means the same+ thing on both halves of the panel.+ """+ 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.",+ }++ installed, _inventory_error = await installed_models()+ memory_gb = total_memory_gb()+ accel, _accel_source = accelerator_gb()+ for entry in tags:+ entry["installed"] = _is_installed(entry["id"], installed)+ if entry["cloud"] or entry["size_gb"] is None:+ entry["fit"], entry["fit_note"] = "unknown", ""+ 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 resultdiff --git a/tests/fixtures/brain/ollama_search.html b/tests/fixtures/brain/ollama_search.htmlnew file mode 100644index 0000000000..6ca399e1b8--- /dev/null+++ b/tests/fixtures/brain/ollama_search.html@@ -0,0 +1,87 @@+<!-- Trimmed snapshot of https://ollama.com/search?q=qwen (2026-08-09).+ Structure verbatim from the live page; entries cut to three and SVG paths+ shortened. The parser must anchor on hrefs and text markers, never on the+ Tailwind classes kept here. -->+<main>+ <ul>+ <li class="flex items-baseline border-b border-neutral-200 py-6">+ <a href="/library/qwen3.5" class="group w-full">+ <div class="flex flex-col mb-1" title="qwen3.5">+ <h2 class="truncate text-xl font-medium underline-offset-2 group-hover:underline md:text-2xl">+ <span >qwen3.5</span>+ </h2>+ <p class="max-w-lg break-words text-neutral-800 text-md">Qwen 3.5 is a family of open-source multimodal models that delivers exceptional utility and performance.</p>+ </div>+ <div class="flex flex-col">+ <div class="flex flex-wrap space-x-2">+ <span class="inline-flex my-1 items-center rounded-md bg-indigo-50 px-2 py-[2px] text-xs font-medium text-indigo-600 sm:text-[13px]">vision</span>+ <span class="inline-flex my-1 items-center rounded-md bg-indigo-50 px-2 py-[2px] text-xs font-medium text-indigo-600 sm:text-[13px]">tools</span>+ <span class="inline-flex my-1 items-center rounded-md bg-indigo-50 px-2 py-[2px] text-xs font-medium text-indigo-600 sm:text-[13px]">thinking</span>+ <span class="inline-flex my-1 items-center rounded-md bg-cyan-50 px-2 py-[2px] text-xs font-medium text-cyan-500 sm:text-[13px]">cloud</span>+ <span class="inline-flex my-1 items-center rounded-md bg-[#ddf4ff] px-2 py-[2px] text-xs font-medium text-blue-600 sm:text-[13px]">0.8b</span>+ <span class="inline-flex my-1 items-center rounded-md bg-[#ddf4ff] px-2 py-[2px] text-xs font-medium text-blue-600 sm:text-[13px]">2b</span>+ <span class="inline-flex my-1 items-center rounded-md bg-[#ddf4ff] px-2 py-[2px] text-xs font-medium text-blue-600 sm:text-[13px]">122b</span>+ </div>+ <p class="my-1 flex space-x-5 text-[13px] font-medium text-neutral-500">+ <span class="flex items-center">+ <svg xmlns="http://www.w3.org/2000/svg" class="mr-1.5 h-[14px] w-[14px] sm:h-4 sm:w-4"></svg>+ <span >17.2M</span>+ <span class="hidden sm:flex"> Pulls</span>+ </span>+ <span class="flex items-center">+ <svg xmlns="http://www.w3.org/2000/svg" class="mr-1.5 h-[14px] w-[14px] sm:h-4 sm:w-4"></svg>+ <span >64</span>+ <span class="hidden sm:flex"> Tags</span>+ </span>+ <span class="flex items-center" title="May 21, 2026 7:08 PM UTC">+ <svg xmlns="http://www.w3.org/2000/svg" class="mr-1.5 h-[14px] w-[14px] sm:h-4 sm:w-4"></svg>+ <span class="hidden sm:flex">Updated </span>+ <span >2 months ago</span>+ </span>+ </p>+ </div>+ </a>+ </li>+ <li class="flex items-baseline border-b border-neutral-200 py-6">+ <a href="/library/qwen3-embedding" class="group w-full">+ <div class="flex flex-col mb-1" title="qwen3-embedding">+ <h2 class="truncate text-xl font-medium underline-offset-2 group-hover:underline md:text-2xl">+ <span >qwen3-embedding</span>+ </h2>+ <p class="max-w-lg break-words text-neutral-800 text-md">The Qwen3 Embedding model series is specifically designed for text embedding and ranking tasks.</p>+ </div>+ <div class="flex flex-col">+ <div class="flex flex-wrap space-x-2">+ <span class="inline-flex my-1 items-center rounded-md bg-indigo-50 px-2 py-[2px] text-xs font-medium text-indigo-600 sm:text-[13px]">embedding</span>+ <span class="inline-flex my-1 items-center rounded-md bg-[#ddf4ff] px-2 py-[2px] text-xs font-medium text-blue-600 sm:text-[13px]">0.6b</span>+ <span class="inline-flex my-1 items-center rounded-md bg-[#ddf4ff] px-2 py-[2px] text-xs font-medium text-blue-600 sm:text-[13px]">4b</span>+ </div>+ <p class="my-1 flex space-x-5 text-[13px] font-medium text-neutral-500">+ <span class="flex items-center">+ <svg xmlns="http://www.w3.org/2000/svg" class="mr-1.5 h-[14px] w-[14px] sm:h-4 sm:w-4"></svg>+ <span >1.4M</span>+ <span class="hidden sm:flex"> Pulls</span>+ </span>+ <span class="flex items-center" title="Jan 3, 2026 1:00 PM UTC">+ <svg xmlns="http://www.w3.org/2000/svg" class="mr-1.5 h-[14px] w-[14px] sm:h-4 sm:w-4"></svg>+ <span class="hidden sm:flex">Updated </span>+ <span >7 months ago</span>+ </span>+ </p>+ </div>+ </a>+ </li>+ <li class="flex items-baseline border-b border-neutral-200 py-6">+ <a href="/library/deepscaler" class="group w-full">+ <div class="flex flex-col mb-1" title="deepscaler">+ <h2 class="truncate text-xl font-medium underline-offset-2 group-hover:underline md:text-2xl">+ <span >deepscaler</span>+ </h2>+ <p class="max-w-lg break-words text-neutral-800 text-md">A fine-tuned version of Deepseek-R1-Distilled-Qwen-1.5B.</p>+ </div>+ </a>+ </li>+ <!-- A nav item without a /library/ link: the parser must skip it. -->+ <li class="nav"><a href="/download">Download</a></li>+ </ul>+</main>diff --git a/tests/fixtures/brain/ollama_tags.html b/tests/fixtures/brain/ollama_tags.htmlnew file mode 100644index 0000000000..a253d7c3e9--- /dev/null+++ b/tests/fixtures/brain/ollama_tags.html@@ -0,0 +1,81 @@+<!-- Trimmed snapshot of https://ollama.com/library/qwen3.5/tags (2026-08-09).+ The live page renders EVERY tag twice — a mobile <a> block and a desktop+ grid block — which is why each tag appears with two hrefs here. The parser+ must dedupe on first occurrence and read the plain-text facts from the+ window between distinct tags. -->+<main>+ <div class="group px-4 py-3">+ <a href="/library/qwen3.5:latest" class="md:hidden flex flex-col space-y-[6px] group">+ <div class="flex items-center font-medium">+ <span class="group-hover:underline">qwen3.5:latest</span>+ </div>+ <div class="flex flex-col text-neutral-500 text-[13px]">+ <span>+ <span class="font-mono">6488c96fa5fa</span> • 6.6GB • 256K context window •+ <span class="hidden sm:inline">Text, Image 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:latest" class="group-hover:underline">qwen3.5:latest</a>+ <input class="command hidden" value="qwen3.5:latest" />+ </span>+ <p class="col-span-2 text-neutral-500 text-[13px]">6.6GB</p>+ <p class="col-span-2 text-neutral-500 text-[13px]">256K</p>+ <div class="col-span-2 text-neutral-500 text-[13px] ">Text, Image</div>+ </div>+ <div class="flex text-neutral-500 text-xs items-center">+ <span class="font-mono text-[11px]">6488c96fa5fa</span> · 5 months ago+ </div>+ </div>+ </div>+ <div class="group px-4 py-3">+ <a href="/library/qwen3.5:cloud" class="md:hidden flex flex-col space-y-[6px] group">+ <div class="flex items-center font-medium">+ <span class="group-hover:underline">qwen3.5:cloud</span>+ </div>+ <div class="flex flex-col text-neutral-500 text-[13px]">+ <span>+ <span class="font-mono">a11b2c3d4e5f</span> • 256K context window •+ <span class="hidden sm:inline">Text, Image 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:cloud" class="group-hover:underline">qwen3.5:cloud</a>+ <input class="command hidden" value="qwen3.5:cloud" />+ </span>+ <p class="col-span-2 text-neutral-500 text-[13px]">256K</p>+ <div class="col-span-2 text-neutral-500 text-[13px] ">Text, Image</div>+ </div>+ </div>+ </div>+ <div class="group px-4 py-3">+ <a href="/library/qwen3.5:0.8b" 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.8b</span>+ </div>+ <div class="flex flex-col text-neutral-500 text-[13px]">+ <span>+ <span class="font-mono">9f8e7d6c5b4a</span> • 0.7GB • 128K 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.8b" class="group-hover:underline">qwen3.5:0.8b</a>+ <input class="command hidden" value="qwen3.5:0.8b" />+ </span>+ <p class="col-span-2 text-neutral-500 text-[13px]">0.7GB</p>+ <p class="col-span-2 text-neutral-500 text-[13px]">128K</p>+ <div class="col-span-2 text-neutral-500 text-[13px] ">Text</div>+ </div>+ </div>+ </div>+</main>diff --git a/tests/integration/test_ollama_library_live.py b/tests/integration/test_ollama_library_live.pynew file mode 100644index 0000000000..fc230f9923--- /dev/null+++ b/tests/integration/test_ollama_library_live.py@@ -0,0 +1,56 @@+"""The library browser's parsers must keep understanding the LIVE ollama.com.++The unit tests pin the parsers against snapshots, which by definition cannot+notice ollama.com shipping a redesign. This is the guard that can: it fetches+the real search and tags pages and asserts the parsers still read them. The+moment the markup drifts past what the anchors tolerate, this fails loudly at+CI time instead of a user finding an inexplicably empty library panel.++Network-dependent, so it is marked ``integration`` and self-skips when+ollama.com cannot be reached. Run explicitly with ``pytest -m integration``.+"""++from __future__ import annotations++import httpx+import pytest++from jarvis.brain.ollama_library import parse_search_html, parse_tags_html++pytestmark = pytest.mark.integration++_TIMEOUT = 15.0+++def _fetch(url: str) -> str:+ try:+ resp = httpx.get(url, timeout=_TIMEOUT, follow_redirects=True)+ except Exception as exc: # noqa: BLE001 — offline is a skip, not a failure+ pytest.skip(f"ollama.com unreachable: {type(exc).__name__} {exc}")+ if resp.status_code != 200:+ pytest.skip(f"ollama.com answered {resp.status_code}")+ return resp.text+++def test_the_live_search_page_still_parses() -> None:+ models = parse_search_html(_fetch("https://ollama.com/search?q=qwen"))+ assert len(models) >= 5, (+ "The live search page for 'qwen' parsed almost empty — ollama.com has "+ "likely changed its markup. Update parse_search_html and the fixture."+ )+ names = {m["name"] for m in models}+ assert any("qwen" in n for n in names)+ # At least the flagship entries carry the facts the panel renders.+ rich = [m for m in models if m["description"] and m["sizes"]]+ assert rich, "No parsed entry carries a description and sizes any more."+++def test_the_live_tags_page_still_parses() -> None:+ tags = parse_tags_html(_fetch("https://ollama.com/library/qwen3.5/tags"), "qwen3.5")+ assert len(tags) >= 5, (+ "The live tags page parsed almost empty — ollama.com has likely "+ "changed its markup. Update parse_tags_html and the fixture."+ )+ with_size = [t for t in tags if t["size_gb"]]+ assert with_size, "No parsed tag carries a download size any more."+ assert any(t["tag"] == "latest" for t in tags)diff --git a/tests/unit/brain/test_ollama_library.py b/tests/unit/brain/test_ollama_library.pynew file mode 100644index 0000000000..fef1eb7402--- /dev/null+++ b/tests/unit/brain/test_ollama_library.py@@ -0,0 +1,211 @@+"""Browsing the full Ollama library: tolerant parsers, honest degradation.++The library browser scrapes ollama.com because there is no JSON search API and+the registry's ``tags/list`` answers 404. Scraping earns its keep only if it+fails HONESTLY: a page that stops parsing must surface as an error sentence,+never as a silently empty panel, and a missing size must read "unknown" — not+quietly reclassify a local tag as cloud-only. These tests pin the parsers+against trimmed snapshots of the real pages and the degradation contract+against a faked fetch layer.+"""++from __future__ import annotations++from pathlib import Path++import pytest++import jarvis.brain.ollama_library as library++_FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "brain"++[email protected](autouse=True)+def _fresh_caches():+ """Module caches survive the process on purpose; tests must not share them."""+ library._search_cache.clear()+ library._tags_cache.clear()+ yield+ library._search_cache.clear()+ library._tags_cache.clear()+++def search_page() -> str:+ return (_FIXTURES / "ollama_search.html").read_text(encoding="utf-8")+++def tags_page() -> str:+ return (_FIXTURES / "ollama_tags.html").read_text(encoding="utf-8")+++# ── search parser ────────────────────────────────────────────────────────+++def test_search_parser_reads_the_full_entry(search_page: str) -> None:+ models = library.parse_search_html(search_page)+ assert [m["name"] for m in models] == ["qwen3.5", "qwen3-embedding", "deepscaler"]++ qwen = models[0]+ assert qwen["description"].startswith("Qwen 3.5 is a family")+ assert qwen["capabilities"] == ["vision", "tools", "thinking"]+ assert qwen["cloud"] is True+ assert qwen["sizes"] == ["0.8b", "2b", "122b"]+ assert qwen["pulls"] == "17.2M"+ assert qwen["updated"] == "2 months ago"+++def test_search_parser_keeps_a_minimal_entry(search_page: str) -> None:+ """An entry the page renders without badges still lists — a partial row+ beats a vanished model."""+ minimal = library.parse_search_html(search_page)[2]+ assert minimal["name"] == "deepscaler"+ assert minimal["capabilities"] == []+ assert minimal["sizes"] == []+ assert minimal["pulls"] == ""+ assert minimal["cloud"] is False+++def test_search_parser_skips_non_library_items(search_page: str) -> None:+ """The nav <li> linking /download must not become a phantom model."""+ names = {m["name"] for m in library.parse_search_html(search_page)}+ assert "download" not in {n.lower() for n in names}+++def test_search_parser_answers_empty_on_garbage() -> None:+ assert library.parse_search_html("<html><body>maintenance</body></html>") == []+++# ── tags parser ──────────────────────────────────────────────────────────+++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"]+++def test_tags_parser_reads_size_context_and_inputs(tags_page: str) -> None:+ latest = library.parse_tags_html(tags_page, "qwen3.5")[0]+ assert latest["id"] == "qwen3.5:latest"+ assert latest["size_gb"] == 6.6+ assert latest["context"] == "256K"+ assert latest["inputs"] == "Text, Image"+ assert latest["updated"] == "5 months ago"+ assert latest["cloud"] is False+++def test_tags_parser_flags_cloud_from_the_name_only(tags_page: str) -> None:+ """Cloud is a NAME fact. A local tag whose size fails to parse must stay+ size-unknown, never become cloud-only."""+ tags = library.parse_tags_html(tags_page, "qwen3.5")+ cloud = next(t for t in tags if t["tag"] == "cloud")+ assert cloud["cloud"] is True+ assert cloud["size_gb"] is None++ broken = library.parse_tags_html(+ '<a href="/library/x:4b">x:4b</a> no size markers here', "x"+ )+ assert broken[0]["cloud"] is False+ assert broken[0]["size_gb"] is None+++# ── async surfaces: degradation, enrichment, caching ─────────────────────+++def _fake_fetch(page: str | None, error: str | None, calls: list[str]):+ async def fetch(+ path: str, params: dict[str, str] | None = None+ ) -> tuple[str | None, str | None]:+ calls.append(path)+ return page, error++ return fetch+++def _machine(monkeypatch):+ """A machine with 32 GB RAM, no GPU, and qwen3.5:latest already pulled."""++ async def _installed() -> tuple[set[str], str | None]:+ return {"qwen3.5:latest"}, 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"))+++async def test_search_marks_installed_models(monkeypatch, search_page: str, _machine) -> None:+ monkeypatch.setattr(library, "_fetch_page", _fake_fetch(search_page, None, []))+ result = await library.search_library("qwen")+ assert result["error"] is None+ by_name = {m["name"]: m for m in result["models"]}+ assert by_name["qwen3.5"]["installed"] is True+ assert by_name["deepscaler"]["installed"] is False+++async def test_search_degrades_honestly_when_offline(monkeypatch, _machine) -> None:+ monkeypatch.setattr(+ library, "_fetch_page", _fake_fetch(None, "ollama.com did not answer …", [])+ )+ result = await library.search_library("qwen")+ assert result["models"] == []+ assert "ollama.com" in result["error"]+++async def test_search_caches_per_query(monkeypatch, search_page: str, _machine) -> None:+ calls: list[str] = []+ monkeypatch.setattr(library, "_fetch_page", _fake_fetch(search_page, None, calls))+ await library.search_library("qwen")+ await library.search_library("qwen")+ assert len(calls) == 1+++async def test_tags_enrich_with_fit_and_installed(monkeypatch, tags_page: str, _machine) -> None:+ monkeypatch.setattr(library, "_fetch_page", _fake_fetch(tags_page, None, []))+ result = await library.library_tags("qwen3.5")+ assert result["error"] is None+ by_tag = {t["tag"]: t for t in result["tags"]}+ assert by_tag["latest"]["installed"] is True+ assert by_tag["latest"]["fit"] == "comfortable"+ assert by_tag["0.8b"]["installed"] is False+ # No size → no invented verdict.+ assert by_tag["cloud"]["fit"] == "unknown"+ assert by_tag["cloud"]["fit_note"] == ""+++async 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+ the fetch layer."""+ result = await library.library_tags("../evil")+ assert result["tags"] == []+ assert result["error"] == "Not a valid library model name."+++async def test_tags_error_when_the_page_stops_parsing(monkeypatch, _machine) -> None:+ """A shape change upstream must surface as a sentence, not an empty list+ that reads as 'this model has no versions'."""+ monkeypatch.setattr(+ library, "_fetch_page", _fake_fetch("<html>redesigned beyond recognition</html>", None, [])+ )+ result = await library.library_tags("qwen3.5")+ assert result["tags"] == []+ assert "qwen3.5" in result["error"]+++async def test_tags_pass_through_a_404_as_unknown_model(monkeypatch, _machine) -> None:+ monkeypatch.setattr(+ library,+ "_fetch_page",+ _fake_fetch(None, "The Ollama library does not know this model.", []),+ )+ result = await library.library_tags("nonexistent-model")+ assert result["tags"] == []+ assert "does not know" in result["error"]