Skip to content

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.

fix(brain): stop a text-only local model from advertising vision

rubenluetke10-beepb56e1b6988f4
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index d9191f8567..f302ae62d5 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -32,7 +32,7 @@ import json
import logging
import re
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
import httpx
@@ -1640,7 +1640,59 @@ class ModelCatalog:
)
resp = await client.get(url, params=params)
resp.raise_for_status()
- return parse_models_response(provider, resp.json())
+ models = parse_models_response(provider, resp.json())
+ if provider == "ollama":
+ models = await self._enrich_ollama_capabilities(client, url, models)
+ return models
+
+ @staticmethod
+ async def _enrich_ollama_capabilities(
+ client: httpx.AsyncClient, tags_url: str, models: list[ModelInfo]
+ ) -> list[ModelInfo]:
+ """Attach each download's DECLARED capabilities from ``/api/show``.
+
+ ``/api/tags`` lists what is installed but says nothing about what each
+ model can DO, so a local install used to reach every capability consumer
+ as "unknown" — and unknown means "assume capable". A host whose only pull
+ is text-only therefore advertised vision, and Screen Context happily
+ asked it about a screenshot it could not see.
+
+ Ollama answers per model instead of per catalog, so this is one small
+ POST per download (a LAN/localhost round-trip, bounded concurrency). The
+ declared capability names are mapped onto the SAME generic fields the
+ gateway catalogs fill, so ``model_capabilities`` / ``pick_vision_model``
+ / ``provider_has_modality_data`` need no local-server special case.
+
+ Fail-open per model: a download whose probe does not answer keeps its
+ unknown (``None``) fields and is treated as capable, exactly as before.
+ Embedding-only downloads are DROPPED — offering bge-m3 in a brain picker
+ guarantees a 400 on the first chat turn.
+ """
+ root = tags_url[: -len("/api/tags")] if tags_url.endswith("/api/tags") else tags_url
+ semaphore = asyncio.Semaphore(8)
+
+ async def probe(info: ModelInfo) -> ModelInfo | None:
+ async with semaphore:
+ try:
+ resp = await client.post(f"{root}/api/show", json={"model": info.id})
+ resp.raise_for_status()
+ caps = resp.json().get("capabilities")
+ except Exception as exc: # noqa: BLE001 — unknown stays capable
+ log.debug("ollama: /api/show failed for %s: %s", info.id, exc)
+ return info
+ if not isinstance(caps, list):
+ return info
+ declared = {str(c) for c in caps}
+ if "completion" not in declared:
+ return None
+ return replace(
+ info,
+ input_modalities=("text", "image") if "vision" in declared else ("text",),
+ supported_parameters=("tools",) if "tools" in declared else (),
+ )
+
+ probed = await asyncio.gather(*(probe(m) for m in models))
+ return [m for m in probed if m is not None]
# -- static fallback ----------------------------------------------
diff --git a/jarvis/plugins/brain/local_openai.py b/jarvis/plugins/brain/local_openai.py
index ea2b76a83c..c941823272 100644
--- a/jarvis/plugins/brain/local_openai.py
+++ b/jarvis/plugins/brain/local_openai.py
@@ -16,11 +16,14 @@ behind a reverse proxy, vLLM with ``--api-key``) check it. Keyless by design
``PROVIDER_SECRET_CANDIDATES`` so the key-aware resolver treats it as always
reachable and a dead server just fast-fails across families.
-Vision is deliberately declared unsupported: whether a given local server
-accepts image content is unknowable here, and the shared streamer then DROPS
-images with a warning instead of letting a text-only server reject the whole
-turn. Vision users take the Ollama card (which negotiates real multimodal
-models) or a cloud brain.
+Vision defaults to UNSUPPORTED and is only ever raised by evidence: whether a
+given local server accepts image content is unknowable in general, so the
+shared streamer DROPS images with a warning rather than letting a text-only
+server reject the whole turn. When the server's own ``/v1/models`` DOES declare
+image input for the selected model (some OpenAI-compatible servers publish the
+modality fields), the cached catalog carries that declaration and this brain
+believes it. Unknown stays blind — a confident description of a picture nobody
+looked at is the failure mode worth being conservative about.
"""
from __future__ import annotations
@@ -52,6 +55,26 @@ _NO_BASE_URL_HELP = (
)
+def _declared_vision_support(model: str) -> bool:
+ """Whether the SELECTED model declares image input, from the cached catalog.
+
+ Mirrors the Ollama card's probe but with the opposite default: Ollama can
+ ask its server what each download can do, a generic OpenAI-compatible
+ server usually cannot be asked at all — so silence means blind here.
+ Synchronous by necessity (``resolve_vision_brain`` asks before any call) and
+ therefore cache-only; it never touches the network.
+ """
+ if not model:
+ return False
+ try:
+ from jarvis.brain.model_catalog import model_capabilities # noqa: PLC0415 — lazy (AP-26)
+
+ return model_capabilities("local-openai", model)["vision"] is True
+ except Exception: # noqa: BLE001 — a probe must never break construction
+ log.debug("local-openai: vision capability probe failed — staying blind")
+ return False
+
+
class LocalOpenAIBrain:
name: str = "local-openai"
# Conservative floor — the real window depends on the served model; the
@@ -65,6 +88,7 @@ class LocalOpenAIBrain:
self._client: Any = None
self._server_root: str | None = None
self._credential: str | None = None
+ self.supports_vision = _declared_vision_support(self._model)
def can_call_tools(self) -> bool:
return self.supports_tools
diff --git a/jarvis/plugins/brain/ollama.py b/jarvis/plugins/brain/ollama.py
index 78c03b71a4..ec6f9b4a7c 100644
--- a/jarvis/plugins/brain/ollama.py
+++ b/jarvis/plugins/brain/ollama.py
@@ -17,9 +17,19 @@ the recommended pull.
Model discovery is NATIVE (``/api/tags`` + ``/api/show``): with no configured
model the brain runs the smallest DOWNLOADED model whose declared capabilities
-match the turn (``completion``, plus ``tools`` for tool turns); ``:cloud``
-references never count as local, and a model-less server produces an honest
-"pull one first" error instead of a hardcoded default that would 404.
+match the turn (``completion``, plus ``tools`` for tool turns, plus ``vision``
+for a turn carrying images); ``:cloud`` references never count as local, and a
+model-less server produces an honest "pull one first" error instead of a
+hardcoded default that would 404.
+
+**Vision is a MODEL property, never a server property.** A blanket
+``supports_vision = True`` on the class made every Ollama install advertise
+sight: ``resolve_vision_brain`` picked it for Screen Context and the CU planner
+let it plan from screenshots, so a host whose only pull is a text-only model
+answered *about* the picture it had never seen. The flag is therefore resolved
+per SELECTED model from the cached catalog (the same route OpenRouter takes),
+the image path negotiates a ``vision``-capable download, and a server without
+one raises an honest error instead of describing a screenshot blind.
"""
from __future__ import annotations
@@ -45,6 +55,10 @@ DEFAULT_SERVER_ROOT = "http://localhost:11434"
# defects there). Used in error/help text only — never silently pulled.
RECOMMENDED_PULL = "qwen3.5"
+# The multimodal counterpart, named only in help text for a turn that carries
+# images and finds no ``vision``-capable download. Never silently pulled.
+RECOMMENDED_VISION_PULL = "qwen3-vl"
+
# Local server: an unreachable endpoint must fail fast (2 s) so the fallback
# chain moves on, while a slow CPU-bound generation may legitimately stream
# for minutes — hence the wide read timeout.
@@ -72,6 +86,54 @@ def normalize_server_root(url: str) -> str:
return root.rstrip("/")
+def _request_has_images(req: BrainRequest) -> bool:
+ """True when any user message of ``req`` carries an image block.
+
+ ``getattr`` for the same backwards-compatibility reason the shared streamer
+ uses it: a Protocol predating multimodal messages has no ``images`` field.
+ """
+ for message in getattr(req, "messages", ()) or ():
+ if getattr(message, "images", ()):
+ return True
+ return False
+
+
+def _declared_vision_support(model: str) -> bool:
+ """Whether this install can be handed an image, read SYNCHRONOUSLY.
+
+ ``resolve_vision_brain`` and the CU planner ask for ``supports_vision``
+ before any call has been made, so the answer may not hit the network here
+ (that would block the caller's event loop). It comes from the cached model
+ catalog instead, which stores each download's declared ``/api/show``
+ capabilities under the generic modality fields.
+
+ Fail-OPEN on unknown: with a configured model whose capabilities are not
+ cached, or a catalog that has never been fetched on this host, the answer
+ stays ``True`` — the image path then negotiates a real vision model and
+ raises an honest error if there is none, which is strictly better than
+ declaring an install blind and silently routing every screenshot to the
+ cloud. Fail-CLOSED once the catalog actually says no: a server whose
+ downloads are all text-only answers ``False`` and drops out of the vision
+ chain, so the resolver crosses to a provider that can see (AP-21/AP-22).
+ """
+ try:
+ from jarvis.brain.model_catalog import ( # noqa: PLC0415 — lazy (AP-26)
+ model_capabilities,
+ pick_vision_model,
+ provider_has_modality_data,
+ )
+
+ if model:
+ vision = model_capabilities("ollama", model)["vision"]
+ return True if vision is None else bool(vision)
+ if not provider_has_modality_data("ollama"):
+ return True
+ return pick_vision_model("ollama") is not None
+ except Exception: # noqa: BLE001 — a probe must never break construction
+ log.debug("ollama: vision capability probe failed — assuming capable")
+ return True
+
+
def default_server_root() -> str:
"""Vendor-default server root: ``OLLAMA_HOST`` if set, else localhost.
@@ -86,6 +148,11 @@ class OllamaBrain:
# Conservative floor — the real window is model-dependent (the qwen line
# reaches 128k); the manager treats this as a budget hint, not a hard cap.
context_window: int = 32_768
+ # Class-attr DEFAULTS (capable). The INSTANCE narrows them per selected
+ # model in ``__init__`` and again once the server has answered — an Ollama
+ # server serves whatever the user pulled, and a text-only pull must not be
+ # sent screenshots (the vision resolver and the CU planner both gate on
+ # ``supports_vision``).
supports_tools: bool = True
supports_vision: bool = True
@@ -94,10 +161,14 @@ class OllamaBrain:
self._client: Any = None
self._server_root: str | None = None
self._credential: str | None = None
- # Discovery cache per requirement profile (False = plain chat,
- # True = chat + tools) — a tool-less turn may run a smaller model
- # than a tool turn without re-asking the server every time.
- self._discovered: dict[bool, str] = {}
+ # Discovery cache per requirement profile (tools, vision) — a plain
+ # chat turn may run a smaller model than a tool turn or an image turn
+ # without re-asking the server every time.
+ self._discovered: dict[tuple[bool, bool], str] = {}
+ # Per-model ``/api/show`` capability cache, shared by discovery and the
+ # image path so one turn never probes the same download twice.
+ self._caps_cache: dict[str, set[str] | None] = {}
+ self.supports_vision = _declared_vision_support(self._model)
def can_call_tools(self) -> bool:
return self.supports_tools
@@ -128,7 +199,9 @@ class OllamaBrain:
)
return self._client
- async def _resolve_model(self, *, need_tools: bool = False) -> str:
+ async def _resolve_model(
+ self, *, need_tools: bool = False, need_vision: bool = False
+ ) -> str:
"""The configured model, else the smallest CAPABLE download.
Hard rules for the silent default (three live incidents 2026-07-25):
@@ -139,13 +212,16 @@ class OllamaBrain:
32 GB box and froze the whole desktop) — but only one whose DECLARED
``/api/show`` capabilities match the turn: ``completion`` always
(bge-m3 would 400 on chat), plus ``tools`` when the request carries
- tools (deepseek-llm 400s on a tool turn). The user's explicit model
- pick always overrides this.
+ tools (deepseek-llm 400s on a tool turn), plus ``vision`` when it
+ carries images (a text-only model does not refuse a screenshot — it
+ answers about the words around it). The user's explicit model pick
+ always overrides this.
"""
if self._model:
return self._model
- if need_tools in self._discovered:
- return self._discovered[need_tools]
+ profile = (need_tools, need_vision)
+ if profile in self._discovered:
+ return self._discovered[profile]
root = self._resolve_root()
try:
async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:
@@ -178,42 +254,99 @@ class OllamaBrain:
continue
if need_tools and "tools" not in caps:
continue
- self._discovered[need_tools] = name
+ # Vision is the one requirement that must NOT fail open: an
+ # unprobeable model is skipped rather than handed a screenshot
+ # it cannot see, because a blind answer looks exactly like a
+ # sighted one.
+ if need_vision and "vision" not in caps:
+ continue
+ elif need_vision:
+ continue
+ self._discovered[(need_tools, need_vision)] = name
log.info(
- "ollama: no model configured — using smallest capable download (tools=%s): %s",
+ "ollama: no model configured — using smallest capable download "
+ "(tools=%s, vision=%s): %s",
need_tools,
+ need_vision,
name,
)
return name
+ if need_vision:
+ self.supports_vision = False
+ raise RuntimeError(
+ f"None of the models downloaded at {root} can see images — run: "
+ f"ollama pull {RECOMMENDED_VISION_PULL} (a multimodal model), "
+ "then retry."
+ )
wanted = "chat + tool calling" if need_tools else "chat"
raise RuntimeError(
f"None of the models downloaded at {root} supports {wanted} — run: "
f"ollama pull {RECOMMENDED_PULL}, then retry."
)
- @staticmethod
- async def _capabilities(name: str, root: str) -> set[str] | None:
+ async def _capabilities(self, name: str, root: str) -> set[str] | None:
"""DECLARED capabilities of one download via native ``/api/show``.
Gate on capability, never the model name (AP-21). ``None`` = the probe
- could not answer — the caller FAILS OPEN and accepts the candidate (a
- probe glitch must never brick the pick; the real call then errors
- honestly)."""
+ could not answer — the caller FAILS OPEN for chat/tools (a probe glitch
+ must never brick the pick; the real call then errors honestly) and
+ fails CLOSED for vision, where a wrong yes is invisible.
+
+ Cached per model for the lifetime of the brain instance: discovery and
+ the image path both ask, and the answer only changes when the user
+ re-pulls a model — at which point the catalog TTL and a new instance
+ pick it up.
+ """
+ if name in self._caps_cache:
+ return self._caps_cache[name]
+ caps_set: set[str] | None = None
try:
async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:
resp = await client.post(f"{root}/api/show", json={"model": name})
resp.raise_for_status()
caps = resp.json().get("capabilities")
+ if isinstance(caps, list):
+ caps_set = {str(c) for c in caps}
except Exception: # noqa: BLE001 — probe glitch must not block the pick
- return None
- if not isinstance(caps, list):
- return None
- return {str(c) for c in caps}
+ caps_set = None
+ self._caps_cache[name] = caps_set
+ return caps_set
+
+ async def _pinned_model_can_see(self, model: str) -> bool:
+ """Whether the user's PINNED model declares ``vision`` (``/api/show``).
+
+ Fails CLOSED on an unanswerable probe: an image turn must not run on a
+ model we cannot confirm as multimodal.
+ """
+ caps = await self._capabilities(model, self._resolve_root())
+ return caps is not None and "vision" in caps
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
client = self._ensure_client()
- model = await self._resolve_model(need_tools=bool(req.tools))
- async for delta in stream_complete(client, model, req):
+ need_vision = _request_has_images(req)
+ model = await self._resolve_model(
+ need_tools=bool(req.tools), need_vision=need_vision
+ )
+ if need_vision and self._model and not await self._pinned_model_can_see(model):
+ # A pinned text-only model is the user's own choice, so we do not
+ # silently swap it — but we also refuse to answer about a picture
+ # it never saw. The caller degrades honestly (Screen Context says
+ # it cannot look; the CU planner skips this brain).
+ self.supports_vision = False
+ raise RuntimeError(
+ f"The configured Ollama model '{model}' cannot see images. Pick a "
+ f"multimodal model on the Ollama card (ollama pull "
+ f"{RECOMMENDED_VISION_PULL}), or leave the model empty so Jarvis "
+ "picks a vision-capable download for image turns."
+ )
+ if need_vision:
+ # The negotiated model DOES see — keep the instance flag honest for
+ # the next synchronous resolver question.
+ self.supports_vision = True
+ # Invariant at this point: either the request carries no images, or the
+ # model just negotiated declares ``vision`` — so the streamer may encode
+ # them.
+ async for delta in stream_complete(client, model, req, supports_vision=True):
yield delta
def estimate_cost(self, req: BrainRequest) -> float:
diff --git a/tests/unit/brain/test_model_catalog_local.py b/tests/unit/brain/test_model_catalog_local.py
index 923f37294f..0b37c5f6ea 100644
--- a/tests/unit/brain/test_model_catalog_local.py
+++ b/tests/unit/brain/test_model_catalog_local.py
@@ -255,6 +255,74 @@ async def test_ollama_fetches_tags_keyless(tmp_path, monkeypatch) -> None:
assert call["params"] == {}
+class _FakeOllamaClient(_FakeClient):
+ """Adds the native ``/api/show`` capability probe to the GET fake."""
+
+ def __init__(self, payload: dict[str, Any], show_caps: dict[str, list[str]]) -> None:
+ super().__init__(payload)
+ self.show_caps = show_caps
+ self.shown: list[str] = []
+
+ async def post(self, url: str, json: dict[str, Any] | None = None) -> _FakeResponse:
+ name = str((json or {}).get("model") or "")
+ self.shown.append(name)
+ assert url.endswith("/api/show")
+ return _FakeResponse({"capabilities": self.show_caps.get(name, [])})
+
+
+async def test_ollama_catalog_carries_declared_capabilities(tmp_path, monkeypatch) -> None:
+ """``/api/tags`` says WHAT is installed, ``/api/show`` says what it can DO.
+
+ Without the second half every local download reached the capability
+ consumers as "unknown" — and unknown means "assume capable", which is how a
+ text-only install came to advertise vision to Screen Context.
+ """
+ client = _FakeOllamaClient(
+ {"models": [{"name": "qwen3.5:9b"}, {"name": "qwen3-vl:8b"}]},
+ {
+ "qwen3.5:9b": ["completion", "tools"],
+ "qwen3-vl:8b": ["completion", "tools", "vision"],
+ },
+ )
+ _local_env(monkeypatch)
+
+ result = await _catalog(tmp_path, client).list_models("ollama")
+
+ caps = {m.id: (m.input_modalities, m.supported_parameters) for m in result.models}
+ assert caps["qwen3.5:9b"] == (("text",), ("tools",))
+ assert caps["qwen3-vl:8b"] == (("text", "image"), ("tools",))
+ assert sorted(client.shown) == ["qwen3-vl:8b", "qwen3.5:9b"]
+
+
+async def test_ollama_catalog_drops_embedding_only_downloads(tmp_path, monkeypatch) -> None:
+ """bge-m3 in a BRAIN picker guarantees a 400 on the first chat turn."""
+ client = _FakeOllamaClient(
+ {"models": [{"name": "bge-m3:latest"}, {"name": "qwen3.5:9b"}]},
+ {"bge-m3:latest": ["embedding"], "qwen3.5:9b": ["completion"]},
+ )
+ _local_env(monkeypatch)
+
+ result = await _catalog(tmp_path, client).list_models("ollama")
+
+ assert [m.id for m in result.models] == ["qwen3.5:9b"]
+
+
+async def test_ollama_catalog_survives_a_server_without_api_show(tmp_path, monkeypatch) -> None:
+ """Fail-open per model: an unanswerable probe leaves the entry unknown
+ (capable), exactly as before this enrichment existed."""
+
+ class _NoShow(_FakeOllamaClient):
+ async def post(self, url, json=None): # type: ignore[override]
+ raise RuntimeError("api/show unavailable")
+
+ _local_env(monkeypatch)
+
+ result = await _catalog(tmp_path, _NoShow(_OLLAMA_TAGS, {})).list_models("ollama")
+
+ assert {m.id for m in result.models} == {"qwen3.5:9b", "glm-5.1:latest"}
+ assert all(m.input_modalities is None for m in result.models)
+
+
async def test_ollama_honors_base_url_override(tmp_path, monkeypatch) -> None:
"""A pasted ``…/v1`` override is normalized to the server root first."""
client = _FakeClient(_OLLAMA_TAGS)
diff --git a/tests/unit/plugins/brain/test_local_openai.py b/tests/unit/plugins/brain/test_local_openai.py
index f4723479fc..bc520e7e51 100644
--- a/tests/unit/plugins/brain/test_local_openai.py
+++ b/tests/unit/plugins/brain/test_local_openai.py
@@ -170,14 +170,39 @@ async def test_unreachable_server_gives_honest_error(monkeypatch, fake_models) -
assert "http://localhost:8000" in msg
+# ── Vision: blind unless the server itself says otherwise ────────────────
+def test_vision_stays_blind_when_the_server_declares_nothing(monkeypatch) -> None:
+ """The common case: an OpenAI-compatible server publishes no modality
+ fields, so the honest answer is "cannot see" — a confident description of a
+ picture nobody looked at is the failure worth being conservative about."""
+ import jarvis.brain.model_catalog as mc
+
+ monkeypatch.setattr(
+ mc, "model_capabilities", lambda provider, model: {"vision": None, "tools": None}
+ )
+ assert LocalOpenAIBrain(model="Qwen/Qwen3.5-9B").supports_vision is False
+
+
+def test_vision_believes_a_server_that_declares_image_input(monkeypatch) -> None:
+ """Some servers DO publish ``architecture.input_modalities``; a user who
+ runs a multimodal model there should not have to move to another card."""
+ import jarvis.brain.model_catalog as mc
+
+ monkeypatch.setattr(
+ mc, "model_capabilities", lambda provider, model: {"vision": True, "tools": True}
+ )
+ assert LocalOpenAIBrain(model="Qwen/Qwen3-VL-8B").supports_vision is True
+
+
# ── Protocol surface ─────────────────────────────────────────────────────
def test_capability_flags_and_cost() -> None:
brain = LocalOpenAIBrain(model="x")
assert brain.supports_tools is True
assert brain.can_call_tools() is True
- # Deliberately False: whether an arbitrary local server accepts image
- # content is unknowable — the shared streamer then DROPS images with a
- # warning instead of letting a text-only server reject the whole turn.
+ # Deliberately False without evidence: whether an arbitrary local server
+ # accepts image content is unknowable — the shared streamer then DROPS
+ # images with a warning instead of letting a text-only server reject the
+ # whole turn.
assert brain.supports_vision is False
req_like = type("R", (), {"messages": (), "max_tokens": 100})()
assert brain.estimate_cost(req_like) == 0.0
diff --git a/tests/unit/plugins/brain/test_ollama.py b/tests/unit/plugins/brain/test_ollama.py
index ad9b06ede5..976f94e94e 100644
--- a/tests/unit/plugins/brain/test_ollama.py
+++ b/tests/unit/plugins/brain/test_ollama.py
@@ -19,6 +19,7 @@ from jarvis.core.config import BrainConfig, BrainProviderConfig, JarvisConfig
from jarvis.plugins.brain.ollama import (
DEFAULT_SERVER_ROOT,
RECOMMENDED_PULL,
+ RECOMMENDED_VISION_PULL,
OllamaBrain,
default_server_root,
normalize_server_root,
@@ -286,11 +287,153 @@ async def test_unreachable_server_gives_honest_error(monkeypatch, fake_tags) ->
assert "http://localhost:11434" in msg
+# ── Vision: a MODEL property, never a server property ────────────────────
+def catalog(monkeypatch):
+ """Stub the cached model catalog the synchronous vision probe reads."""
+ import jarvis.brain.model_catalog as mc
+
+ state = {"caps": {}, "has_data": False, "vision_pick": None}
+
+ monkeypatch.setattr(
+ mc,
+ "model_capabilities",
+ lambda provider, model: state["caps"].get(model, {"vision": None, "tools": None}),
+ )
+ monkeypatch.setattr(mc, "provider_has_modality_data", lambda provider: state["has_data"])
+ monkeypatch.setattr(mc, "pick_vision_model", lambda provider: state["vision_pick"])
+ return state
+
+
+def test_pinned_model_without_vision_declares_itself_blind(catalog) -> None:
+ """The whole point: a text-only pull must not advertise sight, or
+ ``resolve_vision_brain`` hands it a screenshot and it answers about the
+ words around a picture it never saw."""
+ catalog["caps"] = {"qwen3.5:9b": {"vision": False, "tools": True}}
+ assert OllamaBrain(model="qwen3.5:9b").supports_vision is False
+
+
+def test_pinned_multimodal_model_declares_sight(catalog) -> None:
+ catalog["caps"] = {"qwen3-vl:8b": {"vision": True, "tools": True}}
+ assert OllamaBrain(model="qwen3-vl:8b").supports_vision is True
+
+
+def test_unknown_capability_stays_capable(catalog) -> None:
+ """Fail-open on unknown: an uncached model keeps the pre-existing answer,
+ and the image path then negotiates a real vision model."""
+ assert OllamaBrain(model="something-uncached").supports_vision is True
+
+
+def test_server_without_any_vision_download_is_blind(catalog) -> None:
+ """No pinned model + a catalog that HAS the data and lists no multimodal
+ download = an informed no, so the vision chain crosses to a provider that
+ can actually see (AP-22)."""
+ catalog["has_data"] = True
+ catalog["vision_pick"] = None
+ assert OllamaBrain().supports_vision is False
+
+
+def test_server_with_a_vision_download_is_sighted(catalog) -> None:
+ catalog["has_data"] = True
+ catalog["vision_pick"] = "qwen3-vl:8b"
+ assert OllamaBrain().supports_vision is True
+
+
+def test_no_catalog_data_stays_capable(catalog) -> None:
+ catalog["has_data"] = False
+ assert OllamaBrain().supports_vision is True
+
+
+async def test_image_turn_picks_a_vision_capable_download(monkeypatch, fake_tags) -> None:
+ """An image turn skips the smaller text-only download and takes the
+ multimodal one — while plain chat still runs the small model."""
+ _no_override(monkeypatch)
+ fake_tags.payload = {
+ "models": [
+ {"name": "qwen3.5:4b", "size": 1_000},
+ {"name": "qwen3-vl:8b", "size": 5_000},
+ ]
+ }
+ fake_tags.show_caps = {
+ "qwen3.5:4b": ["completion", "tools"],
+ "qwen3-vl:8b": ["completion", "tools", "vision"],
+ }
+ brain = OllamaBrain()
+ assert await brain._resolve_model() == "qwen3.5:4b"
+ assert await brain._resolve_model(need_vision=True) == "qwen3-vl:8b"
+
+
+async def test_image_turn_without_a_vision_download_errors_honestly(
+ monkeypatch, fake_tags
+) -> None:
+ _no_override(monkeypatch)
+ fake_tags.payload = {"models": [{"name": "qwen3.5:4b", "size": 1_000}]}
+ fake_tags.show_caps = {"qwen3.5:4b": ["completion", "tools"]}
+ brain = OllamaBrain()
+ with pytest.raises(RuntimeError) as err:
+ await brain._resolve_model(need_vision=True)
+ assert f"ollama pull {RECOMMENDED_VISION_PULL}" in str(err.value)
+ # The instance corrects its own advertisement so the next synchronous
+ # resolver question gets the informed answer.
+ assert brain.supports_vision is False
+
+
+async def test_unprobeable_model_is_never_used_for_an_image_turn(
+ monkeypatch, fake_tags
+) -> None:
+ """Vision is the ONE requirement that fails CLOSED: a model whose
+ ``/api/show`` probe does not answer may back a chat turn, never an image
+ turn — a blind answer is indistinguishable from a sighted one."""
+ _no_override(monkeypatch)
+ fake_tags.payload = {"models": [{"name": "mystery:latest", "size": 1_000}]}
+
+ async def _show_unavailable(self, url: str, json: dict[str, Any] | None = None) -> None:
+ raise httpx.ConnectError("show unavailable")
+
+ monkeypatch.setattr(fake_tags, "post", _show_unavailable)
+ brain = OllamaBrain()
+ assert await brain._resolve_model() == "mystery:latest"
+ with pytest.raises(RuntimeError):
+ await brain._resolve_model(need_vision=True)
+
+
+async def test_complete_refuses_an_image_on_a_pinned_blind_model(
+ monkeypatch, fake_tags, catalog
+) -> None:
+ """A pinned model is the user's own choice, so it is not silently swapped —
+ but the turn errors instead of describing a screenshot it cannot see."""
+ import openai
+
+ from jarvis.core.protocols import BrainMessage, BrainRequest, ImageBlock
+
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ _no_override(monkeypatch)
+ catalog["caps"] = {"qwen3.5:9b": {"vision": False, "tools": True}}
+ fake_tags.show_caps = {"qwen3.5:9b": ["completion", "tools"]}
+ req = BrainRequest(
+ messages=(
+ BrainMessage(
+ role="user",
+ content="What is on my screen?",
+ images=(ImageBlock(mime="image/png", data_b64="aGk="),),
+ ),
+ )
+ )
+ brain = OllamaBrain(model="qwen3.5:9b")
+ with pytest.raises(RuntimeError) as err:
+ async for _ in brain.complete(req):
+ pass
+ msg = str(err.value)
+ assert "cannot see images" in msg
+ assert RECOMMENDED_VISION_PULL in msg
+
+
# ── Protocol surface ─────────────────────────────────────────────────────
-def test_capability_flags_and_cost() -> None:
+def test_capability_flags_and_cost(catalog) -> None:
brain = OllamaBrain(model="x")
assert brain.supports_tools is True
assert brain.can_call_tools() is True
+ # Unknown capability → capable (the image path does the real gating).
assert brain.supports_vision is True
# Local inference bills nothing — the cost meter must see 0.
req_like = type("R", (), {"messages": (), "max_tokens": 100})()