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(providers): an on-device provider may not look usable before it is installed
Ruben Lütke3269dbe804fe
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex ea52603d20..c0b17a4b9c 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -256,11 +256,40 @@ _INPUT_MARKERS = ("❯", ">", "›")# first version used 8 s and watched twelve real panes die just past it.RESUME_FAILED_WINDOW_S = 45.0-# When to look for the session id of a CLI that cannot be told one (Codex). It-# writes its rollout file a beat after launching, so asking immediately finds-# nothing; two attempts cover a slow machine without turning into polling.+# When to look for the session id of a CLI that cannot be told one (Codex,+# OpenCode, Kimi). It writes its session record a beat after launching, so+# asking immediately finds nothing; two attempts cover a slow machine without+# turning into polling.DISCOVERY_DELAYS_S = (4.0, 12.0)+# When to look AGAIN, counted from the moment the pane's conversation actually+# received its first message.+#+# **The bug this exists for.** Launching one of those CLIs does not create a+# session on disk — the record appears when the conversation first has something+# to record. Measured on this machine: a Codex pane launched at 15:17:44 wrote+# its rollout file at 15:19:32, the instant its first brief was submitted, 106+# seconds after the schedule above had given up for good. Across 338 real Codex+# TUI sessions, 40 % of the files appeared after that window (p90: 402 s), while+# `codex exec` runs — which carry their prompt at launch — landed inside it 98 %+# of the time. So the window was never the problem; measuring it from the wrong+# EVENT was. A pane that lost this race kept `resume = None` for the rest of its+# life, the snapshot stored a pane with no conversation, and the restore brought+# back an empty agent without a word about it. Claude Code never showed it: its+# id is minted at launch (`--session-id`), so it is in the snapshot before the+# CLI has done anything at all.+#+# Hence a second schedule hung off the event that MAKES the session findable —+# a prompt from Jarvis, or a line the user submitted in the pane themselves.+# Short, because by then the CLI is writing; three attempts, because "is writing"+# is not "has flushed".+CONVERSATION_DELAYS_S = (1.5, 5.0, 15.0)++# How long one pane must wait between lookup ROUNDS. Every submit into a pane+# with no handle is a reason to look, and somebody pressing Enter ten times is+# not ten reasons — each round opens up to _MAX_CANDIDATES session files.+LOOKUP_COOLDOWN_S = 15.0+# ---------------------------------------------------------------------------# How many agent CLIs may be COLD-STARTING at the same moment.#@@ -802,6 +831,15 @@ class Terminal:# The pane is the window; this is what the window looks at, and it is the# only reason a closed browser is survivable (see .agent_sessions).resume: ResumeHandle | None = None+ # Is a conversation-id lookup in flight for this pane, and when did the last+ # ROUND begin (monotonic — a wall clock can jump)? Both exist because the+ # lookup now has more than one trigger: the pane starting, and the pane's+ # conversation actually beginning. Without them a busy pane would stack a+ # round on top of every keystroke that submits, and two rounds racing each+ # other could hand one conversation to two panes. Never persisted: they+ # describe a running pane, not the workspace on disk.+ lookup_running: bool = False+ lookup_at: float = 0.0# Did the CURRENT agent process continue that conversation, or start empty?# Reported honestly rather than assumed: a resume can fail, and a user who# is told "resumed" and gets an amnesiac agent has been lied to.@@ -2252,6 +2290,20 @@ class Registry:argv = (*argv, *continuing)term.resumed = Trueelse:+ if term.resume is None and term.prompts_sent and can_resume(term.agent):+ # A pane that was WORKED IN and still has no conversation id is+ # the one failure this path used to swallow whole: the pane came+ # back looking right, empty, with nothing anywhere saying its+ # history had been lost. It means every lookup missed — see+ # `CONVERSATION_DELAYS_S` — so say so where the next person+ # debugging this will look.+ logger.info(+ "Agentic IDE: {} was worked in but no conversation id was ever "+ "recorded for it — starting fresh (the old thread is still in "+ "{}'s own history, just not reachable from here)",+ term.name,+ term.display_name,+ )extra, minted = launch_extra(term.agent)argv = (*argv, *extra)term.resumed = False@@ -2474,7 +2526,12 @@ class Registry:logger.warning("Agentic IDE: pre-trust for {} failed: {}", term.name, exc)def _schedule_lookup(- self, owner: Session, term: Terminal, folder: str, started_at: float+ self,+ owner: Session,+ term: Terminal,+ folder: str,+ started_at: float,+ delays: tuple[float, ...] | None = None,) -> None:"""Find a pane's session id a moment after its CLI created it.@@ -2486,11 +2543,32 @@ class Registry:one": with several open, the front workspace can change twice while thisis sleeping, and a lookup that then read the front one would write aCodex conversation id onto a pane in a different folder.++ ``delays`` is the schedule to try on, because the same search answers two+ different questions: "has the CLI finished starting?" right after a spawn+ (``DISCOVERY_DELAYS_S``) and "has the CLI written the conversation that+ just began?" once the pane has been given something to do+ (``CONVERSATION_DELAYS_S``). ``started_at`` stays the pane's LAUNCH time+ in both cases — a session's recorded timestamp is when it opened, not+ when it was first spoken to, so anything later would rule out the very+ conversation being looked for.++ One round per pane at a time. Two rounds racing would ask the same+ question with the same ``taken`` set and could hand one conversation to+ two panes."""+ # Resolved here rather than as a default argument: a default is bound+ # when this module is imported, which silently pins the schedule to the+ # value it had then — including for anything that adjusts it later.+ schedule = DISCOVERY_DELAYS_S if delays is None else delays+ if term.lookup_running:+ return+ term.lookup_running = True+ term.lookup_at = time.monotonic()async def _look() -> None:try:- for delay in DISCOVERY_DELAYS_S:+ for delay in schedule:await asyncio.sleep(delay)if term not in owner.terminals or owner.id not in self._sessions:return # the pane (or the workspace) is gone@@ -2518,27 +2596,68 @@ class Registry:raiseexcept Exception as exc: # noqa: BLE001 - a convenience, never fatallogger.debug("Agentic IDE: session lookup for {} failed: {}", term.name, exc)+ finally:+ # Even a cancelled round has to let the next trigger through, or+ # a workspace that was closed and reopened would never look+ # again.+ term.lookup_running = False- task = asyncio.ensure_future(_look())+ try:+ task = asyncio.ensure_future(_look())+ except RuntimeError:+ # No running loop — nothing to schedule onto. Only reachable from the+ # keystroke path, which a non-async caller could in principle drive.+ term.lookup_running = False+ logger.debug("Agentic IDE: no event loop to look up {}'s conversation on", term.name)+ returnowner.lookups.add(task)task.add_done_callback(owner.lookups.discard)+ def _lookup_after_conversation(self, owner: Session, term: Terminal) -> None:+ """Look for this pane's conversation id now that it HAS a conversation.++ The trigger, not the timer, is the point — see ``CONVERSATION_DELAYS_S``.+ A CLI that cannot be told its id writes nothing until its conversation+ gets a first message, so the moment a prompt lands (from Jarvis or from+ the user's own keyboard) is the moment the id becomes findable, whether+ that is four seconds after the pane opened or four hours.++ Cheap to call on every submitted line: a pane that already has a handle,+ an agent that mints its own, and a round that just ran all return here+ without touching the disk.+ """+ if term.resume is not None or not term.started_at:+ return+ if not can_resume(term.agent):+ return+ if term.lookup_running:+ return+ if term.lookup_at and time.monotonic() - term.lookup_at < LOOKUP_COOLDOWN_S:+ return+ self._schedule_lookup(owner, term, owner.folder, term.started_at, CONVERSATION_DELAYS_S)+def write(self, key: str, data: str, workspace_id: str | None = None) -> bool:"""Raw keystrokes from the pane's own xterm (not the injection path)."""found = self._locate(key, workspace_id)if found is None:return False- term = found[1]+ owner, term = foundif not term.pty_id:return False- if term.continuation_pending and ("\r" in data or "\n" in data):+ # Gated on a SUBMIT rather than on any keystroke: scrolling, arrow keys+ # and a half-typed line are not an instruction.+ if "\r" in data or "\n" in data:# The user submitted something in the pane themselves, so this one# is being driven again and is no longer waiting to be nudged.- # Gated on a SUBMIT rather than on any keystroke: scrolling, arrow- # keys and a half-typed line are not an instruction, and dropping- # the pane off the list for those would hide a stalled agent behind- # an accidental keypress.+ # Dropping the pane off that list for a mere keypress would hide a+ # stalled agent behind an accidental one.term.continuation_pending = False+ # And the pane's conversation may have just begun, which for most+ # coding CLIs is the first moment its id exists on disk at all. A+ # pane driven only by hand never goes through `send_prompt`, so+ # without this hook it would keep the gap that cost every non-Claude+ # pane its resume handle.+ self._lookup_after_conversation(owner, term)return self._manager().write(term.pty_id, data)async def _nudge_repaint(self, term: Terminal, cols: int, rows: int) -> None:@@ -3055,7 +3174,7 @@ class Registry:found = self.find_terminal(wanted)if found is None:raise self._unknown_terminal(wanted)- _session, term = found+ owner, term = foundif not accepts_prompts(term.agent):# A plain terminal is a live SHELL prompt, so an injected line would# not be read by an agent — it would run as a command. This is the@@ -3108,6 +3227,14 @@ class Registry:# in its input box in full, so offering to type "continue" behind it# would append a second line to a prompt the user still has to send.term.continuation_pending = False+ if submitted is not False:+ # The conversation has (or may have) just begun, so for a CLI that+ # cannot be told its id this is the moment that id starts existing —+ # see `_lookup_after_conversation`. Skipped only for a hard False,+ # which means the text is provably still sitting in the input box:+ # nothing was recorded, and a round spent on that would burn the+ # cooldown the real submit needs.+ self._lookup_after_conversation(owner, term)logger.info("Agentic IDE prompt -> {} ({}, {}): {}",term.name,diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.pyindex 662e8fe632..cb897d33c9 100644--- a/jarvis/brain/app_control.py+++ b/jarvis/brain/app_control.py@@ -187,6 +187,32 @@ def masked_secret_preview(provider_id: str) -> dict[str, Any]:# ----------------------------------------------------------------------+def local_readiness_error(spec: ProviderSpec) -> str | None:+ """Why an on-device provider cannot run yet — or ``None`` when it can.++ Returns ``None`` for every cloud provider too, so a caller can apply it+ unconditionally: locality is decided by the local-model catalog, never by a+ provider name (AP-21).++ This exists because "needs no credential" and "is usable" are different+ facts that an ``auth_mode == "none"`` check silently conflates. An on-device+ provider needs its engine installed and its weights downloaded, and neither+ is implied by the absence of an API key — the exact conflation that let a+ local recogniser present itself as ready on a machine where nothing had been+ installed.+ """+ try:+ from jarvis.speech.local_models import local_status++ state = local_status(getattr(spec, "id", "") or "")+ except Exception as exc: # noqa: BLE001 — an unavailable probe blocks nothing+ log.debug("Local readiness probe failed (%s); treating as not local.", exc)+ return None+ if state is None or state.ready:+ return None+ return state.detail++def is_credential_present(spec: ProviderSpec, binary_path: str | None = None) -> bool:"""True iff ``spec``'s provider has a usable stored credential.@@ -469,6 +495,19 @@ async def apply_provider_switch("Add it in the Settings tab first, then switch."),}+ # The on-device equivalent of the check above, and it has to be its own+ # step: ``is_credential_present`` answers True for every keyless provider by+ # definition, so without this an engine that was never installed would sail+ # through here and only fail later, silently, on the first utterance.+ # Enforced at this one lock so the voice gate, the CLI and the brain tool+ # are covered, not just the REST route.+ not_installed = local_readiness_error(spec)+ if not_installed:+ return {+ "ok": False,+ "error_kind": "not_installed",+ "error": not_installed,+ }if tier == "brain":return await _switch_brain(diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex 7143d78d38..5352abf08e 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -279,6 +279,24 @@ def _ids(ids: list[str]) -> list[ModelInfo]:# single block (voice_de/voice_en/model), so the picker only renders on the# ACTIVE TTS card and sets the global value.TTS_CATALOG: dict[str, tuple[str, list[ModelInfo]]] = {+ # Piper (on-device). A Piper voice speaks ONE language, so this picker is a+ # speaker choice, not a language choice: the provider still resolves the+ # file from the turn's output language. Both sets are listed; the masculine+ # trio is what the install downloads, and the feminine one is fetched on+ # demand. Kept in sync with SHERPA_BUNDLES in jarvis/speech/local_models.py.+ "piper-local": (+ "voice",+ _curated(+ [+ ("vits-piper-de_DE-thorsten-medium", "Thorsten — German, masculine"),+ ("vits-piper-en_US-ryan-medium", "Ryan — English, masculine"),+ ("vits-piper-es_ES-davefx-medium", "Dave — Spanish, masculine"),+ ("vits-piper-de_DE-ramona-low", "Ramona — German, feminine"),+ ("vits-piper-en_US-amy-medium", "Amy — English, feminine"),+ ("vits-piper-es_ES-sharvard-medium", "Sharvard — Spanish, feminine"),+ ]+ ),+ ),# ElevenLabs picks a VOICE ID (opaque hashes), so the curated list carries# human names as labels while the value stays the id. The picker's# "use custom" row lets a user paste their OWN voice id (e.g. a cloned@@ -567,10 +585,15 @@ REALTIME_VOICES: dict[str, list[ModelInfo]] = {# STT model catalogs (the ``[stt] model`` is a single global value).STT_CATALOG: dict[str, list[ModelInfo]] = {"groq-api": _ids(["whisper-large-v3", "whisper-large-v3-turbo"]),- # "faster-whisper" (local) was removed as a user-selectable STT provider in- # v1.0.1 — see the note in provider_spec.py. The wake-word local Whisper and- # the key-free STT fallback do NOT use this catalog (they read [stt].wake_*- # / construct FasterWhisperProvider directly), so no wake/fallback breakage.+ # The on-device recognizers offer exactly ONE model each, deliberately.+ # Their predecessor card was removed in v1.0.1 partly because its picker+ # listed all seven Whisper checkpoints regardless of which had been+ # downloaded — a menu of mostly-absent options. What the installer fetches+ # and what the picker offers are therefore the same single entry.+ # (The wake word is a separate path with its own checkpoint via+ # [stt].wake_*, and is not affected by anything in this catalog.)+ "faster-whisper": _ids(["large-v3"]),+ "nemotron-local": _ids(["nemotron-3.5-asr-streaming-0.6b-560ms-int8"]),"openai-api": _ids(["gpt-4o-transcribe",diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex 220b14dff6..1e06b6042e 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -293,6 +293,20 @@ def _default_make_tts(cfg: Any, provider: str) -> Any:return _build_provider(cfg.tts, provider)+def _local_readiness(provider: str) -> Any:+ """On-disk readiness of an on-device provider; ``None`` for cloud ones.++ Lazily imported and defensively wrapped: a probe failure must not turn the+ provider test into an integration error about the probe itself.+ """+ try:+ from jarvis.speech.local_models import local_status++ return local_status(provider)+ except Exception: # noqa: BLE001 — an unavailable probe means "not local"+ return None++def _default_make_stt(cfg: Any, provider: str) -> Any:import copy as _copy@@ -398,6 +412,15 @@ async def run_provider_test(if not is_present:return ProviderTestResult(provider, NOT_CONFIGURED, "No credential stored.")+ # On-device providers: the equivalent question is not "is there a key" but+ # "are the engine and the model actually on this machine". Asked BEFORE+ # anything is built, because building an on-device provider is deliberately+ # cheap — the weights load on first use (AP-26), so a successful+ # construction proves nothing at all about whether it can run.+ local_state = _local_readiness(provider)+ if local_state is not None and not local_state.ready:+ return ProviderTestResult(provider, NOT_CONFIGURED, local_state.detail)+# Default 1-token probe, shared by the brain tier AND the realtime tier below.if brain_probe is None:async def brain_probe(p: str, m: str) -> Any: # type: ignore[misc]@@ -486,6 +509,22 @@ async def run_provider_test(detail = f"{type(exc).__name__}: {exc}"return ProviderTestResult(provider, classify_provider_error(detail), str(exc), dur)+ if spec.tier == "dictation":+ # This tier is probed by the dictation layer, which owns the wording+ # pass and is the only place allowed to call it — a call site under+ # jarvis/brain/ would put a model call one import away from the spoken+ # hot path (AP-11, guarded by test_polish_boot_safety.py).+ #+ # The refusal is explicit rather than a fall-through: without it the+ # card dropped into the STT branch below and reported the user's SPEECH+ # RECOGNIZER under a wording-provider's name — four cards reading red+ # over a broken local model while every one of them worked.+ return ProviderTestResult(+ provider,+ ERROR,+ "This card is tested by the dictation layer, not by the provider test.",+ )+# sttbuilder = make_stt or _default_make_stttry:@@ -494,31 +533,48 @@ async def run_provider_test(# (and the whole API-Keys screen) while a test/section-health check runs.inst = await asyncio.to_thread(builder, cfg, provider)except (ImportError, ModuleNotFoundError):- # M5: the local faster-whisper STT needs the [desktop] extra. On a headless- # base install the import raises — that is "not installed", an actionable- # amber chip, NOT a red "integration bug".+ # The on-device engines are optional packages a base install omits. That+ # is "not installed" — an actionable amber chip pointing at the in-app+ # install, NOT a red "integration bug".return ProviderTestResult(provider,NOT_CONFIGURED,- "Local STT not installed — add the [desktop] extra (pip install -e '.[desktop]').",+ "The local speech engine is not installed. Install it from this card.",)except Exception as exc: # noqa: BLE001detail = f"{type(exc).__name__}: {exc}"return ProviderTestResult(provider, classify_provider_error(detail), str(exc))- if spec.auth_mode == "none":- # Local provider (faster-whisper): a successful build loads the model;- # we do not run a network call. Building it IS the test.- return ProviderTestResult(provider, OK, "Local provider built.")-+ # An on-device recogniser has to LOAD its model before it can answer, and a+ # multi-gigabyte checkpoint reads from disk for tens of seconds the first+ # time. Held to a network-shaped ceiling it would report "unreachable" while+ # working perfectly, so the local path gets a longer one.+ stt_timeout = max(timeout_s, 180.0) if local_state is not None else timeout_sstart = perf_counter()try:- tr = await asyncio.wait_for(inst.transcribe(_silence_chunks()), timeout=timeout_s)+ tr = await asyncio.wait_for(+ inst.transcribe(_silence_chunks()), timeout=stt_timeout+ )dur = (perf_counter() - start) * 1000.0text = (getattr(tr, "text", "") or "").strip()- return ProviderTestResult(provider, OK, f"transcript={text!r}", dur)+ # Silence in, silence out: an empty transcript is the CORRECT answer+ # here, and the run itself is the proof — the model loaded and decoded.+ detail = (+ f"Ran on this machine — {local_state.model_label} loaded and decoded."+ if local_state is not None+ else f"transcript={text!r}"+ )+ return ProviderTestResult(provider, OK, detail, dur)except TimeoutError:dur = (perf_counter() - start) * 1000.0+ if local_state is not None:+ return ProviderTestResult(+ provider,+ ERROR,+ f"{local_state.model_label} did not finish loading within "+ f"{stt_timeout:.0f}s on this machine.",+ dur,+ )return ProviderTestResult(provider, UNREACHABLE, f"timeout after {timeout_s:.0f}s", dur)except Exception as exc: # noqa: BLE001dur = (perf_counter() - start) * 1000.0diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 2b7882acae..5f2fe76936 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -877,6 +877,30 @@ async def list_providers(request: Request) -> dict[str, Any]:_PROVIDER_TEST_HARD_TIMEOUT_S = 75.0+async def _run_tier_test(+ spec: ProviderSpec, cfg: Any, *, model: str | None = None+) -> Any:+ """Dispatch a card to the probe that can actually judge it.++ Every tier but one is judged by ``run_provider_test``. A dictation card is+ NOT a speech-to-text provider, and it used to fall through to the STT branch+ there — so "Test" on a wording card built the user's RECOGNIZER and reported+ its verdict under the card's name (a broken local model turned four working+ cloud cards red), while the keyless local card answered "ok" in 0.0 ms+ having asked its server nothing at all.++ The wording probe therefore lives in the dictation layer, which is the only+ place allowed to call that pass (AP-11), and this function is the one seam+ that knows which card goes where.+ """+ family = _polish_family(spec)+ if family is not None:+ from jarvis.dictation.polish_probe import probe_polish_family++ return await probe_polish_family(family, cfg, model=model or "")+ return await _provider_test.run_provider_test(spec, cfg, model=model)++@router.post("/providers/{provider_id}/test")async def test_provider_connection(provider_id: str, request: Request@@ -906,7 +930,7 @@ async def test_provider_connection(# as an honest "unreachable" instead of a hung HTTP request.try:result = await asyncio.wait_for(- _provider_test.run_provider_test(spec, cfg),+ _run_tier_test(spec, cfg),timeout=_PROVIDER_TEST_HARD_TIMEOUT_S,)except TimeoutError:@@ -1031,10 +1055,21 @@ async def _tier_section_health(detail="No active provider selected",subject_id=None,)- # Local providers (faster-whisper, SAPI) have no key to be invalid; if one is- # the active provider it is usable. Skip the real test — it could force a heavy- # model load on page open for no signal we don't already have.+ # Local providers have no key to be invalid — but "no key needed" is NOT the+ # same as "usable", and reading it that way is how an on-device card comes to+ # claim it works on a machine where its engine and weights were never+ # installed. So ask the disk (a cheap file check, no model load) before+ # calling the tier healthy. The real inference test still stays off the+ # page-open path: it would force a multi-gigabyte load for no extra signal.if getattr(spec, "auth_mode", None) == "none":+ local_state = _local_runtime_payload(spec)+ if local_state is not None and not local_state["ready"]:+ return SectionHealth(+ status=_section_health.NEEDS_SETUP,+ reason="not_installed",+ detail=f"{spec.label}: {local_state['detail']}",+ subject_id=spec.id,+ )return SectionHealth(status=_section_health.OK,reason="local",@@ -1069,7 +1104,7 @@ async def _tier_section_health(subject_id=spec.id,)try:- result = await _provider_test.run_provider_test(spec, cfg, model=model)+ result = await _run_tier_test(spec, cfg, model=model)except Exception as exc: # noqa: BLE001log.warning("section-health test for %s failed: %s", spec.id, exc)return SectionHealth(@@ -2699,6 +2734,9 @@ _SWITCH_ERROR_STATUS: dict[str, int] = {"wrong_tier": 400,"subagent_only": 409,"missing_credential": 409,+ # Same shape as a missing credential, for the on-device providers: the+ # engine or its model is not on this machine yet.+ "not_installed": 409,"subagent_unavailable": 409,"airgapped_locked": 403,"persist_failed": 500,@@ -2844,9 +2882,11 @@ async def tts_switch(body: SwitchBody, request: Request) -> dict[str, Any]:# Same reasoning as the STT switch: a local provider has no credential to# check, so readiness must be asked of the disk. Activating a voice whose# files are missing would turn every spoken reply into silence.- local_state = _local_runtime_payload(spec)- if local_state is not None and not local_state["ready"]:- raise HTTPException(status_code=409, detail=local_state["detail"])+ from jarvis.brain.app_control import local_readiness_error++ not_installed = local_readiness_error(spec)+ if not_installed:+ raise HTTPException(status_code=409, detail=not_installed)if body.persist:try:@@ -3191,10 +3231,13 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:# A local provider passes the credential check trivially (it has no key), so# readiness has to be asked separately — activating an engine that is not# installed would leave voice input dead with no explanation. This is the- # gate the 2026-07-03 card lacked.- local_status = _local_runtime_payload(spec)- if local_status is not None and not local_status["ready"]:- raise HTTPException(status_code=409, detail=local_status["detail"])+ # gate the 2026-07-03 card lacked. Shared with the voice/CLI/tool switch+ # path via ``local_readiness_error`` so the two can never disagree.+ from jarvis.brain.app_control import local_readiness_error++ not_installed = local_readiness_error(spec)+ if not_installed:+ raise HTTPException(status_code=409, detail=not_installed)if body.persist:try:diff --git a/tests/unit/agentic_ide/test_resume_session.py b/tests/unit/agentic_ide/test_resume_session.pyindex 3277ea38f6..82c9be993a 100644--- a/tests/unit/agentic_ide/test_resume_session.py+++ b/tests/unit/agentic_ide/test_resume_session.py@@ -864,3 +864,146 @@ async def test_a_discovered_conversation_id_is_not_overwritten_by_an_older_save(assert saved is not Nonestored = saved.workspaces[0].terminals[0].resumeassert stored == found, "the discovered id must survive every other save"+++# ------------------------------------------ looking again once there is one+class _LateConversation:+ """A CLI that files its session only once the conversation has a message.++ Which is what Codex, OpenCode and Kimi all do — and the whole reason a+ lookup timed from the pane's LAUNCH kept coming back empty. Measured on a+ real Codex pane: launched 15:17:44, rollout file written 15:19:32, the+ instant its first brief was submitted.+ """++ def __init__(self) -> None:+ self.handle = ResumeHandle(kind="codex_rollout", id="written-late", captured_at=9.0)+ self.spoken_to = False+ self.calls = 0++ def __call__(self, *_args: object, **_kwargs: object) -> ResumeHandle | None:+ self.calls += 1+ return self.handle if self.spoken_to else None+++def late_cli(monkeypatch: pytest.MonkeyPatch) -> _LateConversation:+ cli = _LateConversation()+ monkeypatch.setattr(ide, "discover", cli)+ monkeypatch.setattr(ide, "DISCOVERY_DELAYS_S", (0.0,))+ monkeypatch.setattr(ide, "CONVERSATION_DELAYS_S", (0.0,))+ # Both rounds are instant here, so the real cooldown — which exists to keep+ # a leaning-on-Enter user from re-crawling the history — would swallow the+ # very trigger under test. The one test that IS about the cooldown puts a+ # real value back.+ monkeypatch.setattr(ide, "LOOKUP_COOLDOWN_S", 0.0)+ # The prompt path watches the pane's screen; keep those waits short enough+ # that a test is not paced by them.+ monkeypatch.setattr(ide, "_ARRIVAL_POLL_S", 0.01)+ monkeypatch.setattr(ide, "_ARRIVAL_WINDOW_S", 0.04)+ monkeypatch.setattr(ide, "_SUBMIT_POLL_S", 0.01)+ monkeypatch.setattr(ide, "_SUBMIT_WINDOW_S", 0.04)+ monkeypatch.setattr(ide, "_SUBMIT_RETRY_AFTER_S", 0.02)+ return cli+++async def _settle() -> None:+ for _ in range(20):+ await asyncio.sleep(0.01)+++async def test_a_conversation_that_starts_late_is_still_found(+ registry: ide.Registry, fake_pty: FakePtyManager, tmp_path: Path, late_cli: _LateConversation+) -> None:+ """The bug: a pane prompted after the start window kept no handle at all.++ Nothing is wrong with the search — it is asked at the wrong moment. Launching+ one of these CLIs writes no session, so both attempts after the spawn find+ nothing and the old code then gave up for good. The pane went on to work for+ hours, was snapshotted with ``resume: null``, and came back empty.++ So the search is asked again when the pane's conversation actually BEGINS.+ """+ fake_pty.tui_echo = True+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)+ await _settle()+ assert registry.session.find("Cody").resume is None, "nothing exists to find yet"+ assert late_cli.calls, "the pane still looks right after starting"++ # The pane is given its first instruction, which is what makes the CLI write+ # its session file.+ late_cli.spoken_to = True+ await registry.send_prompt("Cody", "review the pipeline")+ await _settle()++ term = registry.session.find("Cody")+ assert term.resume == late_cli.handle, "the id must be captured once it exists"+ saved = resume_store.load()+ assert saved is not None+ assert saved.workspaces[0].terminals[0].resume == late_cli.handle+++async def test_a_line_the_user_typed_themselves_also_starts_the_search(+ registry: ide.Registry, tmp_path: Path, late_cli: _LateConversation+) -> None:+ """A pane driven by hand never goes through ``send_prompt``.++ Most panes are typed into directly at least once, and that keystroke starts+ the conversation exactly like an injected brief does — so it has to be worth+ the same look, or resuming would work only for panes Jarvis drove.+ """+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)+ await _settle()+ assert registry.session.find("Cody").resume is None++ late_cli.spoken_to = True+ registry.write("Cody", "run the tests") # typing alone is not a conversation+ await _settle()+ assert registry.session.find("Cody").resume is None, "a half-typed line is not a message"++ registry.write("Cody", "\r")+ await _settle()+ assert registry.session.find("Cody").resume == late_cli.handle+++async def test_a_pane_does_not_start_a_new_search_for_every_keystroke(+ registry: ide.Registry,+ tmp_path: Path,+ late_cli: _LateConversation,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Each round opens up to 400 session files; Enter is pressed far more often.++ A pane whose CLI genuinely has nothing to find (offline, uninstalled, a+ conversation the user abandoned) would otherwise crawl its history again for+ every line submitted into it.+ """+ monkeypatch.setattr(ide, "LOOKUP_COOLDOWN_S", 30.0)+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)+ await _settle()+ after_start = late_cli.calls++ for _ in range(5):+ registry.write("Cody", "\r")+ await _settle()++ assert late_cli.calls - after_start <= 1, "the cooldown has to hold the rest back"+++async def test_a_pane_that_already_knows_its_conversation_never_looks_again(+ registry: ide.Registry, tmp_path: Path, late_cli: _LateConversation+) -> None:+ """The handle is the answer; asking again could only replace it with another."""+ late_cli.spoken_to = True+ await registry.start(str(tmp_path), [{"agent": "codex", "name": "Cody"}])+ await registry.attach("Cody", 80, 24, _noop, _noop_exit)+ await _settle()+ assert registry.session.find("Cody").resume == late_cli.handle+ settled = late_cli.calls++ registry.write("Cody", "\r")+ await _settle()+ assert late_cli.calls == settleddiff --git a/tests/unit/brain/test_local_provider_readiness_gate.py b/tests/unit/brain/test_local_provider_readiness_gate.pynew file mode 100644index 0000000000..3fd1414cb6--- /dev/null+++ b/tests/unit/brain/test_local_provider_readiness_gate.py@@ -0,0 +1,200 @@+"""An on-device provider may never present itself as usable before it is installed.++Field report 2026-07-29: the Test button on the Nemotron card answered "ready"+on a machine where the user had never installed anything. Root cause was one+conflation repeated in three places — ``auth_mode == "none"`` (no credential+needed) was read as "works":++* the provider TEST returned OK after merely CONSTRUCTING the provider, which+ for an on-device recogniser is deliberately cheap: the weights load on first+ use (AP-26), so a successful construction proves nothing;+* the section-health rollup reported the tier green for the same reason;+* the shared switch path (voice command, CLI, brain tool) checked only for a+ credential, so an uninstalled engine could be ACTIVATED.++Each is pinned below. The rule: readiness is proven against the disk, never+inferred from the absence of a key.+"""+from __future__ import annotations++import asyncio+from dataclasses import dataclass+from typing import Any++import pytest++from jarvis.brain import app_control, provider_test+from jarvis.brain.provider_test import run_provider_test+++@dataclass(frozen=True)+class _Spec:+ """Minimal stand-in for a keyless on-device provider card."""++ id: str = "nemotron-local"+ label: str = "Nemotron (on this machine)"+ tier: str = "stt"+ auth_mode: str = "none"+ secret_keys: tuple[str, ...] = ()+ optional: bool = False+ brain_switchable: bool = True+++@dataclass(frozen=True)+class _Status:+ ready: bool+ detail: str+ model_label: str = "Nemotron 3.5 (streaming)"+ engine_installed: bool = False+ model_present: bool = False+ runtime: str = "sherpa-onnx"+++class _NeverLoadedProvider:+ """What an on-device provider looks like before first use: an empty shell.++ Constructing it succeeds on ANY machine — that is the whole point of the+ lazy load, and the whole reason construction cannot stand in for a test.+ """++ name = "nemotron-local"++ async def transcribe(self, audio: Any) -> Any:+ raise AssertionError("the test must not reach inference when not installed")+++NOT_INSTALLED = _Status(+ ready=False,+ detail=(+ "The local speech runtime is not installed yet. Install it from here "+ "to run this model on your own machine."+ ),+)+INSTALLED = _Status(+ ready=True,+ detail="Ready — Nemotron 3.5 (streaming) runs entirely on this machine.",+ engine_installed=True,+ model_present=True,+)+++def _patch_status(monkeypatch: pytest.MonkeyPatch, status: _Status | None) -> None:+ """Point both call sites at one fake on-disk verdict."""+ import jarvis.speech.local_models as local_models++ monkeypatch.setattr(+ local_models, "local_status", lambda pid, **kw: status, raising=False+ )+++def test_test_button_reports_not_configured_when_nothing_is_installed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The reported bug: 'Test' said ready on an install with no engine.++ It must answer "not configured" with the sentence that says what to do —+ and must not even attempt inference, since there is nothing to run.+ """+ _patch_status(monkeypatch, NOT_INSTALLED)++ result = asyncio.run(+ run_provider_test(+ _Spec(),+ cfg=None,+ make_stt=lambda cfg, provider: _NeverLoadedProvider(),+ )+ )++ assert result.status == "not_configured"+ assert "not installed" in result.detail+++def test_test_button_runs_real_inference_once_it_is_installed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """With the files present, "ok" must be earned by actually decoding.++ Construction alone used to be the whole test; now the model has to load and+ produce a transcript before the card is allowed to claim anything.+ """+ _patch_status(monkeypatch, INSTALLED)+ decoded: list[str] = []++ class _WorkingProvider:+ name = "nemotron-local"++ async def transcribe(self, audio: Any) -> Any:+ decoded.append("ran")++ class _T:+ text = ""++ return _T()++ result = asyncio.run(+ run_provider_test(+ _Spec(), cfg=None, make_stt=lambda cfg, provider: _WorkingProvider()+ )+ )++ assert decoded == ["ran"], "the test must actually run the model, not just build it"+ assert result.status == "ok"+++def test_cloud_providers_are_unaffected(monkeypatch: pytest.MonkeyPatch) -> None:+ """The local probe must never gate a provider that is not local at all."""+ _patch_status(monkeypatch, None)++ assert provider_test._local_readiness("groq-api") is None+++def test_switch_refuses_an_uninstalled_local_provider(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The shared lock: voice command, CLI and brain tool all pass through here."""+ _patch_status(monkeypatch, NOT_INSTALLED)+ monkeypatch.setattr(app_control, "get_spec", lambda pid: _Spec(), raising=False)++ result = asyncio.run(+ app_control.apply_provider_switch(+ "stt", "nemotron-local", cfg=None, persist=False+ )+ )++ assert result["ok"] is False+ assert result["error_kind"] == "not_installed"+ assert "not installed" in result["error"]+++def test_switch_allows_it_once_installed(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_status(monkeypatch, INSTALLED)+ monkeypatch.setattr(app_control, "get_spec", lambda pid: _Spec(), raising=False)+ switched: list[str] = []+ monkeypatch.setattr(+ app_control,+ "_switch_stt",+ lambda provider, **kw: switched.append(provider) or {"ok": True},+ raising=False,+ )++ result = asyncio.run(+ app_control.apply_provider_switch(+ "stt", "nemotron-local", cfg=None, persist=False+ )+ )++ assert result["ok"] is True+ assert switched == ["nemotron-local"]+++def test_readiness_error_is_none_for_cloud_and_for_ready_local(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_status(monkeypatch, None)+ assert app_control.local_readiness_error(_Spec(id="groq-api")) is None++ _patch_status(monkeypatch, INSTALLED)+ assert app_control.local_readiness_error(_Spec()) is None++ _patch_status(monkeypatch, NOT_INSTALLED)+ assert app_control.local_readiness_error(_Spec()) == NOT_INSTALLED.detaildiff --git a/tests/unit/brain/test_provider_test_service.py b/tests/unit/brain/test_provider_test_service.pyindex d52eb33caf..fd5ba62186 100644--- a/tests/unit/brain/test_provider_test_service.py+++ b/tests/unit/brain/test_provider_test_service.py@@ -119,18 +119,30 @@ def test_brain_probe_bad_key_is_bad_key() -> None:def test_local_provider_none_auth_is_ok_without_network() -> None:- # A local STT provider with auth_mode "none" needs no credential and no- # network: a successful local build IS the "ok" signal. The former- # faster-whisper spec was removed in v1.0.1, so synthesize the spec shape- # here rather than resolve a live registry entry (which now returns None).+ # A local STT provider needs no credential and no network — but "ok" is+ # earned by RUNNING it, not by constructing it. This test asserted the+ # opposite until 2026-07-29 ("a successful local build IS the ok signal"),+ # and that is exactly how the Nemotron card came to report ready on a+ # machine where nothing had been installed: an on-device provider loads its+ # weights lazily, so construction succeeds everywhere and proves nothing.+ ran: list[str] = []++ class _LocalSTT:+ name = "fw"++ async def transcribe(self, _audio):+ ran.append("decoded")+ return SimpleNamespace(text="")+spec = SimpleNamespace(id="local-stt", auth_mode="none", tier="stt")res = _run(run_provider_test(spec, _cfg(), present=True,- make_stt=lambda _cfg, _prov: SimpleNamespace(name="fw"),+ make_stt=lambda _cfg, _prov: _LocalSTT(),))assert res.status == "ok"+ assert ran == ["decoded"], "the local test must actually run the recognizer"def test_codex_connected_is_ok() -> None:@@ -270,3 +282,37 @@ def test_realtime_depleted_credits_are_an_account_error() -> None:))assert res.status == "no_credits"+++# ----------------------------------------------------------------------+# Dictation cards are refused here, not mis-probed+# ----------------------------------------------------------------------+++def test_a_dictation_card_is_refused_instead_of_probed_as_a_recognizer() -> None:+ """The tier had no branch and fell through to the STT probe below it, so+ "Test" on a wording card built the user's RECOGNIZER and reported its+ verdict under the card's name. The wording probe itself may not live in+ this layer (AP-11), so the honest answer here is a refusal — never a+ fall-through to a provider this card has nothing to do with."""+ from jarvis.ui.web.provider_spec import dictation_spec_id++ built = False++ def make_stt(_cfg, _provider): # pragma: no cover - must NOT run+ nonlocal built+ built = True+ raise AssertionError("a wording card must not build an STT provider")++ res = _run(+ run_provider_test(+ get_spec(dictation_spec_id("openai")),+ _cfg(),+ present=True,+ make_stt=make_stt,+ )+ )++ assert built is False+ assert res.status == "error"+ assert "dictation layer" in res.detail