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(orb): give the mascot a real dictation look instead of silence
Ruben Lütked55ca2309b1c
diff --git a/tests/unit/ui/test_orb_mascot_dictation_look.py b/tests/unit/ui/test_orb_mascot_dictation_look.pynew file mode 100644index 0000000000..1bd771106f--- /dev/null+++ b/tests/unit/ui/test_orb_mascot_dictation_look.py@@ -0,0 +1,331 @@+"""A dictation must be VISIBLE on the mascot orb, not only on the bar.++The dictation shortcut promises the same thing the wake word does: something+rises on screen, shows it is listening, then shows it is working, then goes+away. The bar surface delivered that; the mascot orb — the classic display+style, and the one wired on the Windows/Linux native path — delivered nothing+at all, and the failure was invisible from the calling side.++Why it was invisible: ``OrbBusBridge._show_dictation_mode`` wraps the surface+call in a try/except and falls back to the listening look when the surface+rejects the mode. ``OrbOverlay.show`` used to validate the mode *inside* the+closure it hands to its Tk thread, so an unknown mode was dropped later, on+another thread, and the call returned successfully. The fallback therefore+never ran and the user saw nothing — the class of bug where a queue swallows a+rejection and the caller is told everything is fine.++Two things had to be true for that to be fixed, and this file pins both:++1. The mascot renders the dictation modes for real — recording is mic-driven,+ transcribing is a steady work pulse — so nothing has to fall back at all.+2. ``show`` validates on the CALLER's thread, before queuing, so the fallback+ in the bridge is reachable for any surface that genuinely cannot render a+ mode.++Plus a zero-regression budget on the voice modes the orb already had.+"""++from __future__ import annotations++import asyncio+import sys+import threading+import time+from pathlib import Path+from unittest.mock import MagicMock++import pytest++_REPO_ROOT = Path(__file__).resolve().parents[3]+if str(_REPO_ROOT) in sys.path:+ sys.path.remove(str(_REPO_ROOT))+sys.path.insert(0, str(_REPO_ROOT))+sys.modules.pop("ui", None)++pytest.importorskip("tkinter")+pytest.importorskip("numpy")+pytest.importorskip("PIL")++try: # noqa: SIM105 — deliberate try-import (top-level `ui` discovery quirk)+ from ui.orb.bus_bridge import OrbBusBridge # type: ignore[import-not-found]+ from ui.orb.overlay import OrbOverlay, mode_energy # type: ignore[import-not-found]+except ModuleNotFoundError: # pragma: no cover+ pytest.skip(+ "ui.orb not importable in this pytest pythonpath — run from repo root.",+ allow_module_level=True,+ )++from jarvis.core.events import ( # noqa: E402+ DictationCompleted,+ DictationStarted,+ DictationTranscribing,+)+from jarvis.ui.jarvisbar.modes import ( # noqa: E402+ DICTATION_MODES,+ MODES,+ VOICE_MODES,+)+++class _FakeBus:+ def subscribe(self, *_a, **_k) -> None:+ pass+++def _headless_mascot() -> tuple[OrbOverlay, MagicMock]:+ """A real ``OrbOverlay`` with a stand-in Tk root, driven inline.++ ``start()`` is what builds the real window, and it is deliberately not+ called: this exercises the live ``show``/``hide``/``_set_mode`` code paths+ without putting a mascot on anybody's desktop. Claiming this thread as the+ Tk thread makes ``_enqueue_ui`` run its closures immediately instead of+ parking them on a queue nothing drains.+ """+ orb = OrbOverlay()+ root = MagicMock()+ orb._root = root+ orb._mac_transparent = False # normally set by start()+ orb._t0 = time.perf_counter()+ orb._tk_thread_id = threading.get_ident()+ return orb, root+++async def _drain(bridge: OrbBusBridge) -> None:+ """Cancel the lane's timers and let the loop settle."""+ for attr in ("_dictation_standdown_task", "_dictation_failsafe_task"):+ task = getattr(bridge, attr, None)+ if task is not None and not task.done():+ task.cancel()+ await asyncio.sleep(0)+++def _deferred_hide_callbacks(root: MagicMock) -> list:+ """The callbacks the min-show guard parked via ``root.after``."""+ return [+ call.args[1]+ for call in root.after.call_args_list+ if len(call.args) >= 2 and callable(call.args[1])+ ]+++# --------------------------------------------------------------------------+# The whole lifecycle, against the real mascot surface+# --------------------------------------------------------------------------+async def test_a_dictation_is_visible_on_the_mascot_from_key_down_to_close() -> None:+ """Press → speak → release → done, driven through the real bridge into the+ real mascot surface. Every phase must leave a visible trace."""+ orb, root = _headless_mascot()+ bridge = OrbBusBridge( # type: ignore[arg-type]+ bus=_FakeBus(),+ orb=orb,+ hide_on_idle=True,+ idle_animations_enabled=False,+ )++ # 1. Key down — the mascot rises, in its own recording look.+ await bridge._on_dictation_started(DictationStarted(target="insert"))+ assert root.deiconify.called, "the mascot never came up for a dictation"+ assert orb._mode == "dictate", (+ f"the mascot is in {orb._mode!r}; a dictation must not borrow a voice mode"+ )++ # 2. Speaking — the live mic level reaches the surface and drives the look.+ bridge._on_mic_level(0.7)+ assert orb._ext_level == pytest.approx(0.7)+ assert mode_energy(orb._mode, 1.0, orb._ext_level) == pytest.approx(0.7)++ # 3. Release — the working look, visibly a different mode.+ await bridge._on_dictation_transcribing(DictationTranscribing())+ assert orb._mode == "dictate_transcribing"++ # 4. Done — the mascot stands down and is withdrawn.+ root.reset_mock()+ await bridge._on_dictation_completed(DictationCompleted(text="hello there", outcome="inserted"))+ bridge._schedule_dictation_standdown(0.0)+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ await _drain(bridge)++ # The min-show guard defers the withdraw rather than blinking the mascot+ # away; running the callback it parked proves the withdraw is what lands.+ deferred = _deferred_hide_callbacks(root)+ assert deferred, "the stand-down never armed a hide"+ for callback in deferred:+ callback()+ assert root.withdraw.called, "the mascot stayed on screen after the dictation"+++async def test_the_mascot_never_needs_the_voice_mode_fallback() -> None:+ """The bridge keeps a listening-look fallback for foreign surfaces. The+ mascot must never reach it — it has to render dictation as dictation."""+ orb, _root = _headless_mascot()+ bridge = OrbBusBridge( # type: ignore[arg-type]+ bus=_FakeBus(),+ orb=orb,+ hide_on_idle=True,+ idle_animations_enabled=False,+ )+ seen: list[str] = []+ original = orb.show++ def _record(mode: str = "listen") -> None:+ seen.append(mode)+ original(mode=mode)++ orb.show = _record # type: ignore[method-assign]++ await bridge._on_dictation_started(DictationStarted(target="insert"))+ await bridge._on_dictation_transcribing(DictationTranscribing())+ await _drain(bridge)++ assert seen == ["dictate", "dictate_transcribing"]+++# --------------------------------------------------------------------------+# The root cause: a rejection must reach the caller, not a background thread+# --------------------------------------------------------------------------+def test_an_unknown_mode_is_rejected_on_the_callers_thread() -> None:+ """The bridge's fallback is only reachable if the surface says no HERE.++ The Tk thread id is deliberately foreign, so the old implementation would+ have queued the call, returned successfully, and dropped the mode later+ where nothing could observe it.+ """+ orb, _root = _headless_mascot()+ orb._tk_thread_id = threading.get_ident() + 1 # never this thread++ with pytest.raises(ValueError, match="Unknown mode"):+ orb.show(mode="nonsense")+ with pytest.raises(ValueError, match="Unknown mode"):+ orb.set_mode("nonsense")++ assert orb._ui_queue.empty(), "a rejected mode must not be queued for later"+++def test_a_surface_that_rejects_late_is_why_the_bridge_keeps_a_fallback() -> None:+ """Counter-proof for the bug shape: a surface that accepts the call and+ only drops the mode on its own thread leaves the bridge no way to know, so+ the fallback cannot run and the user sees nothing."""+ dropped: list[str] = []++ class _LateRejectingSurface:+ """The pre-fix ``OrbOverlay``: validation happens after the handoff."""++ def show(self, mode: str = "listen") -> None:+ def _apply() -> None: # would run on the surface's own thread+ if mode not in VOICE_MODES:+ dropped.append(mode)++ _apply() # the handoff is what hides this from the caller++ bridge = OrbBusBridge( # type: ignore[arg-type]+ bus=_FakeBus(),+ orb=_LateRejectingSurface(),+ hide_on_idle=True,+ idle_animations_enabled=False,+ )+ bridge._show_dictation_mode("dictate")++ assert dropped == ["dictate"] # silently swallowed, no fallback triggered+++# --------------------------------------------------------------------------+# The look itself+# --------------------------------------------------------------------------+def test_recording_is_driven_by_the_live_mic_level() -> None:+ for level in (0.4, 0.75, 1.0):+ assert mode_energy("dictate", 0.0, level) == pytest.approx(level)+++def test_a_silent_moment_while_recording_still_breathes() -> None:+ """A quiet pause must read as "I am listening", never as a dead mascot."""+ for t in (0.0, 0.7, 1.9, 3.3, 5.0):+ assert mode_energy("dictate", t, 0.0) > 0.05+ assert mode_energy("dictate", t, None) > 0.05+++def test_transcribing_ignores_the_stale_level_the_mic_left_behind() -> None:+ """The mic feed ends when the key is released. Honouring the last sample+ would freeze the mascot at whatever loudness the user ended on."""+ for t in (0.0, 1.1, 2.4):+ quiet = mode_energy("dictate_transcribing", t, 0.0)+ loud = mode_energy("dictate_transcribing", t, 0.95)+ assert quiet == pytest.approx(loud)+ assert quiet > 0.0+++def test_the_working_pulse_actually_moves() -> None:+ samples = {+ round(mode_energy("dictate_transcribing", t, None), 4) for t in (0.0, 0.4, 0.8, 1.2, 1.6)+ }+ assert len(samples) > 1, "a static level would look identical to a frozen orb"+++def test_every_energy_value_stays_in_range() -> None:+ for mode in MODES:+ for level in (None, 0.0, 0.5, 1.0):+ for t in (0.0, 1.3, 4.7):+ assert 0.0 <= mode_energy(mode, t, level) <= 1.0+++# --------------------------------------------------------------------------+# Zero-regression budget on the voice modes+# --------------------------------------------------------------------------+def test_the_voice_modes_keep_their_exact_curves() -> None:+ """The wake-word turn and the thinking animation must be untouched."""+ import math++ for t in (0.0, 1.7, 4.2):+ assert mode_energy("idle", t, None) == 0.0+ assert mode_energy("speak", t, None) == pytest.approx(+ 0.35 + 0.25 * math.sin(t * 1.8) + 0.1 * math.sin(t * 3.3)+ )+ assert mode_energy("think", t, None) == pytest.approx(0.2 + 0.12 * math.sin(t * 2.5))+ assert mode_energy("listen", t, None) == pytest.approx(+ 0.25 + 0.18 * math.sin(t * 1.4) + 0.08 * math.sin(t * 2.7)+ )+ # A live level still wins for every voice mode.+ for mode in VOICE_MODES:+ assert mode_energy(mode, t, 0.6) == pytest.approx(0.6)+++def test_the_voice_modes_are_still_accepted_by_the_surface() -> None:+ orb, root = _headless_mascot()+ for mode in VOICE_MODES:+ orb.show(mode=mode)+ assert orb._mode == mode+ assert root.deiconify.call_count == len(VOICE_MODES)+++async def test_the_none_style_stays_a_silent_no_op() -> None:+ """A user who turned the overlay off must still get nothing — the surface+ accepts every mode and never raises, so the bridge's fallback stays out of+ it and no window is conjured onto a deliberately empty screen."""+ from jarvis.ui.jarvisbar import NullOverlay++ surface = NullOverlay()+ bridge = OrbBusBridge( # type: ignore[arg-type]+ bus=_FakeBus(),+ orb=surface,+ hide_on_idle=True,+ idle_animations_enabled=False,+ )++ await bridge._on_dictation_started(DictationStarted(target="insert"))+ bridge._on_mic_level(0.5)+ await bridge._on_dictation_transcribing(DictationTranscribing())+ await bridge._on_dictation_completed(DictationCompleted(text="hi", outcome="inserted"))+ await _drain(bridge)++ assert not hasattr(surface, "_root")+++def test_the_surface_and_the_bar_share_one_mode_vocabulary() -> None:+ """The orb reads the modes from the single definition instead of restating+ them — the hand-copied-enum drift this repo has been bitten by repeatedly.+ """+ orb, _root = _headless_mascot()+ for mode in MODES:+ orb.show(mode=mode)+ assert orb._mode == mode+ assert set(DICTATION_MODES) <= set(MODES)diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex bc62c2fbe2..c2d865dcc2 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -947,13 +947,28 @@ class OrbBusBridge:def _show_dictation_mode(self, mode: str) -> None:"""Drive the current surface into a dictation coarse mode.- Every JarvisBar surface accepts the dictation modes. The mascot orb is- an older surface that validates against the four voice modes and raises- on anything else; for it the honest equivalent of "recording" is its- listening look, which carries no destructive affordance (the mascot has- no close-X — only drag and the four-click mute gesture), so falling back- cannot arm one. A surface that rejects both is left alone: a missing- visual is cosmetic, and it must never break the bus.+ Every surface this app ships renders both dictation modes natively: the+ JarvisBar as the equalizer and the orbital core, the mascot orb as a+ mic-driven halo and a steady work pulse (``overlay.mode_energy``). So on+ every display style a dictation is actually visible, which is the whole+ point of the feature.++ The fallback below is for a surface this bridge does not own — an older+ or third-party one that only knows the four voice modes. For such a+ surface the honest equivalent of "recording" is its listening look,+ which on the mascot carries no destructive affordance (it has no+ close-X — only drag and the four-click mute gesture), so falling back+ cannot arm one.++ It only works because a surface reports the rejection SYNCHRONOUSLY, on+ this thread. A surface that queues the call onto its own UI thread and+ validates there returns "successfully" and drops the mode later, where+ no exception can reach us — the failure that left the mascot showing+ nothing at all. ``OrbOverlay.show`` validates before it queues for+ exactly this reason.++ A surface that rejects both modes is left alone: a missing visual is+ cosmetic, and it must never break the bus."""try:self._orb.show(mode=mode)diff --git a/ui/orb/overlay.py b/ui/orb/overlay.pyindex 3323df8b5b..dafea01598 100644--- a/ui/orb/overlay.py+++ b/ui/orb/overlay.py@@ -23,8 +23,10 @@ Rendering pipeline:Public API:overlay = OrbOverlay(style="mascot") # SWG/Gigi PNGoverlay.start() # blocks until mainloop exit- overlay.show(mode="listen")+ overlay.show(mode="listen") # voice modes: idle/listen/speak/thinkoverlay.show(mode="speak")+ overlay.show(mode="dictate") # dictation modes: recording ...+ overlay.show(mode="dictate_transcribing") # ... and transcribingoverlay.hide()overlay.set_level(0.42)overlay.set_style("mascot") # runtime switch, no restart@@ -61,6 +63,7 @@ from PIL import Image, ImageDraw, ImageFilter, ImageTkfrom jarvis.core.config import DEFAULT_CONFIG_FILE as JARVIS_TOML_PATHfrom jarvis.core.win32_dpi import ensure_dpi_awareness as _ensure_dpi_awareness+from jarvis.ui.jarvisbar.modes import MODESfrom ui.orb.animations import (ANIMATION_REGISTRY,Animation,@@ -240,6 +243,48 @@ def _transcript_body_height(line_count: int, line_height: int) -> int:return (BUBBLE_PADDING_Y * 2) + (max(1, line_height) * visible_lines)+def mode_energy(mode: str, t: float, ext_level: float | None) -> float:+ """Return the raw drive level (0..1) the mascot renders ``mode`` with.++ The mascot has exactly one expressive channel: energy. It feeds the halo+ threshold, the breathing scale and the brightness, so "what a mode looks+ like" on this surface *is* the curve this function returns. Pulled out of+ :meth:`MascotRenderer.render` so the per-mode contract is directly testable+ without a Tk root, a PNG asset or a frame buffer.++ Voice modes keep their historical behaviour to the letter: a live level+ (mic or TTS loudness) always wins, and each mode has its own synthetic+ fallback curve.++ The two dictation modes are deliberately NOT variations of ``listen``:++ * ``dictate`` — recording. The dictation session feeds the very same mic+ level channel, so the live signal drives the halo exactly like the bar's+ equalizer. It is clamped up from a floor, because a quiet moment while+ recording must still read as "I am listening", never as a dead mascot.+ * ``dictate_transcribing`` — the key is released and the mic feed has+ stopped, so the last sample would otherwise freeze the mascot at whatever+ loudness the user happened to end on. This mode therefore ignores the+ stale level outright and runs a steady work pulse instead — the mascot's+ equivalent of the bar's orbital core.+ """+ if mode == "dictate":+ live = 0.0 if ext_level is None else max(0.0, min(1.0, ext_level))+ floor = 0.22 + 0.14 * math.sin(t * 1.6)+ return max(0.0, min(1.0, max(live, floor)))+ if mode == "dictate_transcribing":+ return max(0.0, min(1.0, 0.30 + 0.16 * math.sin(t * 2.2)))+ if ext_level is not None:+ return max(0.0, min(1.0, ext_level))+ if mode == "speak":+ return 0.35 + 0.25 * math.sin(t * 1.8) + 0.1 * math.sin(t * 3.3)+ if mode == "think":+ return 0.2 + 0.12 * math.sin(t * 2.5)+ if mode == "listen":+ return 0.25 + 0.18 * math.sin(t * 1.4) + 0.08 * math.sin(t * 2.7)+ return 0.0++def _resolve_mascot_path(path_str: str | None) -> Path | None:"""Looks for the mascot PNG in the common locations.@@ -598,17 +643,9 @@ class MascotRenderer:# ------------------------------------------------------------------def render(self, t: float, mode: str, ext_level: float | None) -> Image.Image:- # Level smoothing mirrors the previous voice-reactive dynamics.- if ext_level is not None:- raw = max(0.0, min(1.0, ext_level))- elif mode == "speak":- raw = 0.35 + 0.25 * math.sin(t * 1.8) + 0.1 * math.sin(t * 3.3)- elif mode == "think":- raw = 0.2 + 0.12 * math.sin(t * 2.5)- elif mode == "listen":- raw = 0.25 + 0.18 * math.sin(t * 1.4) + 0.08 * math.sin(t * 2.7)- else:- raw = 0.0+ # Level smoothing mirrors the previous voice-reactive dynamics; the+ # per-mode curve itself lives in ``mode_energy`` so it stays testable.+ raw = mode_energy(mode, t, ext_level)self._level += (raw - self._level) * 0.08breath = 0.5 + 0.5 * math.sin(t * 0.9)energy = max(self._level, breath * 0.1)@@ -2008,6 +2045,22 @@ class OrbOverlay:SHOW_MIN_DURATION_S: float = 2.5def show(self, mode: str = "listen") -> None:+ """Reveal the mascot in ``mode``. Thread-safe.++ The mode is validated SYNCHRONOUSLY, on the caller's thread, before the+ reveal is queued. That ordering is the contract, not a detail: the work+ itself is handed to the Tk thread, so a mode rejected inside ``_show``+ would be dropped later, on another thread, where no exception can ever+ reach the caller — the call would return "successfully" and the user+ would simply see nothing. Callers that keep a fallback look for a+ surface which cannot render a mode depend on hearing about the+ rejection here.++ Raises ``ValueError`` for a mode outside the shared vocabulary.+ """+ if mode not in MODES:+ raise ValueError(f"Unknown mode: {mode!r} (allowed: {', '.join(MODES)})")+def _show() -> None:self._cancel_pending_hide()self._set_mode(mode)@@ -2220,6 +2273,12 @@ class OrbOverlay:self._enqueue_ui(_stop)def set_mode(self, mode: str) -> None:+ """Repaint the mascot in ``mode`` without touching visibility.++ Validated synchronously for the same reason as :meth:`show` — see there.+ """+ if mode not in MODES:+ raise ValueError(f"Unknown mode: {mode!r} (allowed: {', '.join(MODES)})")self._enqueue_ui(lambda: self._set_mode(mode))def set_level(self, level: float) -> None:@@ -2353,8 +2412,10 @@ class OrbOverlay:# --- Internal --------------------------------------------------------def _set_mode(self, mode: str) -> None:- if mode not in ("idle", "listen", "speak", "think"):- raise ValueError(f"Unknown mode: {mode}")+ """Apply ``mode`` on the Tk thread. The public entry points already+ validated it; this stays a guard for the internal call sites."""+ if mode not in MODES:+ raise ValueError(f"Unknown mode: {mode!r} (allowed: {', '.join(MODES)})")self._mode = modedef _enqueue_ui(self, fn) -> None: