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:25)
Ruben Lütke33fa24d0629e
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.mdindex d970f0ee5e..6bba235c6f 100644--- a/docs/architecture-overview.md+++ b/docs/architecture-overview.md@@ -74,7 +74,7 @@ Still unrowed (verify with `ls jarvis/ui/web/*routes*.py` + `git log`): `chats`/L7 UI/UX Tray, Toasts, Admin-API, Desktop-App (FastAPI+React+pywebview), Orb-OverlayL6 Orchestrator State-Machine, Router, BrainManager, Supervisor, Mission-ManagerL5 Harness-Adapter Agent-harness, Codex, Open Interpreter, Python-Script, MCP-Remote-L4 Brain 5 providers (Claude-API, OpenRouter, OpenAI, Gemini, Grok) + Ack-Brain sub-second tier+L4 Brain 5 providers (Claude-API, OpenRouter, OpenAI, Gemini, NVIDIA) + Ack-Brain sub-second tierL3 Intent/Risk Classifier, Risk-Tier-Policy, Approval, Rate-Limit-TrackerL2 Speech Wake → VAD (Silero) → STT (faster-whisper / Google) → TTS (Gemini Flash / SAPI5)L1 Audio I/O WASAPI via sounddevice, Device-Routing, Chime-Feedback@@ -109,7 +109,7 @@ Multi-provider is mandatory — **never hardcode** Anthropic/Claude. Config unde#### Provider-agnostic features (no provider/model hardcoding) — BINDING-Every feature must work with **whatever brain provider the user has selected/activated**, and across all configured providers — there are five API providers (`claude-api`, `openrouter`, `openai`, `gemini`, `grok`) plus two subscription-CLI brains (`codex` over ChatGPT, `antigravity` over the Google login), and any of them may be the active one. **Never branch on a provider name or a model id to enable or disable behavior** — no `if provider == "grok"`, no hardcoded `grok-4.3`, no provider-specific code path. Gate on a **capability** instead: `supports_vision`, `supports_tools`, the runtime `can_call_tools()` (and codex's runtime `supports_vision`). If the capability you need doesn't exist yet, **add a capability flag — do not name-check the provider**.+Every feature must work with **whatever brain provider the user has selected/activated**, and across all configured providers — there are five API providers (`claude-api`, `openrouter`, `openai`, `gemini`, `nvidia`) plus two subscription-CLI brains (`codex` over ChatGPT, `antigravity` over the Google login), and any of them may be the active one. **Never branch on a provider name or a model id to enable or disable behavior** — no `if provider == "grok"`, no hardcoded `grok-4.3`, no provider-specific code path. Gate on a **capability** instead: `supports_vision`, `supports_tools`, the runtime `can_call_tools()` (and codex's runtime `supports_vision`). If the capability you need doesn't exist yet, **add a capability flag — do not name-check the provider**.When the active/selected provider lacks a needed capability — e.g. a text-only CLI brain (`antigravity` / `codex-CLI`) cannot see images for Computer-Use — fall through to the first **available** provider that *has* the capability, provider-agnostically and never pinned to a favorite; if none is available, degrade gracefully with an honest message. A provider or model literal may appear **only** as a documented default/fallback (a plugin's own `DEFAULT_MODEL`) or behind a runtime capability probe — never as the gate that decides whether a feature runs. The Computer-Use "no vision" incident was a *capability-flag* bug (grok's `supports_vision` was wrongly `False`) — the correct fix was to set the flag, **not** to pin Computer-Use to grok. This generalizes AP-6 (don't hardcode Claude) to **don't hardcode *any* provider** (see AP-21).diff --git a/jarvis/marketplace/token_store.py b/jarvis/marketplace/token_store.pyindex 4907070f98..3a3c56246b 100644--- a/jarvis/marketplace/token_store.py+++ b/jarvis/marketplace/token_store.py@@ -103,7 +103,8 @@ class KeyringBackend:def delete(self, key: str) -> None:from jarvis.core.config import delete_secret- delete_secret(key)+ if not delete_secret(key):+ raise RuntimeError(f"keyring delete failed for {key!r}")_CHUNK_SENTINEL = "\x00JCHUNKS\x00" # primary-key header for a chunked value: sentinel + <count>@@ -160,25 +161,55 @@ class ChunkedBackend:return "".join(parts)def set(self, key: str, value: str) -> None:- # Drop any chunks from a previous larger value first so we never leave- # orphaned overflow entries behind.- self._clear_overflow(key)+ """Write ``value``, chunking it when it exceeds the backend's per-entry cap.++ Write-then-swap: the new data (and, for a multi-chunk value, the new+ header) is written FIRST; only once that has fully succeeded do we drop+ chunks a previous, larger value left behind. The old header keeps+ pointing at the old data until the very last step, so a failure+ partway through the new write can roll back cleanly instead of+ leaving a header that points at deleted/missing chunks (the previous+ delete-then-write order did exactly that — a mid-write failure lost+ the last good token).+ """if len(value) <= self._chunk_size:+ # Fits in one entry: no chunks of its own. Write it first, then+ # drop any old overflow pieces a previous larger value left.self._backend.set(key, value)+ self._clear_overflow(key)return+chunks = [value[i : i + self._chunk_size]for i in range(0, len(value), self._chunk_size)]- # Write the pieces first; only stamp the header once they all succeed,- # so a mid-write failure can't leave a header pointing at missing data.+ # Snapshot whatever currently sits at each index we're about to+ # overwrite (old chunk data, or None) so a partial failure can put it+ # back exactly as it was rather than leaving a gap under the still-+ # active OLD header.+ prior = [self._backend.get(self._overflow_key(key, i)) for i in range(len(chunks))]++ written = 0try:for i, piece in enumerate(chunks):self._backend.set(self._overflow_key(key, i), piece)+ written = i + 1+ self._backend.set(key, f"{_CHUNK_SENTINEL}{len(chunks)}")except Exception:- self._clear_overflow(key)+ for i in range(written):+ old_piece = prior[i]+ if old_piece is None:+ self._backend.delete(self._overflow_key(key, i))+ else:+ self._backend.set(self._overflow_key(key, i), old_piece)raise- self._backend.set(key, f"{_CHUNK_SENTINEL}{len(chunks)}")++ # The new header is live now — safe to drop old chunks the new value+ # no longer needs (old_count > new_count leftovers).+ i = len(chunks)+ while self._backend.get(self._overflow_key(key, i)) is not None:+ self._backend.delete(self._overflow_key(key, i))+ i += 1def delete(self, key: str) -> None:self._clear_overflow(key)diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.pyindex bd209ef910..5e25a491b5 100644--- a/jarvis/missions/critic/runner.py+++ b/jarvis/missions/critic/runner.py@@ -1762,7 +1762,7 @@ def _resolve_critic_provider_model() -> tuple[str | None, str | None]:# API-key brain providers that can grade IN-PROCESS via their own BrainProvider# (no external CLI). Order = the cross-family fallback preference.-_API_CRITIC_PROVIDERS: tuple[str, ...] = ("openrouter", "openai", "gemini", "claude-api")+_API_CRITIC_PROVIDERS: tuple[str, ...] = ("openrouter", "openai", "gemini", "claude-api", "nvidia")def _provider_picked_model(provider: str) -> str | None:diff --git a/jarvis/skills/runner.py b/jarvis/skills/runner.pyindex db0b372ced..2253473d43 100644--- a/jarvis/skills/runner.py+++ b/jarvis/skills/runner.py@@ -66,7 +66,8 @@ except Exception: # pragma: no coverselect_autoescape = None # type: ignore_HAVE_JINJA = False-from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.core.protocols import ExecutionContext, RiskTier, ToolResult+from jarvis.safety.risk_tier import ActionBlocked, RiskTierEvaluatorfrom .schema import (Skill,@@ -82,6 +83,23 @@ log = logging.getLogger(__name__)_TOOL_LINE_RE = re.compile(r"^\s*TOOL:\s*(?P<name>\S+)\s*(?P<args>\{.*\})?\s*$")+@dataclass(frozen=True)+class _SkillDeclaredTool:+ """Minimal duck-typed stand-in for :class:`jarvis.core.protocols.Tool`.++ ``RiskTierEvaluator.evaluate()`` only needs ``.name`` (for blacklist/+ whitelist matching + the command string) and ``.risk_tier`` (the+ "tool default" fallback). The runner has not resolved the real ``Tool``+ object at the point it needs to gate the call, and — more importantly —+ the skill AUTHOR's own frontmatter ``risk_policy`` (per-tool override or+ default tier) is the tool-default that should apply here, not whatever+ static tier the underlying tool implementation declares for itself.+ """++ name: str+ risk_tier: RiskTier++class SkillRunner:"""Runtime executor for skills."""@@ -96,6 +114,10 @@ class SkillRunner:self.tool_registry = tool_registryself.bus = busself.safety_enforcer = safety_enforcer+ # Lazily built, cached RiskTierEvaluator backing the internal risk+ # gate used when no ``safety_enforcer`` was injected (AP-3). See+ # ``_risk_evaluator()``.+ self._risk_evaluator_cache: RiskTierEvaluator | None = Noneif _HAVE_JINJA:self._env = SandboxedEnvironment( # type: ignore[call-arg]autoescape=select_autoescape(default=False),@@ -186,23 +208,69 @@ class SkillRunner:except Exception: # noqa: BLE001return None- def _check_risk(self, skill: Skill, tool_name: str) -> tuple[bool, str]:- """Returns (allowed, reason). If safety_enforcer is missing, always allow."""- if self.safety_enforcer is None or skill.frontmatter is None:+ def _risk_evaluator(self) -> RiskTierEvaluator:+ """Lazily builds + caches a ``RiskTierEvaluator`` off the live safety+ config, for the internal fail-closed gate used when no external+ ``safety_enforcer`` was injected (AP-3)."""+ if self._risk_evaluator_cache is None:+ from jarvis.core.config import load_config++ self._risk_evaluator_cache = RiskTierEvaluator(load_config().safety)+ return self._risk_evaluator_cache++ def _check_risk(+ self, skill: Skill, tool_name: str, tool_args: dict[str, Any]+ ) -> tuple[bool, str]:+ """Returns (allowed, reason) for a skill-triggered tool call.++ AP-3: a skill's ``TOOL:`` line must respect the SAME risk-tier gate as+ every other tool invocation — it must never bypass it. If a+ ``safety_enforcer`` was injected (its ``.check(tool_name=, tier=)``),+ defer to it unchanged (back-compat hook). Otherwise this runs the+ production ``RiskTierEvaluator`` (blacklist > whitelist > tool+ default) against the skill's OWN frontmatter-declared tier as the+ "tool default" — the skill author's ``risk_policy`` is what governs+ here, not the executing tool's own static declaration. Fail-closed:+ ``block`` refuses; ``ask`` also refuses (skills/cron triggers have no+ interactive human to ask); only ``safe``/``monitor`` (including a+ whitelist downgrade) execute.+ """+ if skill.frontmatter is None:return True, "no-enforcer"- tier = skill.frontmatter.risk_policy.per_tool_overrides.get(+ declared_tier = skill.frontmatter.risk_policy.per_tool_overrides.get(tool_name, skill.frontmatter.risk_policy.default_tier)- fn = getattr(self.safety_enforcer, "check", None)- if callable(fn):- try:- result = fn(tool_name=tool_name, tier=tier)- if isinstance(result, tuple):- return bool(result[0]), str(result[1])- return bool(result), "enforcer"- except Exception as exc: # noqa: BLE001- return False, f"enforcer error: {exc}"- return True, "no-check-method"++ if self.safety_enforcer is not None:+ fn = getattr(self.safety_enforcer, "check", None)+ if callable(fn):+ try:+ result = fn(tool_name=tool_name, tier=declared_tier)+ if isinstance(result, tuple):+ return bool(result[0]), str(result[1])+ return bool(result), "enforcer"+ except Exception as exc: # noqa: BLE001+ return False, f"enforcer error: {exc}"+ return True, "no-check-method"++ # No injected enforcer — internal risk gate. A broken evaluator must+ # fail CLOSED (refuse), never silently allow.+ try:+ decision = self._risk_evaluator().evaluate(+ _SkillDeclaredTool(name=tool_name, risk_tier=declared_tier), tool_args+ )+ except ActionBlocked as exc:+ return False, f"blocked: {exc.pattern}"+ except Exception as exc: # noqa: BLE001+ log.warning(+ "skill-runner: risk evaluation failed for %s — refusing: %s",+ tool_name, exc,+ )+ return False, f"risk evaluation failed: {exc}"++ if decision.tier == "ask" and decision.approved_by != "whitelist":+ return False, "risk_tier=ask (no interactive approver for skills)"+ return True, f"risk_tier={decision.tier}"async def _publish(self, event: Any) -> None:if self.bus is None:@@ -255,7 +323,7 @@ class SkillRunner:unresolved_tools: list[str] = []for idx, (tool_name, tool_args) in enumerate(calls):- allowed, reason = self._check_risk(skill, tool_name)+ allowed, reason = self._check_risk(skill, tool_name, tool_args)if not allowed:step = {"tool": tool_name,@@ -321,7 +389,7 @@ class SkillRunner:user_utterance=str(args.get("utterance", "")),config=dict(skill.frontmatter.config),memory_read=None,- approved_by="skill-runner",+ approved_by="skill-runner:risk-gate",)step_start = time.monotonic()try:diff --git a/jarvis/ui/web/frontend/src/components/CuModelSelector.tsx b/jarvis/ui/web/frontend/src/components/CuModelSelector.tsxindex bf8fab2d86..4047298377 100644--- a/jarvis/ui/web/frontend/src/components/CuModelSelector.tsx+++ b/jarvis/ui/web/frontend/src/components/CuModelSelector.tsx@@ -16,9 +16,11 @@ import { useT } from "@/i18n";export function CuModelSelector({providerId,recommendedModel,+ healthActive = false,}: {providerId: string;recommendedModel?: string | null;+ healthActive?: boolean;}) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -47,12 +49,33 @@ export function CuModelSelector({async function clearToMain() {setClearing(true);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", {+ detail: { section: "computer-use", provider: providerId },+ }),+ );+ }try {await saveCuModel(providerId, "");setCuModel("");setUsesMain(true);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-config-changed", {+ detail: { section: "computer-use", provider: providerId },+ }),+ );+ }pushToast("success", t("apikeys_cu_model.cleared"));} catch (e) {+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", {+ detail: { section: "computer-use", provider: providerId },+ }),+ );+ }pushToast("error", (e as Error).message);} finally {setClearing(false);@@ -67,6 +90,8 @@ export function CuModelSelector({controlledvisionOnlyrecommendedModel={recommendedModel}+ healthSection="computer-use"+ healthActive={healthActive}headingLabel={t("apikeys_cu_model.heading")}placeholder={t("apikeys_cu_model.use_main")}onSave={async (model) => {diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex 2cd0502e97..7cc03cd021 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -330,6 +330,8 @@ function SubagentModelCard({<BrainModelSelectorproviderId={catalogProvider}currentModel={status.sub_model_override ?? ""}+ healthSection="subagents"+ healthActiveonSave={async (model) => {const r = await saveSubagentModel(model);window.dispatchEvent(new Event("jarvis:agent-switched"));@@ -1128,6 +1130,11 @@ function useSubagentActivate(return;}setActivating(true);+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", {+ detail: { section: "subagents", provider: row.jarvis },+ }),+ );try {const result = await switchSubagentProvider(row.jarvis);const note = result.restart_required ? " (active from next restart)" : "";@@ -1135,6 +1142,11 @@ function useSubagentActivate(window.dispatchEvent(new CustomEvent("jarvis:agent-switched"));await onSwitched();} catch (e) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", {+ detail: { section: "subagents", provider: row.jarvis },+ }),+ );pushToast("error", (e as Error).message);} finally {setActivating(false);diff --git a/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsx b/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsxindex 1592fd02dd..5acfe99ef7 100644--- a/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsx+++ b/jarvis/ui/web/frontend/src/components/OpenRouterTtsVoicePicker.tsx@@ -26,9 +26,11 @@ import { useT, useUiLanguage } from "@/i18n";export function OpenRouterTtsControls({providerId,recommendedModel,+ healthActive = false,}: {providerId: string;recommendedModel?: string | null;+ healthActive?: boolean;}) {// The currently selected TTS model — seeded from the catalog's current// selection and updated when the model picker below saves a new one, so the@@ -62,8 +64,16 @@ export function OpenRouterTtsControls({providerId={providerId}recommendedModel={recommendedModel}onSave={handleModelSave}+ healthSection="tts"+ healthActive={healthActive}/>- {model && <VoicePicker model={model} />}+ {model && (+ <VoicePicker+ model={model}+ providerId={providerId}+ healthActive={healthActive}+ />+ )}</div>);}@@ -105,7 +115,15 @@ function LanguageChip({ code }: { code: string }) {* model's voices (each with a language chip), persists a pick, and plays a short* spoken sample on demand — the sample language is switchable DE/EN.*/-function VoicePicker({ model }: { model: string }) {+function VoicePicker({+ model,+ providerId,+ healthActive,+}: {+ model: string;+ providerId: string;+ healthActive: boolean;+}) {const t = useT();const uiLang = useUiLanguage();const pushToast = useEventStore((s) => s.pushToast);@@ -216,9 +234,23 @@ function VoicePicker({ model }: { model: string }) {async function save(voiceId: string) {setSaving(true);setOpen(false);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", {+ detail: { section: "tts", provider: providerId },+ }),+ );+ }try {const res = await saveTtsVoice(voiceId);setPinned(voiceId);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-config-changed", {+ detail: { section: "tts", provider: providerId },+ }),+ );+ }const note = res.restart_required? ` ${t("apikeys_model.restart_note")}`: res.applied_live@@ -226,6 +258,13 @@ function VoicePicker({ model }: { model: string }) {: "";pushToast("success", `${t("apikeys_voice.saved")}${note}`);} catch (e) {+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", {+ detail: { section: "tts", provider: providerId },+ }),+ );+ }pushToast("error", (e as Error).message);} finally {setSaving(false);diff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsxindex 2e7385a17b..1deb425306 100644--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.tsx@@ -25,7 +25,13 @@ const PROVIDER_DEFAULT = "";* Renders only inside a realtime provider card (`tier === "realtime"`), gated* on the card already having a stored credential — see `ApiKeysView.tsx`.*/-export function RealtimeOptionsControl({ providerId }: { providerId: string }) {+export function RealtimeOptionsControl({+ providerId,+ healthActive = false,+}: {+ providerId: string;+ healthActive?: boolean;+}) {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -67,15 +73,36 @@ export function RealtimeOptionsControl({ providerId }: { providerId: string }) {if (field === "model") setModel(next);else setVoice(next);setSavingField(field);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-selection-pending", {+ detail: { section: "realtime", provider: providerId },+ }),+ );+ }try {await saveRealtimeOptions(providerId,field === "model" ? { model: next } : { voice: next },);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-config-changed", {+ detail: { section: "realtime", provider: providerId },+ }),+ );+ }} catch (e) {// Roll back the optimistic pick on failure.if (field === "model") setModel(prev);else setVoice(prev);+ if (healthActive) {+ window.dispatchEvent(+ new CustomEvent("jarvis:provider-switch-failed", {+ detail: { section: "realtime", provider: providerId },+ }),+ );+ }pushToast("error", (e as Error).message);} finally {setSavingField(null);diff --git a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.tsindex 7380a135d4..e255bf445a 100644--- a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts+++ b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts@@ -8,8 +8,16 @@* Reconnect happens automatically via react-use-websocket (exponential* backoff up to 30s, infinite retries). The UI shows "offline" via* store.connected.+ *+ * Auth tokens (`missions_auth.py`) live in server memory only and are+ * wiped on restart, so a `window.__JARVIS_TOKEN` captured before a restart+ * closes the socket with 4401. `getUrl` is passed as a function (not a+ * plain string) so react-use-websocket re-resolves it on every reconnect+ * attempt, including scheduled ones — a 4401 close flags the next+ * resolution to fetch a fresh token first (mirrors the fallback in+ * WorkspaceTerminal.tsx's `getToken()`).*/-import { useEffect, useMemo } from "react";+import { useCallback, useEffect, useRef } from "react";import useWebSocket, { ReadyState } from "react-use-websocket";import type { EventEnvelope } from "@/types/missions";import { useMissionsStore } from "./store";@@ -36,20 +44,43 @@ function isEventEnvelope(msg: WsMessage): msg is EventEnvelope {);}+/** Give up reconnecting after this many consecutive 4401s in a row — a+ * dead token that keeps failing means something is wrong server-side, not+ * a one-off race with a restart. */+const MAX_CONSECUTIVE_AUTH_FAILURES = 3;++async function fetchFreshToken(): Promise<string> {+ try {+ const res = await fetch("/api/missions/auth/token");+ const body = (await res.json()) as { token?: string };+ const token = body.token ?? "";+ window.__JARVIS_TOKEN = token;+ return token;+ } catch {+ return window.__JARVIS_TOKEN ?? "";+ }+}+export function useMissionWebSocket(): { readyState: ReadyState } {const setConnected = useMissionsStore((s) => s.setConnected);const applyEvent = useMissionsStore((s) => s.applyEvent);+ const needsFreshToken = useRef(false);+ const consecutiveAuthFailures = useRef(0);- const wsUrl = useMemo(() => {+ const getUrl = useCallback(async () => {+ const token = needsFreshToken.current+ ? await fetchFreshToken()+ : (window.__JARVIS_TOKEN ?? "");+ needsFreshToken.current = false;const proto = window.location.protocol === "https:" ? "wss" : "ws";const host = window.location.host;- const token = window.__JARVIS_TOKEN;const query = token ? `?token=${encodeURIComponent(token)}` : "";return `${proto}://${host}/api/missions/ws${query}`;}, []);- const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket(wsUrl, {+ const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket(getUrl, {onOpen: () => {+ consecutiveAuthFailures.current = 0;const lastSeq = useMissionsStore.getState().lastSeq;sendJsonMessage({type: "hello",@@ -57,7 +88,22 @@ export function useMissionWebSocket(): { readyState: ReadyState } {token: window.__JARVIS_TOKEN ?? "",});},- shouldReconnect: () => true,+ onClose: (event) => {+ if (event.code === 4401) {+ needsFreshToken.current = true;+ }+ },+ shouldReconnect: (event) => {+ if (event.code !== 4401) {+ consecutiveAuthFailures.current = 0;+ return true;+ }+ consecutiveAuthFailures.current += 1;+ // Beyond the cap, stop retrying: readyState settles on CLOSED and+ // store.connected stays false, which is the existing "offline"+ // signal the UI already surfaces — no new API needed.+ return consecutiveAuthFailures.current <= MAX_CONSECUTIVE_AUTH_FAILURES;+ },reconnectAttempts: Number.POSITIVE_INFINITY,reconnectInterval: (attempt: number) =>Math.min(1000 * 2 ** attempt, 30000),diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 76b62bbc28..8fff48f49b 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1149,11 +1149,14 @@ function ProviderCard({<OpenRouterTtsControlsproviderId={descriptor.id}recommendedModel={descriptor.recommended_model}+ healthActive={descriptor.active}/>) : (<BrainModelSelectorproviderId={descriptor.id}recommendedModel={descriptor.recommended_model}+ healthSection={descriptor.tier}+ healthActive={descriptor.active}/>))}@@ -1179,6 +1182,11 @@ function ProviderCard({<CuModelSelectorproviderId={descriptor.id}recommendedModel={descriptor.recommended_model}+ healthActive={+ descriptor.tier === "computer-use"+ ? descriptor.active+ : Boolean(descriptor.computer_use_active)+ }/>)}@@ -1187,7 +1195,10 @@ function ProviderCard({already having a stored credential like the other tiers' pickersabove. */}{descriptor.tier === "realtime" && descriptor.configured && (- <RealtimeOptionsControl providerId={descriptor.id} />+ <RealtimeOptionsControl+ providerId={descriptor.id}+ healthActive={descriptor.active}+ />)}{/* Footer: the live connectivity test, visually separated from thediff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 1e43b42037..7ffb01930f 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -435,21 +435,24 @@ def _active_stt(request: Request) -> str | None:def _active_realtime(request: Request) -> str | None:- """The active realtime-voice provider.+ """Return the configured or first credential-ready realtime provider.- Realtime is OpenAI-only today (a single spec in ``PROVIDERS``), so an unset- ``cfg.brain.realtime.provider`` still defaults to ``"openai-realtime"`` — the- sole card shows as active instead of a confusing "nothing selected" state.- Never raises: any resolver error falls back to the default id.+ Resolution delegates to the plugin registry when no explicit selection+ exists, so a fresh install with only one arbitrary supported key activates+ that family without a provider-name default (AP-21/AP-22)."""try:cfg = _resolve_cfg(request)realtime_cfg = getattr(getattr(cfg, "brain", None), "realtime", None)provider = (getattr(realtime_cfg, "provider", None) or "").strip()- return provider or "openai-realtime"- except Exception as exc: # noqa: BLE001 — the health panel must never 500- log.debug("active-realtime resolution failed (%s); using default.", exc)- return "openai-realtime"+ if provider:+ return provider+ from jarvis.realtime.factory import realtime_available_provider++ return realtime_available_provider(cfg)+ except Exception as exc: # noqa: BLE001 -- the health panel must never 500+ log.debug("active-realtime resolution failed (%s); using None.", exc)+ return Nonedef _active_computer_use(request: Request) -> str | None:@@ -2369,13 +2372,12 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:@router.post("/realtime/switch")async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:- """Switches the active realtime-voice provider. Persists to jarvis.toml.+ """Switch the active realtime provider for the next voice session.- Mirrors ``stt_switch``: no live audio switch — the realtime engine is- only selected once the browser realtime client is actually wired in- (Phase 2), so the choice always needs a restart to take effect. Realtime- is cross-family (OpenAI Realtime, Gemini Live, AP-22), so this only- rejects a non-realtime-tier provider id.+ The desktop and browser runtimes resolve ``voice.mode`` plus the selected+ provider when each new voice session opens. An already-open duplex stream+ keeps its negotiated provider, but no application restart is required.+ Realtime is cross-family (AP-22), so validation is registry/tier based.Activating a realtime provider also makes Realtime the ACTIVE voice mode(``[voice].mode``) — the "Active" badge reads ``[voice].mode``, not@@ -2385,17 +2387,23 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:spec = get_spec(body.provider)if spec is None:raise HTTPException(- status_code=404, detail=f"Unbekannter Provider: {body.provider}"+ status_code=404, detail=f"Unknown provider: {body.provider}")if spec.tier != "realtime":raise HTTPException(status_code=400,- detail=f"Provider '{body.provider}' ist kein Realtime-Provider (tier={spec.tier})",+ detail=(+ f"Provider '{body.provider}' is not a realtime provider "+ f"(tier={spec.tier})"+ ),)if not _is_credential_present(spec):raise HTTPException(status_code=409,- detail=f"Provider '{body.provider}' hat keine Credentials — erst API-Key setzen.",+ detail=(+ f"Provider '{body.provider}' has no configured credentials. "+ "Add its API key first."+ ),)if body.persist:@@ -2407,7 +2415,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:raise HTTPException(status_code=500, detail=str(exc)) from excexcept Exception as exc: # noqa: BLE001raise HTTPException(- status_code=500, detail=f"TOML-Write fehlgeschlagen: {exc}"+ status_code=500, detail=f"TOML write failed: {exc}") from exctry:from jarvis.core.config_writer import set_voice_mode@@ -2442,7 +2450,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:"ok": True,"active": body.provider,"persisted": body.persist,- "restart_required": True,+ "restart_required": False,}diff --git a/tests/unit/brain/test_router_lead_provider_health.py b/tests/unit/brain/test_router_lead_provider_health.pynew file mode 100644index 0000000000..d1ae2710b3--- /dev/null+++ b/tests/unit/brain/test_router_lead_provider_health.py@@ -0,0 +1,89 @@+"""Regression: `_first_tool_capable_provider` must honor the SAME provider+health checks the chain walk applies a few lines later in `generate()`+(manager.py, dead_providers + rate_tracker checks just before the per-attempt+try/except).++Before the fix, `_first_tool_capable_provider()` filtered only registry+availability + `_brain_can_call_tools()` — never `self._dead_providers` nor+`self._rate_tracker.is_available(...)`. A dead-listed or rate-limited-but-+tool-capable candidate could still win the router-LEAD slot; the chain walk+then skipped it silently (it never actually answers) while+`self._router_lead_key` kept pointing at it, so `_is_router_lead` misfired for+the REAL lead and the toolless fall-through gate accepted a tool-incapable+provider's answer as final instead of falling through correctly.+"""+from __future__ import annotations++from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+++class _ToolIncapableBrain:+ supports_tools = False+++class _ToolCapableBrain:+ supports_tools = True+++def _manager() -> BrainManager:+ mgr = BrainManager(config=JarvisConfig(), bus=EventBus(), tools={})+ # Not among the gemini/claude-api/openai candidates below, so none of+ # them get skipped for being "the active talker".+ mgr._active_name = "codex" # type: ignore[attr-defined]+ # Deterministic per-provider model names, independent of tier defaults.+ mgr._fast_model = lambda name: f"{name}-fast" # type: ignore[method-assign]+ mgr._registry._loaded = True+ mgr._registry._classes = { # type: ignore[attr-defined]+ "gemini": object, "claude-api": object, "openai": object,+ }+ return mgr+++def test_lead_skips_a_dead_listed_provider_even_if_tool_capable() -> None:+ mgr = _manager()+ # A = gemini: tool-incapable, would be skipped anyway.+ mgr._brain_cache[("gemini", "gemini-fast")] = _ToolIncapableBrain()+ # B = claude-api: tool-capable but dead-listed THIS session (e.g. a+ # missing-key failure earlier this turn/session).+ mgr._dead_providers.add("claude-api")+ mgr._brain_cache[("claude-api", "claude-api-fast")] = _ToolCapableBrain()+ # C = openai: healthy AND tool-capable — the only provider the chain+ # walk would actually reach.+ mgr._brain_cache[("openai", "openai-fast")] = _ToolCapableBrain()++ lead = mgr._first_tool_capable_provider("fast")++ assert lead == ("openai", "openai-fast"), (+ "a dead-listed provider must never win the router-lead slot, even "+ "though it is registered and reports tool support"+ )+++def test_lead_skips_a_rate_limited_provider_even_if_tool_capable() -> None:+ mgr = _manager()+ mgr._brain_cache[("gemini", "gemini-fast")] = _ToolIncapableBrain()+ # B = claude-api: not dead, but in a rate-limit cooldown right now.+ mgr._brain_cache[("claude-api", "claude-api-fast")] = _ToolCapableBrain()+ mgr._rate_tracker.mark_rate_limited("claude-api", "claude-api-fast")+ mgr._brain_cache[("openai", "openai-fast")] = _ToolCapableBrain()++ lead = mgr._first_tool_capable_provider("fast")++ assert lead == ("openai", "openai-fast"), (+ "a rate-limited provider must never win the router-lead slot — the "+ "chain walk would skip it during its own cooldown check"+ )+++def test_lead_still_picks_the_first_healthy_tool_capable_provider() -> None:+ """Sanity check: with nothing dead/rate-limited, order is unaffected."""+ mgr = _manager()+ mgr._brain_cache[("gemini", "gemini-fast")] = _ToolCapableBrain()+ mgr._brain_cache[("claude-api", "claude-api-fast")] = _ToolCapableBrain()+ mgr._brain_cache[("openai", "openai-fast")] = _ToolCapableBrain()++ lead = mgr._first_tool_capable_provider("fast")++ assert lead == ("gemini", "gemini-fast")diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.pyindex daace24c38..cea8d5ac7b 100644--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py@@ -206,6 +206,109 @@ async def test_near_silent_candidate_is_gated_on_energy(fake_vosk) -> None:assert p.stats()["gated_rms"] >= 1+# --- optimistic on_candidate signal (spawn-latency mission 2026-07-10) ---------+++async def test_on_candidate_fires_true_before_confirm_and_is_not_retracted_on_success(+ fake_vosk,+) -> None:+ """The optimistic candidate fires BEFORE the confirm_tail_s wait + verify+ pass, and is never retracted when that same candidate goes on to confirm+ -- only a REJECTED candidate gets a matching ``False`` (see the next+ test)."""+ events: list[bool] = []++ async def _on_candidate(active: bool) -> None:+ events.append(active)++ p = VoskKwsProvider(+ "Hey Nova", model_path="fake", keyword="nova", on_candidate=_on_candidate+ )+ fired = await _run_detect(p, [_chunk() for _ in range(12)])+ assert fired == ["nova"]+ assert events == [True]+++async def test_on_candidate_retracts_on_confirm_rejection(fake_vosk) -> None:+ events: list[bool] = []++ async def _on_candidate(active: bool) -> None:+ events.append(active)++ p = VoskKwsProvider(+ "Hey Nova", model_path="fake", keyword="nova", on_candidate=_on_candidate+ )+ fake_vosk_model_free_text = "das ist etwas ganz anderes" # i18n-allow: utterance under test+ fired: list[str] = []++ async def _late_set() -> None:+ for _ in range(50):+ if fake_vosk["model"] is not None:+ fake_vosk["model"].free_text = fake_vosk_model_free_text+ return+ await asyncio.sleep(0.01)++ async def _drive() -> None:+ async def _iter() -> AsyncIterator[AudioChunk]:+ for _ in range(12):+ await asyncio.sleep(0.005)+ yield _chunk()++ async for kw in p.detect(_iter()):+ fired.append(kw)++ await asyncio.wait_for(asyncio.gather(_late_set(), _drive()), timeout=5.0)+ assert fired == []+ # Optimistic reveal, then a matching retraction once the confirm rejects.+ # A third dangling True follows: the fake grammar re-fires exactly at the+ # chunk stream's end (fire_after=3 chunks after the re-armed recognizer,+ # which lines up with this test's chunk count) — a candidate whose+ # tail-wait never completes because the stream simply ends, same as a+ # real mic stream closing mid-candidate. That is expected, not a bug:+ # there is no matching False because verify_candidate never runs.+ assert events == [True, False, True]+++async def test_on_candidate_never_fires_on_near_silent_audio(fake_vosk) -> None:+ """AP-27: the optimistic pre-gate is raw ENERGY over the actual ring+ audio, never transcript content -- even though the fake grammar "hears"+ the phrase regardless of loudness, near-silent real PCM must never pop+ the bar."""+ events: list[bool] = []++ async def _on_candidate(active: bool) -> None:+ events.append(active)++ p = VoskKwsProvider(+ "Hey Nova", model_path="fake", keyword="nova", on_candidate=_on_candidate+ )+ fired = await _run_detect(p, [_silent_chunk() for _ in range(12)])+ assert fired == []+ assert events == []+++async def test_on_candidate_none_hook_is_a_safe_no_op(fake_vosk) -> None:+ """The default ``on_candidate=None`` must not raise or change behaviour+ (every existing test above already relies on this implicitly)."""+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")+ fired = await _run_detect(p, [_chunk() for _ in range(12)])+ assert fired == ["nova"]+++async def test_on_candidate_broken_hook_does_not_break_detection(fake_vosk) -> None:+ """A raising ``on_candidate`` hook must fail open — never eat a real+ wake (mirrors every other callback boundary in this provider)."""++ async def _boom(active: bool) -> None: # noqa: ARG001+ raise RuntimeError("UI hook exploded")++ p = VoskKwsProvider(+ "Hey Nova", model_path="fake", keyword="nova", on_candidate=_boom+ )+ fired = await _run_detect(p, [_chunk() for _ in range(12)])+ assert fired == ["nova"]++def test_confirm_infrastructure_error_fails_open(fake_vosk, monkeypatch) -> None:# A broken confirm must never eat a real wake (mirrors the echo-confirm# contract on the stt_match path): _verify_candidate returns True on ANYdiff --git a/tests/unit/ui/web/test_docs_routes.py b/tests/unit/ui/web/test_docs_routes.pynew file mode 100644index 0000000000..81489834a6--- /dev/null+++ b/tests/unit/ui/web/test_docs_routes.py@@ -0,0 +1,72 @@+"""REST-route tests for the docs "edit this page" open action.++Fix (MEDIUM): ``POST /api/docs/{slug}/open`` used to branch on+``hasattr(os, "startfile")`` else ``Popen(["xdg-open", ...])`` — macOS has+neither, so the else-branch called a non-existent binary and raised a+``FileNotFoundError`` -> HTTP 500. The route now delegates to+``jarvis.platform.open_path.open_file``, the cross-platform helper already+used by the Outputs view's native file actions.+"""+from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.docs_routes import router+++class _FakeRegistry:+ def __init__(self, docs: dict[str, object]) -> None:+ self._docs = docs++ def get(self, slug: str):+ return self._docs.get(slug)+++def _app(doc_path: Path) -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ doc = SimpleNamespace(path=doc_path)+ app.state.doc_registry = _FakeRegistry({"my-doc": doc})+ return app+++def test_open_doc_calls_open_file(tmp_path: Path):+ target = tmp_path / "my-doc.md"+ target.write_text("# hi", encoding="utf-8")+ client = TestClient(_app(target))+ with patch(+ "jarvis.platform.open_path.open_file", return_value=True+ ) as opn:+ r = client.post("/api/docs/my-doc/open")+ assert r.status_code == 200+ assert r.json() == {"path": str(target.resolve()), "opened": True}+ opn.assert_called_once_with(target.resolve())+++def test_open_doc_failure_is_honest_500_not_launcher_crash(tmp_path: Path):+ """No-launcher-found (the macOS FileNotFoundError shape) must degrade to a+ clean 500, never propagate the underlying OS error."""+ target = tmp_path / "my-doc.md"+ target.write_text("# hi", encoding="utf-8")+ client = TestClient(_app(target))+ with patch("jarvis.platform.open_path.open_file", return_value=False):+ r = client.post("/api/docs/my-doc/open")+ assert r.status_code == 500+++def test_open_doc_404_for_unknown_slug(tmp_path: Path):+ client = TestClient(_app(tmp_path / "unused.md"))+ r = client.post("/api/docs/does-not-exist/open")+ assert r.status_code == 404+++def test_open_doc_404_when_file_deleted_on_disk(tmp_path: Path):+ target = tmp_path / "gone.md" # never written+ client = TestClient(_app(target))+ r = client.post("/api/docs/my-doc/open")+ assert r.status_code == 404diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex 983bb35cd1..3674fea98a 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -919,6 +919,48 @@ def test_capabilities_defaults_false_when_unset(app):assert r.json()["native_file_actions"] is False+# --- /open (session folder in file manager) — cross-platform (Fix 2) --------+# Previously Windows-only (explorer.exe Popen); non-Windows silently returned+# opened=false even though open_path.reveal_in_folder already implements+# Windows/macOS/Linux. The route now delegates to reveal_in_folder everywhere.+++def test_open_session_folder_calls_reveal_in_folder(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ target = root / slug+ target.mkdir(parents=True, exist_ok=True)+ client = TestClient(app)+ with patch(+ "jarvis.platform.open_path.reveal_in_folder", return_value=True+ ) as rev:+ r = client.post(f"/api/outputs/{slug}/open")+ assert r.status_code == 200+ assert r.json() == {"opened": True, "path": str(target.resolve())}+ rev.assert_called_once()+++def test_open_session_folder_reports_failure_honestly(app):+ """A failed launcher (e.g. no display, broken opener) is reported as+ opened=false rather than raising — mirrors the other native-action routes."""+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ (root / slug).mkdir(parents=True, exist_ok=True)+ client = TestClient(app)+ with patch("jarvis.platform.open_path.reveal_in_folder", return_value=False):+ r = client.post(f"/api/outputs/{slug}/open")+ assert r.status_code == 200+ body = r.json()+ assert body["opened"] is False+ assert body["reason"] == "open failed"+++def test_open_session_folder_404_for_unknown_slug(app):+ client = TestClient(app)+ r = client.post("/api/outputs/does-not-exist/open")+ assert r.status_code == 404++# --- /reveal and /open-native routes (Task 6) --------------------------------diff --git a/tests/unit/web/test_realtime_provider_category.py b/tests/unit/web/test_realtime_provider_category.pyindex bbe7373972..e6e6298d42 100644--- a/tests/unit/web/test_realtime_provider_category.py+++ b/tests/unit/web/test_realtime_provider_category.py@@ -1,13 +1,7 @@-"""Realtime provider tier — backend for the API-Keys & Providers "Realtime" tab.--Mirrors the brain/tts/stt tier plumbing: the realtime ProviderSpecs-(``openai-realtime`` and ``gemini-live`` — the Gemini Live adapter module-itself lands in a later task, this only covers the declarative spec), the-``active_realtime`` resolution in ``list_providers``, the credential-presence-section-health check, and the ``POST /realtime/switch`` route. Style follows-``tests/unit/web/test_voice_mode_route.py`` (a lightweight FastAPI app with-just the router mounted, monkeypatched secrets) rather than the heavier-``WebServer`` fixture in ``tests/integration/test_provider_routes.py``.+"""Realtime provider tier for the API-Keys & Providers Realtime tab.++Covers both provider families, registry-based active-provider resolution,+credential health, switching, and per-provider model and voice selection."""from __future__ import annotations@@ -27,6 +21,11 @@ def _only_openai_key(key: str, *_a, **_kw) -> str | None:"""Fake ``cfg_mod.get_secret``: only ``openai_api_key`` looks configured."""return "sk-test" if key == "openai_api_key" else None++def _only_gemini_key(key: str, *_a, **_kw) -> str | None:+ """Fake ``cfg_mod.get_secret`` for a Gemini-only fresh install."""+ return "AIza-test" if key == "gemini_api_key" else None+# ---------------------------------------------------------------------------# ProviderSpec# ---------------------------------------------------------------------------@@ -73,6 +72,18 @@ def test_list_providers_includes_active_realtime_provider(monkeypatch):assert realtime["configured"] is True+def test_list_providers_resolves_gemini_only_fresh_install(monkeypatch):+ monkeypatch.setattr(cfg_mod, "get_secret", _only_gemini_key)+ client = TestClient(_app())++ resp = client.get("/api/providers")++ assert resp.status_code == 200+ by_id = {provider["id"]: provider for provider in resp.json()["providers"]}+ assert by_id["gemini-live"]["active"] is True+ assert by_id["openai-realtime"]["active"] is False++# ---------------------------------------------------------------------------# POST /api/realtime/switch# ---------------------------------------------------------------------------@@ -98,7 +109,7 @@ def test_realtime_switch_persists_with_key(monkeypatch):assert body["ok"] is Trueassert body["active"] == "openai-realtime"assert body["persisted"] is True- assert body["restart_required"] is True+ assert body["restart_required"] is Falseassert writes == ["openai-realtime"]assert app.state.config.brain.realtime is not Noneassert app.state.config.brain.realtime.provider == "openai-realtime"