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): sync the equalizer bars to what is actually heard

Personal Jarvis Maintainercf395a6b2215
diff --git a/jarvis/audio/level_tap.py b/jarvis/audio/level_tap.py
index 78b34c7256..0b6337cf1f 100644
--- a/jarvis/audio/level_tap.py
+++ b/jarvis/audio/level_tap.py
@@ -5,6 +5,14 @@ and would spam the flight-recorder wildcard subscriber (5 s cap). The
jarvis-bar overlay registers a sink; the audio player publishes the per-flush
RMS. When no sink is registered, publishing is a cheap no-op (the player also
skips the RMS computation entirely via ``has_subscribers()``).
+
+Sync contract: ``stream.write()`` returns when PortAudio ACCEPTS a block, not
+when the device makes it audible — the gap is the reported output latency
+(hundreds of ms on Bluetooth). A level published at write time therefore leads
+the heard voice, and the last ~latency of every sentence plays with no levels
+at all (the bars died before the voice finished). ``feed``/``publish`` accept
+``delay_s`` so the player can schedule each block's level for the moment it
+becomes audible; a single lazy dispatcher thread delivers due levels.
"""
from __future__ import annotations
@@ -12,6 +20,7 @@ from __future__ import annotations
import logging
import threading
import time
+from collections import deque
from collections.abc import Callable
from jarvis.audio.mic_level import LevelNormalizer
@@ -19,6 +28,11 @@ from jarvis.audio.mic_level import LevelNormalizer
_log = logging.getLogger("jarvis.audio.level_tap")
_lock = threading.Lock()
+# Delays at or below this are published synchronously — sub-frame lead is
+# imperceptible and keeps the no-latency path (tests, headless, DirectSound
+# with tiny buffers) free of any thread machinery.
+_SYNC_DELAY_S = 0.005
+
# monotonic() timestamp until which TTS audio is known to be on the output
# device. The player only feeds a level at buffer-write time (a brief instant),
# then stream.write() BLOCKS for the whole multi-second playback with no further
@@ -34,6 +48,44 @@ _subscribers: list[Callable[[float], None]] = []
# newly observed peak to full scale.
_norm = LevelNormalizer()
+# Delayed-delivery state: (due_monotonic, level) in append order. Delays within
+# one playback share the same device latency, so the deque stays effectively
+# sorted; a mid-stream latency change can misorder neighbors by a few ms, which
+# is visually irrelevant. The dispatcher thread is created lazily on the first
+# delayed feed and then parks on the condition while idle.
+_pending: deque[tuple[float, float]] = deque()
+_pending_cond = threading.Condition(_lock)
+_dispatcher: threading.Thread | None = None
+
+
+def _dispatch_loop() -> None:
+ while True:
+ with _pending_cond:
+ while not _pending:
+ _pending_cond.wait()
+ due, level = _pending[0]
+ wait_s = due - time.monotonic()
+ if wait_s > 0.0:
+ # Re-check after the timed wait: reset_playing() may have
+ # cleared the queue, or an earlier-due item may have arrived.
+ _pending_cond.wait(timeout=wait_s)
+ continue
+ _pending.popleft()
+ publish(level)
+
+
+def _schedule(level: float, delay_s: float) -> None:
+ global _dispatcher
+ due = time.monotonic() + delay_s
+ with _pending_cond:
+ _pending.append((due, level))
+ if _dispatcher is None or not _dispatcher.is_alive():
+ _dispatcher = threading.Thread(
+ target=_dispatch_loop, name="level-tap-dispatch", daemon=True
+ )
+ _dispatcher.start()
+ _pending_cond.notify()
+
def subscribe(sink: Callable[[float], None]) -> Callable[[], None]:
"""Register a level sink. Returns an unsubscribe callable."""
@@ -55,9 +107,16 @@ def has_subscribers() -> bool:
return bool(_subscribers)
-def publish(level: float) -> None:
- """Push a level in [0, 1] to all sinks. Clamps; swallows sink errors."""
+def publish(level: float, delay_s: float = 0.0) -> None:
+ """Push a level in [0, 1] to all sinks. Clamps; swallows sink errors.
+
+ ``delay_s`` > ``_SYNC_DELAY_S`` defers delivery by that long (see the
+ module docstring's sync contract) via the lazy dispatcher thread.
+ """
lv = 0.0 if level < 0.0 else 1.0 if level > 1.0 else float(level)
+ if delay_s > _SYNC_DELAY_S:
+ _schedule(lv, float(delay_s))
+ return
with _lock:
sinks = tuple(_subscribers)
for sink in sinks:
@@ -67,14 +126,18 @@ def publish(level: float) -> None:
_log.debug("level_tap sink failed", exc_info=True)
-def feed(rms: float) -> None:
+def feed(rms: float, delay_s: float = 0.0) -> None:
"""Normalize a raw TTS output RMS into a reactive 0..1 level and publish it.
This is what the player should call (not ``publish``): the logarithmic
normalizer maps Jarvis's speech across the full bar range, mirroring the
- mic path. ``publish`` stays for raw passthrough / tests.
+ mic path. Pass the device's reported output latency as ``delay_s`` so the
+ level lands when the block is HEARD, not when PortAudio accepted it.
+ ``publish`` stays for raw passthrough / tests. The normalizer runs at feed
+ time (its envelope tracks the audio stream order), only delivery is
+ deferred.
"""
- publish(_norm.push(float(rms)))
+ publish(_norm.push(float(rms)), delay_s)
def note_playing(duration_s: float) -> None:
@@ -97,9 +160,17 @@ def playback_active() -> bool:
def reset_playing() -> None:
"""Clear the playback window (barge-in / stop): audio was aborted, so the
- UI must not keep showing the speaking equalizer for the cancelled tail."""
+ UI must not keep showing the speaking equalizer for the cancelled tail.
+ Pending delayed levels belong to that cancelled tail too — drop them and
+ push an honest zero so the bars collapse with the sound."""
global _audible_until
_audible_until = 0.0
+ with _pending_cond:
+ had_pending = bool(_pending)
+ _pending.clear()
+ _pending_cond.notify()
+ if had_pending:
+ publish(0.0)
def reset() -> None:
@@ -107,5 +178,7 @@ def reset() -> None:
global _audible_until
with _lock:
_subscribers.clear()
+ _pending.clear()
+ _pending_cond.notify()
_norm.reset()
_audible_until = 0.0
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 3af0039293..e28c6cda61 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -821,6 +821,12 @@ class AudioPlayer:
# write still provides back-pressure. ~60 ms blocks are large enough to
# never starve the buffer.
feed_level = level_tap.has_subscribers()
+ # Visual sync: write() returns when PortAudio ACCEPTS a block; the
+ # device makes it audible one output latency later (hundreds of ms on
+ # Bluetooth). Deliver each block's level with that delay so the bar
+ # moves WITH the heard voice — including the final ~latency of every
+ # sentence, which previously played with the bars already collapsed.
+ level_delay_s = self.output_latency_s if feed_level else 0.0
# Master output volume: scale the whole buffer once via the shared gain
# helper (makeup boost + soft limiter above unity, plain attenuation
# below), then write it in sub-blocks. ``arr_out is arr_f`` when the knob
@@ -872,7 +878,10 @@ class AudioPlayer:
if feed_level:
pre = arr_f[start:start + block] # PRE-gain RMS for the visualizer
if pre.size:
- level_tap.feed(float(np.sqrt(np.mean(np.square(pre)))))
+ level_tap.feed(
+ float(np.sqrt(np.mean(np.square(pre)))),
+ delay_s=level_delay_s,
+ )
# Echo-reference envelope (BUG-101): the barge-in detector needs
# what the speakers actually emit, so record the POST-gain block.
# One RMS + deque append per ~60 ms block — no model, no OS API.
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index 34156eb0f9..db7b57885a 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -391,6 +391,11 @@ class JarvisBarOverlay:
# (>= AUDIBLE_LEVEL). Drives the wave↔bars choice in _schedule_frame.
# 0.0 = "long ago" → starts on the wave, not the bars.
self._last_audible_t = 0.0
+ # perf_counter() of the last set_level() of ANY value. The frame loop
+ # renders _ext_level only while fresh (renderer.LEVEL_STALE_S): a feed
+ # that stops without sending zero must read as silence, not as bars
+ # frozen dancing on the last sample.
+ self._last_level_rx_t = 0.0
# monotonic_ns() stamped on every frame tick (alive or dropped). The
# revival watchdog compares against this to tell a living loop from a
# silently-dead one. 0 = "no frame has run yet" → the watchdog holds off.
@@ -509,12 +514,13 @@ class JarvisBarOverlay:
# Direct atomic write (no enqueue) — matches OrbOverlay.set_level.
lv = 0.0 if level < 0.0 else 1.0 if level > 1.0 else float(level)
self._ext_level = lv
+ self._last_level_rx_t = time.perf_counter()
# Remember WHEN real sound last arrived (mic or TTS, both feed here via
# their level taps). _schedule_frame uses this to show bars while sound
# is present and the wave during silence. Atomic float write, like
# _ext_level — safe from the audio/VAD threads with no lock.
if lv >= AUDIBLE_LEVEL:
- self._last_audible_t = time.perf_counter()
+ self._last_audible_t = self._last_level_rx_t
# The bar has no text bubble and no mouth — these stay no-ops so the
# bridge's duck-typed calls remain safe.
@@ -1210,11 +1216,17 @@ class JarvisBarOverlay:
# (player._write_samples), so the equalizer reacts to Jarvis's
# actual loudness — thin and lively, exactly like it reacts to
# your mic. No synthetic floor (that made the bars look
- # uniformly blocky).
+ # uniformly blocky). A stale sample (the feed stopped without a
+ # zero) renders as silence, never as frozen dancing bars.
+ # getattr default: ``__new__``-built test/hot-reload instances
+ # skip __init__; a missing stamp reads as "never received".
img = self._renderer.render(
t,
effective_mode,
- self._ext_level,
+ renderer.effective_ext_level(
+ self._ext_level,
+ now - getattr(self, "_last_level_rx_t", 0.0),
+ ),
hovered=self._hovered,
muted=self._muted,
)
diff --git a/jarvis/ui/jarvisbar/qt_overlay.py b/jarvis/ui/jarvisbar/qt_overlay.py
index 24cca88eb7..8145125940 100644
--- a/jarvis/ui/jarvisbar/qt_overlay.py
+++ b/jarvis/ui/jarvisbar/qt_overlay.py
@@ -396,6 +396,11 @@ class QtJarvisBarOverlay:
self._mode = "idle"
self._ext_level = 0.0
self._last_audible_t = 0.0
+ # Receipt stamp of the last set_level of ANY value: the frame loop
+ # renders the sample only while fresh (renderer.LEVEL_STALE_S), so a
+ # feed that stops without a zero reads as silence instead of bars
+ # frozen dancing on the last forwarded level.
+ self._last_level_rx_t = 0.0
self._muted = False
self._hovered = False
self._static_tick_key: tuple[str, bool, bool] | None = None
@@ -493,8 +498,9 @@ class QtJarvisBarOverlay:
def set_level(self, level: float) -> None:
lv = max(0.0, min(1.0, float(level)))
self._ext_level = lv
+ self._last_level_rx_t = time.perf_counter()
if lv >= AUDIBLE_LEVEL:
- self._last_audible_t = time.perf_counter()
+ self._last_audible_t = self._last_level_rx_t
def set_muted(self, muted: bool) -> None:
self._muted = bool(muted)
@@ -710,7 +716,10 @@ class QtJarvisBarOverlay:
pil_frame = bar_renderer.render(
now - self._t0,
effective_mode,
- self._ext_level,
+ renderer.effective_ext_level(
+ self._ext_level,
+ now - getattr(self, "_last_level_rx_t", 0.0),
+ ),
hovered=self._hovered,
muted=self._muted,
)
diff --git a/jarvis/ui/jarvisbar/renderer.py b/jarvis/ui/jarvisbar/renderer.py
index 577a37ded3..e4fa6629d9 100644
--- a/jarvis/ui/jarvisbar/renderer.py
+++ b/jarvis/ui/jarvisbar/renderer.py
@@ -289,6 +289,23 @@ _DOTS_SPAN_FRAC = 0.62 # dots span / pill width (matches the bars)
MODES = ("idle", "listen", "speak", "think")
+# A level sample is trusted only this long. The feeders (mic ~30-100 ms
+# cadence, TTS ~60 ms blocks) stream continuously while sound exists; when a
+# feed STOPS (bridge state gate, echo suppression, turn commit, mute) no zero
+# arrives and the last sample would otherwise animate the bars forever — the
+# "keeps showing I'm speaking for seconds after I stopped" defect. Comfortably
+# above the slowest healthy cadence so live sound can never flicker stale.
+LEVEL_STALE_S = 0.35
+
+
+def effective_ext_level(
+ ext_level: float, seconds_since_level_rx: float, *, stale_s: float = LEVEL_STALE_S
+) -> float:
+ """The level the frame loop should render: the live sample while fresh,
+ dead zero once the feed has stopped. Pure — shared by the Tk and Qt
+ surfaces so both decay identically."""
+ return float(ext_level) if seconds_since_level_rx <= stale_s else 0.0
+
def pill_center_y(ph: float) -> float:
"""Vertical centre that keeps the pill's BOTTOM edge anchored, so the pill
@@ -618,10 +635,12 @@ class JarvisBarRenderer:
# Asymmetric level easing: rise almost instantly so the bars move in
# sync with the voice, fall fast and snap to dead zero — a lingering
# sub-visible tail otherwise keeps the equalizer wiggling in silence.
+ # 0.8 reaches ~96% of a rising target within two 16 ms frames; the
+ # onset of a word registers the same tick its level sample arrives.
level_target = ext_level if active else 0.0
rising = level_target > self._st.display_level
self._st.display_level = ease(
- self._st.display_level, level_target, 0.6 if rising else 0.5
+ self._st.display_level, level_target, 0.8 if rising else 0.5
)
if not rising and level_target <= 0.0 and self._st.display_level < 0.02:
self._st.display_level = 0.0
diff --git a/tests/unit/audio/test_level_tap.py b/tests/unit/audio/test_level_tap.py
index c6dd9b3bc6..b40f9717e3 100644
--- a/tests/unit/audio/test_level_tap.py
+++ b/tests/unit/audio/test_level_tap.py
@@ -1,6 +1,8 @@
"""Unit tests for the out-of-band TTS level channel (jarvis.audio.level_tap)."""
from __future__ import annotations
+import time
+
from jarvis.audio import level_tap
@@ -76,3 +78,69 @@ def test_note_playing_ignores_nonpositive_and_resets_on_bargein():
level_tap.reset_playing() # barge-in discards the tail
assert level_tap.playback_active() is False
level_tap.reset()
+
+
+def _wait_for(predicate, timeout_s: float = 2.0) -> bool:
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.01)
+ return predicate()
+
+
+def test_delayed_publish_arrives_late_not_immediately():
+ # write() returns when PortAudio ACCEPTS a block; the sound is heard one
+ # output latency later. A delayed publish must therefore NOT reach sinks
+ # synchronously, but must land once the delay has elapsed.
+ level_tap.reset()
+ got: list[float] = []
+ level_tap.subscribe(got.append)
+ try:
+ level_tap.publish(0.8, delay_s=0.15)
+ assert got == [] # not delivered at accept time
+ assert _wait_for(lambda: got == [0.8])
+ finally:
+ level_tap.reset()
+
+
+def test_delayed_publishes_preserve_order():
+ level_tap.reset()
+ got: list[float] = []
+ level_tap.subscribe(got.append)
+ try:
+ level_tap.publish(0.2, delay_s=0.05)
+ level_tap.publish(0.4, delay_s=0.08)
+ level_tap.publish(0.6, delay_s=0.11)
+ assert _wait_for(lambda: len(got) == 3)
+ assert got == [0.2, 0.4, 0.6]
+ finally:
+ level_tap.reset()
+
+
+def test_reset_playing_drops_pending_levels_and_zeroes_the_bars():
+ # Barge-in aborts the audible tail; its scheduled levels belong to audio
+ # that will never be heard, so they are dropped and one honest zero
+ # collapses the equalizer with the sound.
+ level_tap.reset()
+ got: list[float] = []
+ level_tap.subscribe(got.append)
+ try:
+ level_tap.publish(0.9, delay_s=5.0) # far future — must never arrive
+ level_tap.reset_playing()
+ assert _wait_for(lambda: got == [0.0])
+ time.sleep(0.05)
+ assert got == [0.0]
+ finally:
+ level_tap.reset()
+
+
+def test_zero_delay_publish_stays_synchronous():
+ level_tap.reset()
+ got: list[float] = []
+ level_tap.subscribe(got.append)
+ try:
+ level_tap.publish(0.5, delay_s=0.0)
+ assert got == [0.5] # no thread hop for the no-latency path
+ finally:
+ level_tap.reset()
diff --git a/tests/unit/audio/test_player_level_tap.py b/tests/unit/audio/test_player_level_tap.py
index 4294f0da3a..97febfa179 100644
--- a/tests/unit/audio/test_player_level_tap.py
+++ b/tests/unit/audio/test_player_level_tap.py
@@ -5,6 +5,7 @@ real PortAudio device is opened; asserts the per-flush RMS reaches a subscriber.
"""
from __future__ import annotations
+import asyncio
from types import SimpleNamespace
import numpy as np
@@ -67,3 +68,33 @@ async def test_player_no_publish_without_subscriber():
# No subscriber registered → must not raise, and the RMS is skipped.
await _make_player().play_chunks(_one_loud_chunk())
assert level_tap.has_subscribers() is False
+
+
+class _LatentFakeStream(_FakeStream):
+ """A device that reports real output latency, like Bluetooth on macOS."""
+
+ latency = 0.2
+
+
+async def test_player_delays_levels_by_the_device_output_latency():
+ # write() returns at buffer-accept time; the block is HEARD one output
+ # latency later. The visualizer level must follow the heard timeline: no
+ # sample may reach the sink before the device latency has elapsed.
+ import time
+
+ level_tap.reset()
+ got: list[tuple[float, float]] = [] # (arrival_monotonic, level)
+ level_tap.subscribe(lambda lv: got.append((time.monotonic(), lv)))
+ pl = _make_player()
+ pl._open_output_stream = lambda rate: (_LatentFakeStream(), rate)
+ t0 = time.monotonic()
+ try:
+ await pl.play_chunks(_one_loud_chunk())
+ deadline = time.monotonic() + 2.0
+ while not got and time.monotonic() < deadline:
+ await asyncio.sleep(0.01)
+ finally:
+ level_tap.reset()
+ assert got, "expected the delayed level samples to arrive"
+ first_arrival, _lv = got[0]
+ assert first_arrival - t0 >= 0.15 # ~latency later, never at accept time
diff --git a/tests/unit/audio/test_player_volume.py b/tests/unit/audio/test_player_volume.py
index d057780e45..76167a81bb 100644
--- a/tests/unit/audio/test_player_volume.py
+++ b/tests/unit/audio/test_player_volume.py
@@ -88,7 +88,7 @@ def test_visualizer_sees_pre_gain_loudness_when_boosted(monkeypatch):
"""
fed: list[float] = []
monkeypatch.setattr(level_tap, "has_subscribers", lambda: True)
- monkeypatch.setattr(level_tap, "feed", lambda v: fed.append(v))
+ monkeypatch.setattr(level_tap, "feed", lambda v, delay_s=0.0: fed.append(v))
_play(1.0, 20000) # 100% → boosted output (~1.0 peak)
raw_rms = 20000 / 32768.0 # ~0.61
# Every fed value is the raw signal RMS, NOT the boosted/limited output.
diff --git a/tests/unit/ui/jarvisbar/test_renderer.py b/tests/unit/ui/jarvisbar/test_renderer.py
index ef0bf59adc..8f1b9cdac9 100644
--- a/tests/unit/ui/jarvisbar/test_renderer.py
+++ b/tests/unit/ui/jarvisbar/test_renderer.py
@@ -372,3 +372,27 @@ def test_idle_pill_is_empty_no_standby_dots():
def test_active_bars_are_slim_not_chunky():
# Slim-bar style: the equalizer strokes are thin, not the old chunky ~6px bars.
assert R.bar_half_w_for(R.ACTIVE_W) <= 2.0
+
+
+def test_effective_ext_level_passes_fresh_samples_through():
+ # A sample younger than the stale window renders as-is: live sound moves
+ # the bars with no attenuation.
+ assert R.effective_ext_level(0.7, 0.0) == 0.7
+ assert R.effective_ext_level(0.7, R.LEVEL_STALE_S) == 0.7
+
+
+def test_effective_ext_level_decays_a_stopped_feed_to_silence():
+ # When a feeder stops without sending zero (bridge state gate, echo
+ # suppression, turn commit), the last sample must NOT keep animating the
+ # bars — the 2026-07-21 "still shows me speaking for 3-4 s after I
+ # stopped" defect. Past the stale window the level reads as dead silence.
+ assert R.effective_ext_level(0.7, R.LEVEL_STALE_S + 0.01) == 0.0
+ assert R.effective_ext_level(1.0, 5.0) == 0.0
+
+
+def test_level_stale_window_covers_the_slowest_healthy_feed_cadence():
+ # Mic feeds arrive per captured chunk (~30-100 ms), TTS per ~60 ms write
+ # block. The stale window must sit clearly above both so live sound can
+ # never flicker stale between samples, yet far below one second so a
+ # stopped feed collapses promptly.
+ assert 0.2 <= R.LEVEL_STALE_S <= 0.6