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:06)

Ruben Lütkea21559932fee
diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.py
index 3eb6c0c8b7..7eafb15c9e 100644
--- a/jarvis/browser_voice/route.py
+++ b/jarvis/browser_voice/route.py
@@ -54,11 +54,10 @@ def _build_browser_session(
key) — the caller then closes the socket cleanly. A test can inject
``state.browser_voice_session_factory`` to bypass the real provider build.
"""
- # Realtime mode branch (default OFF): only when [voice].mode == "realtime"
- # AND an OpenAI key exists. Otherwise fall through to the classic bridge.
- # The realtime engine is an optional, still-internal module stripped from
- # public distribution snapshots (distribution-denylist), so its absence just
- # means "no realtime" — fall through instead of crashing the voice session.
+ # Default-off Realtime branch. The registry-backed factory selects every
+ # credential-ready duplex family in configured order; no provider name is
+ # load-bearing. An installation without that optional module or without a
+ # usable duplex credential falls through to the classic browser bridge.
try:
from jarvis.realtime.factory import build_realtime_session
except ImportError:
@@ -76,6 +75,20 @@ def _build_browser_session(
if rt is not None:
return rt
+ return _build_classic_browser_session(
+ state=state,
+ cfg=cfg,
+ bus=bus,
+ session_id=session_id,
+ send_binary=send_binary,
+ send_json=send_json,
+ )
+
+
+def _build_classic_browser_session(
+ *, state: Any, cfg: Any, bus: Any, session_id: str, send_binary: Any, send_json: Any
+) -> Any:
+ """Build the key-aware STT -> brain -> TTS browser fallback lazily."""
factory = getattr(state, "browser_voice_session_factory", None)
if factory is not None:
return factory(session_id=session_id, send_binary=send_binary, send_json=send_json)
@@ -167,6 +180,41 @@ async def browser_voice_ws(ws: WebSocket) -> None:
log.debug("browser_voice: dropping malformed control frame")
continue
if isinstance(control, dict):
- await session.handle_control(control)
+ try:
+ await session.handle_control(control)
+ except Exception as exc: # noqa: BLE001 — AP-20: terminal or fallback
+ can_fallback = (
+ control.get("type") == "audio_start"
+ and bool(getattr(session, "is_realtime", False))
+ )
+ 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,
+ )
+ break
finally:
await session.end(reason="ws_closed")
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index bda6f8918c..ed44f350f0 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -46,6 +46,8 @@ def _session_instructions(language: str) -> str:
class RealtimeVoiceSession:
"""One duplex conversation shared by browser and desktop surfaces."""
+ is_realtime = True
+
def __init__(
self,
*,
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 186ddbb810..34cce3f94c 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -29,6 +29,7 @@ import { usePluginAttention } from "@/hooks/usePluginAttention";
import { cn } from "@/lib/utils";
import { useMemo } from "react";
import { useT } from "@/i18n";
+import { BrowserRealtimeControl } from "@/components/voice/BrowserRealtimeControl";
interface NavItem {
id: SectionId;
@@ -241,6 +242,7 @@ export function Sidebar() {
<span className="text-muted-foreground/50">{t("sidebar.wake_hint")}</span>
)}
</div>
+ <BrowserRealtimeControl />
</div>
<nav className="flex-1 overflow-y-auto scrollbar-jarvis p-2">
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
new file mode 100644
index 0000000000..bf5df25779
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx
@@ -0,0 +1,78 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { BrowserRealtimeControl } from "./BrowserRealtimeControl";
+
+const fakes = vi.hoisted(() => ({
+ native: false,
+ mode: "realtime",
+ available: true,
+ connect: vi.fn(async () => undefined),
+ disconnect: vi.fn(async () => undefined),
+}));
+
+vi.mock("@/hooks/useCapabilities", () => ({
+ useCapabilities: () => ({ data: { native_file_actions: fakes.native, platform: "linux" } }),
+}));
+
+vi.mock("@/hooks/useVoiceMode", () => ({
+ useVoiceMode: () => ({
+ mode: fakes.mode,
+ realtimeAvailable: fakes.available,
+ setMode: vi.fn(),
+ isLoading: false,
+ isSaving: false,
+ }),
+}));
+
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
+
+vi.mock("@/lib/realtimeAudio", () => ({
+ RealtimeAudioClient: class {
+ connect = fakes.connect;
+ disconnect = fakes.disconnect;
+ },
+}));
+
+describe("BrowserRealtimeControl", () => {
+ beforeEach(() => {
+ fakes.native = false;
+ fakes.mode = "realtime";
+ fakes.available = true;
+ fakes.connect.mockClear();
+ fakes.disconnect.mockClear();
+ });
+
+ it("is hidden in the desktop shell to prevent a second microphone", () => {
+ fakes.native = true;
+ render(<BrowserRealtimeControl />);
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("is hidden while the classic pipeline is selected", () => {
+ fakes.mode = "pipeline";
+ render(<BrowserRealtimeControl />);
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("starts browser-owned realtime audio from an explicit user gesture", async () => {
+ render(<BrowserRealtimeControl />);
+
+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));
+
+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));
+ expect(
+ screen.getByRole("button", { name: "sidebar.realtime_stop" }),
+ ).toHaveAttribute("aria-pressed", "true");
+ });
+
+ it("explains that a key is required instead of opening the microphone", () => {
+ fakes.available = false;
+ render(<BrowserRealtimeControl />);
+
+ const button = screen.getByRole("button", { name: "sidebar.realtime_unavailable" });
+ expect(button).toBeDisabled();
+ fireEvent.click(button);
+ expect(fakes.connect).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
new file mode 100644
index 0000000000..21d29389b5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx
@@ -0,0 +1,149 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { Loader2, Mic, MicOff, RotateCcw } from "lucide-react";
+
+import { useCapabilities } from "@/hooks/useCapabilities";
+import { useVoiceMode } from "@/hooks/useVoiceMode";
+import { useT } from "@/i18n";
+import { RealtimeAudioClient } from "@/lib/realtimeAudio";
+import { useEventStore } from "@/store/events";
+import { cn } from "@/lib/utils";
+
+type ConnectionState = "idle" | "connecting" | "connected" | "error";
+
+/** Browser-owned microphone control for remote/headless installations.
+ *
+ * The desktop shell already owns the physical microphone through
+ * SpeechPipeline, so this control is rendered only when the capability route
+ * says native desktop actions are unavailable. That prevents two concurrent
+ * capture streams while still making a headless VPS usable entirely in-app.
+ */
+export function BrowserRealtimeControl() {
+ const t = useT();
+ const capabilities = useCapabilities();
+ const { mode, realtimeAvailable } = useVoiceMode();
+ const setVoice = useEventStore((store) => store.setVoice);
+ const setTranscription = useEventStore((store) => store.setTranscription);
+ const [state, setState] = useState<ConnectionState>("idle");
+ const [effectiveProvider, setEffectiveProvider] = useState("");
+ const [error, setError] = useState("");
+ const clientRef = useRef<RealtimeAudioClient | null>(null);
+ const browserSurface = capabilities.data?.native_file_actions === false;
+ const visible = browserSurface && mode === "realtime";
+
+ const stop = useCallback(async () => {
+ const client = clientRef.current;
+ clientRef.current = null;
+ await client?.disconnect();
+ setState("idle");
+ setEffectiveProvider("");
+ setError("");
+ setVoice("idle");
+ }, [setVoice]);
+
+ const start = useCallback(async () => {
+ if (!realtimeAvailable || state === "connecting") return;
+ await clientRef.current?.disconnect();
+ setState("connecting");
+ setError("");
+ setEffectiveProvider("");
+
+ const client = new RealtimeAudioClient({
+ onTranscript: (text, isFinal, role) => {
+ if (role === "user") setTranscription(text, isFinal);
+ if (role === "user" && isFinal) setVoice("thinking");
+ },
+ onAudio: () => setVoice("speaking"),
+ onStatus: (status, payload) => {
+ if (status === "audio_ready") {
+ const provider = typeof payload.provider === "string" ? payload.provider : "";
+ if (provider) setEffectiveProvider(provider);
+ setState("connected");
+ setVoice("listening");
+ } else if (status === "mode_fallback") {
+ setEffectiveProvider(t("sidebar.realtime_pipeline_fallback"));
+ } else if (status === "turn_complete" || status === "tts_end") {
+ setVoice("listening");
+ } else if (status === "tts_cancel") {
+ setVoice("listening");
+ } else if (status === "provider_error" || status === "disconnected") {
+ setState("error");
+ setError(t("sidebar.realtime_error"));
+ setVoice("error");
+ }
+ },
+ });
+ clientRef.current = client;
+ try {
+ await client.connect();
+ setState("connected");
+ } catch {
+ if (clientRef.current === client) clientRef.current = null;
+ setState("error");
+ setError(t("sidebar.realtime_error"));
+ setVoice("error");
+ }
+ }, [realtimeAvailable, setTranscription, setVoice, state, t]);
+
+ useEffect(() => {
+ if (visible) return;
+ const client = clientRef.current;
+ clientRef.current = null;
+ if (client) void client.disconnect();
+ }, [visible]);
+
+ useEffect(
+ () => () => {
+ const client = clientRef.current;
+ clientRef.current = null;
+ if (client) void client.disconnect();
+ },
+ [],
+ );
+
+ if (!visible) return null;
+
+ const connected = state === "connected";
+ const connecting = state === "connecting";
+ const unavailable = !realtimeAvailable;
+ const label = unavailable
+ ? t("sidebar.realtime_unavailable")
+ : connected
+ ? t("sidebar.realtime_stop")
+ : state === "error"
+ ? t("sidebar.realtime_retry")
+ : t("sidebar.realtime_start");
+ const Icon = connecting ? Loader2 : connected ? MicOff : state === "error" ? RotateCcw : Mic;
+
+ return (
+ <div className="mt-2 rounded-md border border-border/70 bg-background/50 p-2">
+ <button
+ type="button"
+ disabled={unavailable || connecting}
+ aria-label={label}
+ aria-pressed={connected}
+ onClick={() => void (connected ? stop() : start())}
+ className={cn(
+ "flex min-h-9 w-full touch-manipulation items-center justify-center gap-2 rounded-md px-2",
+ "text-xs font-medium transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",
+ connected
+ ? "bg-primary text-primary-foreground hover:bg-primary/90"
+ : "border border-border bg-card text-foreground hover:border-primary/50",
+ (unavailable || connecting) && "cursor-not-allowed opacity-60",
+ )}
+ >
+ <Icon
+ className={cn("h-3.5 w-3.5", connecting && "animate-spin motion-reduce:animate-none")}
+ aria-hidden="true"
+ />
+ <span>{connecting ? t("sidebar.realtime_connecting") : label}</span>
+ </button>
+ <div className="mt-1.5 min-h-4 text-[10px] text-muted-foreground" aria-live="polite">
+ {error ||
+ (connected
+ ? `${t("sidebar.realtime_connected")} ${effectiveProvider}`.trim()
+ : t("sidebar.realtime_browser_hint"))}
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 632327f056..1b300887ad 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -208,7 +208,16 @@
"brain_label": "Brain",
"brain_tooltip": "Brain-Provider wechseln",
"apikeys_alert": "Ein Anbieter ist eingerichtet, funktioniert aber nicht — zum Beheben API Keys öffnen",
- "plugins_reconnect_alert": "Eine Plugin-Verbindung ist abgelaufen — zum Neuverbinden Skills & Tools öffnen"
+ "plugins_reconnect_alert": "Eine Plugin-Verbindung ist abgelaufen — zum Neuverbinden Skills & Tools öffnen",
+ "realtime_start": "Realtime-Sprache starten",
+ "realtime_stop": "Realtime-Sprache beenden",
+ "realtime_retry": "Realtime-Sprache erneut versuchen",
+ "realtime_connecting": "Verbindung wird hergestellt…",
+ "realtime_connected": "Verbunden über",
+ "realtime_browser_hint": "Auf diesem Gerät verwendet dein Browser das Mikrofon.",
+ "realtime_pipeline_fallback": "Klassische Pipeline als Fallback",
+ "realtime_unavailable": "Realtime-API-Key einrichten",
+ "realtime_error": "Die Sprachverbindung konnte nicht gestartet werden. Teste den aktiven Realtime-Anbieter unter API Keys und versuche es erneut."
},
"chats_view": {
"title": "Chat",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 23ba9eaad5..9cfdeef03e 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -208,7 +208,16 @@
"brain_label": "Brain",
"brain_tooltip": "Switch brain provider",
"apikeys_alert": "A provider is set up but not working — open API Keys to fix it",
- "plugins_reconnect_alert": "A plugin connection expired — open Skills & Tools to reconnect it"
+ "plugins_reconnect_alert": "A plugin connection expired — open Skills & Tools to reconnect it",
+ "realtime_start": "Start Realtime Voice",
+ "realtime_stop": "Stop Realtime Voice",
+ "realtime_retry": "Retry Realtime Voice",
+ "realtime_connecting": "Connecting…",
+ "realtime_connected": "Connected via",
+ "realtime_browser_hint": "Your browser owns the microphone on this device.",
+ "realtime_pipeline_fallback": "Classic pipeline fallback",
+ "realtime_unavailable": "Configure a Realtime API Key",
+ "realtime_error": "Couldn’t start voice. Test the active Realtime provider under API Keys, then retry."
},
"chats_view": {
"title": "Chat",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index e1a91b9276..e8dc8b1d87 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -208,7 +208,16 @@
"brain_label": "Cerebro",
"brain_tooltip": "Cambiar proveedor de IA",
"apikeys_alert": "Un proveedor está configurado pero no funciona — abre API Keys para solucionarlo",
- "plugins_reconnect_alert": "Una conexión de plugin expiró — abre Skills & Tools para volver a conectarla"
+ "plugins_reconnect_alert": "Una conexión de plugin expiró — abre Skills & Tools para volver a conectarla",
+ "realtime_start": "Iniciar Voz en Tiempo Real",
+ "realtime_stop": "Detener Voz en Tiempo Real",
+ "realtime_retry": "Reintentar Voz en Tiempo Real",
+ "realtime_connecting": "Conectando…",
+ "realtime_connected": "Conectado mediante",
+ "realtime_browser_hint": "Tu navegador controla el micrófono en este dispositivo.",
+ "realtime_pipeline_fallback": "Sistema de voz clásico como alternativa",
+ "realtime_unavailable": "Configura una clave API de tiempo real",
+ "realtime_error": "No se pudo iniciar la voz. Prueba el proveedor activo en API Keys y vuelve a intentarlo."
},
"chats_view": {
"title": "Chat",
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts
index 2ea38a5331..5f91a9ab33 100644
--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from "vitest";
-import { buildAudioSocketUrl } from "./realtimeAudio";
+import { buildAudioSocketUrl, StreamingPcm16Resampler } from "./realtimeAudio";
describe("realtime audio client", () => {
beforeEach(() => {
@@ -10,4 +10,26 @@ describe("realtime audio client", () => {
it("builds a wss /ws/audio url with the token", () => {
expect(buildAudioSocketUrl()).toBe("wss://app.example/ws/audio?token=tok");
});
+
+ it("resamples provider PCM from 24 kHz to a 48 kHz AudioContext", () => {
+ const input = Int16Array.from({ length: 2_400 }, (_, i) => i - 1_200);
+ const output = new Int16Array(
+ new StreamingPcm16Resampler(24_000, 48_000).process(input.buffer),
+ );
+
+ expect(output.length).toBeGreaterThanOrEqual(4_798);
+ expect(output.length).toBeLessThanOrEqual(4_800);
+ });
+
+ it("keeps interpolation continuous across WebSocket frame boundaries", () => {
+ const input = Int16Array.from({ length: 2_400 }, (_, i) => i * 4 - 4_800);
+ const whole = new Int16Array(
+ new StreamingPcm16Resampler(24_000, 48_000).process(input.buffer),
+ );
+ const streamed = new StreamingPcm16Resampler(24_000, 48_000);
+ const first = new Int16Array(streamed.process(input.slice(0, 1_200).buffer));
+ const second = new Int16Array(streamed.process(input.slice(1_200).buffer));
+
+ expect([...first, ...second]).toEqual([...whole]);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
index 79a28e1e83..db3ebc5a63 100644
--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts
@@ -1,5 +1,5 @@
-// Dedicated /ws/audio client for realtime voice. Separate from the JSON-only
-// WSClient (src/lib/ws.ts): this one carries binary int16 PCM (arraybuffer).
+// Dedicated /ws/audio client for browser-owned voice. Separate from the
+// JSON-only WSClient: this socket carries raw mono PCM16 in both directions.
export function buildAudioSocketUrl(): string {
const proto = window.location.protocol === "https:" ? "wss" : "ws";
@@ -9,62 +9,259 @@ export function buildAudioSocketUrl(): string {
return `${proto}://${host}/ws/audio${query}`;
}
+export type RealtimeStatusPayload = Record<string, unknown>;
+
export type RealtimeCallbacks = {
- onTranscript?: (text: string, isFinal: boolean) => void;
- onStatus?: (status: string) => void;
+ onTranscript?: (text: string, isFinal: boolean, role: string) => void;
+ onStatus?: (status: string, payload: RealtimeStatusPayload) => void;
+ onAudio?: () => void;
};
+/** Stateful linear PCM16 resampler used for provider audio playback.
+ *
+ * Realtime providers currently emit 24 kHz PCM, while AudioContext commonly
+ * runs at 44.1 or 48 kHz. Carrying one sample and the fractional source
+ * position across WebSocket frames avoids pitch/speed errors and chunk-edge
+ * discontinuities without a native dependency.
+ */
+export class StreamingPcm16Resampler {
+ private readonly step: number;
+ private tail: number | null = null;
+ private position = 0;
+
+ constructor(
+ readonly fromRate: number,
+ readonly toRate: number,
+ ) {
+ if (fromRate <= 0 || toRate <= 0) throw new Error("PCM sample rates must be positive");
+ this.step = fromRate / toRate;
+ }
+
+ process(pcm: ArrayBuffer): ArrayBuffer {
+ if (pcm.byteLength === 0) return new ArrayBuffer(0);
+ if (pcm.byteLength % 2 !== 0) throw new Error("PCM16 input contains a partial sample");
+ if (this.fromRate === this.toRate) return pcm.slice(0);
+
+ const incoming = new Int16Array(pcm);
+ const samples = new Float64Array(incoming.length + (this.tail === null ? 0 : 1));
+ let offset = 0;
+ if (this.tail !== null) {
+ samples[0] = this.tail;
+ offset = 1;
+ }
+ for (let i = 0; i < incoming.length; i++) samples[i + offset] = incoming[i];
+ if (samples.length < 2) {
+ this.tail = samples[0] ?? null;
+ return new ArrayBuffer(0);
+ }
+
+ const limit = samples.length - 1;
+ if (this.position >= limit) {
+ this.position -= limit;
+ this.tail = samples[samples.length - 1];
+ return new ArrayBuffer(0);
+ }
+ const count = Math.ceil((limit - this.position) / this.step);
+ const output = new Int16Array(count);
+ let sourcePosition = this.position;
+ for (let i = 0; i < count; i++) {
+ const left = Math.floor(sourcePosition);
+ const fraction = sourcePosition - left;
+ const value = samples[left] + (samples[left + 1] - samples[left]) * fraction;
+ output[i] = Math.max(-32768, Math.min(32767, Math.round(value)));
+ sourcePosition += this.step;
+ }
+ this.position = sourcePosition - limit;
+ this.tail = samples[samples.length - 1];
+ return output.buffer;
+ }
+
+ reset(): void {
+ this.tail = null;
+ this.position = 0;
+ }
+}
+
export class RealtimeAudioClient {
private ws: WebSocket | null = null;
private ctx: AudioContext | null = null;
private captureNode: AudioWorkletNode | null = null;
+ private captureSink: GainNode | null = null;
private playbackNode: AudioWorkletNode | null = null;
private stream: MediaStream | null = null;
+ private playbackResampler: StreamingPcm16Resampler | null = null;
+ private connecting: Promise<void> | null = null;
+ private ready = false;
+ private intentionalClose = false;
constructor(private cb: RealtimeCallbacks = {}) {}
- async connect(): Promise<void> {
- this.ctx = new AudioContext();
- await this.ctx.audioWorklet.addModule(new URL("./pcm-worklet.ts", import.meta.url));
-
- this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- const src = this.ctx.createMediaStreamSource(this.stream);
- this.captureNode = new AudioWorkletNode(this.ctx, "pcm-capture");
- this.playbackNode = new AudioWorkletNode(this.ctx, "pcm-playback");
- this.playbackNode.connect(this.ctx.destination);
- src.connect(this.captureNode);
-
- this.ws = new WebSocket(buildAudioSocketUrl());
- this.ws.binaryType = "arraybuffer";
-
- this.ws.onopen = () => {
- this.ws?.send(JSON.stringify({ type: "audio_start", sample_rate: this.ctx?.sampleRate ?? 48000 }));
- };
- this.captureNode.port.onmessage = (e) => {
- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(e.data as ArrayBuffer);
- };
- this.ws.onmessage = (e) => {
- if (typeof e.data === "string") {
- const msg = JSON.parse(e.data);
- if (msg.type === "transcript") this.cb.onTranscript?.(msg.text, !!msg.is_final);
- else if (msg.type === "tts_cancel") this.playbackNode?.port.postMessage({ type: "flush" });
- else this.cb.onStatus?.(msg.type);
- } else {
- this.playbackNode?.port.postMessage({ type: "pcm", data: e.data }, [e.data as ArrayBuffer]);
- }
- };
+ connect(): Promise<void> {
+ if (this.ready) return Promise.resolve();
+ if (this.connecting) return this.connecting;
+ this.connecting = this.open().finally(() => {
+ this.connecting = null;
+ });
+ return this.connecting;
+ }
+
+ private async open(): Promise<void> {
+ this.intentionalClose = false;
+ try {
+ this.ctx = new AudioContext({ latencyHint: "interactive" });
+ await this.ctx.audioWorklet.addModule(new URL("./pcm-worklet.ts", import.meta.url));
+ await this.ctx.resume();
+
+ this.stream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ channelCount: { ideal: 1 },
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ },
+ });
+ const source = this.ctx.createMediaStreamSource(this.stream);
+ this.captureNode = new AudioWorkletNode(this.ctx, "pcm-capture");
+ this.playbackNode = new AudioWorkletNode(this.ctx, "pcm-playback");
+ // Keep the capture worklet in the active audio graph without feeding the
+ // microphone back to the user. Browser AEC still sees the real playback
+ // node connected below and can remove it from captured audio.
+ this.captureSink = this.ctx.createGain();
+ this.captureSink.gain.value = 0;
+ source.connect(this.captureNode);
+ this.captureNode.connect(this.captureSink);
+ this.captureSink.connect(this.ctx.destination);
+ this.playbackNode.connect(this.ctx.destination);
+
+ this.ws = new WebSocket(buildAudioSocketUrl());
+ this.ws.binaryType = "arraybuffer";
+ this.captureNode.port.onmessage = (event) => {
+ if (this.ready && this.ws?.readyState === WebSocket.OPEN) {
+ this.ws.send(event.data as ArrayBuffer);
+ }
+ };
+
+ await this.waitUntilReady(this.ws);
+ } catch (error) {
+ await this.teardown(false);
+ throw error instanceof Error ? error : new Error(String(error));
+ }
+ }
+
+ private waitUntilReady(socket: WebSocket): Promise<void> {
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const timeout = window.setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ reject(new Error("Realtime voice connection timed out"));
+ }, 20_000);
+
+ const fail = (error: Error) => {
+ if (!settled) {
+ settled = true;
+ window.clearTimeout(timeout);
+ reject(error);
+ }
+ };
+
+ socket.onopen = () => {
+ socket.send(
+ JSON.stringify({ type: "audio_start", sample_rate: this.ctx?.sampleRate ?? 48_000 }),
+ );
+ };
+ socket.onerror = () => fail(new Error("Realtime voice socket failed"));
+ socket.onclose = (event) => {
+ this.ready = false;
+ if (!this.intentionalClose) {
+ this.cb.onStatus?.("disconnected", { code: event.code, reason: event.reason });
+ fail(new Error(event.reason || `Realtime voice socket closed (${event.code})`));
+ }
+ };
+ socket.onmessage = (event) => {
+ if (typeof event.data !== "string") {
+ this.handleAudio(event.data as ArrayBuffer);
+ return;
+ }
+ let message: RealtimeStatusPayload;
+ try {
+ message = JSON.parse(event.data) as RealtimeStatusPayload;
+ } catch {
+ return;
+ }
+ const type = typeof message.type === "string" ? message.type : "unknown";
+ if (type === "transcript" && typeof message.text === "string") {
+ this.cb.onTranscript?.(
+ message.text,
+ Boolean(message.is_final),
+ typeof message.role === "string" ? message.role : "user",
+ );
+ } else if (type === "tts_cancel") {
+ this.playbackResampler?.reset();
+ this.playbackNode?.port.postMessage({ type: "flush" });
+ } else if (type === "audio_ready") {
+ this.setOutputRate(message.output_sample_rate);
+ this.ready = true;
+ if (!settled) {
+ settled = true;
+ window.clearTimeout(timeout);
+ resolve();
+ }
+ } else if (type === "tts_start") {
+ this.setOutputRate(message.sample_rate);
+ } else if (type === "turn_complete" || type === "tts_end") {
+ this.playbackResampler?.reset();
+ }
+ this.cb.onStatus?.(type, message);
+ };
+ });
+ }
+
+ private setOutputRate(value: unknown): void {
+ const providerRate = typeof value === "number" && value > 0 ? value : 24_000;
+ const contextRate = this.ctx?.sampleRate ?? 48_000;
+ this.playbackResampler = new StreamingPcm16Resampler(providerRate, contextRate);
+ }
+
+ private handleAudio(pcm: ArrayBuffer): void {
+ if (!this.playbackResampler) this.setOutputRate(24_000);
+ const converted = this.playbackResampler?.process(pcm) ?? pcm;
+ if (converted.byteLength === 0) return;
+ this.playbackNode?.port.postMessage({ type: "pcm", data: converted }, [converted]);
+ this.cb.onAudio?.();
}
async disconnect(): Promise<void> {
+ this.intentionalClose = true;
+ await this.teardown(true);
+ }
+
+ private async teardown(sendStop: boolean): Promise<void> {
+ const socket = this.ws;
+ this.ws = null;
+ this.ready = false;
+ if (sendStop && socket?.readyState === WebSocket.OPEN) {
+ try {
+ socket.send(JSON.stringify({ type: "audio_stop" }));
+ } catch {
+ // The socket may close between readyState and send.
+ }
+ }
+ socket?.close();
+ this.captureNode?.disconnect();
+ this.captureSink?.disconnect();
+ this.playbackNode?.disconnect();
+ this.stream?.getTracks().forEach((track) => track.stop());
try {
- this.ws?.send(JSON.stringify({ type: "audio_stop" }));
+ await this.ctx?.close();
} catch {
- // socket may already be closing
+ // Closing an already closed AudioContext is harmless.
}
- this.ws?.close();
- this.stream?.getTracks().forEach((t) => t.stop());
- await this.ctx?.close();
- this.ws = null;
+ this.captureNode = null;
+ this.captureSink = null;
+ this.playbackNode = null;
+ this.playbackResampler = null;
+ this.stream = null;
this.ctx = null;
}
}
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 45e28c99e2..7c4d3635b8 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -648,6 +648,9 @@ async def test_provider_connection(
),
latency_ms=_PROVIDER_TEST_HARD_TIMEOUT_S * 1000.0,
)
+ # This exact result is newer than any overlapping section sweep. Cancel the
+ # older snapshot so the UI refresh cannot resurrect a pre-test status.
+ _invalidate_section_health_state(request)
return ProviderTestResponse(
provider=result.provider,
status=result.status,
@@ -674,6 +677,15 @@ assert set(get_args(SectionHealthStatusLiteral)) == set(
# re-run the REAL connectivity tests on every render. ``?refresh=true`` (used by
# the UI after a key save / provider switch) bypasses it.
_SECTION_HEALTH_TTL_S = 45.0
+_SECTION_HEALTH_KEYS = (
+ "brain",
+ "computer-use",
+ "tts",
+ "stt",
+ "realtime",
+ "subagents",
+ "advanced",
+)
class SectionHealth(BaseModel):
@@ -687,6 +699,10 @@ class SectionHealth(BaseModel):
reason: str = "unknown"
# Plain-English one-liner for the hover tooltip (provider label + detail).
detail: str = ""
+ # Exact provider/integration this result belongs to. The frontend must never
+ # attach a result to a different active card, even while a slow probe from the
+ # previous selection is still completing.
+ subject_id: str | None = None
class SectionHealthResponse(BaseModel):
@@ -707,6 +723,7 @@ async def _tier_section_health(cfg: Any, spec: ProviderSpec | None) -> SectionHe
status=_section_health.NEEDS_SETUP,
reason="no_active",
detail="No active provider selected",
+ subject_id=None,
)
# Local providers (faster-whisper, SAPI) have no key to be invalid; if one is
# the active provider it is usable. Skip the real test — it could force a heavy
@@ -716,6 +733,7 @@ async def _tier_section_health(cfg: Any, spec: ProviderSpec | None) -> SectionHe
status=_section_health.OK,
reason="local",
detail=f"{spec.label}: local, no key needed",
+ subject_id=spec.id,
)
try:
configured = _is_credential_present(
@@ -728,19 +746,24 @@ async def _tier_section_health(cfg: Any, spec: ProviderSpec | None) -> SectionHe
status=_section_health.NEEDS_SETUP,
reason="not_configured",
detail=f"{spec.label}: no key set",
+ subject_id=spec.id,
)
try:
result = await _provider_test.run_provider_test(spec, cfg)
except Exception as exc: # noqa: BLE001
log.warning("section-health test for %s failed: %s", spec.id, exc)
return SectionHealth(
- status=_section_health.UNKNOWN, reason="error", detail=f"{spec.label}: check failed"
+ status=_section_health.UNKNOWN,
+ reason="error",
+ detail=f"{spec.label}: check failed",
+ subject_id=spec.id,
)
status = _section_health.section_status_for_test(result.status, configured=True)
return SectionHealth(
status=status,
reason=result.status,
detail=f"{spec.label}: {result.detail or result.status}",
+ subject_id=spec.id,
)
@@ -818,30 +841,33 @@ def _claude_worker_display_label(*, default: str) -> str:
return "Claude (subscription)" if oauth_status != "absent" else default
+def _selected_jarvis_agent_provider(cfg: Any) -> str | None:
+ """Return the exact provider selected for Jarvis-Agent work."""
+ brain = getattr(cfg, "brain", None) if cfg is not None else None
+ if brain is None:
+ return None
+ worker = getattr(brain, "worker", None)
+ provider = (getattr(worker, "provider", None) if worker else None) or getattr(
+ brain, "primary", None
+ )
+ return (provider or "").strip() or None
+
+
def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:
- """Subagents tab: reflects whether the SELECTED heavy-task worker is usable.
+ """Jarvis-Agents tab: report whether the selected worker is usable.
A real "does it answer" call for a CLI worker is heavy, so v1 reports the
connectedness signal — connected/keyed → ok, otherwise needs_setup. Since
2026-07-07 it distinguishes degraded (fallback carries) from error
(nothing reachable).
"""
- brain = getattr(cfg, "brain", None) if cfg is not None else None
- if brain is None:
+ provider = _selected_jarvis_agent_provider(cfg)
+ if provider is None:
return SectionHealth(
status=_section_health.NEEDS_SETUP,
reason="no_active",
- detail="No subagent worker selected",
- )
- sub = getattr(brain, "worker", None)
- provider = (getattr(sub, "provider", None) if sub else None) or getattr(
- brain, "primary", None
- )
- if not provider:
- return SectionHealth(
- status=_section_health.NEEDS_SETUP,
- reason="no_active",
- detail="No subagent worker selected",
+ detail="No Jarvis-Agent worker selected",
+ subject_id=None,
)
spec = get_spec(provider)
label = spec.label if spec is not None else provider
@@ -849,7 +875,10 @@ def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:
label = _claude_worker_display_label(default=label)
if _worker_usable(provider) and not _worker_flagged_dead(provider):
return SectionHealth(
- status=_section_health.OK, reason="ok", detail=f"Subagent worker: {label}"
+ status=_section_health.OK,
+ reason="ok",
+ detail=f"Jarvis-Agent worker: {label}",
+ subject_id=provider,
)
# The selected worker cannot run right now. Distinguish "a fallback
# family carries the missions" (amber) from "nothing is reachable —
@@ -865,29 +894,30 @@ def _jarvis_agent_section_health(cfg: Any) -> SectionHealth:
status=_section_health.NEEDS_SETUP,
reason="degraded",
detail=(
- f"Subagent worker '{label}' is unavailable — missions run on "
+ f"Jarvis-Agent worker '{label}' is unavailable — missions run on "
f"{families[0]} until it is reconnected"
),
+ subject_id=provider,
)
return SectionHealth(
status=_section_health.ERROR,
reason="no_provider",
detail=(
- f"No subagent provider is reachable — missions will fail. "
+ f"No Jarvis-Agent provider is reachable — missions will fail. "
f"Reconnect '{label}' or add an API key."
),
+ subject_id=provider,
)
-async def _realtime_section_health(request: Request) -> SectionHealth:
+async def _realtime_section_health(cfg: Any, spec: ProviderSpec | None) -> SectionHealth:
"""Test the active provider's actual duplex handshake.
Credential presence alone previously painted a depleted or schema-broken
provider green. Reuse the standard tier health mapping so the Realtime tab
reports the same honest account/integration states as every other tier.
"""
- cfg = _resolve_cfg(request)
- return await _tier_section_health(cfg, get_spec(_active_realtime(request) or ""))
+ return await _tier_section_health(cfg, spec)
def _advanced_section_health(request: Request) -> SectionHealth:
@@ -899,6 +929,7 @@ def _advanced_section_health(request: Request) -> SectionHealth:
detail = ""
reason = "unknown"
tm = getattr(request.app.state, "telephony_manager", None)
+ subject_id = "telephony" if tm is not None else None
if tm is not None and getattr(tm, "reachable", None) is False:
err = getattr(tm, "reachable_error", None)
if err:
@@ -906,99 +937,191 @@ def _advanced_section_health(request: Request) -> SectionHealth:
detail = f"Telephony unreachable: {err}"
reason = "telephony"
return SectionHealth(
- status=_section_health.aggregate(contributions), reason=reason, detail=detail
+ status=_section_health.aggregate(contributions),
+ reason=reason,
+ detail=detail,
+ subject_id=subject_id,
)
+def _section_health_subjects(request: Request, cfg: Any) -> dict[str, str | None]:
+ """Capture the exact runtime selection behind every health section."""
+ telephony = getattr(request.app.state, "telephony_manager", None)
+ return {
+ "brain": _active_brain(request),
+ "computer-use": _active_computer_use(request),
+ "tts": _active_tts(request),
+ "stt": _active_stt(request),
+ "realtime": _active_realtime(request),
+ "subagents": _selected_jarvis_agent_provider(cfg),
+ "advanced": "telephony" if telephony is not None else None,
+ }
+
+
+def _section_health_fingerprint(
+ request: Request, subjects: dict[str, str | None]
+) -> tuple[tuple[str, str], ...]:
+ """Return a secret-free cache key for the full health selection snapshot."""
+ 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) + (
+ ("advanced-reachable", repr(reachable)),
+ )
+
+
+def _invalidate_section_health_state(request: Request) -> None:
+ """Discard cached and in-flight health work after a configuration change."""
+ request.app.state._section_health_cache = None
+ tasks = getattr(request.app.state, "_section_health_tasks", None)
+ if not isinstance(tasks, dict):
+ return
+ for task in tuple(tasks.values()):
+ if isinstance(task, asyncio.Task) and not task.done():
+ task.cancel()
+ tasks.clear()
+
+
@router.get("/providers/section-health")
async def section_health(request: Request, refresh: bool = False) -> SectionHealthResponse:
"""Per-tab health for the API-Keys segmented tabs ("is this part working?").
- The brain/tts/stt tiers get a REAL connectivity test of their active provider
- (run in parallel), the Subagents tab reflects whether the selected worker is
- connected, and the Advanced tab only flags a configured optional integration
- that is actually failing. The result is cached for a few seconds so opening the
- page / switching tabs does not re-run the real calls each render;
- ``?refresh=true`` forces a fresh check after a key save or provider switch.
+ Every selectable provider surface is checked against one immutable selection
+ snapshot. Cache entries and in-flight tasks carry that snapshot fingerprint,
+ so a slow result from a previous provider can never be reused for the current
+ one. Checks for a superseded snapshot are cancelled without blocking the new
+ provider's check.
"""
- cache = getattr(request.app.state, "_section_health_cache", None)
- now = time.time()
- if (
- not refresh
- and isinstance(cache, dict)
- and now - cache.get("checked_at", 0.0) < _SECTION_HEALTH_TTL_S
- ):
- return SectionHealthResponse(
- sections=cache["payload"], checked_at=cache["checked_at"], cached=True
- )
-
- # Coalesce concurrent (re)checks: a provider switch fires several UI events in
- # a burst, each of which used to launch its OWN full sweep of REAL provider
- # tests — a multi-second storm that made the whole screen feel broken. Requests
- # arriving while one sweep runs wait for it and reuse its result — a waiting
- # ?refresh=true only reuses a sweep that FINISHED while it waited (so an
- # explicit refresh still always reflects a check started after the request,
- # the contract the UI relies on after a key save / provider switch).
- entered = time.time()
- lock = getattr(request.app.state, "_section_health_refresh_lock", None)
- if lock is None:
- lock = asyncio.Lock()
- request.app.state._section_health_refresh_lock = lock
- async with lock:
+ while True:
+ cfg = _resolve_cfg(request)
+ subjects = _section_health_subjects(request, cfg)
+ fingerprint = _section_health_fingerprint(request, subjects)
cache = getattr(request.app.state, "_section_health_cache", None)
- checked_at = cache.get("checked_at", 0.0) if isinstance(cache, dict) else 0.0
now = time.time()
- fresh_enough = (
- checked_at >= entered if refresh else now - checked_at < _SECTION_HEALTH_TTL_S
- )
- if isinstance(cache, dict) and fresh_enough:
+ if (
+ not refresh
+ and isinstance(cache, dict)
+ and cache.get("fingerprint") == fingerprint
+ and now - cache.get("checked_at", 0.0) < _SECTION_HEALTH_TTL_S
+ ):
return SectionHealthResponse(
- sections=cache["payload"], checked_at=checked_at, cached=True
+ sections=cache["payload"],
+ checked_at=cache["checked_at"],
+ cached=True,
)
- return await _compute_section_health(request, now)
+ lock = getattr(request.app.state, "_section_health_task_lock", None)
+ if lock is None:
+ lock = asyncio.Lock()
+ request.app.state._section_health_task_lock = lock
+
+ async with lock:
+ tasks = getattr(request.app.state, "_section_health_tasks", None)
+ if not isinstance(tasks, dict):
+ tasks = {}
+ request.app.state._section_health_tasks = tasks
+
+ # A globally selected provider changed. Its previous task is obsolete
+ # and must not hold the new provider behind a 60-second timeout.
+ for old_fingerprint, old_task in tuple(tasks.items()):
+ if old_fingerprint == fingerprint:
+ continue
+ if isinstance(old_task, asyncio.Task) and not old_task.done():
+ old_task.cancel()
+ tasks.pop(old_fingerprint, None)
+
+ task = tasks.get(fingerprint)
+ if not isinstance(task, asyncio.Task) or task.done():
+ task = asyncio.create_task(
+ _compute_section_health(request, cfg, subjects),
+ name="section-health-snapshot",
+ )
+ tasks[fingerprint] = task
-async def _compute_section_health(request: Request, now: float) -> SectionHealthResponse:
- """One full sweep of the per-tab health checks (called under the refresh lock)."""
- cfg = _resolve_cfg(request)
+ try:
+ sections = await asyncio.shield(task)
+ except asyncio.CancelledError:
+ # ``shield`` distinguishes an obsolete shared task from cancellation
+ # of this HTTP request. Retry only the former against the new snapshot.
+ if task.cancelled():
+ refresh = True
+ continue
+ raise
+
+ current_cfg = _resolve_cfg(request)
+ current_subjects = _section_health_subjects(request, current_cfg)
+ current_fingerprint = _section_health_fingerprint(request, current_subjects)
+ if current_fingerprint != fingerprint:
+ refresh = True
+ continue
+
+ checked_at = time.time()
+ request.app.state._section_health_cache = {
+ "checked_at": checked_at,
+ "fingerprint": fingerprint,
+ "payload": sections,
+ }
+ async with lock:
+ tasks = getattr(request.app.state, "_section_health_tasks", None)
+ if isinstance(tasks, dict) and tasks.get(fingerprint) is task:
+ tasks.pop(fingerprint, None)
+ return SectionHealthResponse(
+ sections=sections,
+ checked_at=checked_at,
+ cached=False,
+ )
+
+
+async def _compute_section_health(
+ request: Request,
+ cfg: Any,
+ subjects: dict[str, str | None],
+) -> dict[str, SectionHealth]:
+ """Compute one immutable, provider-bound health snapshot."""
sections: dict[str, SectionHealth] = {}
if cfg is None:
- for key in ("brain", "tts", "stt", "realtime", "subagents", "advanced"):
+ for key in _SECTION_HEALTH_KEYS:
sections[key] = SectionHealth(
status=_section_health.UNKNOWN,
reason="unavailable",
detail="Configuration unavailable",
+ subject_id=subjects.get(key),
)
- else:
- brain_spec = get_spec(_active_brain(request) or "")
- tts_spec = get_spec(_active_tts(request) or "")
- stt_spec = get_spec(_active_stt(request) or "")
- sections["brain"], sections["tts"], sections["stt"] = await asyncio.gather(
- _tier_section_health(cfg, brain_spec),
- _tier_section_health(cfg, tts_spec),
- _tier_section_health(cfg, stt_spec),
- )
- # Realtime performs an async duplex handshake. The remaining helpers are
- # synchronous (keyring reads, CLI status subprocesses) and stay off-loop.
- try:
- sections["realtime"] = await _realtime_section_health(request)
- except Exception as exc: # noqa: BLE001
- log.warning("section-health realtime check failed: %s", exc)
- sections["realtime"] = SectionHealth()
- try:
- sections["subagents"] = await asyncio.to_thread(_jarvis_agent_section_health, cfg)
- except Exception as exc: # noqa: BLE001
- log.warning("section-health subagent check failed: %s", exc)
- sections["subagents"] = SectionHealth()
+ return sections
+
+ async def _safe_check(
+ section: str,
+ check: Any,
+ ) -> SectionHealth:
try:
- sections["advanced"] = await asyncio.to_thread(_advanced_section_health, request)
+ return await check
except Exception as exc: # noqa: BLE001
- log.warning("section-health advanced check failed: %s", exc)
- sections["advanced"] = SectionHealth()
+ log.warning("section-health %s check failed: %s", section, exc)
+ return SectionHealth(
+ status=_section_health.UNKNOWN,
+ reason="error",
+ detail="Health check failed",
+ subject_id=subjects.get(section),
+ )
- request.app.state._section_health_cache = {"checked_at": now, "payload": sections}
- return SectionHealthResponse(sections=sections, checked_at=now, cached=False)
+ checks = {
+ "brain": _tier_section_health(cfg, get_spec(subjects["brain"] or "")),
+ "computer-use": _tier_section_health(
+ cfg, get_spec(subjects["computer-use"] or "")
+ ),
+ "tts": _tier_section_health(cfg, get_spec(subjects["tts"] or "")),
+ "stt": _tier_section_health(cfg, get_spec(subjects["stt"] or "")),
+ "realtime": _realtime_section_health(
+ cfg, get_spec(subjects["realtime"] or "")
+ ),
+ "subagents": asyncio.to_thread(_jarvis_agent_section_health, cfg),
+ "advanced": asyncio.to_thread(_advanced_section_health, request),
+ }
+ results = await asyncio.gather(
+ *(_safe_check(section, check) for section, check in checks.items())
+ )
+ sections.update(zip(checks, results, strict=True))
+ return sections
# ----------------------------------------------------------------------
@@ -1242,6 +1365,7 @@ async def _apply_brain_model(
request,
SecretConfigured(key=f"brain.providers.{provider_id}.model", action="set"),
)
+ _invalidate_section_health_state(request)
return BrainModelSaveResponse(
ok=True, provider=provider_id, model=model, persisted=persisted,
applied_live=applied_live, restart_required=restart_required, probe=probe_payload,
@@ -1308,6 +1432,7 @@ def _apply_tts_selection(
except Exception as exc: # noqa: BLE001
log.error("TTS live re-apply for %s failed: %s", provider_id, exc, exc_info=True)
+ _invalidate_section_health_state(request)
return BrainModelSaveResponse(
ok=True, provider=provider_id, model=value, persisted=persisted,
applied_live=applied_live, restart_required=not applied_live, probe=None,
@@ -1339,6 +1464,7 @@ def _apply_stt_model(
except Exception as exc: # noqa: BLE001
log.debug("In-memory stt model update skipped: %s", exc)
+ _invalidate_section_health_state(request)
return BrainModelSaveResponse(
ok=True, provider=provider_id, model=value, persisted=persisted,
applied_live=False, restart_required=True, probe=None,
@@ -1436,6 +1562,7 @@ async def set_cu_model(
SecretConfigured(key=f"brain.providers.{provider_id}.cu_model", action="set"),
)
effective = value or _current_brain_model(cfg, provider_id)
+ _invalidate_section_health_state(request)
return CuModelResponse(
ok=True,
provider=provider_id,
@@ -1562,6 +1689,7 @@ async def set_realtime_options(
SecretConfigured(key=f"brain.providers.{provider_id}", action="set"),
)
current_model, current_voice = _current_realtime_selection(cfg, provider_id)
+ _invalidate_section_health_state(request)
return RealtimeOptionsSaveResponse(
ok=True,
provider=provider_id,
@@ -1650,6 +1778,7 @@ async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict
if not cfg_mod.set_secret(key, body.value):
raise HTTPException(status_code=500, detail="Keyring-Write fehlgeschlagen")
await _emit(request, SecretConfigured(key=key, action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"key": key,
@@ -1663,6 +1792,7 @@ async def delete_secret_value(key: str, request: Request) -> dict[str, Any]:
raise HTTPException(status_code=404, detail=f"Unbekannter Secret-Key: {key}")
cfg_mod.delete_secret(key) # idempotent — wirft nicht wenn nicht vorhanden
await _emit(request, SecretConfigured(key=key, action="delete"))
+ _invalidate_section_health_state(request)
return {"ok": True, "key": key}
@@ -1773,6 +1903,7 @@ async def brain_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
"the choice will not survive a restart.",
body.provider,
)
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": result.get("new_provider", body.provider),
@@ -1868,6 +1999,7 @@ async def tts_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
await _emit(request, SecretConfigured(key="tts.provider", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": body.provider,
@@ -2170,6 +2302,7 @@ async def stt_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
await _emit(request, SecretConfigured(key="stt.provider", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": body.provider,
@@ -2248,6 +2381,7 @@ async def realtime_switch(body: SwitchBody, request: Request) -> dict[str, Any]:
await _emit(request, SecretConfigured(key="brain.realtime.provider", action="set"))
await _emit(request, SecretConfigured(key="voice.mode", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": body.provider,
@@ -2327,6 +2461,7 @@ async def computer_use_switch(body: SwitchBody, request: Request) -> dict[str, A
request, SecretConfigured(key="brain.computer_use.provider", action="set")
)
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": body.provider,
@@ -2402,6 +2537,7 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
) from exc
_apply_worker_in_memory(request, _CODEX_SUBAGENT_CANONICAL)
await _emit(request, SecretConfigured(key="brain.worker.provider", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": _CODEX_SUBAGENT_CANONICAL,
@@ -2450,6 +2586,7 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
) from exc
_apply_worker_in_memory(request, ANTIGRAVITY_SUBAGENT_CANONICAL)
await _emit(request, SecretConfigured(key="brain.worker.provider", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": ANTIGRAVITY_SUBAGENT_CANONICAL,
@@ -2510,6 +2647,7 @@ async def jarvis_agent_switch(body: SwitchBody, request: Request) -> dict[str, A
await _emit(request, SecretConfigured(key="brain.worker.provider", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"active": provider,
@@ -2564,6 +2702,7 @@ async def jarvis_agent_model(body: SubagentModelBody, request: Request) -> dict[
await _emit(request, SecretConfigured(key="brain.worker.model", action="set"))
+ _invalidate_section_health_state(request)
return {
"ok": True,
"model": model,
diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.py
index 8468fd673c..5b3720ca6f 100644
--- a/tests/integration/test_provider_routes.py
+++ b/tests/integration/test_provider_routes.py
@@ -5,7 +5,9 @@ The tests run hermetically, without writing real credentials.
"""
from __future__ import annotations
+import asyncio
from collections.abc import Iterator
+from types import SimpleNamespace
from typing import Any
import pytest
@@ -165,12 +167,24 @@ def test_section_health_returns_all_tabs(
assert resp.status_code == 200
body = resp.json()
assert set(body["sections"]) == {
- "brain", "tts", "stt", "realtime", "subagents", "advanced",
+ "brain",
+ "computer-use",
+ "tts",
+ "stt",
+ "realtime",
+ "subagents",
+ "advanced",
}
valid = {"ok", "needs_setup", "error", "unknown"}
for sec in body["sections"].values():
assert sec["status"] in valid
assert body["cached"] is False
+ assert body["sections"]["brain"]["subject_id"] == "openai"
+ expected_cu = (
+ server_with_brain.cfg.brain.computer_use.provider
+ or server_with_brain.cfg.brain.primary
+ )
+ assert body["sections"]["computer-use"]["subject_id"] == expected_cu
# No telephony manager mounted → the optional Advanced tab stays silent.
assert body["sections"]["advanced"]["status"] == "unknown"
@@ -205,6 +219,60 @@ def test_section_health_caches_then_refresh_bypasses(
)
+async def test_section_health_switch_cancels_old_provider_without_misattribution(
+ server_with_brain: WebServer,
+ secret_store: _InMemorySecretStore,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A slow NVIDIA result must never block or label the new OpenRouter card."""
+ from jarvis.brain import provider_test as provider_test_module
+ from jarvis.ui.web import provider_routes
+
+ secret_store.data.update(
+ {
+ "nvidia_api_key": "nvapi-test",
+ "openrouter_api_key": "sk-or-test",
+ }
+ )
+ server_with_brain.app.state.brain.active_provider = "nvidia"
+ nvidia_started = asyncio.Event()
+ nvidia_cancelled = asyncio.Event()
+
+ async def _probe(spec: Any, cfg: Any) -> _FakeTestResult: # noqa: ANN401
+ if spec.id == "nvidia":
+ nvidia_started.set()
+ try:
+ await asyncio.Future()
+ except asyncio.CancelledError:
+ nvidia_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(nvidia_started.wait(), timeout=1.0)
+
+ server_with_brain.app.state.brain.active_provider = "openrouter"
+ 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 nvidia_cancelled.is_set()
+ assert new_response.sections["brain"].subject_id == "openrouter"
+ assert new_response.sections["brain"].status == "ok"
+ assert old_response.sections["brain"].subject_id == "openrouter"
+ assert "NVIDIA" not in old_response.sections["brain"].detail
+
+
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.py
index a7b36f4a43..8e3aec091d 100644
--- a/tests/unit/brain/test_section_health.py
+++ b/tests/unit/brain/test_section_health.py
@@ -7,10 +7,13 @@ we only pin the rules so the tab indicator can never silently change meaning.
"""
from __future__ import annotations
+from types import SimpleNamespace
+
import pytest
from jarvis.brain import provider_test
from jarvis.brain import section_health as sh
+from jarvis.ui.web.provider_spec import PROVIDERS
class TestSectionStatusForTest:
@@ -72,6 +75,27 @@ def test_vocabulary_is_exactly_four() -> None:
assert len(sh.SECTION_HEALTH_STATUSES) == 4
[email protected]("spec", PROVIDERS, ids=lambda spec: spec.id)
+async def test_every_catalog_provider_health_is_bound_to_its_exact_id(
+ spec, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The generic guard covers every Brain, TTS, STT, and Realtime card."""
+ from jarvis.ui.web import provider_routes
+
+ monkeypatch.setattr(provider_routes, "_is_credential_present", lambda *args: True)
+
+ async def _probe(selected, cfg):
+ return SimpleNamespace(status="ok", detail="")
+
+ monkeypatch.setattr(provider_test, "run_provider_test", _probe)
+
+ result = await provider_routes._tier_section_health(SimpleNamespace(), spec)
+
+ assert result.status == sh.OK
+ assert result.subject_id == spec.id
+
+
class TestSubagentSectionHealth:
"""Live-honest Sub-Agents tab health (2026-07-06 incident: the tab stayed
green while every worker spawn 401'd on an expired OAuth token)."""
@@ -99,6 +123,7 @@ class TestSubagentSectionHealth:
monkeypatch.setattr(pr, "_worker_flagged_dead", lambda p: False)
health = pr._jarvis_agent_section_health(self._cfg())
assert health.status == sh.OK
+ assert health.subject_id == "claude-api"
def test_selected_dead_with_fallback_is_needs_setup(self, monkeypatch) -> None:
from jarvis.ui.web import provider_routes as pr
@@ -144,6 +169,7 @@ class TestSubagentSectionHealth:
health = pr._jarvis_agent_section_health(self._cfg())
assert health.status == sh.ERROR
assert health.reason == "no_provider"
+ assert health.subject_id == "claude-api"
def test_degraded_label_says_subscription_for_oauth_user(
self, monkeypatch, tmp_path
diff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.py
index 7454dba43c..07938a5510 100644
--- a/tests/unit/browser_voice/test_route.py
+++ b/tests/unit/browser_voice/test_route.py
@@ -11,6 +11,7 @@ from types import SimpleNamespace
from fastapi import WebSocketDisconnect
+import jarvis.browser_voice.route as route_mod
from jarvis.browser_voice.route import browser_voice_ws
@@ -121,3 +122,37 @@ async def test_route_breaks_on_runtimeerror():
ws = _RaisingWS([], state=_state(rec))
await browser_voice_ws(ws)
assert rec.ended
+
+
+async def test_realtime_handshake_failure_crosses_to_classic_browser_pipeline(
+ monkeypatch,
+):
+ classic = _RecSession()
+
+ class _FailedRealtime(_RecSession):
+ is_realtime = True
+
+ async def handle_control(self, msg: dict) -> None:
+ raise RuntimeError("simulated duplex handshake failure")
+
+ failed = _FailedRealtime()
+ state = _state(classic)
+ state.config.voice = SimpleNamespace(mode="realtime")
+ monkeypatch.setattr(route_mod, "_build_browser_session", lambda **_kwargs: failed)
+ ws = _FakeWS(
+ [
+ {
+ "type": "websocket.receive",
+ "text": '{"type":"audio_start","sample_rate":48000}',
+ },
+ {"type": "websocket.disconnect", "code": 1000},
+ ],
+ state=state,
+ )
+
+ await browser_voice_ws(ws)
+
+ assert failed.ended
+ assert classic.controls == [{"type": "audio_start", "sample_rate": 48_000}]
+ assert classic.ended
+ assert {"type": "mode_fallback", "mode": "pipeline"} in ws.sent_json
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index f6cefc6574..1a05a76a0e 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -196,7 +196,7 @@ async def test_clean_turn_streams_audio_and_transcript():
bus=None,
)
await sess.handle_control({"type": "audio_start", "sample_rate": 16000})
- await asyncio.sleep(0.05) # let the receive pump drain the fake events
+ await sess.wait_finished()
await sess.end(reason="test")
assert any(m.get("type") == "transcript" for m in jsons)
assert binaries # audio was released after the clean transcript
@@ -225,7 +225,7 @@ async def test_hard_leak_transcript_drops_audio():
bus=None,
)
await sess.handle_control({"type": "audio_start", "sample_rate": 16000})
- await asyncio.sleep(0.05)
+ await sess.wait_finished()
await sess.end(reason="test")
# The pre-leak audio was buffered, then dropped when the leak transcript arrived.
assert binaries == []
@@ -265,7 +265,7 @@ async def test_later_segment_leak_audio_not_emitted():
bus=None,
)
await sess.handle_control({"type": "audio_start", "sample_rate": 16000})
- await asyncio.sleep(0.05)
+ await sess.wait_finished()
await sess.end(reason="test")
assert a1 in binaries
assert a2 not in binaries