Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

chore: auto-save WIP via Claude stop-hook safety net (2026-07-10 18:07)

Ruben Lütkebbe43e5b8b59
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index c0b5b12ab8..3e190ef374 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -1638,6 +1638,26 @@ _SELF_CONTROL_NOUN_RE = re.compile(
r"|worker)\b",
re.IGNORECASE,
)
+# Always-on compact self-control truth (forensic 2026-07-10): the LONG
+# directive below is injected only when _SELF_CONTROL_PATTERN matches, but a
+# keyword-free phrasing ("ich will dich ab jetzt Edith rufen koennen") sails # i18n-allow: quoted German utterance under test
+# past the regex — the router LLM then answered in prose and CLAIMED the
+# change without any tool call. Broadening the keyword list would be
+# whack-a-mole (the AP-27 tightening class); instead this short line rides in
+# EVERY substantive prompt so the model always knows it has the power and
+# that claiming without calling is forbidden. The keyworded directive stays
+# as the detailed intensifier.
+_SELF_CONTROL_STANDING = (
+ "SELF-CONTROL (always in effect): When the user asks you to change "
+ "anything about Jarvis itself — name/wake phrase, voice, volume, "
+ "providers, languages, settings, restart, missions/tasks — you CAN do it "
+ "yourself: prefer the `app-command` tool (validated registry commands), "
+ "`set_config_value` for a plain config key, `cli_jarvisctl` as fallback. "
+ "NEVER state or imply that a change or action happened unless a tool "
+ "call actually returned success in THIS turn; without such a result, say "
+ "honestly that you have not done it yet."
+)
+
_SELF_CONTROL_DIRECTIVE = (
"SELF-CONTROL: The user is asking to change or control Jarvis's OWN settings, "
"configuration, providers, voice, language, or behavior. You have full "
@@ -2985,6 +3005,11 @@ class BrainManager:
)
parts.append(base)
+ # Always-on self-control truth (see _SELF_CONTROL_STANDING rationale):
+ # keyword-free self-control phrasings must still find the tool path,
+ # and "claimed it, did nothing" is forbidden in every turn.
+ parts.append(_SELF_CONTROL_STANDING)
+
# Tool selection rules — prevents the LLM from wildly firing
# ``cli_supabase`` for "recherchiere zu Supabase" instead of using
# ``search_web``. Intent → tool class → concrete tool.
diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.py
index 7eafb15c9e..45565ee5d4 100644
--- a/jarvis/browser_voice/route.py
+++ b/jarvis/browser_voice/route.py
@@ -156,6 +156,38 @@ async def browser_voice_ws(ws: WebSocket) -> None:
await ws.close(code=1011, reason="speech stack unavailable")
return
+ audio_start_control: dict[str, Any] | None = None
+
+ async def _switch_to_classic(reason: str) -> bool:
+ nonlocal session
+ if not bool(getattr(session, "is_realtime", False)):
+ return False
+ log.warning(
+ "browser_voice: realtime session unavailable; using classic pipeline: %s",
+ reason,
+ )
+ await session.end(reason="realtime_fallback")
+ fallback = _build_classic_browser_session(
+ state=state,
+ cfg=cfg,
+ bus=bus,
+ session_id=session_id,
+ send_binary=_send_binary,
+ send_json=_send_json,
+ )
+ if fallback is None:
+ await ws.close(code=1011, reason="speech stack unavailable")
+ return False
+ session = fallback
+ await _send_json({"type": "mode_fallback", "mode": "pipeline"})
+ if audio_start_control is not None:
+ try:
+ await session.handle_control(audio_start_control)
+ except Exception as exc: # noqa: BLE001 — fallback is terminal
+ log.warning("browser_voice: classic fallback failed: %s", exc)
+ return False
+ return True
+
try:
while True:
try:
@@ -170,7 +202,24 @@ async def browser_voice_ws(ws: WebSocket) -> None:
break
data = msg.get("bytes")
if data is not None:
- await session.handle_audio_frame(data)
+ if bool(getattr(session, "failed", False)):
+ detail = str(getattr(session, "failure_detail", "") or "stream ended")
+ if not await _switch_to_classic(detail):
+ break
+ try:
+ await session.handle_audio_frame(data)
+ except Exception as exc: # noqa: BLE001 — terminal or family fallback
+ if not await _switch_to_classic(str(exc)):
+ log.warning("browser_voice: audio handling failed: %s", exc)
+ break
+ try:
+ await session.handle_audio_frame(data)
+ except Exception as fallback_exc: # noqa: BLE001 — terminal
+ log.warning(
+ "browser_voice: classic audio fallback failed: %s",
+ fallback_exc,
+ )
+ break
continue
text = msg.get("text")
if text is not None:
@@ -180,6 +229,8 @@ async def browser_voice_ws(ws: WebSocket) -> None:
log.debug("browser_voice: dropping malformed control frame")
continue
if isinstance(control, dict):
+ if control.get("type") == "audio_start":
+ audio_start_control = dict(control)
try:
await session.handle_control(control)
except Exception as exc: # noqa: BLE001 — AP-20: terminal or fallback
@@ -190,31 +241,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:
if not can_fallback:
log.warning("browser_voice: control handling failed: %s", exc)
break
- log.warning(
- "browser_voice: realtime handshake failed; using classic pipeline: %s",
- exc,
- )
- await session.end(reason="handshake_failed")
- fallback = _build_classic_browser_session(
- state=state,
- cfg=cfg,
- bus=bus,
- session_id=session_id,
- send_binary=_send_binary,
- send_json=_send_json,
- )
- if fallback is None:
- await ws.close(code=1011, reason="speech stack unavailable")
- break
- session = fallback
- await _send_json({"type": "mode_fallback", "mode": "pipeline"})
- try:
- await session.handle_control(control)
- except Exception as fallback_exc: # noqa: BLE001 — terminal
- log.warning(
- "browser_voice: classic fallback failed: %s",
- fallback_exc,
- )
+ if not await _switch_to_classic(str(exc)):
break
finally:
await session.end(reason="ws_closed")
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index 0719f1a225..74982db6fe 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -41,6 +41,7 @@ import logging
import time
from collections import deque
from collections.abc import AsyncIterator
+from concurrent.futures import ThreadPoolExecutor
from difflib import SequenceMatcher
from typing import Any
@@ -211,9 +212,36 @@ class VoskKwsProvider:
rec.SetWords(True)
return rec
+ def _warmup_decode(self) -> None:
+ """Run ONE throwaway grammar + free decode pass so the FIRST real
+ candidate's verify does not also pay Kaldi's cold-start cost
+ (recognizer graph build, ivector/CMVN buffer allocation — separate
+ from the ``Model()`` load itself). Mirrors
+ ``OpenWakeWordProvider._warmup_model``'s parity fix for the same
+ class of "first inference after load is slow" cost. Fail-closed: a
+ warm-up error must never break boot or arm a broken detector — the
+ real detect loop still builds fresh recognizers on the first genuine
+ candidate regardless of whether this succeeded.
+ """
+ try:
+ from vosk import KaldiRecognizer
+
+ silence = np.zeros(int(0.3 * self._sample_rate), dtype=np.int16).tobytes()
+ g = self._new_grammar_rec()
+ g.AcceptWaveform(silence)
+ g.FinalResult()
+ f = KaldiRecognizer(self._ensure_model(), self._sample_rate)
+ f.SetWords(True)
+ f.AcceptWaveform(silence)
+ f.FinalResult()
+ except Exception as exc: # noqa: BLE001 — warm-up must never break boot
+ log.debug("vosk-kws warm-up decode skipped: %s", exc)
+
async def start(self) -> None:
- """Pre-load the model off the event loop (never on the boot path)."""
+ """Pre-load AND warm the model — moves Kaldi's cold-start decode cost
+ off the first real wake candidate and onto boot warm-up instead."""
await asyncio.to_thread(self._ensure_model)
+ await asyncio.to_thread(self._warmup_decode)
async def stop(self) -> None:
self._model = None
@@ -288,6 +316,23 @@ class VoskKwsProvider:
Fail-OPEN only on infrastructure errors (a broken confirm must never
eat a real wake); a clean "the phrase is not there" is a rejection.
+
+ Latency (spawn-latency mission, 2026-07-10): the grammar re-score and
+ the free decode are independent Kaldi passes over the SAME audio —
+ the free decode does not consume the re-score's output, only the
+ LATER span-filtering step does. Measured on the real German small
+ model (data/wake_models/vosk/de/vosk-model-small-de-0.15): the free
+ pass costs 3-5x the grammar pass (e.g. 235ms vs 70ms over a 3 s
+ window), so running them sequentially pays their SUM even though the
+ wall-clock floor is only their MAX. They run concurrently in two
+ worker threads against ONE shared, read-only ``Model`` — Vosk's
+ documented multi-client pattern (one Model, many independent
+ KaldiRecognizer sessions decoding concurrently), not the AP-24 hazard
+ (that guards a single recognizer's mutable per-call state shared
+ across concurrent callers; here each thread owns its own fresh
+ recognizer). This changes only wall-clock time, never the decision:
+ both passes decode the identical ``pcm`` and every downstream
+ threshold/comparison is untouched.
"""
try:
from vosk import KaldiRecognizer
@@ -299,14 +344,30 @@ class VoskKwsProvider:
)
pcm = (window * 32767.0).astype(np.int16).tobytes()
- # 1) grammar re-score: real confidence + time span for the phrase.
- # One attempt over the full ring, deliberately: a second try over
- # a shorter cut measurably HELPED room speech more than genuine
- # calls (FA matrix 3 -> 7 with a last-1.8 s retry), because the
- # grammar happily forces any short speech snippet onto the phrase.
- g = self._new_grammar_rec()
- g.AcceptWaveform(pcm)
- gres = json.loads(g.FinalResult())
+ # 1) grammar re-score (real confidence + time span) and
+ # 3) free decode (unconstrained) run CONCURRENTLY — see the
+ # latency note above. One attempt each over the full ring,
+ # deliberately: a second grammar try over a shorter cut
+ # measurably HELPED room speech more than genuine calls (FA
+ # matrix 3 -> 7 with a last-1.8 s retry), because the grammar
+ # happily forces any short speech snippet onto the phrase.
+ def _grammar_pass() -> dict:
+ g = self._new_grammar_rec()
+ g.AcceptWaveform(pcm)
+ return json.loads(g.FinalResult())
+
+ def _free_pass() -> dict:
+ f = KaldiRecognizer(self._ensure_model(), self._sample_rate)
+ f.SetWords(True)
+ f.AcceptWaveform(pcm)
+ return json.loads(f.FinalResult())
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ grammar_future = pool.submit(_grammar_pass)
+ free_future = pool.submit(_free_pass)
+ gres = grammar_future.result()
+ fres = free_future.result()
+
gwords = [
w for w in gres.get("result", [])
if w.get("word") in self._grammar_words
@@ -343,11 +404,7 @@ class VoskKwsProvider:
)
return False
- # 3) free decode, localised to the phrase span
- f = KaldiRecognizer(self._ensure_model(), self._sample_rate)
- f.SetWords(True)
- f.AcceptWaveform(pcm)
- fres = json.loads(f.FinalResult())
+ # localise the (already-decoded) free words to the phrase span
local = [
w.get("word", "") for w in fres.get("result", [])
if w.get("end", 0.0) >= span_a and w.get("start", 0.0) <= span_b
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index ed44f350f0..ab6a4a2886 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -90,6 +90,8 @@ class RealtimeVoiceSession:
self._output_samples_sent = 0
self._ended = False
self._provider_errors: list[str] = []
+ self._failed = asyncio.Event()
+ self._failure_detail = ""
self._active_model = ""
self._turn_id = ""
self._turn_index = 0
@@ -302,6 +304,8 @@ class RealtimeVoiceSession:
self._output_samples_sent = 0
elif event.type == "error":
message = str(event.error or "provider error")
+ self._failure_detail = message
+ self._failed.set()
log.warning("realtime[%s] provider error: %s", self.session_id, message)
await self._publish_error(
"RealtimeProviderError", message, recoverable=True
@@ -310,6 +314,8 @@ class RealtimeVoiceSession:
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 — AP-20: pump error is terminal
+ self._failure_detail = str(exc) or "Realtime receive loop ended"
+ self._failed.set()
log.warning("realtime[%s] pump ended", self.session_id, exc_info=True)
await self._publish_error(
type(exc).__name__,
@@ -539,6 +545,15 @@ class RealtimeVoiceSession:
def active_provider(self) -> str:
return str(getattr(self._provider, "name", "") or "")
+ @property
+ def failed(self) -> bool:
+ """Whether the accepted duplex stream became unusable mid-session."""
+ return self._failed.is_set()
+
+ @property
+ def failure_detail(self) -> str:
+ return self._failure_detail
+
async def wait_finished(self) -> None:
task = self._pump_task
if task is not None:
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
index bf5df25779..2fff6a58e6 100644
--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
@@ -62,8 +62,10 @@ describe("BrowserRealtimeControl", () => {
await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));
expect(
- screen.getByRole("button", { name: "sidebar.realtime_stop" }),
- ).toHaveAttribute("aria-pressed", "true");
+ screen.getByRole("button", { name: "sidebar.realtime_stop" }).getAttribute(
+ "aria-pressed",
+ ),
+ ).toBe("true");
});
it("explains that a key is required instead of opening the microphone", () => {
@@ -71,7 +73,7 @@ describe("BrowserRealtimeControl", () => {
render(<BrowserRealtimeControl />);
const button = screen.getByRole("button", { name: "sidebar.realtime_unavailable" });
- expect(button).toBeDisabled();
+ expect((button as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(button);
expect(fakes.connect).not.toHaveBeenCalled();
});
diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
index 34112d59a5..48d5b9bd84 100644
--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
export type AuthMode = "api_key" | "codex" | "antigravity" | "none";
export type ProviderTier = "brain" | "tts" | "stt" | "realtime" | "computer-use";
@@ -212,6 +212,8 @@ export interface SectionHealth {
reason: string;
/** Plain-English one-liner for the hover tooltip. */
detail: string;
+ /** Exact provider/integration checked by the backend. */
+ subject_id: string | null;
}
export interface SectionHealthResponse {
@@ -225,9 +227,13 @@ export interface SectionHealthResponse {
* TTL cache — used right after a key save / provider switch so the dot reflects
* the change immediately instead of a stale cached result.
*/
-export async function getSectionHealth(refresh = false): Promise<SectionHealthResponse> {
+export async function getSectionHealth(
+ refresh = false,
+ signal?: AbortSignal,
+): Promise<SectionHealthResponse> {
const res = await fetch(
`/api/providers/section-health${refresh ? "?refresh=true" : ""}`,
+ { signal, cache: "no-store" },
);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as SectionHealthResponse;
@@ -244,12 +250,21 @@ export async function getSectionHealth(refresh = false): Promise<SectionHealthRe
*/
export function useSectionHealth() {
const [health, setHealth] = useState<Record<string, SectionHealth>>({});
+ const requestVersion = useRef(0);
+ const requestController = useRef<AbortController | null>(null);
const reload = useCallback(async (refresh = false) => {
+ const version = ++requestVersion.current;
+ requestController.current?.abort();
+ const controller = new AbortController();
+ requestController.current = controller;
try {
- const data = await getSectionHealth(refresh);
- setHealth(data.sections ?? {});
- } catch {
+ const data = await getSectionHealth(refresh, controller.signal);
+ if (version === requestVersion.current) {
+ setHealth(data.sections ?? {});
+ }
+ } catch (error) {
+ if ((error as Error).name === "AbortError") return;
// best-effort — keep whatever we last had rather than clearing to nothing
}
}, []);
diff --git a/tests/unit/brain/test_self_control_standing.py b/tests/unit/brain/test_self_control_standing.py
new file mode 100644
index 0000000000..485b6ccc47
--- /dev/null
+++ b/tests/unit/brain/test_self_control_standing.py
@@ -0,0 +1,62 @@
+"""The always-on self-control line must reach EVERY system prompt.
+
+Forensic 2026-07-10: a keyword-free self-control utterance ("ich will dich
+ab jetzt Edith rufen koennen") missed _SELF_CONTROL_PATTERN, so the router
+LLM got no self-control guidance, answered in prose, and CLAIMED the wake-
+word change without any tool call. The standing line closes that hole
+without keyword whack-a-mole; these tests pin it.
+""" # i18n-allow: quoted German utterance under test
+from __future__ import annotations
+
+from jarvis.brain.manager import (
+ _SELF_CONTROL_STANDING,
+ BrainManager,
+)
+from jarvis.core.config import load_config
+
+
+def _manager() -> BrainManager:
+ """A BrainManager with __init__ bypassed — only the attrs the prompt needs."""
+ m = BrainManager.__new__(BrainManager)
+ m._soul = None
+ m._user_profile = None
+ m._people = None
+ m._core_memory = None
+ m._awareness_manager = None
+ m._system_prompt_extra = ""
+ m._wiki_context_suffix = ""
+ m._reply_language = "auto"
+ m._active_turn_identity = None
+ cfg = load_config()
+ cfg.performance.cache_optimized_prompt = False
+ m._config = cfg
+ return m
+
+
+def test_standing_line_present_without_keyword_directive() -> None:
+ """No keyworded directive set — the standing line must be there anyway."""
+ m = _manager()
+ assert getattr(m, "_self_control_directive", "") == ""
+ prompt = m._build_system_prompt()
+ assert _SELF_CONTROL_STANDING in prompt
+
+
+def test_standing_line_names_the_structured_path_and_forbids_claiming() -> None:
+ assert "app-command" in _SELF_CONTROL_STANDING
+ low = _SELF_CONTROL_STANDING.lower()
+ # The anti-"said it, did nothing" rule, in plain words.
+ assert "never" in low
+ assert "tool call" in low
+ # Wake-phrase renames are the reproduced failure — must be named so a
+ # keyword-free phrasing still maps.
+ assert "wake" in low
+
+
+def test_keyworded_directive_still_stacks_on_top() -> None:
+ from jarvis.brain.manager import _SELF_CONTROL_DIRECTIVE
+
+ m = _manager()
+ m._self_control_directive = _SELF_CONTROL_DIRECTIVE
+ prompt = m._build_system_prompt()
+ assert _SELF_CONTROL_STANDING in prompt
+ assert _SELF_CONTROL_DIRECTIVE in prompt
diff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.py
index 07938a5510..8a00b42cf6 100644
--- a/tests/unit/browser_voice/test_route.py
+++ b/tests/unit/browser_voice/test_route.py
@@ -156,3 +156,35 @@ async def test_realtime_handshake_failure_crosses_to_classic_browser_pipeline(
assert classic.controls == [{"type": "audio_start", "sample_rate": 48_000}]
assert classic.ended
assert {"type": "mode_fallback", "mode": "pipeline"} in ws.sent_json
+
+
+async def test_dead_realtime_stream_crosses_to_classic_on_next_audio_frame(monkeypatch):
+ classic = _RecSession()
+
+ class _DeadRealtime(_RecSession):
+ is_realtime = True
+ failed = True
+ failure_detail = "provider stream ended"
+
+ dead = _DeadRealtime()
+ state = _state(classic)
+ state.config.voice = SimpleNamespace(mode="realtime")
+ monkeypatch.setattr(route_mod, "_build_browser_session", lambda **_kwargs: dead)
+ ws = _FakeWS(
+ [
+ {
+ "type": "websocket.receive",
+ "text": '{"type":"audio_start","sample_rate":48000}',
+ },
+ {"type": "websocket.receive", "bytes": b"\x01\x00\x02\x00"},
+ {"type": "websocket.disconnect", "code": 1000},
+ ],
+ state=state,
+ )
+
+ await browser_voice_ws(ws)
+
+ assert dead.ended
+ assert classic.controls == [{"type": "audio_start", "sample_rate": 48_000}]
+ assert classic.audio == [b"\x01\x00\x02\x00"]
+ assert {"type": "mode_fallback", "mode": "pipeline"} in ws.sent_json