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.

fix(jarvisbar): make close reliable during voice startup

Ruben Lütkea1033ddd02f8
diff --git a/desktop-ttu-latest.json b/desktop-ttu-latest.json
index 6909356f9a..bda25b7979 100644
--- a/desktop-ttu-latest.json
+++ b/desktop-ttu-latest.json
@@ -36,4 +36,4 @@
"anchor": "spawn -> /api/health responds 200 (= DesktopApp._wait_for_backend success = window creation point)",
"secondary_anchor": "median_bind_wall_ms = spawn -> BOOT_READY print (bootstrap bind; may precede a responsive health endpoint)",
"ttu_anchor": "spawn -> VOICE_USABLE_MS print (VoiceBootStatus ready=True: wake model warmed + VAD + TTS client up \u2014 the honest time-to-usable anchor; VOICE_READY_MS = pipeline task started is secondary)"
-}
\ No newline at end of file
+}
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index a3e53e46d8..d752cab004 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -22,6 +22,7 @@ import logging
import os
import random
import re
+import threading
import time
from collections import deque
from collections.abc import AsyncIterator, Awaitable, Callable
@@ -1437,6 +1438,13 @@ class SpeechPipeline:
self._state = PipelineState.IDLE
self._call_event = asyncio.Event()
self._hangup_event = asyncio.Event()
+ # ``request_hangup`` is also called by the JarvisBar's dedicated Tk
+ # thread. asyncio primitives are not thread-safe, so ``run()`` records
+ # their owning loop and external callers marshal the hangup onto it.
+ self._runtime_loop: asyncio.AbstractEventLoop | None = None
+ # A thread-safe edge latch keeps repeated X clicks from queueing the
+ # expensive hard-stop path more than once during the same teardown.
+ self._external_hangup_pending = threading.Event()
self._current_voice_session_id: str | None = None
# Configured voice mode and effective in-flight engine are deliberately
# separate. A settings write can happen while a call is already open;
@@ -3523,6 +3531,10 @@ class SpeechPipeline:
# ------------------------------------------------------------------
async def run(self) -> None:
+ # Capture the loop that owns ``_call_event`` / ``_hangup_event`` before
+ # warm-up. UI controls can become clickable while warm-up is still in
+ # progress, so recording it later would leave a small unsafe window.
+ self._runtime_loop = asyncio.get_running_loop()
await self._warmup()
# Permanent-Vision: Background-Refresh-Loop hier im Pipeline-Event-Loop
# starten. Ohne das kriegt `VisionContextProvider.current()` nie einen
@@ -4202,14 +4214,47 @@ class SpeechPipeline:
"""End the live voice session from outside the audio path.
The jarvis-bar's hover-to-close cross calls this (and any future UI
- close affordance). Thread-safe like ``request_voice_session``: it routes
- through the single hangup chokepoint, whose primitives (``Event.set``,
- player stop, CU-cancel) are safe to invoke from the Tk thread. A no-op
- in practice when no session is active — the never-consumed event is
- cleared at the next session start.
+ close affordance). The bar runs on a dedicated Tk thread, while the
+ hangup event and its waiters belong to the pipeline's asyncio loop.
+ Marshal the complete hard-stop chokepoint onto that owning loop; calling
+ ``asyncio.Event.set()`` directly from Tk is unsupported and can fail to
+ wake the waiter until unrelated I/O arrives. Repeated clicks during one
+ teardown are idempotent. A no-op request while idle is cleared when the
+ next session starts.
"""
+ pending = getattr(self, "_external_hangup_pending", None)
+ if pending is not None and pending.is_set():
+ log.debug("request_hangup ignored: external hangup already pending")
+ return
+ if pending is not None:
+ pending.set()
log.info("📵 request_hangup — closing the voice session")
- self._trigger_voice_hangup()
+
+ def _dispatch() -> None:
+ try:
+ self._trigger_voice_hangup()
+ except Exception:
+ # A failed dispatch must be retryable; successful requests stay
+ # latched until the authoritative session teardown reaches IDLE.
+ if pending is not None:
+ pending.clear()
+ raise
+
+ owner = getattr(self, "_runtime_loop", None)
+ try:
+ current = asyncio.get_running_loop()
+ except RuntimeError:
+ current = None
+ if owner is not None and owner.is_running() and current is not owner:
+ try:
+ owner.call_soon_threadsafe(_dispatch)
+ return
+ except RuntimeError:
+ # The loop closed between is_running() and scheduling. The
+ # synchronous fallback still stops audio/CU and is harmless
+ # when no asyncio waiter remains alive.
+ log.debug("request_hangup: owner loop closed during dispatch")
+ _dispatch()
def request_ptt_toggle(self) -> None:
"""Toggle endpoint-free dictation — the jarvis-bar's square button.
@@ -4235,10 +4280,19 @@ class SpeechPipeline:
active "listen" look when a wake popped it but the post-hangup wake-lock
cooldown rejected the session — no ``VoiceSessionStarted`` is published
and no ``IDLE`` state follows, so nothing resets the bar (freeze
- forensic 2026-06-28). The turn-state is the authoritative signal: it is
- ``IDLE`` iff no ``_active_session`` loop is running.
+ forensic 2026-06-28).
+
+ ``_state`` becomes ACTIVE before ``VoiceSessionStarted`` is published,
+ while ``_turn_state`` does not leave IDLE until every start subscriber
+ returns. A slow subscriber therefore creates a real session-start window
+ where checking only the turn-state misclassifies the visible X as an
+ idle-body click and calls ``request_voice_session()`` instead of hanging
+ up. Treat either lifecycle signal as active so the close control remains
+ valid throughout startup, the live turn, and teardown.
"""
return (
+ getattr(self, "_state", PipelineState.IDLE) is not PipelineState.IDLE
+ or
getattr(self, "_turn_state", TurnTakingState.IDLE)
is not TurnTakingState.IDLE
)
@@ -4808,6 +4862,7 @@ class SpeechPipeline:
log.info("🔒 Wake-Lock aktiv — ignoriere (noch %.1fs)", remaining)
self._ptt_mode = False
continue
+ self._external_hangup_pending.clear()
self._hangup_event.clear()
# Fresh session: forget any hard-hangup flag left by a no-op hangup
# while idle, so ONLY this session's own ending decides its lock.
@@ -4839,12 +4894,35 @@ class SpeechPipeline:
)
)
hangup_reason = HANGUP_ERROR
- log.info("Voice session accepted (configured engine=%s).", self._active_voice_mode)
- # Reveal the voice surface and enable microphone feedback.
- await self._set_turn_state(TurnTakingState.LISTENING)
try:
- await self._play_ack(ptt=self._ptt_mode)
- hangup_reason = await self._active_session()
+ # VoiceSessionStarted dispatch can legitimately take time (for
+ # example while desktop audio ducking enumerates other apps).
+ # The JarvisBar X is already visible during that await. If it
+ # was pressed, do not resurrect LISTENING, play an ack, or open
+ # the microphone after the user has explicitly closed the call.
+ if (
+ self._hangup_event.is_set()
+ or self._external_hangup_pending.is_set()
+ ):
+ hangup_reason = HANGUP_HOTKEY
+ log.info(
+ "Voice session cancelled during startup; skipping audio open."
+ )
+ else:
+ log.info(
+ "Voice session accepted (configured engine=%s).",
+ self._active_voice_mode,
+ )
+ # Reveal the voice surface and enable microphone feedback.
+ await self._set_turn_state(TurnTakingState.LISTENING)
+ await self._play_ack(ptt=self._ptt_mode)
+ if (
+ self._hangup_event.is_set()
+ or self._external_hangup_pending.is_set()
+ ):
+ hangup_reason = HANGUP_HOTKEY
+ else:
+ hangup_reason = await self._active_session()
except Exception as exc: # noqa: BLE001
log.exception("Voice session failed: %s", exc)
finally:
@@ -4889,6 +4967,7 @@ class SpeechPipeline:
self._state = PipelineState.IDLE
# Return the supervisor to IDLE and hide the active surface.
await self._set_turn_state(TurnTakingState.IDLE)
+ self._external_hangup_pending.clear()
if reopen_after_engine_change and self._activation_allowed():
# An internal engine reconnect has no response tail to
# protect against. Re-arm immediately with the latest
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index 2a1d2bfb8e..c091d2f895 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -120,6 +120,12 @@ _IDLE_SETTLE_TICKS = 30
TARGET_FRAME_MS = 16
MIN_FRAME_DELAY_MS = 1
+# Once the close-X is accepted, suppress rapid follow-up clicks long enough for
+# the authoritative IDLE state to arrive. Without this guard a double-click can
+# hit the same screen position after the optimistic visual collapse and be
+# reinterpreted as an idle-body click that immediately starts a new session.
+HANGUP_CLICK_GUARD_S = 1.0
+
def _primary_work_area() -> tuple[int, int, int, int] | None:
"""Primary-monitor work area (left, top, right, bottom) EXCLUDING the
@@ -195,6 +201,7 @@ class JarvisBarOverlay:
self._feedback_publisher: Callable[[str, dict], None] | None = None
self._on_show_window: Callable[[], None] | None = None
self._hovered = False # mouse over the bar → reveal the close cross
+ self._hangup_click_block_until = 0.0
# Local mirror of the global voice-mute state (mic muted FOR JARVIS only).
# Flipped optimistically on a mic-button click and reconciled by the
# authoritative VoiceMuteChanged via set_muted(). A bool write is atomic
@@ -795,6 +802,11 @@ class JarvisBarOverlay:
# session. All entries are thread-safe from the Tk thread.
if click_x is None:
click_x = renderer.WIN_W / 2
+ # The first accepted X click optimistically removes the active look.
+ # Ignore follow-up clicks during that short transition so they cannot be
+ # reclassified as idle-body clicks and accidentally reopen the session.
+ if time.monotonic() < self._hangup_click_block_until:
+ return
try:
from jarvis.core.runtime_refs import get_speech_pipeline
@@ -840,6 +852,14 @@ class JarvisBarOverlay:
hangup = getattr(pipeline, "request_hangup", None)
if callable(hangup):
hangup()
+ # Give immediate, local feedback instead of waiting for
+ # microphone/provider teardown plus the EventBus IDLE
+ # round-trip. The authoritative bridge state will
+ # reconcile the same value when teardown completes.
+ self._mode = "idle"
+ self._hangup_click_block_until = (
+ time.monotonic() + HANGUP_CLICK_GUARD_S
+ )
elif action == "talk":
pipeline.request_voice_session()
# "none" → nothing
diff --git a/tests/unit/speech/test_request_hangup_threadsafe.py b/tests/unit/speech/test_request_hangup_threadsafe.py
new file mode 100644
index 0000000000..e38a7caa22
--- /dev/null
+++ b/tests/unit/speech/test_request_hangup_threadsafe.py
@@ -0,0 +1,77 @@
+"""Regression coverage for JarvisBar-to-pipeline hangup dispatch.
+
+The bar owns a Tk thread, while SpeechPipeline's asyncio events and waiters
+belong to the pipeline loop. Directly setting an asyncio.Event from Tk is not
+thread-safe: in debug mode it raises, and in production it may not wake the
+loop until unrelated I/O arrives. The public request method must marshal once
+onto the owner loop and remain synchronous when it is already on that loop.
+"""
+from __future__ import annotations
+
+import asyncio
+import threading
+
+import pytest
+
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+def _pipeline(owner_loop) -> SpeechPipeline:
+ pipeline = SpeechPipeline.__new__(SpeechPipeline)
+ pipeline._runtime_loop = owner_loop
+ pipeline._external_hangup_pending = threading.Event()
+ return pipeline
+
+
+async def test_foreign_thread_hangup_runs_on_owner_loop() -> None:
+ loop = asyncio.get_running_loop()
+ loop_thread = threading.get_ident()
+ called_on: list[int] = []
+ pipeline = _pipeline(loop)
+ pipeline._trigger_voice_hangup = lambda: called_on.append(threading.get_ident())
+
+ caller = threading.Thread(target=pipeline.request_hangup)
+ caller.start()
+ caller.join(timeout=1.0)
+ assert not caller.is_alive()
+
+ await asyncio.sleep(0)
+ assert called_on == [loop_thread]
+
+
+async def test_owner_loop_hangup_runs_synchronously() -> None:
+ loop = asyncio.get_running_loop()
+ called_on: list[int] = []
+ pipeline = _pipeline(loop)
+ pipeline._trigger_voice_hangup = lambda: called_on.append(threading.get_ident())
+
+ pipeline.request_hangup()
+
+ assert called_on == [threading.get_ident()]
+
+
+class _QueuedLoop:
+ def __init__(self) -> None:
+ self.callbacks = []
+
+ def is_running(self) -> bool:
+ return True
+
+ def call_soon_threadsafe(self, callback) -> None:
+ self.callbacks.append(callback)
+
+
+def test_repeated_external_hangup_queues_only_once() -> None:
+ loop = _QueuedLoop()
+ calls = []
+ pipeline = _pipeline(loop)
+ pipeline._trigger_voice_hangup = lambda: calls.append("hangup")
+
+ pipeline.request_hangup()
+ pipeline.request_hangup()
+
+ assert len(loop.callbacks) == 1
+ loop.callbacks[0]()
+ assert calls == ["hangup"]
diff --git a/tests/unit/speech/test_request_voice_session.py b/tests/unit/speech/test_request_voice_session.py
index 1aacbec7ed..b47d5844a2 100644
--- a/tests/unit/speech/test_request_voice_session.py
+++ b/tests/unit/speech/test_request_voice_session.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import asyncio
-from jarvis.speech.pipeline import PipelineState, SpeechPipeline
+from jarvis.speech.pipeline import PipelineState, SpeechPipeline, TurnTakingState
class _FakeBrain:
@@ -57,6 +57,20 @@ def test_noop_when_not_idle_and_does_not_seed() -> None:
assert brain.seeded is None
+def test_session_is_active_while_start_subscribers_are_still_running() -> None:
+ """The close X must remain a hangup during the startup state gap.
+
+ PipelineState becomes ACTIVE before VoiceSessionStarted is dispatched, but
+ the turn-state stays IDLE until all start subscribers return. This is the
+ exact interval in which the live bar previously routed X clicks back into
+ request_voice_session(), which then rejected them as "pipeline not idle".
+ """
+ p = _pipe(state=PipelineState.ACTIVE)
+ p._turn_state = TurnTakingState.IDLE
+
+ assert p.is_session_active() is True
+
+
def test_noop_when_ptt_active() -> None:
p = _pipe(ptt=True)
assert p.request_voice_session() is False
diff --git a/tests/unit/speech/test_session_start_hangup.py b/tests/unit/speech/test_session_start_hangup.py
new file mode 100644
index 0000000000..e96cbcc0b2
--- /dev/null
+++ b/tests/unit/speech/test_session_start_hangup.py
@@ -0,0 +1,91 @@
+"""Regression coverage for closing a voice session during startup dispatch."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+
+import pytest
+
+from jarvis.core.events import VoiceSessionEnded, VoiceSessionStarted
+from jarvis.sessions.constants import HANGUP_HOTKEY
+from jarvis.speech.pipeline import PipelineState, SpeechPipeline, TurnTakingState
+
+
+class _FakeTTS:
+ name = "fake-tts"
+ supports_streaming = False
+
+ async def synthesize(self, text: str, **_kwargs) -> AsyncIterator[bytes]:
+ if False: # pragma: no cover - protocol-shaped empty iterator
+ yield text.encode()
+
+
+async def test_close_during_session_started_dispatch_skips_audio_startup() -> None:
+ """A close accepted while a slow start subscriber runs must stay closed.
+
+ The bar is already interactive while VoiceSessionStarted is being
+ dispatched. Once the dispatch returns, a pending hangup must bypass the
+ LISTENING transition, acknowledgement, and microphone/session startup.
+ """
+ pipeline = SpeechPipeline(tts=_FakeTTS(), bus=None, enable_whisper_wake=False)
+ pipeline._activation_allowed = lambda: True # type: ignore[method-assign]
+
+ ack_calls: list[bool] = []
+ active_calls: list[bool] = []
+ ended_events: list[VoiceSessionEnded] = []
+ cycle_done = asyncio.Event()
+
+ async def _publish(event) -> None: # noqa: ANN001
+ if isinstance(event, VoiceSessionStarted):
+ # Model the Tk-thread request being accepted while the owner loop is
+ # still inside a slow VoiceSessionStarted subscriber. Delay the
+ # actual loop callback deliberately: the synchronous, thread-safe
+ # pending latch must be sufficient to stop startup on its own.
+ class _DelayedOwnerLoop:
+ def is_running(self) -> bool:
+ return True
+
+ def call_soon_threadsafe(self, _callback) -> None: # noqa: ANN001
+ return None
+
+ pipeline._runtime_loop = _DelayedOwnerLoop()
+ pipeline.request_hangup()
+ elif isinstance(event, VoiceSessionEnded):
+ ended_events.append(event)
+
+ async def _set_turn_state(state, **_kwargs) -> None: # noqa: ANN001
+ if state is TurnTakingState.IDLE and ended_events:
+ cycle_done.set()
+
+ async def _play_ack(*, ptt: bool) -> None:
+ ack_calls.append(ptt)
+
+ async def _active_session() -> str:
+ active_calls.append(True)
+ return "unexpected"
+
+ async def _play_earcon(*_args, **_kwargs) -> None:
+ return None
+
+ pipeline._publish_event = _publish # type: ignore[method-assign]
+ pipeline._set_turn_state = _set_turn_state # type: ignore[method-assign]
+ pipeline._play_ack = _play_ack # type: ignore[method-assign]
+ pipeline._active_session = _active_session # type: ignore[method-assign]
+ pipeline._play_earcon = _play_earcon # type: ignore[method-assign]
+ pipeline._call_event.set()
+
+ state_task = asyncio.create_task(pipeline._state_loop())
+ try:
+ await asyncio.wait_for(cycle_done.wait(), timeout=1.0)
+ finally:
+ state_task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await state_task
+
+ assert ack_calls == []
+ assert active_calls == []
+ assert pipeline._state is PipelineState.IDLE
+ assert len(ended_events) == 1
+ assert ended_events[0].hangup_reason == HANGUP_HOTKEY
diff --git a/tests/unit/ui/jarvisbar/test_click_no_session_guard.py b/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
index 5f0cf3533f..d3a2827d7d 100644
--- a/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
+++ b/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
@@ -71,6 +71,34 @@ def test_live_session_close_x_still_hangs_up(monkeypatch):
assert fake.hangup_calls == 1 # a genuine session is still hang-up-able
assert fake.session_calls == 0
+ assert bar._mode == "idle" # immediate visual acknowledgement
+
+
+def test_repeated_close_click_does_not_reopen_session(monkeypatch):
+ """A rapid second click lands where the X used to be after the optimistic
+ collapse; it must not be reinterpreted as an idle-body session start."""
+ now = [100.0]
+ monkeypatch.setattr(
+ "jarvis.ui.jarvisbar.overlay.time.monotonic", lambda: now[0]
+ )
+ bar = JarvisBarOverlay()
+ bar._mode = "listen"
+ fake = _FakePipeline(session_active=True)
+ _patch_pipeline(monkeypatch, fake)
+
+ bar._on_click(_x_glyph(), hovered=True)
+ now[0] += 0.2
+ bar._on_click(_x_glyph(), hovered=True)
+
+ assert fake.hangup_calls == 1
+ assert fake.session_calls == 0
+
+ # The guard is bounded: after the backend has reached idle, the same area
+ # behaves like the normal idle body and can deliberately start a new call.
+ fake._session_active = False
+ now[0] += 1.0
+ bar._on_click(_x_glyph(), hovered=True)
+ assert fake.session_calls == 1
def test_missing_accessor_preserves_legacy_hangup(monkeypatch):