Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(voice): serve the classic browser voice bridge and start it on headless hosts (#400)
Ruben Lütke9c60b6e92562
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 4f11de4664..3b579c1782 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -16019,3 +16019,34 @@ real Tk root and Toplevel: 0x11 after the first map and after withdraw/show.Side effect: the overlays also vanish from other capture tools (ShareX, OBS),which is the documented intent of the module. Guard:`tests/unit/platform/test_capture_exclusion.py`.++## BUG-231: browser voice could not start on a headless host, in any voice mode (HIGH, FIXED 2026-10-05)++**Symptom.** On `jarvis serve` (a VPS, `JARVIS_VOICE=0`) typed chat worked,+but the documented browser-voice path never opened `/ws/audio`. Every Start+button answered "Voice is not running on this computer", and in pipeline mode+a `[browser_voice] enabled = true` table changed nothing (GitHub issue #399).++**Cause.** Three links were missing. (1) `[browser_voice]` was never a+`JarvisConfig` field, so `load_config` dropped the table; the connect gate,+inverted to default-off on 2026-07-08 (`0a4d541b4`), therefore kept+`/ws/audio` closed in pipeline mode for everyone. (2) Every Start button posts+`/api/voice/call`, which needs the desktop speech pipeline a headless host+never has; the only browser-side start was the desktop's realtime hand-over+(`BrowserVoiceRequested`). (3) The visible browser-microphone card that could+start a call itself left the sidebar on 2026-09-12 (`51b4d4015`). The issue's+note that Gemini Live lacks browser audio is not the cause: the provider+declares it; `browser_audio` in `/api/settings/voice-mode` reads only an+explicitly pinned realtime provider.++**Fix.** `BrowserVoiceConfig(enabled=True)` is now `JarvisConfig.browser_voice`;+`browser_voice_enabled(cfg)` serves the classic bridge in pipeline mode by+default and realtime mode always. `GET /api/voice/state` reports+`browser_call` when no speech pipeline and no desktop shell exist. On a 503+from `/api/voice/call`, `useVoiceCall` reads that flag and lets+`BrowserRealtimeControl` hold the call in this browser+(`lib/browserVoiceCall.ts`); the voice-state resync leaves such a call alone.+Guards: `tests/unit/web/test_voice_mode_route.py`,+`tests/unit/browser_voice/test_route.py`,+`tests/unit/ui/test_voice_call_routes.py`, `useVoiceCall.test.tsx`,+`BrowserRealtimeControl.test.tsx`.diff --git a/docs/headless-vps-deployment.md b/docs/headless-vps-deployment.mdindex 8e77982d3a..cf7134883b 100644--- a/docs/headless-vps-deployment.md+++ b/docs/headless-vps-deployment.md@@ -166,15 +166,33 @@ port. The tunnel is simpler and is what most people should use.The server has no microphone. The browser voice bridge is how you talk to it:your browser captures the audio, streams it to `/ws/audio` over the WebSocket,-and the server runs speech-to-text, the brain and text-to-speech.+and the server answers according to your voice mode:-It is on by default (`[browser_voice] enabled`). Open the UI, allow the-microphone when the browser asks, and talk.+- **Realtime mode** (the default): a realtime provider answers when one is set+ up. Without one, the same speech-to-text → brain → text-to-speech chain as+ pipeline mode does.+- **Pipeline mode** (`[voice] mode = "pipeline"`): the server runs your+ configured speech-to-text, the brain and text-to-speech.++It is on by default. Open the UI, switch the front page to voice mode, press+**Start**, allow the microphone when the browser asks, and talk. **Stop** ends+the call. The browser that pressed Start holds the call, so close that tab and+the call ends with it.++To switch the pipeline-mode bridge off, add this to `jarvis.toml`:++```toml+[browser_voice]+enabled = false+```++Realtime mode keeps the socket open either way, because the realtime call runs+over it.**The one thing that will trip you up:** browsers only hand out a microphone ina *secure context* — HTTPS, or `localhost`. Over `http://your-vps-ip:47821`-your browser will silently refuse, and the UI will look like the microphone is-broken when the browser never granted it.+your browser refuses the microphone, and Jarvis shows "Browser voice requires+HTTPS (or localhost)" instead of starting the call.Two ways out, and the first is easier:diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 8711a312eb..071fa3a734 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1063,12 +1063,12 @@ implementations, not stubs.| Computer-Use / desktop actions (click, type, hotkey, scroll, drag, windows, apps, screenshots, UI trees) | Full per-OS backends (Win32/UIA, Quartz/AX, xdotool/AT-SPI); honest degradation on Wayland/headless/missing TCC grants. macOS: Accessibility is asked when Jarvis first types, clicks or focuses a window, Screen Recording at the first user-started capture; AX reads never prompt, and nothing is asked at launch || On-demand Screen Context | One-shot capture is wired into the production brain on Windows, macOS, and Linux/X11; UIA/AX/AT-SPI text is source-filtered, the indicator precedes capture, and Wayland/headless/missing grants refuse honestly (on macOS a flat wallpaper-only frame is refused, never delivered) || Appshots (front-window capture on a shortcut, button or request) | Capture, privacy and delivery are OS-neutral (Screen Context engine, `jarvis/appshot`). The two-sided shortcuts (both Alt, both Shift, both Ctrl) read key state per OS: Windows `GetAsyncKeyState`, macOS `CGEventSourceKeyState` (whether this read needs the Input Monitoring grant is UNVERIFIED; the repo contradicts itself and no Mac measured it, so it is not an Input Monitoring row — see `docs/macos-permissions.md`), Linux/X11 `XQueryKeymap`; Wayland/headless report it unavailable on the Appshots page. The flash and the area picker (both Shift keys, drag a rectangle) are PySide6 overlays where one can run; Wayland/headless report the area picker unavailable. Verified live on Windows only; see `docs/appshots.md` |-| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; headless disables voice honestly; WASAPI logic is inert-by-data off Windows. macOS microphone: asked at the first dictation, push-to-talk, voice session, wake-word switch or mic self-test, never at launch (2026-10-02 pass) |+| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; a headless host has no local voice stack, so the browser that presses Start holds the call over `/ws/audio` (realtime, or the classic STT → brain → TTS bridge while `[browser_voice].enabled`, the default — issue #399); WASAPI logic is inert-by-data off Windows. macOS microphone: asked at the first dictation, push-to-talk, voice session, wake-word switch or mic self-test, never at launch (2026-10-02 pass) || macOS privacy permissions (TCC) | One just-in-time service (`jarvis/platform/permission_service.py`, AP-35, ADR-0038): `check` is silent, `ensure` asks only from a user gesture and only from the installed app (or after a confirmation naming the grantee); Windows and Linux return NOT_REQUIRED before touching anything. The app draws nothing around macOS's dialog; after a denied user-started use it shows one toast with one action. Verified against fake frameworks and runner packaging probes only, not on a physical Mac (`docs/macos-permissions.md` section 7) || Computer-Use / desktop actions (click, type, hotkey, scroll, drag, windows, apps, screenshots, UI trees) | Full per-OS backends (Win32/UIA, Quartz/AX, xdotool/AT-SPI); honest degradation on Wayland/headless/missing TCC grants || On-demand Screen Context | One-shot capture is wired into the production brain on Windows, macOS, and Linux/X11; UIA/AX/AT-SPI text is source-filtered, the indicator precedes capture, and Wayland/headless/missing grants refuse honestly || Appshots (front-window capture on a shortcut, button or request) | Capture, privacy and delivery are OS-neutral (Screen Context engine, `jarvis/appshot`). The two-sided shortcuts (both Alt, both Shift, both Ctrl) read key state per OS: Windows `GetAsyncKeyState`, macOS `CGEventSourceKeyState` (Input Monitoring grant), Linux/X11 `XQueryKeymap`; Wayland/headless report it unavailable on the Appshots page. The flash and the area picker (both Shift keys, drag a rectangle, then mark it up with its toolbar) are PySide6 overlays where one can run; the markings are burnt into the capture with Pillow on every OS (`jarvis/appshot/markup.py`); Wayland/headless report the area picker unavailable. The appshot editor is web code and behaves the same everywhere; its Copy writes the PNG natively (`jarvis/platform/clipboard_image.py`): Windows `CF_DIB` + the registered PNG format, macOS `osascript` as `«class PNGf»`, Linux `wl-copy` or `xclip`, and with neither the browser clipboard. Save goes to `~/Downloads` on every OS. Verified live on Windows only; see `docs/appshots.md` |-| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; headless disables voice honestly; WASAPI logic is inert-by-data off Windows |+| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; a headless host has no local voice stack, so the browser that presses Start holds the call over `/ws/audio` (realtime, or the classic STT → brain → TTS bridge while `[browser_voice].enabled`, the default — issue #399); WASAPI logic is inert-by-data off Windows || Core (launcher, config, keyring, restart, autostart, tray, elevation, paths) | Clean; per-OS autostart (Registry / LaunchAgent / XDG `.desktop`), keyring falls back to a 0600 file on headless hosts || Data / agents (wiki, contacts, telephony, sessions, missions, skills, self-mod, channels, MCP) | Clean; mission workers run on POSIX with a real process-group reaper || Agent society hands (own shell, browser via browser-use, learned skills) | Shell: local subprocess in the agent's workspace on every OS (Git Bash/PowerShell/bash/sh pick as the chat's folder tools), no container by decision. Browser: browser-use lives in a managed venv under the data dir (its pins collide with the app's), installed on demand — `uv`/`venv`, a 3.11–3.13 interpreter preferred, Chromium downloaded once; headless runs need no display, so a headless Linux box runs agents' browsers; the headed login session needs a display (409 without one is the follow-up); attach mode needs a running Chrome with `--remote-debugging-port`. Learning is pure files + the brain, OS-neutral |diff --git a/jarvis.toml.example b/jarvis.toml.exampleindex d1e2f91bd3..231a176219 100644--- a/jarvis.toml.example+++ b/jarvis.toml.example@@ -183,6 +183,13 @@ output_device = "auto"echo_cancellation = true # requested; raw PortAudio reports unavailable honestlysample_rate = 16000 # mandatory 16 kHz (AP-L-16)+# ── Browser voice (hosts without a microphone: a VPS, `jarvis serve`) ──+# The browser that presses Start holds the call over /ws/audio. Realtime mode+# always serves it; this switch covers the classic speech-to-text -> brain ->+# text-to-speech bridge in pipeline mode. See docs/headless-vps-deployment.md.+[browser_voice]+enabled = true+# ── UI / tray ──[ui]tray_enabled = truediff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex f19c19df02..c90af00add 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -47,20 +47,28 @@ _USAGE_FALLBACK_DISABLED_DETAIL = ("model settings. Automatic usage-billed API fallback is disabled; ""Jarvis did not switch to another provider.")+# The close reason a browser shows the person when the classic chain cannot be+# built. WebSocket close reasons are capped at 123 bytes.+_SPEECH_STACK_UNAVAILABLE_REASON = (+ "Voice could not start: a speech-to-text, brain or text-to-speech "+ "provider is missing. Check API Keys."+)# BCP-47 from the canonical per-turn resolver (de/en/es)._LANG_MAP = {"de": "de-DE", "en": "en-US", "es": "es-ES"}-def _browser_voice_enabled(cfg: Any) -> bool:- """Default OFF. The socket is only served when the user has explicitly- enabled a browser voice surface: realtime mode ([voice].mode == "realtime")- or the classic browser bridge ([browser_voice].enabled == true).+def browser_voice_enabled(cfg: Any) -> bool:+ """Whether ``/ws/audio`` serves a browser-held call under this config.++ Realtime mode always serves it: the socket carries the realtime call and+ its classic fallback. Pipeline mode serves the classic STT -> brain -> TTS+ bridge while ``[browser_voice].enabled`` is on, which is the default — a+ config object without the section behaves like the schema default."""if getattr(getattr(cfg, "voice", None), "mode", "pipeline") == "realtime":return True- bv = getattr(cfg, "browser_voice", None)- return bool(getattr(bv, "enabled", False)) if bv is not None else False+ return bool(getattr(getattr(cfg, "browser_voice", None), "enabled", True))def _resolve_language(cfg: Any) -> str:@@ -441,7 +449,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:except Exception: # noqa: BLE001 - Config failure degrades to unavailable voice.cfg = None- if cfg is not None and not _browser_voice_enabled(cfg):+ if cfg is not None and not browser_voice_enabled(cfg):await ws.close(code=1008, reason="browser voice disabled")return@@ -487,7 +495,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:reason = ("realtime access unavailable"if not _automatic_usage_fallback_allowed(cfg)- else "speech stack unavailable"+ else _SPEECH_STACK_UNAVAILABLE_REASON)await ws.close(code=1011, reason=reason)return@@ -559,7 +567,7 @@ async def browser_voice_ws(ws: WebSocket) -> None:send_json=output.send_json,)if fallback is None:- await ws.close(code=1011, reason="speech stack unavailable")+ await ws.close(code=1011, reason=_SPEECH_STACK_UNAVAILABLE_REASON)return Falsesession = fallbackawait _send_json({"type": "mode_fallback", "mode": "pipeline"})diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 5ff935c192..0bf2204c5a 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3359,6 +3359,27 @@ class VoiceConfig(BaseModel):no_first_frame_phrase_floor_s: float | None = None+class BrowserVoiceConfig(BaseModel):+ """``[browser_voice]`` — the browser-microphone voice bridge (``/ws/audio``).++ On a host without its own microphone (a VPS, ``jarvis serve``) the browser+ that presses Start holds the call: it streams the microphone to+ ``/ws/audio`` and plays the reply. ``extra="allow"`` so an unknown future+ key never blocks boot (AP-16).+ """++ model_config = ConfigDict(extra="allow")++ # Serves the classic STT -> brain -> TTS bridge in PIPELINE mode. Realtime+ # mode always serves the socket, because it carries the realtime call and+ # that call's classic fallback, so this switch does not apply there. Read+ # by ``jarvis.browser_voice.route.browser_voice_enabled`` at connect time.+ # Default on: before 2026-07-08 a missing section meant enabled, the+ # headless deployment guide documents it as on, and the socket is behind+ # the same credential check as every other route (issue #399).+ enabled: bool = True++class CompletenessConfig(BaseModel):"""Configuration for the utterance-completeness pre-processing classifier.@@ -4669,6 +4690,9 @@ class JarvisConfig(BaseModel):# Voice-flow knobs (incomplete-prompt completion buffer settings).# Spec: docs/superpowers/specs/2026-05-25-incomplete-prompt-completion-design.mdvoice: VoiceConfig = Field(default_factory=VoiceConfig)+ # [browser_voice] — the browser-microphone bridge for hosts without a+ # microphone of their own (see BrowserVoiceConfig).+ browser_voice: BrowserVoiceConfig = Field(default_factory=BrowserVoiceConfig)# AI Pointer — deictic-gated "what is under the mouse cursor" context.# Spec: docs/plans/ai-pointer/DESIGN.mdpointer: PointerConfig = Field(default_factory=PointerConfig)diff --git a/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.test.tsxnew file mode 100644index 0000000000..1d2eb065df--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.test.tsx@@ -0,0 +1,127 @@+/**+ * The one start/stop path every voice surface shares. A start always asks the+ * host first; only a host with no speech pipeline at all (a VPS, `jarvis+ * serve`) that says so hands the call to this browser (issue #399).+ */+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useEventStore } from "@/store/events";+import { useVoiceCall } from "./useVoiceCall";++const fakes = vi.hoisted(() => ({+ requestVoiceCall: vi.fn(),+ requestVoiceHangup: vi.fn(),+ fetchVoiceRuntimeState: vi.fn(),+ startBrowserVoiceCall: vi.fn(),+ stopBrowserVoiceCall: vi.fn(),+}));++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));++vi.mock("@/lib/voiceApi", () => ({+ requestVoiceCall: () => fakes.requestVoiceCall(),+ requestVoiceHangup: () => fakes.requestVoiceHangup(),+ fetchVoiceRuntimeState: () => fakes.fetchVoiceRuntimeState(),+}));++vi.mock("@/lib/browserVoiceCall", () => ({+ startBrowserVoiceCall: () => fakes.startBrowserVoiceCall(),+ stopBrowserVoiceCall: () => fakes.stopBrowserVoiceCall(),+}));++const toast = vi.fn();++function noPipeline(): Error {+ return Object.assign(new Error("Voice is not running on this computer."), { status: 503 });+}++describe("useVoiceCall", () => {+ beforeEach(() => {+ for (const fake of Object.values(fakes)) fake.mockReset();+ fakes.requestVoiceCall.mockResolvedValue({ armed: true });+ fakes.requestVoiceHangup.mockResolvedValue({ stopped: true });+ fakes.startBrowserVoiceCall.mockReturnValue(true);+ fakes.stopBrowserVoiceCall.mockReturnValue(false);+ toast.mockClear();+ useEventStore.setState({ voiceState: "idle", pushToast: toast });+ });++ afterEach(() => {+ cleanup();+ });++ it("asks the host and nothing else when the host arms the call", async () => {+ const { result } = renderHook(() => useVoiceCall());++ await act(() => result.current.toggleCall());++ expect(fakes.requestVoiceCall).toHaveBeenCalledTimes(1);+ expect(fakes.fetchVoiceRuntimeState).not.toHaveBeenCalled();+ expect(fakes.startBrowserVoiceCall).not.toHaveBeenCalled();+ expect(toast).not.toHaveBeenCalled();+ });++ it("lets this browser hold the call on a host with no speech pipeline", async () => {+ fakes.requestVoiceCall.mockRejectedValue(noPipeline());+ fakes.fetchVoiceRuntimeState.mockResolvedValue({+ available: false,+ voiceState: "idle",+ browserCall: true,+ });+ const { result } = renderHook(() => useVoiceCall());++ await act(() => result.current.toggleCall());++ expect(fakes.startBrowserVoiceCall).toHaveBeenCalledTimes(1);+ expect(toast).not.toHaveBeenCalled();+ });++ it("keeps the honest error when the host does not offer a browser call", async () => {+ fakes.requestVoiceCall.mockRejectedValue(noPipeline());+ fakes.fetchVoiceRuntimeState.mockResolvedValue({+ available: false,+ voiceState: "idle",+ browserCall: false,+ });+ const { result } = renderHook(() => useVoiceCall());++ await act(() => result.current.toggleCall());++ expect(fakes.startBrowserVoiceCall).not.toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith("error", "Voice is not running on this computer.");+ });++ it("never reads another failure as a missing pipeline", async () => {+ fakes.requestVoiceCall.mockRejectedValue(+ Object.assign(new Error("Voice request failed (500)."), { status: 500 }),+ );+ const { result } = renderHook(() => useVoiceCall());++ await act(() => result.current.toggleCall());++ expect(fakes.fetchVoiceRuntimeState).not.toHaveBeenCalled();+ expect(fakes.startBrowserVoiceCall).not.toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith("error", "Voice request failed (500).");+ });++ it("ends a call this browser holds without asking the host", async () => {+ useEventStore.setState({ voiceState: "listening" });+ fakes.stopBrowserVoiceCall.mockReturnValue(true);+ const { result } = renderHook(() => useVoiceCall());++ await act(() => result.current.toggleCall());++ expect(fakes.stopBrowserVoiceCall).toHaveBeenCalledTimes(1);+ expect(fakes.requestVoiceHangup).not.toHaveBeenCalled();+ });++ it("hangs up through the host when this browser holds no call", async () => {+ useEventStore.setState({ voiceState: "speaking" });+ const { result } = renderHook(() => useVoiceCall());++ await act(() => result.current.toggleCall());++ expect(fakes.requestVoiceHangup).toHaveBeenCalledTimes(1);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.ts b/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.tsindex 4cabfd878e..f0a967dbc3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/useVoiceCall.ts@@ -1,6 +1,11 @@import { useCallback, useState } from "react";import { useT } from "@/i18n";-import { requestVoiceCall, requestVoiceHangup } from "@/lib/voiceApi";+import { startBrowserVoiceCall, stopBrowserVoiceCall } from "@/lib/browserVoiceCall";+import {+ fetchVoiceRuntimeState,+ requestVoiceCall,+ requestVoiceHangup,+} from "@/lib/voiceApi";import { useEventStore, type VoiceState } from "@/store/events";import { useHomeStore } from "@/store/home";@@ -18,12 +23,28 @@ export function isVoiceActive(state: VoiceState): boolean {);}+/** A start the host refused because it runs no speech pipeline (HTTP 503). */+function hostRunsNoPipeline(error: unknown): boolean {+ return (error as { status?: unknown } | null)?.status === 503;+}++/** Whether the host says this browser may hold the call itself. */+async function browserMayHoldTheCall(): Promise<boolean> {+ const runtime = await fetchVoiceRuntimeState();+ return runtime?.browserCall === true;+}+/**- * The one start/stop path shared by every Agentic IDE voice surface.+ * The one start/stop path shared by every voice surface.** Keeping the request and its user-visible failure handling here prevents the* toolbar button and the floating bubble from becoming two controls that look* alike but behave differently.+ *+ * A start asks the host first, exactly as the call hotkey does. Only when the+ * host has no speech pipeline at all (a VPS, `jarvis serve`) and says the+ * browser may hold the call does this browser open the call itself — the+ * microphone is the one in front of the person, not one the server lacks.*/export function useVoiceCall() {const t = useT();@@ -39,11 +60,22 @@ export function useVoiceCall() {setBusy(true);try {if (active) {- await requestVoiceHangup();+ // A call this browser holds ends here; the host has nothing to hang up.+ if (!stopBrowserVoiceCall()) await requestVoiceHangup();} else {- const { armed } = await requestVoiceCall();- if (!armed) {- pushToast("warning", t("agentic_grid.voice_bubble.start_failed"));+ try {+ const { armed } = await requestVoiceCall();+ if (!armed) {+ pushToast("warning", t("agentic_grid.voice_bubble.start_failed"));+ }+ } catch (error) {+ if (+ !hostRunsNoPipeline(error) ||+ !(await browserMayHoldTheCall()) ||+ !startBrowserVoiceCall()+ ) {+ throw error;+ }}}} catch (error) {diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsxindex 5f02916af1..ea13f55900 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx@@ -2,6 +2,11 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useEventStore } from "@/store/events";+import {+ browserVoiceCallLive,+ startBrowserVoiceCall,+ stopBrowserVoiceCall,+} from "@/lib/browserVoiceCall";import {setBrowserVoiceInputOwnership,setVoiceInputLevel,@@ -28,7 +33,7 @@ const fakes = vi.hoisted(() => ({onInputLevel?: (level: number) => void;onStatus?: (status: string, payload: Record<string, unknown>) => void;},- options: null as null | { requiresWebRtcOffer?: boolean },+ options: null as null | { requiresWebRtcOffer?: boolean; browserAudio?: boolean },}));vi.mock("@/hooks/useCapabilities", () => ({@@ -475,4 +480,88 @@ describe("BrowserRealtimeControl", () => {expect(screen.getByText("sidebar.realtime_https_required")).toBeTruthy();expect(fakes.connect).not.toHaveBeenCalled();});++ // Issue #399: on a host with no speech pipeline the browser that presses+ // Start holds the call itself, in pipeline mode through the classic chain.+ describe("call held by this browser", () => {+ beforeEach(() => {+ fakes.mode = "pipeline";+ fakes.available = false;+ useEventStore.setState({ toasts: [] });+ });++ it("starts in pipeline mode with plain PCM and keeps the call through the mode gate", async () => {+ // A realtime transport pinned in the settings must not leak into a+ // classic call: it has no WebRTC peer and no browser-audio contract.+ fakes.requiresWebRtcOffer = true;+ fakes.browserAudio = true;+ render(<BrowserRealtimeControl controlOnly />);++ act(() => {+ expect(startBrowserVoiceCall()).toBe(true);+ });++ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));+ expect(fakes.options).toMatchObject({ requiresWebRtcOffer: false, browserAudio: false });+ expect(useEventStore.getState().voiceState).toBe("connecting");+ expect(browserVoiceCallLive()).toBe(true);++ act(() => fakes.callbacks?.onStatus?.("audio_ready", {}));+ expect(useEventStore.getState().voiceState).toBe("listening");+ // Pipeline mode hides the realtime surface; it must not hang this up.+ expect(fakes.disconnect).not.toHaveBeenCalled();++ act(() => {+ expect(stopBrowserVoiceCall()).toBe(true);+ });+ await waitFor(() => expect(fakes.disconnect).toHaveBeenCalledTimes(1));+ expect(useEventStore.getState().voiceState).toBe("idle");+ expect(browserVoiceCallLive()).toBe(false);+ });++ it("reports a failed start as a toast and frees the controls", async () => {+ fakes.connect.mockRejectedValueOnce(new Error("socket closed"));+ render(<BrowserRealtimeControl controlOnly />);++ act(() => {+ startBrowserVoiceCall();+ });++ await waitFor(() => expect(useEventStore.getState().voiceState).toBe("idle"));+ // A classic call has no realtime provider to blame; the line points at+ // the chain it actually runs on.+ expect(+ useEventStore.getState().toasts.map(({ kind, message }) => ({ kind, message })),+ ).toEqual([{ kind: "error", message: "sidebar.browser_voice_error" }]);+ expect(screen.queryByRole("alert")).toBeNull();+ expect(browserVoiceCallLive()).toBe(false);+ });++ it("shows the server's sentence when the server closes the call", async () => {+ render(<BrowserRealtimeControl controlOnly />);+ act(() => {+ startBrowserVoiceCall();+ });+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));++ act(() =>+ fakes.callbacks?.onStatus?.("disconnected", {+ code: 1011,+ reason: "Voice could not start: a provider is missing. Check API Keys.",+ }),+ );++ await waitFor(() => expect(useEventStore.getState().voiceState).toBe("idle"));+ expect(useEventStore.getState().toasts.map((toast) => toast.message)).toEqual([+ "Voice could not start: a provider is missing. Check API Keys.",+ ]);+ expect(fakes.disconnect).toHaveBeenCalled();+ });++ it("is owned only by the app-root control", () => {+ render(<BrowserRealtimeControl />);+ expect(startBrowserVoiceCall()).toBe(false);+ expect(stopBrowserVoiceCall()).toBe(false);+ });+ });});diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex b07c8bf819..1857e7621d 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -7,6 +7,10 @@ import { Card } from "@/components/ui/card";import { useCapabilities } from "@/hooks/useCapabilities";import { useVoiceMode } from "@/hooks/useVoiceMode";import { useT } from "@/i18n";+import {+ registerBrowserVoiceCallOwner,+ setBrowserVoiceCallLive,+} from "@/lib/browserVoiceCall";import { hasEmbeddedDesktopBridge, isEmbeddedMacWindow } from "@/lib/embeddedDesktop";import {browserRealtimeSupportIssue,@@ -83,6 +87,12 @@ async function reportHostMicrophoneDenied(): Promise<void> {* 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.+ *+ * Two ways a call starts here. The desktop hands a realtime call to this+ * document (`BrowserVoiceRequested`). Or, on a host with no speech pipeline+ * at all, the person presses Start and useVoiceCall asks this control to hold+ * the call itself (lib/browserVoiceCall) — in either voice mode, because the+ * server picks a realtime session or the classic STT -> brain -> TTS chain.*/export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?: boolean } = {}) {const t = useT();@@ -132,11 +142,18 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:// listening — or the pill looks ready while the Tool Model is still// working.const resumeThinkingAfterSpeechRef = useRef(false);+ // A call the person started here because the host has no speech pipeline.+ // State for rendering, a ref for the callbacks that outlive a render.+ const [localCall, setLocalCall] = useState(false);+ const localCallRef = useRef(false);const browserSurface = Boolean(capabilities.data &&(browserAudio || capabilities.data.native_file_actions === false || !hasEmbeddedDesktopBridge()),);const visible = browserSurface && mode === "realtime";+ // A locally started call is live in either voice mode; leaving realtime+ // mode must not hang it up.+ const callSurface = visible || localCall;const supportIssue = visible ? browserRealtimeSupportIssue() : null;const supportMessage = useCallback(@@ -155,6 +172,11 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:connectionGenerationRef.current += 1;const client = clientRef.current;clientRef.current = null;+ if (localCallRef.current) {+ localCallRef.current = false;+ setLocalCall(false);+ setBrowserVoiceCallLive(false);+ }setState("idle");setEffectiveProvider("");setError("");@@ -169,16 +191,44 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:await client?.disconnect();}, [setVoice]);- const start = useCallback(async (options?: { fromGesture?: boolean }) => {- if (!realtimeAvailable || clientRef.current || state === "connecting") return;+ const start = useCallback(async (options?: { fromGesture?: boolean; local?: boolean }) => {+ // A local start does not wait for realtime: on a host with no speech+ // pipeline the server answers with a realtime session or the classic+ // chain, whichever it can build.+ const local = options?.local === true;+ if ((!local && !realtimeAvailable) || clientRef.current || state === "connecting") return;const generation = connectionGenerationRef.current + 1;connectionGenerationRef.current = generation;+ if (local) {+ localCallRef.current = true;+ setLocalCall(true);+ setBrowserVoiceCallLive(true);+ // Every Start/Stop surface reads this; it also keeps a second press+ // from starting a second call while the microphone opens.+ setVoice("connecting");+ }setState("connecting");setError("");setEffectiveProvider("");levelRef.current = 0;clearVoiceInputLevel("browser");clearVoiceOutputLevel("browser");+ // A local call in pipeline mode has no realtime transport, so none of its+ // media options apply: the classic bridge streams plain PCM both ways. A+ // call the desktop hands over keeps exactly the options it always had.+ const realtimeTransport = !local || mode === "realtime";+ const callBrowserAudio = realtimeTransport && browserAudio;+ // A classic call has no realtime provider to test, so its fallback line+ // points at the three providers that chain runs on instead.+ const startFailed = t(+ realtimeTransport ? "sidebar.realtime_error" : "sidebar.browser_voice_error",+ );+ // A call the person started here reports a failure as a toast and frees+ // the controls again; there is no card on the page to hold an error line.+ const endLocalCall = (message: string) => {+ pushToast("error", message);+ void stop();+ };let client: RealtimeAudioClient;const isCurrent = () =>connectionGenerationRef.current === generation && clientRef.current === client;@@ -188,7 +238,7 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:if (!isCurrent()) return;// Live adapters project all speaker snapshots onto the shared bus.// Keeping a second local caption would overwrite the conversation.- if (browserAudio) return;+ if (callBrowserAudio) return;if (role === "user") setTranscription(text, isFinal);if (role === "user" && isFinal) setVoice("thinking");},@@ -299,10 +349,15 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:status === "tts_browser_error") {setError(t("sidebar.realtime_browser_tts_unavailable"));+ if (local) pushToast("warning", t("sidebar.realtime_browser_tts_unavailable"));setVoice("listening");} else if (status === "audio_closed") {void stop();} else if (status === "provider_error" || status === "disconnected") {+ if (local) {+ endLocalCall(backendDetail || startFailed);+ return;+ }clientRef.current = null;void client.disconnect();setState("error");@@ -313,7 +368,12 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:}},},- { requiresWebRtcOffer, webRtcStartEventRequired, startBudgetMs, browserAudio },+ {+ requiresWebRtcOffer: realtimeTransport && requiresWebRtcOffer,+ webRtcStartEventRequired,+ startBudgetMs,+ browserAudio: callBrowserAudio,+ },);clientRef.current = client;try {@@ -325,7 +385,6 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:clientRef.current = null;void client.disconnect();clearVoiceInputLevel("browser");- setState("error");const micDenied = cause instanceof DOMException && cause.name === "NotAllowedError";// In the embedded Mac window a refused microphone is macOS's decision, not a// browser site setting: there is no site settings page to point at. The@@ -333,18 +392,24 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:// ("Open System Settings") takes over; a wake-started call never does.const hostDenied = micDenied && isEmbeddedMacWindow();if (hostDenied && options?.fromGesture) void reportHostMicrophoneDenied();- setError(+ const message =cause instanceof RealtimeAudioSupportError? supportMessage(cause.issue): hostDenied? t("sidebar.realtime_microphone_denied_desktop"): micDenied? t("sidebar.realtime_microphone_denied")- : t("sidebar.realtime_error"),- );+ : startFailed;+ if (local) {+ endLocalCall(message);+ return;+ }+ setState("error");+ setError(message);setVoice("error");}}, [+ mode,pushToast,realtimeAvailable,requiresWebRtcOffer,@@ -359,6 +424,22 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:t,]);+ // This document's browser-held call: on a host with no speech pipeline,+ // every Start/Stop surface reaches it through useVoiceCall. Only the+ // app-root instance (`controlOnly`) owns it, and the latest start/stop are+ // read through refs so the registration does not churn on every render.+ const startRef = useRef(start);+ startRef.current = start;+ const stopRef = useRef(stop);+ stopRef.current = stop;+ useEffect(() => {+ if (!controlOnly) return undefined;+ return registerBrowserVoiceCallOwner({+ start: () => void startRef.current({ fromGesture: true, local: true }),+ stop: () => void stopRef.current(),+ });+ }, [controlOnly]);+useEffect(() => {if (!browserAudio || !wakeOwner) return;const onVisible = () => {@@ -407,14 +488,14 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:// This surface owns BOTH directions while it is live: it holds the// microphone and it plays the reply, so the backend's own levels for// either one would be a second, unsynchronised opinion.- const owns = visible && (state === "connecting" || state === "connected");+ const owns = callSurface && (state === "connecting" || state === "connected");setBrowserVoiceInputOwnership(owns);setBrowserVoiceOutputOwnership(owns);- }, [state, visible]);+ }, [state, callSurface]);useEffect(() => {- if (!visible) void stop();- }, [stop, visible]);+ if (!callSurface) void stop();+ }, [stop, callSurface]);// This document owns the call: an automatic reload (a rebuilt bundle) would// unmount this control and hang up mid-sentence. Hold reloads while it lives.diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.test.tsx b/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.test.tsxindex c03f56df6f..d57092d3e8 100644--- a/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.test.tsx+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.test.tsx@@ -6,10 +6,11 @@* to idle, an unreadable answer changes nothing, and a live event beats the* snapshot that was already in flight.*/-import { cleanup, render, waitFor } from "@testing-library/react";+import { act, cleanup, render, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useVoiceStateResync } from "@/hooks/useVoiceStateResync";+import { setBrowserVoiceCallLive } from "@/lib/browserVoiceCall";import { useEventStore } from "@/store/events";function Harness() {@@ -127,4 +128,25 @@ describe("useVoiceStateResync", () => {await waitFor(() => expect(useEventStore.getState().voiceState).toBe("listening"));expect(fetch).not.toHaveBeenCalled();});++ it("leaves a call this browser holds alone on a host with no pipeline", async () => {+ // Issue #399: the backend snapshot cannot see a classic browser call and+ // answers "unavailable"; correcting against it would end the call's+ // display mid conversation.+ vi.stubGlobal(+ "fetch",+ answer({ available: false, state: "unavailable", voice_state: "idle", browser_call: true }),+ );+ setBrowserVoiceCallLive(true);+ try {+ render(<Harness />);+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 20));+ });+ expect(useEventStore.getState().voiceState).toBe("listening");+ expect(fetch).not.toHaveBeenCalled();+ } finally {+ setBrowserVoiceCallLive(false);+ }+ });});diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.tsindex 532e4fae86..7f9203c243 100644--- a/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.ts+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceStateResync.ts@@ -1,5 +1,6 @@import { useCallback, useEffect } from "react";+import { browserVoiceCallLive } from "@/lib/browserVoiceCall";import { fetchVoiceRuntimeState } from "@/lib/voiceApi";import { useDocumentVisible } from "@/hooks/useDocumentVisible";import { useEventStore } from "@/store/events";@@ -29,6 +30,11 @@ import { useEventStore } from "@/store/events";* field) changes nothing.* * A state that changed while the request was in flight wins — a live event* is newer than the snapshot that was already on its way.+ *+ * A call this browser holds itself (a host with no speech pipeline) is left+ * alone: its own socket drives the state, and the backend's pipeline snapshot+ * cannot see a classic browser call, so it would end the call's display mid+ * conversation.*/export function useVoiceStateResync(): void {const connected = useEventStore((s) => s.connected);@@ -40,7 +46,7 @@ export function useVoiceStateResync(): void {const before = store.voiceState;// Idle is the state this hook corrects TO — nothing to check, and the// common case, so the section switch costs no request at all.- if (before === "idle") return;+ if (before === "idle" || browserVoiceCallLive()) return;const truth = await fetchVoiceRuntimeState();if (truth === null) return;@@ -48,6 +54,7 @@ export function useVoiceStateResync(): void {const now = useEventStore.getState();if (now.voiceState !== before) return; // a live event overtook the snapshot+ if (browserVoiceCallLive()) return; // a browser call started meanwhilenow.setVoice("idle");// The live-transcript box follows the same session boundary the websocket// clears it on; left alone, the last utterance of the dead session sitsdiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex be5a076b14..3829333cfd 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -715,6 +715,7 @@"realtime_pipeline_fallback": "Klassische Pipeline als Fallback","realtime_unavailable": "Realtime-Anbieter verbinden oder einrichten","realtime_error": "Die Sprachverbindung konnte nicht gestartet werden. Teste den aktiven Realtime-Anbieter unter API Keys und versuche es erneut.",+ "browser_voice_error": "Die Sprachverbindung konnte nicht gestartet werden. Prüfe Sprache zu Text, das Brain und Text zu Sprache unter API Keys und versuche es erneut.","realtime_provider_fallback": "{0} war nicht mehr verfügbar, deshalb läuft das Gespräch jetzt über einen anderen Anbieter — die Abrechnung kann abweichen. {1}","realtime_provider_fallback_short": "Das Gespräch hat {0} verlassen und läuft über einen anderen Anbieter.","realtime_provider_warning": "Der Realtime-Anbieter meldet ein behebbares Problem; das Gespräch läuft weiter.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex ffaa10b3f1..6c8118d12e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -715,6 +715,7 @@"realtime_pipeline_fallback": "Classic pipeline fallback","realtime_unavailable": "Connect or configure a Realtime provider","realtime_error": "Couldn’t start voice. Test the active Realtime provider under API Keys, then retry.",+ "browser_voice_error": "Couldn’t start voice. Check speech-to-text, the Brain and text-to-speech under API Keys, then retry.","realtime_provider_fallback": "{0} became unavailable, so the call moved to another provider — billing may differ. {1}","realtime_provider_fallback_short": "The call moved off {0} to another provider.","realtime_provider_warning": "The realtime provider reported a recoverable problem; the call continues.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 242c101831..9b662a70da 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -715,6 +715,7 @@"realtime_pipeline_fallback": "Sistema de voz clásico como alternativa","realtime_unavailable": "Conecta o configura un proveedor de tiempo real","realtime_error": "No se pudo iniciar la voz. Prueba el proveedor activo en API Keys y vuelve a intentarlo.",+ "browser_voice_error": "No se pudo iniciar la voz. Revisa voz a texto, el Brain y texto a voz en API Keys y vuelve a intentarlo.","realtime_provider_fallback": "{0} dejó de estar disponible, así que la llamada pasó a otro proveedor: la facturación puede cambiar. {1}","realtime_provider_fallback_short": "La llamada dejó {0} y continúa con otro proveedor.","realtime_provider_warning": "El proveedor Realtime informó de un problema recuperable; la llamada continúa.",diff --git a/jarvis/ui/web/frontend/src/lib/browserVoiceCall.test.ts b/jarvis/ui/web/frontend/src/lib/browserVoiceCall.test.tsnew file mode 100644index 0000000000..dc5b9d91f3--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/browserVoiceCall.test.ts@@ -0,0 +1,61 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ browserVoiceCallLive,+ registerBrowserVoiceCallOwner,+ setBrowserVoiceCallLive,+ startBrowserVoiceCall,+ stopBrowserVoiceCall,+} from "./browserVoiceCall";++describe("browserVoiceCall", () => {+ let unregister: (() => void) | null = null;++ afterEach(() => {+ unregister?.();+ unregister = null;+ setBrowserVoiceCallLive(false);+ });++ it("reports that nobody can hold a call before an owner registers", () => {+ expect(startBrowserVoiceCall()).toBe(false);+ expect(stopBrowserVoiceCall()).toBe(false);+ });++ it("hands Start to the owner and Stop only while a call is live", () => {+ const owner = { start: vi.fn(), stop: vi.fn() };+ unregister = registerBrowserVoiceCallOwner(owner);++ expect(startBrowserVoiceCall()).toBe(true);+ expect(owner.start).toHaveBeenCalledTimes(1);+ // Nothing is open yet, so a Stop is not this browser's to handle.+ expect(stopBrowserVoiceCall()).toBe(false);++ setBrowserVoiceCallLive(true);+ expect(browserVoiceCallLive()).toBe(true);+ expect(stopBrowserVoiceCall()).toBe(true);+ expect(owner.stop).toHaveBeenCalledTimes(1);+ });++ it("forgets the call when its owner unmounts", () => {+ const owner = { start: vi.fn(), stop: vi.fn() };+ const release = registerBrowserVoiceCallOwner(owner);+ setBrowserVoiceCallLive(true);++ release();++ expect(browserVoiceCallLive()).toBe(false);+ expect(startBrowserVoiceCall()).toBe(false);+ });++ it("ignores a stale unregister after a newer owner took over", () => {+ const first = registerBrowserVoiceCallOwner({ start: vi.fn(), stop: vi.fn() });+ const second = { start: vi.fn(), stop: vi.fn() };+ unregister = registerBrowserVoiceCallOwner(second);++ first();++ expect(startBrowserVoiceCall()).toBe(true);+ expect(second.start).toHaveBeenCalledTimes(1);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/browserVoiceCall.ts b/jarvis/ui/web/frontend/src/lib/browserVoiceCall.tsnew file mode 100644index 0000000000..11f3d072cd--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/browserVoiceCall.ts@@ -0,0 +1,55 @@+/**+ * The voice call this document's browser holds itself.+ *+ * On a host with no speech pipeline of its own (a VPS, `jarvis serve`) the+ * browser that presses Start holds the call: it opens /ws/audio, streams the+ * microphone and plays the reply. The one control that owns that socket+ * (components/voice/BrowserRealtimeControl, mounted once per document)+ * registers here, so every Start/Stop surface reaches it through+ * useVoiceCall instead of growing a second copy of the call logic.+ *+ * Plain module state, like voiceInputLevel.ts: the flag is read on demand by+ * the start/stop path and by the state resync, and never rendered.+ */++export interface BrowserVoiceCallOwner {+ start(): void;+ stop(): void;+}++let owner: BrowserVoiceCallOwner | null = null;+let live = false;++/** Register this document's call owner; the returned function unregisters it. */+export function registerBrowserVoiceCallOwner(next: BrowserVoiceCallOwner): () => void {+ owner = next;+ return () => {+ if (owner !== next) return;+ owner = null;+ live = false;+ };+}++/** The owner reports whether its browser-held call is connecting or open. */+export function setBrowserVoiceCallLive(value: boolean): void {+ live = value;+}++/** Whether this document holds a browser call right now. */+export function browserVoiceCallLive(): boolean {+ return live;+}++/** Start a browser-held call. `false` when no owner is mounted here. */+export function startBrowserVoiceCall(): boolean {+ if (owner === null) return false;+ owner.start();+ return true;+}++/** End this document's browser-held call. `false` when none is open. */+export function stopBrowserVoiceCall(): boolean {+ if (owner === null || !live) return false;+ owner.stop();+ return true;+}diff --git a/jarvis/ui/web/frontend/src/lib/voiceApi.test.ts b/jarvis/ui/web/frontend/src/lib/voiceApi.test.tsnew file mode 100644index 0000000000..bb15811b40--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/voiceApi.test.ts@@ -0,0 +1,50 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { fetchVoiceRuntimeState, requestVoiceCall } from "./voiceApi";++function answer(body: unknown, status = 200) {+ return vi.fn(async () => ({+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ })) as unknown as typeof fetch;+}++describe("voiceApi", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("reads whether this browser should hold the call", async () => {+ vi.stubGlobal(+ "fetch",+ answer({ available: false, state: "unavailable", voice_state: "idle", browser_call: true }),+ );++ expect(await fetchVoiceRuntimeState()).toEqual({+ available: false,+ voiceState: "idle",+ browserCall: true,+ });+ });++ it("never offers a browser call when an older backend does not say so", async () => {+ vi.stubGlobal("fetch", answer({ available: true, state: "idle" }));++ expect(await fetchVoiceRuntimeState()).toEqual({+ available: true,+ voiceState: "idle",+ browserCall: false,+ });+ });++ it("tells a host without a speech pipeline apart by its status", async () => {+ vi.stubGlobal("fetch", answer({ detail: "voice-pipeline-unavailable" }, 503));++ const failure = await requestVoiceCall().catch((error: unknown) => error);++ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toBe("Voice is not running on this computer.");+ expect((failure as { status?: number }).status).toBe(503);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/voiceApi.ts b/jarvis/ui/web/frontend/src/lib/voiceApi.tsindex 9fb8d63590..72f6d0d48b 100644--- a/jarvis/ui/web/frontend/src/lib/voiceApi.ts+++ b/jarvis/ui/web/frontend/src/lib/voiceApi.ts@@ -9,6 +9,13 @@ export interface VoiceHangupAnswer {stopped: boolean;}+/**+ * A failed voice request. `status` lets a caller tell "this host runs no+ * speech pipeline" (503) apart from a real failure; the message is what the+ * person reads.+ */+export type VoiceRequestError = Error & { status: number };+async function post<T>(path: string): Promise<T> {const res = await fetch(path, { method: "POST", cache: "no-store" });if (!res.ok) {@@ -18,10 +25,11 @@ async function post<T>(path: string): Promise<T> {} catch {/* a non-JSON error body — the status line below still names the failure */}- if (res.status === 503) {- throw new Error("Voice is not running on this computer.");- }- throw new Error(detail || `Voice request failed (${res.status}).`);+ const message =+ res.status === 503+ ? "Voice is not running on this computer."+ : detail || `Voice request failed (${res.status}).`;+ throw Object.assign(new Error(message), { status: res.status }) as VoiceRequestError;}return (await res.json()) as T;}@@ -119,6 +127,9 @@ export interface VoiceRuntimeState {/** The fine-grained state every voice surface renders, straight from the* supervisor. `"idle"` whenever no session is running. */voiceState: string;+ /** No speech pipeline will ever run here (a VPS, `jarvis serve`), and+ * /ws/audio accepts a call: the browser that presses Start holds it. */+ browserCall: boolean;}/**@@ -140,17 +151,24 @@ export async function fetchVoiceRuntimeState(): Promise<VoiceRuntimeState | nullavailable?: unknown;state?: unknown;voice_state?: unknown;+ browser_call?: unknown;};const available = body.available === true;+ // An older backend without the field never offers a browser-held call.+ const browserCall = body.browser_call === true;if (typeof body.voice_state === "string") {- return { available, voiceState: body.voice_state };+ return { available, voiceState: body.voice_state, browserCall };}// A backend from before the field existed still answers the coarse// question honestly: an idle pipeline IS "no session runs", which is the// whole correction this is read for. Anything else stays "unknown" so a// live call is never touched on a guess.if (typeof body.state === "string") {- return { available, voiceState: body.state === "idle" ? "idle" : "unknown" };+ return {+ available,+ voiceState: body.state === "idle" ? "idle" : "unknown",+ browserCall,+ };}return null;} catch (error) {diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 6442d652d1..d97fcc1077 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -647,7 +647,8 @@ class WebServer:app.state.telephony_manager = TelephonyManager()# Browser-microphone voice bridge (B2): /ws/audio — the headless/VPS# voice path via the browser's own mic/speaker, no sounddevice. Always- # mounted; gated by [browser_voice].enabled (default on) at connect time.+ # mounted; checked at connect time: realtime mode always serves it,+ # pipeline mode while [browser_voice].enabled is on (the default).from jarvis.browser_voice.route import router as browser_voice_routerapp.include_router(browser_voice_router)diff --git a/jarvis/ui/web/voice_call_routes.py b/jarvis/ui/web/voice_call_routes.pyindex b7fdae154a..1f27484d1d 100644--- a/jarvis/ui/web/voice_call_routes.py+++ b/jarvis/ui/web/voice_call_routes.py@@ -2,7 +2,8 @@Endpoints (mounted by the WebServer in ``_build_app()``):- GET /api/voice/state → is a speech pipeline running, and what it is doing.+ GET /api/voice/state → is a speech pipeline running, what it is doing,+ and whether the browser should hold the call.POST /api/voice/call → arm a wake-style voice session (the click-shapedwake word — same path as the call hotkey).POST /api/voice/hangup → hard-stop the voice channel (same contract as the@@ -23,7 +24,7 @@ from __future__ import annotationsimport loggingfrom typing import Any-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, HTTPException, Requestlog = logging.getLogger(__name__)@@ -40,8 +41,31 @@ def _pipeline() -> Any:return None+def _browser_call(request: Request, pipeline: Any) -> bool:+ """Whether the browser that presses Start should hold the call itself.++ True only on a host that will never run a speech pipeline of its own — no+ pipeline AND no desktop shell (a desktop app that is still booting has no+ pipeline yet, and a browser-held call there would be a second microphone+ owner) — and whose ``/ws/audio`` would accept the call. Without a config+ attached to the app the answer is False: it cannot be read, so it is not+ offered.+ """+ if pipeline is not None:+ return False+ state = request.app.state+ if bool(getattr(state, "native_file_actions", False)):+ return False+ cfg = getattr(state, "config", None) or getattr(state, "cfg", None)+ if cfg is None:+ return False+ from jarvis.browser_voice.route import browser_voice_enabled++ return browser_voice_enabled(cfg)++@router.get("/state")-async def voice_state() -> dict[str, Any]:+async def voice_state(request: Request) -> dict[str, Any]:"""Whether voice is available here, and what the pipeline is doing now.``voice_state`` is the fine-grained state every voice surface renders@@ -58,9 +82,15 @@ async def voice_state() -> dict[str, Any]:state without a running session is unearned detail, never the truth. Arunning session whose supervisor cannot be read answers ``unknown`` ratherthan a guess — the caller leaves a live call alone on anything but ``idle``.++ ``browser_call`` tells a browser on a host without a speech pipeline (a+ VPS, ``jarvis serve``) to hold the call itself over ``/ws/audio`` instead+ of asking this host to arm a microphone it does not have (issue #399)."""from jarvis.live.runtime import active+ pipeline = _pipeline()+ browser_call = _browser_call(request, pipeline)sessions = active()if sessions:phase = getattr(sessions[0], "phase", "listening")@@ -70,10 +100,15 @@ async def voice_state() -> dict[str, Any]:"available": True,"state": "active","voice_state": phase,+ "browser_call": browser_call,}- pipeline = _pipeline()if pipeline is None:- return {"available": False, "state": "unavailable", "voice_state": "idle"}+ return {+ "available": False,+ "state": "unavailable",+ "voice_state": "idle",+ "browser_call": browser_call,+ }state = str(getattr(getattr(pipeline, "_state", None), "name", "unknown")).lower()supervisor = getattr(pipeline, "_supervisor", None)supervisor_state = str(getattr(supervisor, "state", "") or "").lower() or "unknown"@@ -81,6 +116,7 @@ async def voice_state() -> dict[str, Any]:"available": True,"state": state,"voice_state": supervisor_state if state == "active" else "idle",+ "browser_call": browser_call,}diff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.pyindex 8fe1e176fa..2e62b38856 100644--- a/tests/unit/browser_voice/test_route.py+++ b/tests/unit/browser_voice/test_route.py@@ -133,10 +133,9 @@ async def _wait_for_json(def _state(session, cfg=None):- # Default cfg explicitly opts into the classic bridge (Task 7 inverted the- # gate to default-OFF; these tests exercise the classic dispatch/session- # behavior, not the gate itself — see test_route_closes_when_disabled for- # that).+ # These tests exercise the classic dispatch/session behavior, not the gate+ # itself — see test_route_closes_when_disabled and+ # test_route_serves_the_classic_bridge_in_pipeline_mode_by_default for that.default_cfg = SimpleNamespace(browser_voice=SimpleNamespace(enabled=True))return SimpleNamespace(config=cfg if cfg is not None else default_cfg,@@ -517,10 +516,46 @@ async def test_route_closes_when_disabled():assert rec.audio == [] # never reached the loop+async def test_route_serves_the_classic_bridge_in_pipeline_mode_by_default():+ # Issue #399: a real JarvisConfig in pipeline mode, no [browser_voice]+ # table. The socket must reach the classic session instead of closing.+ from jarvis.core.config import JarvisConfig++ class _ReadySession(_RecSession):+ def __init__(self) -> None:+ super().__init__()+ self.send_json = None++ async def handle_control(self, msg: dict) -> None:+ await super().handle_control(msg)+ if msg.get("type") == "audio_start" and self.send_json is not None:+ await self.send_json({"type": "audio_ready"})++ session = _ReadySession()++ def _factory(**kwargs):+ session.send_json = kwargs["send_json"]+ return session++ state = _state(session, cfg=JarvisConfig.model_validate({"voice": {"mode": "pipeline"}}))+ state.browser_voice_session_factory = _factory+ 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 ws.closed is None+ assert [message["type"] for message in ws.sent_json] == ["output_state", "audio_ready"]+ assert session.ended is True++async def test_route_closes_when_speech_stack_unavailable():state = SimpleNamespace(- # Explicit opt-in (Task 7 default-OFF gate) so the socket reaches the- # session build instead of closing early on the disabled gate.config=SimpleNamespace(browser_voice=SimpleNamespace(enabled=True)),bus=None,browser_voice_session_factory=lambda **kw: None, # build failed (no key)@@ -528,6 +563,10 @@ async def test_route_closes_when_speech_stack_unavailable():ws = _FakeWS([], state=state)await browser_voice_ws(ws)assert ws.closed is not None and ws.closed[0] == 1011+ # The reason reaches the person as the browser's error line, so it names+ # what to fix instead of an internal term.+ assert "Check API Keys" in ws.closed[1]+ assert len(ws.closed[1].encode()) <= 123async def test_route_breaks_on_runtimeerror():diff --git a/tests/unit/ui/test_voice_call_routes.py b/tests/unit/ui/test_voice_call_routes.pyindex 318cb99ce3..b113e7c7e0 100644--- a/tests/unit/ui/test_voice_call_routes.py+++ b/tests/unit/ui/test_voice_call_routes.py@@ -42,13 +42,25 @@ class _Pipeline:return self._stopped-def _client(monkeypatch, pipeline) -> TestClient:+def _client(monkeypatch, pipeline, *, config=None, desktop_shell=False) -> TestClient:monkeypatch.setattr(voice_call_routes, "_pipeline", lambda: pipeline)app = FastAPI()app.include_router(router)+ if config is not None:+ app.state.config = config+ if desktop_shell:+ app.state.native_file_actions = Truereturn TestClient(app)+def _cfg(mode: str = "pipeline", **browser_voice):+ from jarvis.core.config import JarvisConfig++ return JarvisConfig.model_validate(+ {"voice": {"mode": mode}, "browser_voice": browser_voice}+ )++def test_call_arms_a_wake_style_session(monkeypatch):pipeline = _Pipeline()client = _client(monkeypatch, pipeline)@@ -85,15 +97,49 @@ def test_headless_answers_honestly_instead_of_500(monkeypatch):"available": False,"state": "unavailable","voice_state": "idle",+ # No config attached: the bridge cannot be read, so it is not offered.+ "browser_call": False,}+def test_headless_host_tells_the_browser_to_hold_the_call(monkeypatch):+ # Issue #399: `jarvis serve` has no speech pipeline, so the browser that+ # presses Start holds the call over /ws/audio.+ client = _client(monkeypatch, None, config=_cfg("pipeline"))+ body = client.get("/api/voice/state").json()+ assert body["available"] is False+ assert body["browser_call"] is True+++def test_headless_realtime_mode_also_offers_the_browser_call(monkeypatch):+ client = _client(monkeypatch, None, config=_cfg("realtime", enabled=False))+ assert client.get("/api/voice/state").json()["browser_call"] is True+++def test_switched_off_bridge_is_not_offered(monkeypatch):+ client = _client(monkeypatch, None, config=_cfg("pipeline", enabled=False))+ assert client.get("/api/voice/state").json()["browser_call"] is False+++def test_desktop_shell_without_a_pipeline_never_offers_a_browser_call(monkeypatch):+ # A desktop app that is still booting has no pipeline yet; a browser-held+ # call there would be a second microphone owner.+ client = _client(monkeypatch, None, config=_cfg("pipeline"), desktop_shell=True)+ assert client.get("/api/voice/state").json()["browser_call"] is False+++def test_a_running_pipeline_owns_the_call(monkeypatch):+ client = _client(monkeypatch, _Pipeline(), config=_cfg("pipeline"))+ assert client.get("/api/voice/state").json()["browser_call"] is False++def test_state_names_the_pipeline_state(monkeypatch):client = _client(monkeypatch, _Pipeline())assert client.get("/api/voice/state").json() == {"available": True,"state": "idle","voice_state": "idle",+ "browser_call": False,}@@ -109,6 +155,7 @@ def test_state_mirrors_the_supervisor_while_a_session_runs(monkeypatch):"available": True,"state": "active","voice_state": "listening",+ "browser_call": False,}@@ -131,4 +178,5 @@ def test_state_clamps_a_left_over_supervisor_state_to_idle(monkeypatch):"available": True,"state": "idle","voice_state": "idle",+ "browser_call": False,}diff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.pyindex 890398cdd5..96ba4f6db3 100644--- a/tests/unit/web/test_voice_mode_route.py+++ b/tests/unit/web/test_voice_mode_route.py@@ -1,40 +1,67 @@-"""Task 7 — the browser-voice connect gate, inverted to default OFF.+"""The browser-voice connect gate, then the voice-mode settings routes.-``_browser_voice_enabled`` now serves the /ws/audio socket only when the user-has explicitly opted into a voice surface: realtime mode ([voice].mode ==-"realtime") or the classic bridge ([browser_voice].enabled == True). A missing-[browser_voice] section is False, not True (the old default-ON contract).+``browser_voice_enabled`` decides whether /ws/audio serves a browser-held+call. Realtime mode always serves it (the socket carries the realtime call and+its classic fallback). Pipeline mode serves the classic STT -> brain -> TTS+bridge while ``[browser_voice].enabled`` is on — the default. Issue #399: the+section used to be missing from ``JarvisConfig``, so ``load_config`` dropped+it and pipeline mode could never serve the bridge.-NOTE: a later task (T8) appends settings-route handler tests to this same-file — keep additions here additive and self-contained.+NOTE: the settings-route handler tests further down share this file — keep+additions here additive and self-contained."""from __future__ import annotations+from pathlib import Pathfrom types import SimpleNamespacefrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from jarvis.browser_voice.route import _browser_voice_enabled+from jarvis.browser_voice.route import browser_voice_enabled+from jarvis.core import config as cfg_mod+from jarvis.core.config import JarvisConfigfrom jarvis.ui.web.settings_routes import router-def test_gate_default_off_when_pipeline_and_no_browser_voice():- cfg = SimpleNamespace(voice=SimpleNamespace(mode="pipeline"))- assert _browser_voice_enabled(cfg) is False+def test_gate_on_by_default_in_pipeline_mode():+ cfg = JarvisConfig.model_validate({"voice": {"mode": "pipeline"}})+ assert cfg.browser_voice.enabled is True+ assert browser_voice_enabled(cfg) is True+++def test_gate_off_when_the_classic_bridge_is_switched_off():+ cfg = JarvisConfig.model_validate(+ {"voice": {"mode": "pipeline"}, "browser_voice": {"enabled": False}}+ )+ assert browser_voice_enabled(cfg) is False-def test_gate_on_for_realtime_mode():- cfg = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))- assert _browser_voice_enabled(cfg) is True+def test_gate_on_for_realtime_mode_even_with_the_classic_bridge_off():+ # The desktop hands realtime media to the WebView over the same socket;+ # the classic switch must never take that away.+ cfg = JarvisConfig.model_validate(+ {"voice": {"mode": "realtime"}, "browser_voice": {"enabled": False}}+ )+ assert browser_voice_enabled(cfg) is True+++def test_gate_treats_a_config_without_the_section_like_the_default():+ cfg = SimpleNamespace(voice=SimpleNamespace(mode="pipeline"))+ assert browser_voice_enabled(cfg) is True-def test_gate_on_for_explicit_classic_browser_voice():- cfg = SimpleNamespace(- voice=SimpleNamespace(mode="pipeline"), browser_voice=SimpleNamespace(enabled=True)+def test_load_config_keeps_the_browser_voice_table(tmp_path: Path):+ # The exact reproduction from issue #399: the table used to be dropped+ # during validation, so ``load_config().browser_voice`` raised.+ path = tmp_path / "jarvis.toml"+ path.write_text(+ '[voice]\nmode = "pipeline"\n\n[browser_voice]\nenabled = false\n',+ encoding="utf-8",)- assert _browser_voice_enabled(cfg) is True+ loaded = cfg_mod.load_config(path)+ assert loaded.browser_voice.enabled is False# ---------------------------------------------------------------------------