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): make the bar's X abort a chat turn, not just a voice turn
Ruben Lütke2b4b77ce6791
diff --git a/jarvis/core/runtime_refs.py b/jarvis/core/runtime_refs.pyindex 78a74c0685..f51a48a605 100644--- a/jarvis/core/runtime_refs.py+++ b/jarvis/core/runtime_refs.py@@ -25,13 +25,23 @@ these are write-once-at-bootstrap / read-many. No lock needed."""from __future__ import annotations+import asynciofrom typing import Any+from loguru import logger+# Each ref is a 1-element list so the setter can rebind without ``global``._BRAIN_MANAGER: list[Any] = []_SPEECH_PIPELINE: list[Any] = []_MCP_REGISTRY: list[Any] = []+# The currently-running CHAT brain turn, as ``(task, loop)``. Registered by the+# chat dispatcher (``desktop_app._on_user_message``) for the lifetime of one+# ``await generate(...)`` and cancelled edge-triggered by the voice-hangup+# chokepoint so the bar's X stops a chat turn too — not just a voice turn (live+# bug 2026-06-19: ~27 ignored X presses while a chat turn kept thinking).+_ACTIVE_CHAT_TURN: list[Any] = []+def _set(ref: list[Any], value: Any) -> None:if ref:@@ -70,8 +80,59 @@ def get_mcp_registry() -> Any | None:return _MCP_REGISTRY[0] if _MCP_REGISTRY else None+def set_active_chat_turn(task: asyncio.Task[Any], loop: asyncio.AbstractEventLoop) -> None:+ """Arm the bar's X for THIS chat turn.++ Called by the chat dispatcher right before it awaits ``brain.generate(...)``.+ The owning ``loop`` is stored alongside the task so the cancel can be+ scheduled thread-safely — ``request_hangup`` runs on the Tk overlay thread,+ not the asyncio loop.+ """+ if _ACTIVE_CHAT_TURN:+ _ACTIVE_CHAT_TURN[0] = (task, loop)+ else:+ _ACTIVE_CHAT_TURN.append((task, loop))+++def clear_active_chat_turn(task: asyncio.Task[Any]) -> None:+ """Disarm the X once the turn is done — but only for THIS task.++ A late ``finally`` from a finished turn must never retract the registration+ of the turn that is running now, or it would silently disarm the X.+ """+ if _ACTIVE_CHAT_TURN and _ACTIVE_CHAT_TURN[0][0] is task:+ _ACTIVE_CHAT_TURN.clear()+++def cancel_active_chat_turn() -> bool:+ """Cancel the in-flight chat turn, if any. The single chat-abort chokepoint.++ Returns ``True`` when a turn was armed (a cancel was scheduled), ``False``+ when nothing was running. Edge-triggered — it fires exactly when the X is+ pressed — so there is no stale-``Event`` problem: an idle chat path is a+ clean no-op. The cancel is marshalled onto the task's owning loop via+ ``call_soon_threadsafe`` because the caller may be on the Tk thread; a dead+ loop is swallowed (the turn is gone anyway). Cancelling also disarms, so a+ second X press is a no-op.+ """+ if not _ACTIVE_CHAT_TURN:+ return False+ task, loop = _ACTIVE_CHAT_TURN[0]+ _ACTIVE_CHAT_TURN.clear()+ if task.done():+ return False+ try:+ loop.call_soon_threadsafe(task.cancel)+ except RuntimeError:+ # Loop already closed / not running — the turn cannot still be alive.+ logger.debug("cancel_active_chat_turn: owning loop is gone (non-fatal)")+ return False+ return True++def _reset_for_tests() -> None:"""Clear all refs. Test-only helper (fixtures call this in teardown)."""_BRAIN_MANAGER.clear()_SPEECH_PIPELINE.clear()_MCP_REGISTRY.clear()+ _ACTIVE_CHAT_TURN.clear()diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 37e97a36f3..f7fa839919 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -3425,6 +3425,17 @@ class SpeechPipeline:log.info("Voice-Hangup: active Computer-Use mission cancelled.")except Exception: # noqa: BLE001 — hangup must never crashlog.debug("CU cancel-on-hangup failed (non-fatal)", exc_info=True)+ # The X must also stop a CHAT turn, not only a voice turn. A chat turn+ # runs on a separate dispatcher (``desktop_app._on_user_message``) that+ # never observes ``_hangup_event`` — so before this it kept thinking+ # through every X press (live bug 2026-06-19: ~27 ignored presses). The+ # cancel is edge-triggered and loop-safe (this may run on the Tk thread).+ try:+ from jarvis.core.runtime_refs import cancel_active_chat_turn+ if cancel_active_chat_turn():+ log.info("Voice-Hangup: active chat turn cancelled.")+ except Exception: # noqa: BLE001 — hangup must never crash+ log.debug("chat-turn cancel-on-hangup failed (non-fatal)", exc_info=True)# Discard any pending continuation fragment so it can't leak into the# next voice session (the user has explicitly ended this one), and# cancel its clarifying-question timer so no question fires after hangup.diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex fd751cc9a1..6b6b7076ff 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -21,7 +21,7 @@ import sysimport threadingimport timefrom pathlib import Path-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Awaitable# Windows-UTF8-Fix (analog zu jarvis.__main__)if sys.platform == "win32":@@ -353,6 +353,52 @@ def _is_brain_diagnostic(text: str) -> bool:)+# Returned by ``_await_cancellable_chat_turn`` when the bar's X aborted the turn.+# A sentinel (not a raised ``CancelledError``) so the dispatcher can absorb the+# X-press while a genuine outer/shutdown cancellation still propagates untouched.+_CHAT_TURN_ABORTED = object()+++async def _await_cancellable_chat_turn(+ coro: Awaitable[Any], loop: asyncio.AbstractEventLoop+) -> Any:+ """Run a chat brain turn as a task the bar's X can abort.++ The voice path already honours the X via the speech pipeline's hangup+ waiter; a chat turn runs on a separate dispatcher, so it must arm the same+ chokepoint itself. The turn is registered with ``runtime_refs`` for the+ duration of the ``await`` and disarmed in ``finally`` (live bug 2026-06-19:+ ~27 ignored X presses while a chat turn kept thinking).++ Two cancellations are told apart precisely (code-review 2026-06-19). Note+ that ``task.cancelled()`` is NOT a usable discriminator: cancelling the outer+ task also cancels the inner one it awaits (asyncio cancels the ``_fut_waiter``),+ so the inner task ends cancelled in BOTH cases. The reliable signal is whether+ *this* coroutine's own task carries a pending cancellation:++ * the X cancels only the INNER ``task`` (via ``cancel_active_chat_turn`` →+ ``call_soon_threadsafe(task.cancel)``); our own task is untouched+ (``current_task().cancelling() == 0``) → we return ``_CHAT_TURN_ABORTED``+ so the caller drops to IDLE; and+ * an OUTER cancellation (shutdown / bus-gather teardown) cancels *our* task+ (``cancelling() > 0``) → we re-raise, honouring Python's cooperative+ -cancellation contract (the inner task is already cancelled with us).+ """+ from jarvis.core import runtime_refs++ task = asyncio.create_task(coro)+ runtime_refs.set_active_chat_turn(task, loop)+ try:+ return await task+ except asyncio.CancelledError:+ current = asyncio.current_task()+ if current is not None and current.cancelling() > 0:+ raise # our own task is being torn down — propagate+ return _CHAT_TURN_ABORTED # only the inner turn was cancelled — the X+ finally:+ runtime_refs.clear_active_chat_turn(task)++# ---------------------------------------------------------------------------# Single-Instance-Lock# ---------------------------------------------------------------------------@@ -755,21 +801,31 @@ class DesktopApp:)return+ loop = asyncio.get_running_loop()try:await supervisor.set_state("THINKING")generate = getattr(brain, "generate", None)+ # Both brain shapes run as an X-abortable task so the bar's X+ # (request_hangup → cancel_active_chat_turn) stops a chat turn+ # too, not just a voice turn (bug 2026-06-19: the X was ignored+ # on the chat path).if callable(generate):# source_layer lets the router exempt a drag-dropped mission# recap (ui.web.ws.mission_inject) from force-spawn — a recap# is discussed inline, never re-dispatched (doom-loop fix# 2026-06-16). Other callers default to None (normal routing).- reply = await generate(- evt.text,- trace_id=evt.trace_id,- source_layer=evt.source_layer,+ reply = await _await_cancellable_chat_turn(+ generate(+ evt.text,+ trace_id=evt.trace_id,+ source_layer=evt.source_layer,+ ),+ loop,)else:- reply = await brain(evt.text)+ reply = await _await_cancellable_chat_turn(+ brain(evt.text), loop+ )except Exception as exc: # noqa: BLE001detail = f"{type(exc).__name__}: {exc}"message = f"Brain error: {detail}"@@ -799,6 +855,13 @@ class DesktopApp:await supervisor.set_state("IDLE")return+ if reply is _CHAT_TURN_ABORTED:+ # The user pressed the bar's X mid-think — honour it and drop+ # back to IDLE instead of speaking a half-finished turn.+ logger.info("Chat turn aborted by the bar's X — back to IDLE.")+ await supervisor.set_state("IDLE")+ return+try:await supervisor.set_state("SPEAKING")if reply:diff --git a/tests/unit/core/test_runtime_refs_chat_abort.py b/tests/unit/core/test_runtime_refs_chat_abort.pynew file mode 100644index 0000000000..ce3d0e20e7--- /dev/null+++ b/tests/unit/core/test_runtime_refs_chat_abort.py@@ -0,0 +1,93 @@+"""The bar's X must abort an in-flight CHAT turn, not just a voice turn.++Live bug 2026-06-19: clicking the whisper-bar X (``request_hangup``) while a+chat-originated brain turn was THINKING did nothing — the chat dispatcher+(``desktop_app._on_user_message``) ran a bare ``await generate(...)`` with no+task handle and never observed the voice pipeline's ``_hangup_event``. The+earlier fix only made the *voice* thinking phase abortable.++These tests cover the decoupled abort seam in ``runtime_refs``: the chat+dispatcher registers its running task here and the hangup chokepoint cancels it+edge-triggered (no stale-``Event`` problem), thread-safely via the owning loop.+"""+from __future__ import annotations++import asyncio++import pytest++from jarvis.core import runtime_refs++[email protected](autouse=True)+def _clean_refs():+ runtime_refs._reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+++async def test_cancel_active_chat_turn_cancels_registered_task():+ """A registered chat turn is cancelled when the X fires request_hangup."""+ loop = asyncio.get_running_loop()+ started = asyncio.Event()++ async def slow_turn():+ started.set()+ await asyncio.sleep(60) # an in-flight brain turn the user wants to stop+ return "should never arrive"++ task = asyncio.create_task(slow_turn())+ await started.wait()+ runtime_refs.set_active_chat_turn(task, loop)++ assert runtime_refs.cancel_active_chat_turn() is True++ with pytest.raises(asyncio.CancelledError):+ await task+ assert task.cancelled()+++async def test_cancel_is_noop_when_no_turn_active():+ """No active chat turn → the X is a harmless no-op (returns False)."""+ assert runtime_refs.cancel_active_chat_turn() is False+++async def test_clear_only_clears_the_matching_task():+ """A finished turn must not clear a newer turn's registration.++ Turns are serialized by the supervisor, but if an old turn's ``finally``+ runs late it must only retract its OWN task — otherwise it would disarm the+ X for the turn currently running.+ """+ loop = asyncio.get_running_loop()+ old = asyncio.create_task(asyncio.sleep(60))+ new = asyncio.create_task(asyncio.sleep(60))++ runtime_refs.set_active_chat_turn(new, loop)+ runtime_refs.clear_active_chat_turn(old) # stale clear — must be ignored++ # ``new`` is still armed, so the X still cancels it.+ assert runtime_refs.cancel_active_chat_turn() is True++ for t in (old, new):+ t.cancel()+ with pytest.raises(asyncio.CancelledError):+ await t+++async def test_clear_disarms_so_a_later_x_is_a_noop():+ """After the turn finishes and clears itself, a stray X press does nothing."""+ loop = asyncio.get_running_loop()+ task = asyncio.create_task(asyncio.sleep(60))+ runtime_refs.set_active_chat_turn(task, loop)+ runtime_refs.clear_active_chat_turn(task)++ assert runtime_refs.cancel_active_chat_turn() is False++ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await taskdiff --git a/tests/unit/speech/test_hangup_cancels_chat_turn.py b/tests/unit/speech/test_hangup_cancels_chat_turn.pynew file mode 100644index 0000000000..babe3229c9--- /dev/null+++ b/tests/unit/speech/test_hangup_cancels_chat_turn.py@@ -0,0 +1,66 @@+"""The voice-hangup chokepoint must also cancel an in-flight CHAT turn.++Live bug 2026-06-19: the whisper-bar X (``request_hangup`` → ``_trigger_voice_hangup``)+set the voice ``_hangup_event`` and cancelled active Computer-Use, but a chat+turn dispatched through ``desktop_app._on_user_message`` runs on a separate path+that ignored the X — so the brain kept thinking through ~27 X presses. The fix+wires ``_trigger_voice_hangup`` to ``runtime_refs.cancel_active_chat_turn`` so the+single hangup chokepoint stops a chat turn too.+"""+from __future__ import annotations++import asyncio++import pytest++from jarvis.core import runtime_refs+from jarvis.speech.pipeline import SpeechPipeline+++class _FakePlayer:+ def stop(self) -> None: # the hangup stops the player first+ pass++[email protected](autouse=True)+def _clean_refs():+ runtime_refs._reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+++def _hangup_pipeline() -> SpeechPipeline:+ """A SpeechPipeline stub carrying only what ``_trigger_voice_hangup`` reads+ before the chat-cancel call (the continuation cleanup after it is wrapped in+ a swallowing try/except, so missing attrs there are harmless)."""+ p = SpeechPipeline.__new__(SpeechPipeline)+ p._player = _FakePlayer()+ p._session_end_reason = None+ p._hangup_event = asyncio.Event()+ return p+++async def test_voice_hangup_cancels_an_active_chat_turn():+ loop = asyncio.get_running_loop()+ started = asyncio.Event()++ async def chat_turn():+ started.set()+ await asyncio.sleep(60) # the brain is THINKING; the user hits X++ task = asyncio.create_task(chat_turn())+ await started.wait()+ runtime_refs.set_active_chat_turn(task, loop)++ _hangup_pipeline()._trigger_voice_hangup()++ with pytest.raises(asyncio.CancelledError):+ await task+ assert task.cancelled()+++async def test_voice_hangup_is_harmless_with_no_chat_turn():+ """A hangup with no chat turn armed must not raise."""+ _hangup_pipeline()._trigger_voice_hangup() # no exception == passdiff --git a/tests/unit/ui/test_cancellable_chat_turn.py b/tests/unit/ui/test_cancellable_chat_turn.pynew file mode 100644index 0000000000..dc0c94c8c1--- /dev/null+++ b/tests/unit/ui/test_cancellable_chat_turn.py@@ -0,0 +1,94 @@+"""The chat dispatcher must run its brain turn as a cancellable, X-armed task.++Extracted from ``desktop_app._on_user_message`` so the abort behaviour is unit+-testable. ``_await_cancellable_chat_turn`` distinguishes two kinds of+cancellation precisely (code-review 2026-06-19):++* the bar's X cancels the INNER brain task → the helper returns the+ ``_CHAT_TURN_ABORTED`` sentinel so the dispatcher drops to IDLE; and+* an OUTER cancellation (app shutdown / bus-gather teardown) is propagated+ unchanged (and the inner task is cancelled too, so it can't leak) — swallowing+ it would break Python's cooperative-cancellation contract.+"""+from __future__ import annotations++import asyncio++import pytest++from jarvis.core import runtime_refs+from jarvis.ui.desktop_app import _CHAT_TURN_ABORTED, _await_cancellable_chat_turn++[email protected](autouse=True)+def _clean_refs():+ runtime_refs._reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+++async def test_returns_reply_normally_and_disarms_the_x():+ async def generate():+ return "the answer"++ result = await _await_cancellable_chat_turn(+ generate(), asyncio.get_running_loop()+ )++ assert result == "the answer"+ # Turn done → the X is disarmed (a later press is a no-op).+ assert runtime_refs.cancel_active_chat_turn() is False+++async def test_x_press_returns_the_aborted_sentinel():+ started = asyncio.Event()++ async def generate():+ started.set()+ await asyncio.sleep(60) # the brain is THINKING+ return "should never arrive"++ loop = asyncio.get_running_loop()+ turn = asyncio.create_task(_await_cancellable_chat_turn(generate(), loop))+ await started.wait()++ # The bar's X → request_hangup → cancel_active_chat_turn (inner task only).+ assert runtime_refs.cancel_active_chat_turn() is True++ # The X path is absorbed: a sentinel, NOT a raised CancelledError.+ assert (await turn) is _CHAT_TURN_ABORTED+ # And it disarmed itself, so a stray second press does nothing.+ assert runtime_refs.cancel_active_chat_turn() is False+++async def test_outer_cancellation_propagates_and_cancels_the_inner_turn():+ """App shutdown cancels the dispatcher coroutine itself — that must NOT be+ swallowed (it would break clean teardown), and the inner brain task must be+ cancelled too so it can't leak."""+ started = asyncio.Event()+ inner_cleaned = asyncio.Event()++ async def generate():+ started.set()+ try:+ await asyncio.sleep(60)+ except asyncio.CancelledError:+ inner_cleaned.set()+ raise+ return "should never arrive"++ loop = asyncio.get_running_loop()+ outer = asyncio.create_task(_await_cancellable_chat_turn(generate(), loop))+ await started.wait()++ # Simulate shutdown: cancel the OUTER coroutine, NOT via the registry.+ outer.cancel()++ with pytest.raises(asyncio.CancelledError):+ await outer++ await asyncio.wait_for(inner_cleaned.wait(), timeout=1.0) # inner not leaked+ assert runtime_refs.cancel_active_chat_turn() is False # disarmed