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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 18:23)
Ruben Lütke33141726d718
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex c5ad16de1a..dbeb3ae1e6 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -3279,6 +3279,7 @@ class BrainManager:def _reset_provider_caches(self) -> None:"""Clears session state that would block a freshly set key."""self._dead_providers.clear()+ self._dead_provider_models.clear()self._brain_cache.clear()self._rate_tracker.clear()@@ -3297,6 +3298,9 @@ class BrainManager:"""was_dead = provider in self._dead_providersself._dead_providers.discard(provider)+ self._dead_provider_models = {+ k for k in self._dead_provider_models if k[0] != provider+ }keys_to_drop = [k for k in self._brain_cache if k[0] == provider]for k in keys_to_drop:self._brain_cache.pop(k, None)@@ -3369,6 +3373,9 @@ class BrainManager:for key in [k for k in self._brain_cache if k[0] == canonical]:self._brain_cache.pop(key, None)self._dead_providers.discard(canonical)+ self._dead_provider_models = {+ k for k in self._dead_provider_models if k[0] != canonical+ }return canonical == self._active_name@staticmethod@@ -7470,15 +7477,33 @@ class BrainManager:(prov_name, model, "rate_limit", "HTTP 429"))else:log.warning("Brain %s(%s) fehlgeschlagen: %s", prov_name, model, exc)- if (- kind in _DEAD_LIST_KINDS- and prov_name not in self._dead_providers- ):- self._dead_providers.add(prov_name)- log.warning(- "Provider %s fuer diese Session deaktiviert (%s) — die Kette "- "weicht auf einen anderen verfuegbaren Anbieter aus. "- "Setup: Sidebar -> API-Keys.", prov_name, kind)+ if kind in _DEAD_LIST_KINDS and prov_name not in self._dead_providers:+ # account_blocked (e.g. a bare 402) is model-scoped when+ # the SAME provider still has an untried model later in+ # this turn's chain (a capped paid model with a funded+ # free model behind it, tests/unit/brain/+ # test_depleted_credits_classification.py covers only the+ # classifier, not this chain policy). missing_key/bad_key+ # are credential problems and stay provider-wide — a dead+ # key blocks every model, not just this one.+ remaining_model = any(+ other_name == prov_name+ and other_model != model+ and (other_name, other_model) not in self._dead_provider_models+ for other_name, other_model in chain[idx + 1:]+ )+ if kind == "account_blocked" and remaining_model:+ self._dead_provider_models.add((prov_name, model))+ log.warning(+ "Model %s(%s) billing-blocked — anderes Modell "+ "desselben Anbieters bleibt in dieser Kette aktiv.",+ prov_name, model)+ else:+ self._dead_providers.add(prov_name)+ log.warning(+ "Provider %s fuer diese Session deaktiviert (%s) — die Kette "+ "weicht auf einen anderen verfuegbaren Anbieter aus. "+ "Setup: Sidebar -> API-Keys.", prov_name, kind)provider_errors.append((prov_name, model, kind, msg[:200]))# NOTE BUG-019 (2026-05-11): this generic ``continue`` does# not touch the failing provider's *internal* state. Fordiff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.pyindex 74982db6fe..19c5ecde6e 100644--- a/jarvis/plugins/wake/vosk_kws_provider.py+++ b/jarvis/plugins/wake/vosk_kws_provider.py@@ -40,7 +40,7 @@ import jsonimport loggingimport timefrom collections import deque-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Awaitable, Callablefrom concurrent.futures import ThreadPoolExecutorfrom difflib import SequenceMatcherfrom typing import Any@@ -93,6 +93,15 @@ _COOLDOWN_S = 5.0# passed)._CONFIRM_TAIL_S = 0.6+# How much of the RECENT ring to check for the optimistic candidate signal's+# cheap pre-gate (spawn-latency mission 2026-07-10). This is deliberately a+# SEPARATE, cheaper check from the authoritative span-localised RMS gate in+# ``_verify_candidate`` — it only exists to stop the optimistic, visual-only+# ``on_candidate(True)`` from firing on a grammar hit pulled onto near-silence+# (word-agnostic, AP-27-conform: energy only, never transcript content). The+# authoritative confirm below is unchanged and remains the real gate.+_CANDIDATE_RMS_TAIL_S = 0.4+def _folded(text: str) -> str:return " ".join(sound_fold(t) for t in normalize_phrase_for_match(text))@@ -146,6 +155,18 @@ class VoskKwsProvider:# -3 dBFS (gain capped at 40 dB) exactly like the other wake paths.target_peak: float = 0.7079,max_gain: float = 100.0,+ # Optimistic, visual-only candidate signal (spawn-latency mission+ # 2026-07-10): awaited with True the moment a grammar candidate+ # passes the cheap RMS pre-gate — BEFORE the confirm_tail_s wait and+ # the (now-parallelised, but still real) verify pass — and with+ # False if that candidate is later rejected. Mirrors the OWW+ # candidate/retract semantics the pipeline already publishes as+ # ``WakeCandidateDetected``, just sourced from inside this provider+ # (unlike OWW, this provider's own ``detect()`` does not yield until+ # AFTER its full internal confirm, so the pipeline has no other way+ # to learn about a candidate this early). None = no signal (tests /+ # callers that do not care).+ on_candidate: Callable[[bool], Awaitable[None]] | None = None,) -> None:self._phrase = phrase.strip()self._keyword = keyword or "_".join(normalize_phrase_for_match(phrase)) or "wake"@@ -169,6 +190,7 @@ class VoskKwsProvider:self._confirm_ratio = max(self._confirm_ratio, 0.62)self._target_peak = float(target_peak)self._max_gain = float(max_gain)+ self._on_candidate = on_candidateself._model: Any = Noneself._grammar_words = [w for w in self._phrase.lower().split() if w]# Duck-typing parity with OpenWakeWordProvider: the pipeline's ready@@ -273,6 +295,23 @@ class VoskKwsProvider:raw = b"".join(self._ring)return np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0+ def _recent_rms(self, tail_s: float) -> float:+ """Cheap RMS over the last ``tail_s`` seconds of ring audio.++ Used ONLY as the fast pre-gate for the optimistic ``on_candidate``+ signal (word-agnostic, AP-27-conform) — the authoritative,+ span-localised RMS check in ``_verify_candidate`` is unchanged and+ stays the real gate for whether the wake actually fires.+ """+ if not self._ring:+ return 0.0+ n_bytes = int(tail_s * self._sample_rate) * 2+ raw = b"".join(self._ring)[-n_bytes:] if n_bytes > 0 else b""+ if not raw:+ return 0.0+ arr = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0+ return float(np.sqrt(np.mean(arr * arr) + 1e-12)) if len(arr) else 0.0+def _grammar_hit(self, rec: Any, pcm: bytes) -> tuple[bool, float] | None:"""Feed one chunk; return (is_final, min_conf) on a phrase hit else None."""if rec.AcceptWaveform(pcm):@@ -426,12 +465,35 @@ class VoskKwsProvider:# -- detection loop --------------------------------------------------------+ async def _signal_candidate(self, active: bool) -> None:+ """Best-effort ``on_candidate`` notification — a broken/absent hook+ must never break wake detection itself (fail-open, matches every+ other callback boundary in this provider)."""+ if self._on_candidate is None:+ return+ try:+ await self._on_candidate(active)+ except Exception: # noqa: BLE001+ log.debug("vosk-kws on_candidate(%s) callback failed", active, exc_info=True)+async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:"""Consume audio chunks, yield the keyword on a confirmed hit.The grammar recognizer streams chunk-by-chunk (measured ~0.02xrealtime — a 100 ms chunk costs ~2 ms, safe inline). The confirm pass(~0.1-0.2 s) runs in a worker thread only on candidates.++ Spawn-latency mission (2026-07-10): this loop's own confirm_tail_s+ wait + verify pass is the dominant cost between "the user finishes+ the phrase" and "the wake is authoritatively confirmed" — deliberately+ NOT shortened here (recall-calibrated, see the constants above). What+ CAN move earlier is the visual-only bar reveal: ``on_candidate(True)``+ fires the moment a grammar hit clears cooldown + the cheap RMS+ pre-gate, i.e. BEFORE confirm_tail_s and the verify pass, so the UI+ can react in roughly one poll cadence. ``on_candidate(False)`` fires+ if that same candidate is later rejected, so a false grammar hit only+ costs a brief visual flash, never a phantom session (the actual+ session only ever opens on a real ``yield`` below)."""await asyncio.to_thread(self._ensure_model)rec = self._new_grammar_rec()@@ -442,6 +504,10 @@ class VoskKwsProvider:# the wait — their endpoint already passed.pending: tuple[bool, float] | None = Nonepending_tail = 0+ # True while an optimistic on_candidate(True) is outstanding for the+ # candidate currently being confirmed — tracks whether a matching+ # on_candidate(False) retraction is owed on rejection.+ signalled_candidate = Falseasync for chunk in chunks:self._stat_chunks += 1pcm = chunk.pcm@@ -466,6 +532,13 @@ class VoskKwsProvider:if is_final and conf < self._min_final_conf:rec = self._new_grammar_rec()continue+ # Optimistic, visual-only reveal (see the docstring above).+ # Gated on raw RMS over the recent ring — word-agnostic,+ # AP-27-conform — so a grammar hit pulled onto near-silence+ # never pops the bar.+ if self._recent_rms(_CANDIDATE_RMS_TAIL_S) >= self._match_min_rms:+ signalled_candidate = True+ await self._signal_candidate(True)if not is_final and self._confirm_tail_bytes > 0:pending = (is_final, conf)pending_tail = 0@@ -475,10 +548,14 @@ class VoskKwsProvider:confirmed = await asyncio.to_thread(self._verify_candidate, window)if not confirmed:self._stat_suppressed_confirm += 1+ if signalled_candidate:+ await self._signal_candidate(False)+ signalled_candidate = Falserec = self._new_grammar_rec()continueself._stat_fired += 1last_fire_t = now+ signalled_candidate = Falselog.info("vosk-kws: WAKE fired for %r (%s candidate)",self._phrase,diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 8ae7777c0b..f54813cac3 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -529,10 +529,23 @@ class RealtimeVoiceSession:{"success": False, "error": "Tool call is not available."},)return- original_name, result = await self._tool_bridge.execute(- wire_name=wire_name,- arguments=arguments,- )+ try:+ original_name, result = await self._tool_bridge.execute(+ wire_name=wire_name,+ arguments=arguments,+ )+ except Exception: # noqa: BLE001 -- a failed tool must not kill duplex audio+ log.warning("realtime tool execution failed: %s", wire_name, exc_info=True)+ await self._publish_error(+ "RealtimeToolError",+ f"Realtime tool execution failed: {wire_name}",+ recoverable=True,+ )+ original_name = wire_name+ result = {+ "success": False,+ "error": "The tool failed safely and was not completed.",+ }if result.get("success"):self._executed_tool_names.add(original_name)await self._session.send_tool_result(call_id, wire_name, result)diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex d7f8199401..b08a450da6 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -147,7 +147,7 @@ class RealtimeToolBridge:"error": "Tool is not available in this session.",}if self._vetoed_tool == name:- return wire_name, {+ return name, {"success": False,"error": "The user declined this action. Do not ask again in this turn.",}diff --git a/jarvis/skills/authoring/service.py b/jarvis/skills/authoring/service.pyindex 728eb04087..09657e1d7f 100644--- a/jarvis/skills/authoring/service.py+++ b/jarvis/skills/authoring/service.py@@ -73,6 +73,12 @@ class SkillCreateRequest:source_url: str | None = Nonedocs_url: str | None = Noneauthor: str = ""+ # Optional lifecycle-state override (AP-15). ``None`` — the manual "New+ # skill" form's default — omits the frontmatter key entirely, so the+ # loader resolves the skill to VALIDATED ("on") as documented below. The+ # AI creator (``creator_service.py``) passes ``state="draft"`` here so+ # its LLM-generated skills land inactive until a human promotes them.+ state: str | None = Nonedef slugify(name: str) -> str:@@ -98,8 +104,10 @@ def body_has_instructions(body: str) -> bool:def _build_frontmatter(req: SkillCreateRequest) -> dict[str, Any]:"""Assemble the YAML frontmatter dict, omitting empty optional fields.- Deliberately omits ``state`` so the loader resolves the skill to VALIDATED- ("on") — an explicit user-authored skill is usable immediately.+ Omits ``state`` when ``req.state`` is ``None`` (the manual form's+ default) so the loader resolves the skill to VALIDATED ("on") — an+ explicit user-authored skill is usable immediately. When ``req.state``+ is set (the AI creator passes ``"draft"``, AP-15) it is written verbatim."""fm: dict[str, Any] = {"schema_version": "1",@@ -108,6 +116,8 @@ def _build_frontmatter(req: SkillCreateRequest) -> dict[str, Any]:"description": req.description,"category": (req.category or "general").strip() or "general",}+ if req.state:+ fm["state"] = req.stateif req.tags:fm["tags"] = list(req.tags)if req.author:diff --git a/jarvis/skills/creator_service.py b/jarvis/skills/creator_service.pyindex 4e21473c6d..8a76bf03ed 100644--- a/jarvis/skills/creator_service.py+++ b/jarvis/skills/creator_service.py@@ -211,8 +211,10 @@ def render_skill_md(draft: dict[str, Any]) -> str:"""Render a SKILL.md string from a creator draft dict (state forced draft).Unlike the manual form (which writes a usable VALIDATED skill), the AI- creator stamps ``state: draft`` because the content is LLM-generated — but- here we only *render* for preview/validate; ``commit`` decides persistence.+ creator stamps ``state: draft`` because the content is LLM-generated+ (AP-15) — a human must explicitly promote it before it goes live. This+ render is what the user previews AND what ``commit`` persists (via+ ``SkillCreateRequest(state="draft")``), so the two never disagree."""fm: dict[str, Any] = {"schema_version": "1",@@ -220,6 +222,7 @@ def render_skill_md(draft: dict[str, Any]) -> str:"version": "0.1.0","description": str(draft.get("description", "")),"category": str(draft.get("category", "general")) or "general",+ "state": "draft",}if draft.get("tags"):fm["tags"] = list(draft["tags"])@@ -335,7 +338,13 @@ class SkillCreatorService:return await self._draft_or_refine(inp, refine=True)async def commit(self, draft: dict[str, Any]) -> Skill:- """Persist a reviewed draft as a real skill via the shared writer."""+ """Persist a reviewed draft as a real skill via the shared writer.++ Always writes ``state="draft"`` frontmatter (AP-15): the content is+ LLM-generated (or an unreviewed deterministic skeleton), so it must+ land inactive until a human explicitly promotes it — matching what+ ``render_skill_md`` already previews to the user.+ """if not isinstance(draft, dict):raise ValueError("draft must be an object")req = SkillCreateRequest(@@ -347,6 +356,7 @@ class SkillCreatorService:requires_tools=tuple(draft.get("requires_tools", []) or ()),risk_policy=draft.get("risk_policy") or None,body=str(draft.get("body", "")),+ state="draft",)service = SkillAuthoringService(registry=self._registry,diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 9c3e40ef25..86eb57b3ba 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1140,6 +1140,7 @@ class SpeechPipeline:phrase=wake_plan.phrase,model_path=wake_plan.vosk_model_path or "",keyword=wake_plan.oww_keyword,+ on_candidate=self._on_vosk_wake_candidate,)elif wake_plan is not None:self._wake = OpenWakeWordProvider(@@ -1846,6 +1847,7 @@ class SpeechPipeline:phrase=plan.phrase,model_path=getattr(plan, "vosk_model_path", None) or "",keyword=plan.oww_keyword,+ on_candidate=self._on_vosk_wake_candidate,)self._openwakeword_enabled = Trueif self._whisper_wake is not None and self._wake_matcher is not None:@@ -4293,6 +4295,30 @@ class SpeechPipeline:log.exception("Wake-Loop Fehler: %s", exc)await asyncio.sleep(0.5)+ async def _on_vosk_wake_candidate(self, active: bool) -> None:+ """Optimistic, visual-only bar reveal for the vosk_kws engine+ (spawn-latency mission 2026-07-10).++ Unlike OpenWakeWord, ``VoskKwsProvider.detect()`` does not yield+ anything until AFTER its own internal confirm (grammar re-score ++ energy gate + free-decode sound confirm) already completed — so the+ OWW-result-timed optimistic publish further down in+ ``_run_parallel_wake`` runs too late to help this engine (it would+ fire right before the authoritative ``WakeWordDetected`` anyway).+ The provider instead calls back HERE the moment a grammar candidate+ clears its own cheap RMS pre-gate — well before its confirm_tail_s+ wait and verify pass — so the visual reveal lands in roughly one+ poll cadence. ``active=False`` retracts if that candidate is later+ rejected. Visual only: never opens a session, mirrors+ ``_on_wake_candidate`` on the orb-bridge side (ui/orb/bus_bridge.py).+ """+ try:+ await self._publish_event(+ WakeCandidateDetected(source_layer="speech", active=active)+ )+ except Exception as exc: # noqa: BLE001 — a broken publish must not kill wake+ log.warning("vosk wake-candidate publish failed: %s", exc)+def _should_show_optimistic_candidate(self) -> bool:"""Whether an unverified OWW hit may pop the overlay bar immediately.@@ -4618,7 +4644,23 @@ class SpeechPipeline:# Custom-model candidates never reveal optimistically# (constant flicker, see the helper's docstring).show_candidate = self._should_show_optimistic_candidate()- if show_candidate:+ # vosk_kws already published its OWN, earlier+ # candidate signal directly from the provider+ # (see _on_vosk_wake_candidate) — timed BEFORE its+ # internal confirm_tail_s wait, unlike this+ # OWW-result-timed publish which only runs AFTER+ # vosk's full internal verify already completed.+ # Publishing True again here would be a redundant,+ # mistimed duplicate landing almost simultaneously+ # with WakeWordDetected. `show_candidate` itself+ # stays UNCHANGED so the lock/not-activatable+ # retract path further below still correctly+ # retracts the EARLIER provider-side show if this+ # wake gets discarded.+ engine = getattr(+ getattr(self, "_wake_plan", None), "engine", ""+ )+ if show_candidate and engine != "vosk_kws":await self._publish_event(WakeCandidateDetected(source_layer="speech", active=Truediff --git a/jarvis/ui/web/docs_routes.py b/jarvis/ui/web/docs_routes.pyindex d231d21fdb..96e5a14747 100644--- a/jarvis/ui/web/docs_routes.py+++ b/jarvis/ui/web/docs_routes.py@@ -211,17 +211,16 @@ def get_doc(request: Request, slug: str) -> dict[str, Any]:def open_doc_in_editor(request: Request, slug: str) -> dict[str, Any]:"""Opens the Markdown file in the OS default editor.- On Windows: ``os.startfile`` launches the file-type handler (typically- Notepad, VSCode, or a Markdown editor). We do NOT launch elevated —- that path is read+write for the user-owner already; the user+ Cross-platform via ``jarvis.platform.open_path.open_file`` (Windows+ ``os.startfile``, macOS ``open``, Linux ``xdg-open``). We do NOT launch+ elevated — that path is read+write for the user-owner already; the useralready has write access to the doc repo anyway.Caution: on some systems Notepad is configured with BOM-savebehavior; re-saving can mangle the frontmatter. The``jarvis-doc-author`` skill remains the preferred authoring path."""- import os- import subprocess+ from jarvis.platform import open_pathreg = _require_registry(request)doc = reg.get(slug)@@ -232,19 +231,10 @@ def open_doc_in_editor(request: Request, slug: str) -> dict[str, Any]:if not target.is_file():raise HTTPException(status_code=404, detail="file no longer exists")- try:- if hasattr(os, "startfile"):- # Windows-specific — the file-type association decides which- # editor opens. Non-blocking.- os.startfile(str(target)) # noqa: S606- else: # pragma: no cover (only relevant to Windows in this app)- subprocess.Popen(["xdg-open", str(target)])- return {"path": str(target), "opened": True}- except OSError as exc:- log.warning("open_doc_in_editor failed for %s: %s", slug, exc)- raise HTTPException(- status_code=500, detail=f"editor start failed: {exc}",- ) from exc+ opened = open_path.open_file(target)+ if not opened:+ raise HTTPException(status_code=500, detail="editor start failed")+ return {"path": str(target), "opened": True}# ----------------------------------------------------------------------diff --git a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsxindex 126bc52012..6f97eb3783 100644--- a/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx+++ b/jarvis/ui/web/frontend/src/components/BrainModelSelector.tsx@@ -105,6 +105,8 @@ export function BrainModelSelector({currentModel,recommendedModel,onSave,+ healthSection,+ healthActive = false,headingLabel,placeholder,controlled,@@ -124,6 +126,11 @@ export function BrainModelSelector({* route. Defaults to ``saveBrainProviderModel(providerId, model)``.*/onSave?: (model: string) => Promise<BrainModelSaveResult>;+ /** Health section affected by this selection. When the provider is active,+ * its obsolete result is hidden while the save/probe is in flight. */+ healthSection?: "brain" | "tts" | "stt" | "computer-use" | "subagents";+ /** Whether this picker belongs to the provider currently powering that section. */+ healthActive?: boolean;/*** Override the section heading (e.g. "Computer-Use model"). Defaults to the* standard model/voice heading. Presentation only.@@ -282,10 +289,37 @@ export function BrainModelSelector({setProbe(null);setOpen(false);setQuery("");+ if (healthSection && healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", {+ detail: { section: healthSection, provider: providerId },+ }),+ );+ }try {const res = onSave ? await onSave(model) : await saveBrainProviderModel(providerId, model);setPinned(res.model);setProbe(res.probe ?? null);+ if (healthSection && healthActive) {+ if (res.probe) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-tested", {+ detail: {+ section: healthSection,+ provider: res.provider,+ active: true,+ result: { provider: res.provider, ...res.probe },+ },+ }),+ );+ } else {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-config-changed", {+ detail: { section: healthSection, provider: res.provider },+ }),+ );+ }+ }const note = res.restart_required? ` ${t("apikeys_model.restart_note")}`: res.applied_live@@ -293,6 +327,13 @@ export function BrainModelSelector({: "";pushToast("success", `${t("apikeys_model.saved")}${note}`);} catch (e) {+ if (healthSection && healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", {+ detail: { section: healthSection, provider: providerId },+ }),+ );+ }pushToast("error", (e as Error).message);} finally {setSaving(false);diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 3eb1f1decd..6794eb113c 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -331,6 +331,7 @@ export function useSectionHealth() {"jarvis:subagent-switched","jarvis:agent-switched","jarvis:provider-tested",+ "jarvis:provider-config-changed","jarvis:provider-selection-pending","jarvis:provider-switch-failed",];diff --git a/jarvis/ui/web/missions_ws_routes.py b/jarvis/ui/web/missions_ws_routes.pyindex 62d6f7ed5d..75949b6714 100644--- a/jarvis/ui/web/missions_ws_routes.py+++ b/jarvis/ui/web/missions_ws_routes.py@@ -50,6 +50,10 @@ router = APIRouter(prefix="/api/missions", tags=["missions-ws"])_QUEUE_MAXSIZE = 200_HELLO_TIMEOUT_S = 5.0+# Sent at most once per connection when a drop-oldest overflow happens, so+# the client knows its stream has a gap and should resync via REST.+_GAP_FRAME: dict[str, Any] = {"type": "gap"}+class ConnectionManager:"""Per-client bounded ``asyncio.Queue`` + global fanout.@@ -60,63 +64,108 @@ class ConnectionManager:"""def __init__(self) -> None:- self._clients: dict[str, asyncio.Queue[EventEnvelope]] = {}+ self._clients: dict[str, asyncio.Queue[EventEnvelope | dict[str, Any]]] = {}self._lock = asyncio.Lock()+ self._gap_notified: set[str] = set()async def connect(self,client_id: str,last_seq: int,store: "MissionEventStore",- ) -> asyncio.Queue[EventEnvelope]:- """Registers a client and enqueues all replay events since ``last_seq``.-- Replay runs synchronously before registration — this way the client- never misses events that would be published between ``events_since()``- and ``subscribe_all()``.+ ) -> asyncio.Queue[EventEnvelope | dict[str, Any]]:+ """Registers a client, then enqueues all replay events since ``last_seq``.++ Registration happens BEFORE the replay query so that any event+ ``fanout()`` publishes while the query is in flight lands in the+ queue instead of being lost in the gap between ``events_since()``+ and registration. Once the query returns we drain whatever landed+ there in the meantime (no ``await`` in between — single-threaded+ event loop, so nothing else can touch the queue during the drain)+ and merge it after the replay, skipping anything the replay already+ covers so the client never sees a duplicate."""- queue: asyncio.Queue[EventEnvelope] = asyncio.Queue(+ queue: asyncio.Queue[EventEnvelope | dict[str, Any]] = asyncio.Queue(maxsize=_QUEUE_MAXSIZE)- # Replay first, then register — otherwise live fanout races the replay.- replay = await store.events_since(last_seq)- for env in replay:- try:- queue.put_nowait(env)- except asyncio.QueueFull:- # Replay burst larger than the queue — the oldest replay- # events take priority over live events.- try:- queue.get_nowait()- queue.put_nowait(env)- except (asyncio.QueueEmpty, asyncio.QueueFull):- passasync with self._lock:self._clients[client_id] = queue++ replay = await store.events_since(last_seq)++ live_during_replay: list[EventEnvelope] = []+ while not queue.empty():+ item = queue.get_nowait()+ if isinstance(item, EventEnvelope):+ live_during_replay.append(item)++ max_replayed_seq = (+ replay[-1].seq+ if replay and replay[-1].seq is not None+ else last_seq+ )+ merged = list(replay) + [+ env+ for env in live_during_replay+ if env.seq is not None and env.seq > max_replayed_seq+ ]+ for env in merged:+ self._enqueue(client_id, queue, env)return queueasync def disconnect(self, client_id: str) -> None:async with self._lock:self._clients.pop(client_id, None)+ self._gap_notified.discard(client_id)++ def _enqueue(+ self,+ client_id: str,+ queue: asyncio.Queue[EventEnvelope | dict[str, Any]],+ env: EventEnvelope,+ ) -> None:+ """``put_nowait`` with drop-oldest; on drop, arm a one-time gap notice."""+ try:+ queue.put_nowait(env)+ return+ except asyncio.QueueFull:+ pass+ try:+ queue.get_nowait()+ queue.put_nowait(env)+ except asyncio.QueueEmpty:+ pass+ except asyncio.QueueFull:+ logger.warning(+ "missions_ws: client=%s queue still full after drop",+ client_id,+ )+ self._notify_gap(client_id, queue)++ def _notify_gap(+ self,+ client_id: str,+ queue: asyncio.Queue[EventEnvelope | dict[str, Any]],+ ) -> None:+ """Enqueues one ``{"type": "gap"}`` frame per client so it resyncs via REST."""+ if client_id in self._gap_notified:+ return+ self._gap_notified.add(client_id)+ try:+ queue.put_nowait(_GAP_FRAME)+ except asyncio.QueueFull:+ try:+ queue.get_nowait()+ queue.put_nowait(_GAP_FRAME)+ except (asyncio.QueueEmpty, asyncio.QueueFull):+ passasync def fanout(self, env: EventEnvelope) -> None:"""``MissionBus.subscribe_all`` handler. Drop-oldest per client."""# Snapshot without a lock — modifications to the dict are asyncio-thread-safe# (one loop per server), and we're only reading values.for client_id, queue in list(self._clients.items()):- try:- queue.put_nowait(env)- except asyncio.QueueFull:- try:- queue.get_nowait()- queue.put_nowait(env)- except asyncio.QueueEmpty:- pass- except asyncio.QueueFull:- logger.warning(- "missions_ws: client=%s queue still full after drop",- client_id,- )+ self._enqueue(client_id, queue, env)@propertydef client_count(self) -> int:@@ -189,12 +238,28 @@ async def missions_ws(ws: WebSocket) -> None:msg = await ws.receive_json()except WebSocketDisconnect:return- except Exception as exc: # noqa: BLE001+ except RuntimeError as exc:+ # AP-20: an unclean client disconnect raises RuntimeError+ # ("WebSocket is not connected ...") instead of+ # WebSocketDisconnect. `continue` here would re-poll the dead+ # socket forever — treat it as terminal.+ logger.debug(+ "missions_ws: reader socket error (%s) — closing", exc+ )+ return+ except ValueError as exc:+ # Malformed JSON (json.JSONDecodeError is a ValueError) on an+ # otherwise-live socket — skip the bad frame, keep reading.logger.debug("missions_ws: client frame decode error (%s) — ignoring",exc,)continue+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "missions_ws: reader unexpected error (%s) — closing", exc+ )+ return# Reserved for future control frames (pause/resume etc.).if isinstance(msg, dict) and msg.get("type") == "ping":# Silent pong skip — bus pings are enough.@@ -208,8 +273,9 @@ async def missions_ws(ws: WebSocket) -> None:try:while True:env = await queue.get()+ frame = env.model_dump(mode="json") if isinstance(env, EventEnvelope) else envtry:- await ws.send_json(env.model_dump(mode="json"))+ await ws.send_json(frame)except WebSocketDisconnect:breakexcept Exception as exc: # noqa: BLE001diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex 48f49326d3..5cbca45fb3 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -18,7 +18,6 @@ import loggingimport mimetypesimport osimport re-import subprocessimport timefrom pathlib import Pathfrom typing import Any@@ -27,7 +26,6 @@ from fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModelfrom starlette.responses import FileResponse, HTMLResponse-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.missions.kontrollierer.deliverable_paths import (is_nondeliverable_scratch,)@@ -1021,7 +1019,7 @@ async def open_artifact_with(@router.post("/{slug}/open")async def open_output(slug: str, request: Request) -> dict[str, Any]:- """Open the session folder in the OS file explorer (Windows: explorer.exe).+ """Open the session folder in the OS file explorer (Explorer/Finder/xdg).Best-effort, non-blocking — frontend ignores errors. Restricts the pathinside `outputs_root` so a crafted slug can't open arbitrary folders.@@ -1034,17 +1032,10 @@ async def open_output(slug: str, request: Request) -> dict[str, Any]:raise HTTPException(status_code=400, detail="invalid slug") from excif not target.is_dir():raise HTTPException(status_code=404, detail=f"unknown slug: {slug}")- if os.name == "nt":- try:- subprocess.Popen( # noqa: S603,S607,ASYNC220 — explorer.exe path is os-fixed; Popen returns immediately (no event-loop block)- ["explorer.exe", str(target)],- creationflags=NO_WINDOW_CREATIONFLAGS,- close_fds=True,- )- except OSError as exc:- logger.warning("outputs: explorer.exe failed for %s: %s", target, exc)- raise HTTPException(- status_code=500, detail=f"open failed: {exc}"- ) from exc- return {"opened": True, "path": str(target)}- return {"opened": False, "path": str(target), "reason": "non-Windows host"}++ from jarvis.platform import open_path++ opened = await asyncio.to_thread(open_path.reveal_in_folder, target)+ if not opened:+ return {"opened": False, "path": str(target), "reason": "open failed"}+ return {"opened": True, "path": str(target)}diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 7c4d3635b8..1e43b42037 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -959,14 +959,46 @@ def _section_health_subjects(request: Request, cfg: Any) -> dict[str, str | Nonedef _section_health_fingerprint(- request: Request, subjects: dict[str, str | None]+ request: Request,+ cfg: Any,+ subjects: dict[str, str | None],) -> tuple[tuple[str, str], ...]:- """Return a secret-free cache key for the full health selection snapshot."""+ """Return a secret-free cache key for the full health selection snapshot.++ Provider identity alone is insufficient: changing a Brain, Computer-Use,+ TTS, STT, or Realtime model while its provider stays selected must also+ supersede the old probe. Otherwise an old model timeout can be cached and+ displayed against the newly selected, working model.+ """telephony = getattr(request.app.state, "telephony_manager", None)reachable = getattr(telephony, "reachable", None) if telephony is not None else None- return tuple((key, subjects.get(key) or "") for key in _SECTION_HEALTH_KEYS) + (+ brain = getattr(cfg, "brain", None) if cfg is not None else None+ providers = getattr(brain, "providers", None)++ def _provider_value(section: str, field: str) -> str:+ provider_id = subjects.get(section) or ""+ provider_cfg = providers.get(provider_id) if isinstance(providers, dict) else None+ return str(getattr(provider_cfg, field, None) or "")++ tts = getattr(cfg, "tts", None) if cfg is not None else None+ stt = getattr(cfg, "stt", None) if cfg is not None else None+ worker = getattr(brain, "worker", None) if brain is not None else None+ configuration = (+ ("brain-model", _provider_value("brain", "model")),+ ("computer-use-model", _provider_value("computer-use", "cu_model")),+ ("tts-model", str(getattr(tts, "model", None) or "")),+ ("tts-voice-de", str(getattr(tts, "voice_de", None) or "")),+ ("tts-voice-en", str(getattr(tts, "voice_en", None) or "")),+ ("stt-model", str(getattr(stt, "model", None) or "")),+ ("realtime-model", _provider_value("realtime", "model")),+ ("realtime-voice", _provider_value("realtime", "voice")),+ ("jarvis-agent-model", str(getattr(worker, "model", None) or "")),("advanced-reachable", repr(reachable)),)+ return (+ tuple((key, subjects.get(key) or "") for key in _SECTION_HEALTH_KEYS)+ + configuration+ )def _invalidate_section_health_state(request: Request) -> None:@@ -994,7 +1026,7 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHealwhile True:cfg = _resolve_cfg(request)subjects = _section_health_subjects(request, cfg)- fingerprint = _section_health_fingerprint(request, subjects)+ fingerprint = _section_health_fingerprint(request, cfg, subjects)cache = getattr(request.app.state, "_section_health_cache", None)now = time.time()if (@@ -1049,7 +1081,9 @@ async def section_health(request: Request, refresh: bool = False) -> SectionHealcurrent_cfg = _resolve_cfg(request)current_subjects = _section_health_subjects(request, current_cfg)- current_fingerprint = _section_health_fingerprint(request, current_subjects)+ current_fingerprint = _section_health_fingerprint(+ request, current_cfg, current_subjects+ )if current_fingerprint != fingerprint:refresh = Truecontinue@@ -1168,6 +1202,26 @@ def _provider_cu_model(cfg: Any, provider: str) -> str:return (getattr(pc, "cu_model", None) or "") if pc is not None else ""+def _set_brain_model_in_memory(cfg: Any, provider: str, value: str) -> None:+ """Keep route-level config aligned with the live BrainManager selection.++ The manager owns a separate config object. Without this mirror update,+ section health can keep probing the previous model after the new model has+ already been persisted and applied successfully.+ """+ try:+ providers = cfg.brain.providers+ pc = providers.get(provider)+ if pc is None:+ from jarvis.core.config import BrainProviderConfig++ pc = BrainProviderConfig()+ providers[provider] = pc+ pc.model = value or None+ except Exception as exc: # noqa: BLE001 -- detached config is best-effort+ log.debug("In-memory brain model update skipped for %s: %s", provider, exc)++def _set_cu_model_in_memory(cfg: Any, provider: str, value: str) -> None:"""Update ``cfg.brain.providers[provider].cu_model`` live so the next CUmission uses it without a restart (the loop reads cfg fresh each mission).@@ -1339,6 +1393,9 @@ async def _apply_brain_model(status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}") from exc+ cfg = _resolve_cfg(request)+ _set_brain_model_in_memory(cfg, provider_id, model)+brain = getattr(request.app.state, "brain", None)applied_live = Falseif brain is not None and hasattr(brain, "apply_provider_model"):@@ -1351,7 +1408,6 @@ async def _apply_brain_model(probe_payload: BrainModelProbe | None = Noneif probe:- cfg = _resolve_cfg(request)probe_model = model or _current_brain_model(cfg, provider_id)result = await _probe_brain_model(provider_id, probe_model)probe_payload = BrainModelProbe(diff --git a/jarvis/ui/web/wiki_ws.py b/jarvis/ui/web/wiki_ws.pyindex 63c1fe735d..a60e44780a 100644--- a/jarvis/ui/web/wiki_ws.py+++ b/jarvis/ui/web/wiki_ws.py@@ -29,6 +29,7 @@ next fetch — there is no need to replay missed events here.from __future__ import annotationsimport asyncio+import contextlibimport loggingfrom typing import TYPE_CHECKING@@ -96,9 +97,38 @@ async def wiki_live(ws: WebSocket) -> None:bus.subscribe(WikiPageChanged, _on_event)+ async def _reader() -> None:+ """Purely detects client disconnect — no inbound frames are expected.++ Without this, a tab closed while idle (no further wiki events) is+ never noticed: the forwarding loop below only wakes up on+ ``queue.get()``, so a subscriber + task would leak for the rest of+ the server's lifetime. Racing this against the queue read (see the+ ``asyncio.wait`` below) lets a disconnect interrupt an idle wait.+ """+ while True:+ try:+ await ws.receive_text()+ except WebSocketDisconnect:+ return+ except RuntimeError:+ # AP-20: an unclean disconnect raises RuntimeError, not+ # WebSocketDisconnect — treat any read error as terminal.+ return++ reader_task = asyncio.create_task(_reader(), name="wiki_ws-reader")try:while True:- event = await queue.get()+ get_task = asyncio.create_task(queue.get())+ done, _pending = await asyncio.wait(+ {reader_task, get_task}, return_when=asyncio.FIRST_COMPLETED+ )+ if reader_task in done:+ get_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await get_task+ break+ event = get_task.result()try:await ws.send_json({@@ -115,9 +145,10 @@ async def wiki_live(ws: WebSocket) -> None:# mid-write — terminates the stream cleanly.log.debug("wiki_ws: send failed (%s) — closing stream", exc)break- except WebSocketDisconnect:- passfinally:+ reader_task.cancel()+ with contextlib.suppress(asyncio.CancelledError, Exception):+ await reader_task# Always remove our subscription so the bus does not grow a# dead reference when the client disconnects.try:diff --git a/pyproject.toml b/pyproject.tomlindex 73aca6f693..a860d35ef4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -146,7 +146,7 @@ dev = [# (plain `pip install .`) remains the internal torch-free floor for CI and# tiny headless servers; users are pointed at [full].full = [- "personal-jarvis[desktop,telephony,channels,local-voice]",+ "personal-jarvis[desktop,desktop-macos,telephony,channels,local-voice]",]# Twilio telephony voice agent (call Jarvis on a phone number). Optional extra# per the cloud-first doctrine: the base install must boot without it, and thediff --git a/tests/integration/test_fallback_chain.py b/tests/integration/test_fallback_chain.pyindex 01e2981d10..6404609747 100644--- a/tests/integration/test_fallback_chain.py+++ b/tests/integration/test_fallback_chain.py@@ -318,6 +318,96 @@ async def test_dead_provider_skipped_on_subsequent_turns():)+class _PaymentRequiredBrain:+ """Brain stub that fails like a real provider hitting a bare billing+ rejection (HTTP 402) — classified as `account_blocked` by+ `_classify_provider_error`, the SAME kind the depleted-credits forensic+ (tests/unit/brain/test_depleted_credits_classification.py) covers.+ """+ name = "payment-required-brain"+ context_window = 8192+ supports_tools = True+ supports_vision = False++ def __init__(self) -> None:+ self.call_count = 0++ async def complete(self, req): # type: ignore[no-untyped-def]+ self.call_count += 1+ raise RuntimeError("Error code: 402 - Payment Required")+ yield # pragma: no cover++ def estimate_cost(self, req) -> float: # type: ignore[no-untyped-def]+ return 0.0+++async def test_402_dead_lists_only_the_model_when_a_sibling_model_remains():+ """A billing rejection (402) on ONE model of a provider must not dead-list+ the WHOLE provider while a different, untried model of the SAME provider+ is still later in this turn's chain (e.g. a capped paid model with a+ funded free model behind it) — the model-scoped twin of the existing+ provider-level dead-list (AP-22).+ """+ bus = EventBus()+ config = JarvisConfig()+ manager = BrainManager(config=config, bus=bus, tools={})+ manager._registry._loaded = True++ dead_paid = _PaymentRequiredBrain()+ working_free = FakeBrain(text_response="Antwort vom Free-Modell")++ manager._brain_cache[("openrouter", "paid-model")] = dead_paid+ manager._brain_cache[("openrouter", "free-model")] = working_free+ manager._build_fallback_chain = lambda level: [+ ("openrouter", "paid-model"),+ ("openrouter", "free-model"),+ ]++ result = await manager.generate("hi", use_history=False)++ assert "Free-Modell" in result+ assert dead_paid.call_count == 1+ assert ("openrouter", "paid-model") in manager._dead_provider_models+ assert "openrouter" not in manager._dead_providers, (+ "the whole provider must stay alive while a sibling model is untried"+ )+++async def test_402_dead_lists_whole_provider_when_no_sibling_model_remains():+ """When EVERY model of a provider hits a 402 this turn (no untried+ sibling model left in the chain), the provider itself falls back to the+ existing provider-level dead-list so the chain crosses to another family+ — the exact behavior the depleted-credits forensic protects.+ """+ bus = EventBus()+ config = JarvisConfig()+ manager = BrainManager(config=config, bus=bus, tools={})+ manager._registry._loaded = True++ dead_paid = _PaymentRequiredBrain()+ dead_free = _PaymentRequiredBrain()+ working_other_family = FakeBrain(text_response="Antwort von Gemini")++ manager._brain_cache[("openrouter", "paid-model")] = dead_paid+ manager._brain_cache[("openrouter", "free-model")] = dead_free+ manager._brain_cache[("gemini", "gemini-flash")] = working_other_family+ manager._build_fallback_chain = lambda level: [+ ("openrouter", "paid-model"),+ ("openrouter", "free-model"),+ ("gemini", "gemini-flash"),+ ]++ result = await manager.generate("hi", use_history=False)++ assert "Gemini" in result+ assert "openrouter" in manager._dead_providers, (+ "with no untried sibling model left, the provider must still "+ "dead-list so the chain crosses family"+ )++@pytest.mark.asyncioasync def test_dead_providers_reset_on_switch():"""A provider switch (user sets a key, says 'switch to gemini') resetsdiff --git a/tests/integration/test_provider_model_routes.py b/tests/integration/test_provider_model_routes.pyindex b61bfcb7c2..4794662249 100644--- a/tests/integration/test_provider_model_routes.py+++ b/tests/integration/test_provider_model_routes.py@@ -142,6 +142,11 @@ def test_put_model_persists_applies_and_probes(assert ("gemini", "gemini-3.1-pro-preview") in writesbrain: _FakeBrain = server.app.state.brainassert ("gemini", "gemini-3.1-pro-preview") in brain.applied+ # Route-level config drives section health and must not retain the old model.+ assert (+ server.app.state.config.brain.providers["gemini"].model+ == "gemini-3.1-pro-preview"+ )def test_put_model_inactive_provider_not_live(diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.pyindex c70e4d59c0..912b231090 100644--- a/tests/integration/test_provider_routes.py+++ b/tests/integration/test_provider_routes.py@@ -274,6 +274,59 @@ async def test_section_health_switch_cancels_old_provider_without_misattributionassert "NVIDIA" not in old_response.sections["brain"].detail+async def test_section_health_model_switch_cancels_old_probe_for_same_provider(+ server_with_brain: WebServer,+ secret_store: _InMemorySecretStore,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A timeout from an old model must not label a new model on the same card."""+ from jarvis.brain import provider_test as provider_test_module+ from jarvis.core.config import BrainProviderConfig+ from jarvis.ui.web import provider_routes++ secret_store.data["openrouter_api_key"] = "sk-or-test"+ server_with_brain.app.state.brain.active_provider = "openrouter"+ server_with_brain.cfg.brain.providers["openrouter"] = BrainProviderConfig(+ model="slow-model"+ )+ old_started = asyncio.Event()+ old_cancelled = asyncio.Event()++ async def _probe(spec: Any, cfg: Any) -> _FakeTestResult: # noqa: ANN401+ selected_model = cfg.brain.providers["openrouter"].model+ if spec.id == "openrouter" and selected_model == "slow-model":+ old_started.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ old_cancelled.set()+ raise+ return _FakeTestResult("ok", "")++ monkeypatch.setattr(provider_test_module, "run_provider_test", _probe)+ monkeypatch.setattr(+ provider_routes,+ "_jarvis_agent_section_health",+ lambda cfg: provider_routes.SectionHealth(status="ok", subject_id="openai"),+ )+ request = SimpleNamespace(app=server_with_brain.app)++ old_request = asyncio.create_task(provider_routes.section_health(request, refresh=True))+ await asyncio.wait_for(old_started.wait(), timeout=1.0)++ server_with_brain.cfg.brain.providers["openrouter"].model = "working-model"+ new_response = await asyncio.wait_for(+ provider_routes.section_health(request, refresh=True), timeout=1.0+ )+ old_response = await asyncio.wait_for(old_request, timeout=1.0)++ assert old_cancelled.is_set()+ assert new_response.sections["brain"].subject_id == "openrouter"+ assert new_response.sections["brain"].status == "ok"+ assert old_response.sections["brain"].status == "ok"++def test_list_providers_exposes_credential_help_and_billing(server_with_brain: WebServer, secret_store: _InMemorySecretStore) -> None:diff --git a/tests/unit/brain/test_section_health.py b/tests/unit/brain/test_section_health.pyindex 8e3aec091d..959c30bfde 100644--- a/tests/unit/brain/test_section_health.py+++ b/tests/unit/brain/test_section_health.py@@ -96,6 +96,52 @@ async def test_every_catalog_provider_health_is_bound_to_its_exact_id(assert result.subject_id == spec.id+def test_health_fingerprint_covers_every_model_selection_surface() -> None:+ """Every model-bearing API surface supersedes an older health snapshot."""+ from jarvis.ui.web import provider_routes as pr++ openrouter = SimpleNamespace(model="brain-a", cu_model="cu-a")+ realtime = SimpleNamespace(model="realtime-a", voice="voice-a")+ cfg = SimpleNamespace(+ brain=SimpleNamespace(+ providers={"openrouter": openrouter, "openai-realtime": realtime},+ worker=SimpleNamespace(model="worker-a"),+ ),+ tts=SimpleNamespace(model="tts-a", voice_de="de-a", voice_en="en-a"),+ stt=SimpleNamespace(model="stt-a"),+ )+ request = SimpleNamespace(+ app=SimpleNamespace(state=SimpleNamespace(telephony_manager=None))+ )+ subjects = {+ "brain": "openrouter",+ "computer-use": "openrouter",+ "tts": "openrouter-tts",+ "stt": "openrouter-stt",+ "realtime": "openai-realtime",+ "subagents": "openrouter",+ "advanced": None,+ }+ baseline = pr._section_health_fingerprint(request, cfg, subjects)++ mutations = (+ (openrouter, "model"),+ (openrouter, "cu_model"),+ (cfg.tts, "model"),+ (cfg.tts, "voice_de"),+ (cfg.tts, "voice_en"),+ (cfg.stt, "model"),+ (realtime, "model"),+ (realtime, "voice"),+ (cfg.brain.worker, "model"),+ )+ for owner, field in mutations:+ original = getattr(owner, field)+ setattr(owner, field, f"{original}-changed")+ assert pr._section_health_fingerprint(request, cfg, subjects) != baseline+ setattr(owner, field, original)++class TestSubagentSectionHealth:"""Live-honest Sub-Agents tab health (2026-07-06 incident: the tab stayedgreen while every worker spawn 401'd on an expired OAuth token)."""diff --git a/tests/unit/diagnostics/test_doctor.py b/tests/unit/diagnostics/test_doctor_diagnostics.pysimilarity index 100%rename from tests/unit/diagnostics/test_doctor.pyrename to tests/unit/diagnostics/test_doctor_diagnostics.pydiff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.pyindex 37aecd209b..bb712a81d2 100644--- a/tests/unit/realtime/test_gemini_live.py+++ b/tests/unit/realtime/test_gemini_live.py@@ -11,8 +11,13 @@ from jarvis.plugins.realtime.gemini_live import GeminiLiveProvider, _GeminiLiveSfrom jarvis.realtime.protocol import RealtimeSessionConfig-def _fake_message(*, data=None, server_content=None, go_away=None):- return SimpleNamespace(data=data, server_content=server_content, go_away=go_away)+def _fake_message(*, data=None, server_content=None, tool_call=None, go_away=None):+ return SimpleNamespace(+ data=data,+ server_content=server_content,+ tool_call=tool_call,+ go_away=go_away,+ )@pytest.mark.asyncio@@ -149,3 +154,66 @@ async def test_open_session_uses_current_default_model("gemini-3.1-flash-live-preview")await session.close()+++async def test_tools_are_declared_mapped_and_answered(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ holder = _patch_genai_client(monkeypatch)+ declaration = {+ "name": "open_app",+ "description": "Open an application.",+ "parameters": {+ "type": "object",+ "properties": {"app_name": {"type": "string"}},+ },+ }+ provider_session = await GeminiLiveProvider(api_key="test-key").open_session(+ RealtimeSessionConfig(tools=(declaration,))+ )+ _model, config = holder["client"].aio.live.connect_calls[0]+ dumped = config.model_dump(exclude_none=True)+ assert dumped["tools"][0]["function_declarations"][0]["name"] == "open_app"++ class FakeLiveSession:+ def __init__(self):+ self.responses = []++ async def receive(self):+ yield _fake_message(+ tool_call=SimpleNamespace(+ function_calls=[+ SimpleNamespace(+ id="call-1",+ name="open_app",+ args={"app_name": "Calculator"},+ )+ ]+ )+ )++ async def send_tool_response(self, *, function_responses):+ self.responses.extend(function_responses)++ live = FakeLiveSession()+ mapped = _GeminiLiveSession(+ session=live,+ connection_cm=SimpleNamespace(),+ client=SimpleNamespace(),+ session_id="tool-session",+ )+ events = [event async for event in mapped.receive()]++ assert events[0].type == "tool_call"+ assert events[0].call_id == "call-1"+ assert events[0].tool_args == {"app_name": "Calculator"}++ await mapped.send_tool_result(+ "call-1",+ "open_app",+ {"success": True, "output": "opened", "error": None},+ )+ assert live.responses[0].id == "call-1"+ assert live.responses[0].name == "open_app"+ await provider_session.close()diff --git a/tests/unit/realtime/test_openai_realtime.py b/tests/unit/realtime/test_openai_realtime.pyindex 6856b939f2..70303a6770 100644--- a/tests/unit/realtime/test_openai_realtime.py+++ b/tests/unit/realtime/test_openai_realtime.py@@ -15,6 +15,12 @@ from jarvis.realtime.protocol import RealtimeSessionConfigclass _FakeConn:def __init__(self) -> None:self.session_updates: list[dict[str, Any]] = []+ self.created_items: list[dict[str, Any]] = []+ self.response_creates = 0+ self.conversation = SimpleNamespace(+ item=SimpleNamespace(create=self._create_item)+ )+ self.response = SimpleNamespace(create=self._create_response)self._events = iter([SimpleNamespace(type="session.created"),@@ -38,6 +44,12 @@ class _FakeConn:async def update(self, session: dict[str, Any]) -> None:self.session_updates.append(session)+ async def _create_item(self, *, item: dict[str, Any]) -> None:+ self.created_items.append(item)++ async def _create_response(self) -> None:+ self.response_creates += 1+class _FakeConnectCM:def __init__(self, conn: _FakeConn) -> None:@@ -163,3 +175,51 @@ async def test_handshake_error_rejects_session(monkeypatch: pytest.MonkeyPatch)@pytest.mark.asyncioasync def test_keyless_provider_is_unavailable() -> None:assert await OpenAIRealtimeProvider().can_open_duplex_session() is False+++async def test_tools_are_declared_mapped_and_answered(monkeypatch: pytest.MonkeyPatch):+ holder = _patch_openai_client(monkeypatch)+ declaration = {+ "name": "open_app",+ "description": "Open an application.",+ "parameters": {+ "type": "object",+ "properties": {"app_name": {"type": "string"}},+ },+ }+ session = await OpenAIRealtimeProvider(api_key="test-key").open_session(+ RealtimeSessionConfig(tools=(declaration,))+ )+ conn = holder["client"].realtime.last_conn+ payload = conn.session_updates[0]++ assert payload["tools"] == [{"type": "function", **declaration}]+ assert payload["tool_choice"] == "auto"++ conn._events = iter(+ [+ SimpleNamespace(+ type="response.function_call_arguments.done",+ call_id="call-1",+ name="open_app",+ arguments='{"app_name":"Calculator"}',+ )+ ]+ )+ session._events = conn.__aiter__()+ events = [event async for event in session.receive()]++ assert len(events) == 1+ assert events[0].type == "tool_call"+ assert events[0].tool_args == {"app_name": "Calculator"}++ await session.send_tool_result(+ "call-1",+ "open_app",+ {"success": True, "output": "opened", "error": None},+ )+ assert conn.created_items[0]["type"] == "function_call_output"+ assert conn.created_items[0]["call_id"] == "call-1"+ assert conn.response_creates == 1+ await session.close()diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 1a05a76a0e..356923e04d 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -13,6 +13,7 @@ class FakeSession:def __init__(self, events):self._events = eventsself.sent_audio = []+ self.tool_results = []self.truncated = []self.closed = False@@ -33,6 +34,9 @@ class FakeSession:async def interrupt(self):pass+ async def send_tool_result(self, call_id, name, result):+ self.tool_results.append((call_id, name, result))+async def close(self):self.closed = True@@ -71,6 +75,39 @@ class FakeBus:self.events.append(event)+class FakeToolBridge:+ declarations = (+ {+ "name": "open_app",+ "description": "Open an application.",+ "parameters": {+ "type": "object",+ "properties": {"app_name": {"type": "string"}},+ "required": ["app_name"],+ },+ },+ )++ def __init__(self):+ self.languages = []+ self.transcripts = []+ self.calls = []+ self.closed = False++ def set_language(self, language):+ self.languages.append(language)++ async def handle_user_transcript(self, text):+ self.transcripts.append(text)++ async def execute(self, *, wire_name, arguments):+ self.calls.append((wire_name, arguments))+ return "open_app", {"success": True, "output": "opened", "error": None}++ async def close(self):+ self.closed = True++def _cfg(*, providers=None):from types import SimpleNamespace@@ -343,3 +380,82 @@ async def test_browser_session_start_precedes_realtime_turn_events():assert names.index("VoiceSessionStarted") < names.index("RealtimeSessionReady")assert names.index("VoiceSessionStarted") < names.index("VoiceTurnStarted")assert names[-1] == "VoiceSessionEnded"+++async def test_tool_call_waits_for_final_input_transcript_and_uses_bridge():+ bridge = FakeToolBridge()+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="tool_call",+ call_id="call-1",+ tool_name="open_app",+ tool_args={"app_name": "Calculator"},+ ),+ RealtimeEvent(+ type="input_transcript",+ text="Open Calculator",+ is_final=True,+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = RealtimeVoiceSession(+ session_id="tool-session",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ tool_bridge=bridge,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert provider.opened_with.tools == bridge.declarations+ assert bridge.transcripts == ["Open Calculator"]+ assert bridge.calls == [("open_app", {"app_name": "Calculator"})]+ assert provider.session.tool_results == [+ (+ "call-1",+ "open_app",+ {"success": True, "output": "opened", "error": None},+ )+ ]+ assert bridge.closed is True+++async def test_untranscribed_tool_call_is_rejected_without_execution():+ bridge = FakeToolBridge()+ provider = FakeProvider(+ [+ RealtimeEvent(+ type="tool_call",+ call_id="call-2",+ tool_name="open_app",+ tool_args={"app_name": "Calculator"},+ ),+ RealtimeEvent(type="turn_complete"),+ ]+ )+ sess = RealtimeVoiceSession(+ session_id="tool-no-transcript",+ send_binary=lambda _data: asyncio.sleep(0),+ send_json=lambda _message: asyncio.sleep(0),+ provider=provider,+ config=_cfg(),+ bus=None,+ tool_bridge=bridge,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert bridge.calls == []+ assert provider.session.tool_results[0][0:2] == ("call-2", "open_app")+ assert provider.session.tool_results[0][2]["success"] is Falsediff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.pynew file mode 100644index 0000000000..64cc8b3858--- /dev/null+++ b/tests/unit/realtime/test_tools.py@@ -0,0 +1,141 @@+"""Safety and provider-neutrality tests for realtime tool execution."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.realtime.tools import RealtimeToolBridge+from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL+++class FakeTool:+ def __init__(self, name: str = "open_app") -> None:+ self.name = name+ self.description = "Open a local application."+ self.schema = {+ "type": "object",+ "properties": {"app_name": {"type": "string"}},+ "required": ["app_name"],+ }+ self.risk_tier = "ask"++ async def execute(self, *_args, **_kwargs):+ raise AssertionError("Realtime must never execute a tool directly")+++class FakeExecutor:+ def __init__(self, *, confirmation_required: bool = False) -> None:+ self.confirmation_required = confirmation_required+ self.execute_calls = []+ self.confirmed_calls = []+ self.cancelled = []+ self.denied = []++ async def execute(self, tool, arguments, **kwargs):+ self.execute_calls.append((tool, arguments, kwargs))+ if self.confirmation_required:+ return SimpleNamespace(+ success=False,+ output={"tool_name": tool.name},+ error=VOICE_CONFIRM_SENTINEL,+ )+ return SimpleNamespace(success=True, output="opened", error=None)++ async def execute_confirmed(self, trace_id, **kwargs):+ self.confirmed_calls.append((trace_id, kwargs))+ return SimpleNamespace(success=True, output="confirmed", error=None)++ async def cancel_pending(self, trace_id):+ self.cancelled.append(trace_id)+ return True++ async def publish_guard_denied(self, name, reason, *, trace_id):+ self.denied.append((name, reason, trace_id))+++def _bridge(*, name: str = "open_app", confirmation_required: bool = False):+ tool = FakeTool(name)+ executor = FakeExecutor(confirmation_required=confirmation_required)+ bridge = RealtimeToolBridge(+ tools={name: tool}, executor=executor, language="en"+ )+ return bridge, tool, executor+++def test_declaration_uses_a_cross_provider_safe_wire_name():+ bridge, _tool, _executor = _bridge(name="call-contact")++ declaration = bridge.declarations[0]++ assert declaration["name"].replace("_", "").isalnum()+ assert len(declaration["name"]) <= 64+ assert declaration["parameters"]["required"] == ["app_name"]+++async def test_available_tool_runs_only_through_tool_executor():+ bridge, tool, executor = _bridge()+ await bridge.handle_user_transcript("Open Calculator")++ name, result = await bridge.execute(+ wire_name="open_app", arguments={"app_name": "Calculator"}+ )++ assert name == "open_app"+ assert result == {"success": True, "output": "opened", "error": None}+ assert executor.execute_calls[0][0] is tool+ assert executor.execute_calls[0][1] == {"app_name": "Calculator"}+ assert executor.execute_calls[0][2]["config_snapshot"]["voice_confirm"] is True+++async def test_missing_required_argument_is_denied_before_executor():+ bridge, _tool, executor = _bridge()+ await bridge.handle_user_transcript("Open it")++ _name, result = await bridge.execute(wire_name="open_app", arguments={})++ assert result["success"] is False+ assert "Missing required" in result["error"]+ assert executor.execute_calls == []+ assert executor.denied+++async def test_clear_yes_resumes_the_original_pending_action_once():+ bridge, _tool, executor = _bridge(confirmation_required=True)+ await bridge.handle_user_transcript("Open Calculator")++ _name, first = await bridge.execute(+ wire_name="open_app", arguments={"app_name": "Calculator"}+ )+ await bridge.handle_user_transcript("Yes")+ _name, second = await bridge.execute(+ wire_name="open_app", arguments={"app_name": "Something else"}+ )++ assert first["confirmation_required"] is True+ assert second == {"success": True, "output": "confirmed", "error": None}+ assert len(executor.execute_calls) == 1+ assert len(executor.confirmed_calls) == 1+++async def test_clear_no_cancels_and_blocks_same_turn_retry():+ bridge, _tool, executor = _bridge(confirmation_required=True)+ await bridge.handle_user_transcript("Open Calculator")+ await bridge.execute(+ wire_name="open_app", arguments={"app_name": "Calculator"}+ )++ await bridge.handle_user_transcript("No")+ _name, result = await bridge.execute(+ wire_name="open_app", arguments={"app_name": "Calculator"}+ )++ assert len(executor.cancelled) == 1+ assert result["success"] is False+ assert "declined" in result["error"]+ assert len(executor.execute_calls) == 1diff --git a/tests/unit/skills/test_authoring_service.py b/tests/unit/skills/test_authoring_service.pyindex 269d5c9a25..5ea303ffe0 100644--- a/tests/unit/skills/test_authoring_service.py+++ b/tests/unit/skills/test_authoring_service.py@@ -91,6 +91,23 @@ async def test_create_skill_is_on_by_default()+async def test_create_omits_state_field_from_frontmatter(+ registry: SkillRegistry, skills_root: Path+) -> None:+ """Regression guard for AP-15's manual-path carve-out: the "New skill"+ form must NOT stamp a ``state`` key at all (as opposed to the AI+ creator's ``commit()``, which always writes ``state: draft``) — its+ absence is what makes the loader default to VALIDATED ("on")."""+ svc = _service(registry, skills_root)+ await svc.create(+ SkillCreateRequest(name="No State Field", body="## No State Field\n\nDo it.\n")+ )+ skill_md = skills_root / "no-state-field" / "SKILL.md"+ fm = yaml.safe_load(skill_md.read_text(encoding="utf-8").split("---", 2)[1])+ assert "state" not in fm++@pytest.mark.asyncioasync def test_create_persists_voice_trigger(registry: SkillRegistry, skills_root: Pathdiff --git a/tests/unit/skills/test_creator_service.py b/tests/unit/skills/test_creator_service.pyindex 58eb73d93f..625c261cb9 100644--- a/tests/unit/skills/test_creator_service.py+++ b/tests/unit/skills/test_creator_service.py@@ -29,6 +29,7 @@ from jarvis.skills.creator_service import (validate_skill_md,)from jarvis.skills.registry import SkillRegistry+from jarvis.skills.schema import SkillLifecycleState# ----------------------------------------------------------------------@@ -147,6 +148,21 @@ def test_render_draft_produces_parseable_skill_md() -> None:assert validation["ok"] is True+def test_render_draft_stamps_state_draft_in_frontmatter() -> None:+ """AP-15: the AI creator's rendered preview must carry ``state: draft`` so+ the loader never resolves LLM-generated content to VALIDATED/"on"."""+ draft = {+ "name": "Rendered Skill",+ "description": "desc",+ "category": "general",+ "body": "## Rendered Skill\n\nHello.\n",+ }+ skill_md = render_skill_md(draft)+ _, frontmatter = validate_skill_md(skill_md)+ assert frontmatter is not None+ assert frontmatter["state"] == "draft"++# ----------------------------------------------------------------------# draft() — deterministic fallback + brain path# ----------------------------------------------------------------------@@ -231,3 +247,11 @@ async def test_commit_persists_draft_to_registry(registry, skills_root) -> None:assert fetched.frontmatter is not Noneassert "run-shell" in fetched.frontmatter.requires_toolsassert (skills_root / "committed-skill" / "SKILL.md").exists()++ # AP-15: an AI-generated skill must land as DRAFT, never auto-active —+ # both on the returned Skill object and in the persisted file the loader+ # will re-parse on the next reload.+ assert created.state == SkillLifecycleState.DRAFT+ assert fetched.state == SkillLifecycleState.DRAFT+ on_disk = (skills_root / "committed-skill" / "SKILL.md").read_text(encoding="utf-8")+ assert "state: draft" in on_diskdiff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.pyindex 3a40666bb5..a0789a58c2 100644--- a/tests/unit/web/test_voice_mode_route.py+++ b/tests/unit/web/test_voice_mode_route.py@@ -51,7 +51,12 @@ def _app(mode="pipeline", key="sk-x", monkeypatch=None):def test_get_voice_mode(monkeypatch):import jarvis.realtime.factory as rf- monkeypatch.setattr(rf, "get_provider_secret", lambda _p: "sk-x")++ def openai_only(candidates):+ keys = {c[0] for c in candidates}+ return "sk-x" if "openai_api_key" in keys else None++ monkeypatch.setattr(rf, "get_secret_any", openai_only)client = TestClient(_app(mode="realtime"))r = client.get("/api/settings/voice-mode")assert r.status_code == 200@@ -66,10 +71,11 @@ def test_get_voice_mode_cross_family_gemini_only(monkeypatch):only a Gemini key gets realtime_available=true, active_provider=gemini-live."""import jarvis.realtime.factory as rf- def only_gemini(name: str) -> str | None:- return "sk-x" if name == "gemini" else None+ def only_gemini(candidates: tuple[tuple[str, str | None], ...]) -> str | None:+ keys = {c[0] for c in candidates}+ return "sk-x" if "gemini_api_key" in keys else None- monkeypatch.setattr(rf, "get_provider_secret", only_gemini)+ monkeypatch.setattr(rf, "get_secret_any", only_gemini)client = TestClient(_app(mode="pipeline"))r = client.get("/api/settings/voice-mode")assert r.status_code == 200@@ -80,7 +86,7 @@ def test_get_voice_mode_cross_family_gemini_only(monkeypatch):def test_get_voice_mode_no_realtime_key_anywhere(monkeypatch):import jarvis.realtime.factory as rf- monkeypatch.setattr(rf, "get_provider_secret", lambda _name: None)+ monkeypatch.setattr(rf, "get_secret_any", lambda _candidates: None)client = TestClient(_app(mode="pipeline"))r = client.get("/api/settings/voice-mode")body = r.json()@@ -98,7 +104,7 @@ def test_put_voice_mode_realtime_without_key_is_400(monkeypatch):"""A3: PUT-guard rejects selecting realtime when no family has a key —prevents pinning the boot default to an unreachable engine."""import jarvis.realtime.factory as rf- monkeypatch.setattr(rf, "get_provider_secret", lambda _name: None)+ monkeypatch.setattr(rf, "get_secret_any", lambda _candidates: None)client = TestClient(_app())r = client.put("/api/settings/voice-mode", json={"mode": "realtime", "persist": False})assert r.status_code == 400@@ -107,7 +113,7 @@ def test_put_voice_mode_realtime_without_key_is_400(monkeypatch):def test_put_voice_mode_updates_live_and_persists(monkeypatch):import jarvis.realtime.factory as rfpersisted = {"called": False}- monkeypatch.setattr(rf, "get_provider_secret", lambda _p: "sk-x")+ monkeypatch.setattr(rf, "get_secret_any", lambda _candidates: "sk-x")def fake_set(mode, **kw):persisted["called"] = True