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(jarvisbar): wake a Tk thread that fell asleep with every timer armed
rubenluetke10-beep14ab7d0eccd0
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex e986216118..de95e345c2 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -14234,3 +14234,69 @@ a side effect, which is worth ~1 more call per minute under Groq's**Related.** BUG-200 (the polish/Prompt Mode pointer under "where to lookfirst"); the memory note that Groq's TPM tier caps Prompt Mode at a fewcalls per minute before the chain crosses families.++## BUG-202: the Jarvis Bar stopped reacting — "Hey Jarvis" was answered by voice, dictation delivered text, and the pill stayed collapsed through all of it (HIGH, FIXED 2026-08-28)++**Symptom.** Screenshot 16:03 (`.jarvis/drops/20260828-160318-*.png`): the+native bar on its resting outline pill. The log for the same minutes shows a+complete voice turn — `vosk-kws: WAKE fired` 16:02:16, `OrbBridge._on_state:+LISTENING → CONNECTING → LISTENING → THINKING → SPEAKING`, `_on_audio_out_first+→ speaking overlay + mouth` — and five hold-key dictations after it, every one+transcribed and delivered (3, 449, 1 933, 888, 117 chars). The bridge received+every event and called `show("listen")` on the bar. Nothing was drawn.++**Cause.** The bar's Tk thread was asleep, not dead. `py-spy dump --native` on+the live app showed thread `jarvisbar-tk-mainloop` in+`Tcl_DoOneEvent → Tcl_WaitForEvent → GetMessageW`, and a 10 s sample at 1 kHz+(10 000 samples of that thread) caught it in `mainloop` every single time —+never in `_schedule_frame`, `_schedule_frame_watchdog`, `_schedule_ui_queue`,+the z-order guard or the cursor-monitor guard. All five `after` chains were+armed (nothing had called `stop()`, no "re-arm skipped" warning in the log) and+none fired: Tcl's Windows notifier had lost the timer wake-up that returns from+`GetMessage`, once. On a bar whose idle pill had settled (the 2026-08-22 CPU+diet skips repaints once idle is static) no paint, move or hover produced any+other message, so the wait never ended. `show("listen")` set `_mode` — the+frame loop reads it directly — but no frame ran to draw it. The in-Tk watchdog+of BUG-032 sits in the same timer queue and slept with it.++Proof of the mechanism: posting `WM_NULL` to the bar's window from another+process (`PostMessageW`, 75 messages over 3 s) put the thread back into its+callbacks immediately (17 frame samples, 2 watchdog, 3 UI-queue in 2 s), and+after the posting stopped the loop kept ticking on its own (40 callback samples+in the next 3 s, 41 in a sample minutes later). One message was the whole cure.++Not the cause, checked on the way: today's Ink & Paper commits touched no+Python under `jarvis/ui/jarvisbar/` (last change 2026-08-27); no second bar+window existed (a sibling session's `pytest` run had booted a full desktop app+with a real bar at 15:36, but its window was gone); `.venv` imports the repo+tree; the working-tree edits to `audio/capture.py` / `speech/pipeline.py` do+not touch the level feed; the network was up (Groq answered every dictation).++**Fix.** A wake-up that does not depend on the Tk thread's own timers.++- `process_utils.wake_thread_message_loop(native_thread_id)` posts `WM_NULL`+ with `PostThreadMessageW` — non-blocking, ignored by every window procedure,+ and enough to return from `GetMessage` so Tcl runs its overdue timers.+ `thread_message_loop_wake_supported()` is the capability probe: only a+ per-thread message queue can be woken this way, so off Windows both are+ quiet no-ops and no waker thread is started (the X11/Aqua notifiers wait on+ a socket/pipe and a run loop and have not shown this sleep).+- `JarvisBarOverlay` records the Tk thread's OS id at start and runs a daemon+ `jarvisbar-loop-waker` OUTSIDE Tk: every 0.5 s it reads the frame heartbeat+ `_last_frame_ns` (stamped on every tick, including skipped ones) and posts+ one wake-up when it is older than 1 s, rate-limited to one per second, with+ one warning per sleep and an info line when the loop ticks again.+- `show()` calls the same check with a 250 ms threshold before enqueueing, so+ a wake reveal after a sleep is drawn on the next tick instead of waiting for+ the poll.++Tests: `tests/unit/ui/jarvisbar/test_loop_waker.py` (kick on a stale+heartbeat, none on a fresh one, hold-off before the first frame, one wake per+window, sleep counter reset on recovery, nothing after `stop()`, `show()` wakes+at once, the helper and the waker thread are no-ops off Windows, a dead thread+id reports `False` on Windows).++**Related.** BUG-032 (the in-Tk revival watchdog — still right for a loop that+died while the thread runs; this is the case where the thread itself waits).+The `disable_windows_app_ghosting` note in `process_utils` describes the other+face of a non-pumping Tk thread (the black box around the pill).diff --git a/jarvis/core/process_utils.py b/jarvis/core/process_utils.pyindex df6e9453dc..a3bd5341ef 100644--- a/jarvis/core/process_utils.py+++ b/jarvis/core/process_utils.py@@ -182,9 +182,53 @@ def disable_windows_app_ghosting() -> bool:return True+_WM_NULL = 0x0000+++def thread_message_loop_wake_supported() -> bool:+ """True where :func:`wake_thread_message_loop` can actually wake a thread.++ Only Windows has a per-thread message queue that a blocked ``GetMessage``+ waits on; the X11 and Aqua notifiers wait on a socket/pipe and a run loop+ respectively, and neither has shown the lost-timer sleep this call exists+ for. Callers use this to skip the waker thread entirely instead of running+ a loop that can never act.+ """+ return sys.platform == "win32"+++def wake_thread_message_loop(native_thread_id: int) -> bool:+ """Make a thread blocked in ``GetMessage`` return once, without side effects.++ Posts ``WM_NULL`` — a message every window procedure ignores — to the+ thread's queue with ``PostThreadMessageW``. The one thing it changes is that+ the thread's blocking ``GetMessage`` returns, which lets an event loop that+ sits on top of it (Tcl's Windows notifier, for the Jarvis Bar) run its+ overdue timers. The Jarvis Bar's Tk thread was found asleep in exactly that+ call with every ``after`` chain armed and none firing: Tcl's timer wake-up+ had been lost once, and nothing else on a settled idle bar generates a+ message, so the bar stayed frozen on its idle pill for the rest of the+ session (BUG-202). One posted message revived it.++ Non-blocking and never raises. Returns ``True`` when the message was+ queued, ``False`` off Windows, when the thread has no message queue yet, or+ when the call could not be made.+ """+ if sys.platform != "win32":+ return False+ try:+ import ctypes # noqa: PLC0415 — Windows-only, keep it off the import floor++ return bool(ctypes.windll.user32.PostThreadMessageW(int(native_thread_id), _WM_NULL, 0, 0))+ except Exception: # noqa: BLE001 — a failed nudge is reported, never raised+ return False++__all__ = ["NO_WINDOW_CREATIONFLAGS","disable_windows_app_ghosting","ensure_standard_streams","resolve_executable",+ "thread_message_loop_wake_supported",+ "wake_thread_message_loop",]diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.pyindex fecc3da7c8..74069b63ee 100644--- a/jarvis/ui/jarvisbar/overlay.py+++ b/jarvis/ui/jarvisbar/overlay.py@@ -104,6 +104,21 @@ AUDIBLE_HOLD_S = 0.5WATCHDOG_INTERVAL_MS = 1000FRAME_STALL_THRESHOLD_NS = 2_000_000_000 # 2 s of silence ⇒ the loop is dead+# Loop waker (BUG-202). The watchdog above shares the Tk thread's timer queue+# with the loop it guards, so it cannot help when the THREAD is the thing that+# stopped: the Tk mainloop was found asleep in ``GetMessage`` with every after+# chain armed and none firing — Tcl's Windows notifier had lost its timer+# wake-up once, and a settled idle bar generates no other message that would+# return from that wait. From then on ``show("listen")`` set the mode but no+# frame ever drew it: "Hey Jarvis" answered by voice while the pill stayed+# collapsed. The cure was one posted message, so a small daemon thread OUTSIDE+# Tk watches the same heartbeat and posts one whenever it goes stale, and+# ``show()`` posts at once so a wake reveal never waits for the poll. Both are+# quiet no-ops where the platform has no per-thread message queue.+LOOP_WAKER_POLL_S = 0.5+LOOP_ASLEEP_THRESHOLD_NS = 1_000_000_000 # 1 s without a tick ⇒ the Tk thread is asleep+SHOW_WAKE_THRESHOLD_NS = 250_000_000 # a reveal after 250 ms of silence kicks at once+# Frame pacing (BUG: "JarvisBar stutters" forensic, 2026-07-10). A 41s GIF# capture frame-diffed to only ~5 visual updates/second on average, in a# burst-then-freeze pattern (freezes up to 1.25s). Measured root causes, on@@ -438,6 +453,13 @@ class JarvisBarOverlay:# 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.self._last_frame_ns = 0+ # Loop waker state (BUG-202): the Tk thread's OS thread id (the address+ # a wake-up message is posted to), the monotonic_ns() of the last kick+ # (rate limit), and how many kicks the current sleep has taken (one+ # warning per sleep, not one per poll).+ self._tk_native_thread_id: int | None = None+ self._last_wake_ns = 0+ self._sleep_kicks = 0# Idle-static skip bookkeeping (see _IDLE_SETTLE_TICKS docstring above# _schedule_frame): tracks how many consecutive ticks have shared the# same (effective_mode, hovered, muted) key, so a settled idle pill's@@ -510,6 +532,10 @@ class JarvisBarOverlay:self._mode = modeif self._root is None:return+ # A reveal is the moment the user is looking: if the Tk thread has+ # gone quiet, wake it now rather than at the waker's next poll, so the+ # mode just set is drawn on the very next tick (BUG-202).+ self._kick_if_asleep(threshold_ns=SHOW_WAKE_THRESHOLD_NS)# Keep accepting state updates while boot is warming so release can show# the latest correct mode, but never map the native window before the# voice-usable signal. This guard closes the historical bypass where a@@ -714,6 +740,8 @@ class JarvisBarOverlay:log.debug("jarvisbar DPI-awareness setup skipped", exc_info=True)self._tk_thread_id = threading.get_ident()+ # The OS-level id is what a wake-up message is addressed to (BUG-202).+ self._tk_native_thread_id = threading.get_native_id()# Some window managers map Tk's default-size root eagerly. Hide it# before assigning ``self._root`` or applying any styles so that stale@@ -865,6 +893,7 @@ class JarvisBarOverlay:self._schedule_frame()self._schedule_ui_queue()self._schedule_frame_watchdog() # independent anti-freeze revival loop+ self._start_loop_waker() # outside Tk: wakes the thread itself (BUG-202)self._schedule_z_order_guard()self._schedule_cursor_monitor_guard() # follow the mouse across monitorsif not self._should_start_withdrawn():@@ -1436,6 +1465,87 @@ class JarvisBarOverlay:except Exception: # noqa: BLE001log.warning("JarvisBar frame watchdog re-arm skipped", exc_info=True)+ # ------------------------------------------------------------------ #+ # Loop waker — lives OUTSIDE the Tk thread (BUG-202) #+ # ------------------------------------------------------------------ #+ def _wake_tk_loop(self) -> bool:+ """Post one no-op message to the Tk thread so a blocked wait returns."""+ tid = getattr(self, "_tk_native_thread_id", None)+ if tid is None:+ return False+ from jarvis.core.process_utils import wake_thread_message_loop++ return wake_thread_message_loop(tid)++ def _kick_if_asleep(+ self,+ *,+ threshold_ns: int = LOOP_ASLEEP_THRESHOLD_NS,+ now_ns: int | None = None,+ ) -> bool:+ """Wake the Tk thread when the frame heartbeat is older than ``threshold_ns``.++ Safe to call from any thread and at any rate: it reads two integers,+ posts at most one message per ``LOOP_ASLEEP_THRESHOLD_NS`` window, and+ holds off entirely before the first frame has been stamped (the loop is+ still booting, not asleep). Returns ``True`` when a wake-up was posted.++ A wake that does not bring the heartbeat back means the thread is not+ merely waiting but busy or truly hung; the poll keeps kicking at the+ rate limit, warns once per sleep, and says when the loop is back.+ """+ if not self._running or self._root is None:+ return False+ last = getattr(self, "_last_frame_ns", 0)+ if not last:+ return False+ now = time.monotonic_ns() if now_ns is None else now_ns+ age = now - last+ if age < threshold_ns:+ kicks = getattr(self, "_sleep_kicks", 0)+ if kicks:+ self._sleep_kicks = 0+ log.info("JarvisBar Tk loop is ticking again after %d wake-up(s).", kicks)+ return False+ if (now - getattr(self, "_last_wake_ns", 0)) < LOOP_ASLEEP_THRESHOLD_NS:+ return False+ self._last_wake_ns = now+ if not self._wake_tk_loop():+ return False+ self._sleep_kicks = getattr(self, "_sleep_kicks", 0) + 1+ if self._sleep_kicks == 1:+ log.warning(+ "JarvisBar Tk loop asleep for %.1fs (every timer armed, none firing) — "+ "posted a wake-up from outside Tk.",+ age / 1e9,+ )+ return True++ def _loop_waker_run(self) -> None:+ while self._running:+ time.sleep(LOOP_WAKER_POLL_S)+ try:+ self._kick_if_asleep()+ except Exception: # noqa: BLE001 — the waker must outlive any one check+ log.debug("JarvisBar loop waker check failed", exc_info=True)++ def _start_loop_waker(self) -> None:+ """Start the daemon that wakes a sleeping Tk thread; a no-op elsewhere.++ Only a platform with a per-thread message queue can be woken this way+ (see ``process_utils.thread_message_loop_wake_supported``); on the+ others the X11/Aqua notifiers have not shown the lost-timer sleep, so+ no thread is started rather than one that could never act.+ """+ from jarvis.core.process_utils import thread_message_loop_wake_supported++ if not thread_message_loop_wake_supported():+ log.debug("JarvisBar loop waker not started: no thread message queue here")+ return+ threading.Thread(+ target=self._loop_waker_run, name="jarvisbar-loop-waker", daemon=True+ ).start()+def _schedule_z_order_guard(self) -> None:"""Keep a mapped bar above apps that are opened after it.diff --git a/tests/unit/ui/jarvisbar/test_loop_waker.py b/tests/unit/ui/jarvisbar/test_loop_waker.pynew file mode 100644index 0000000000..7d00af4c41--- /dev/null+++ b/tests/unit/ui/jarvisbar/test_loop_waker.py@@ -0,0 +1,159 @@+"""The JarvisBar's Tk thread must be woken from OUTSIDE Tk when it falls asleep.++Forensic (BUG-202, 2026-08-28): "Hey Jarvis" was answered by voice while the+bar stayed on its collapsed idle pill. py-spy showed the Tk thread parked in+``GetMessage`` with every ``after`` chain armed and none firing — Tcl's+Windows notifier had lost its timer wake-up once, and a settled idle bar+generates no other message that returns from that wait. The in-Tk watchdog+shares that timer queue, so it slept too. One posted ``WM_NULL`` revived the+loop; these tests pin the waker that posts it. Headless — no real Tk display.+"""++from __future__ import annotations++import sys+import time++from jarvis.core import process_utils+from jarvis.ui.jarvisbar.overlay import (+ LOOP_ASLEEP_THRESHOLD_NS,+ SHOW_WAKE_THRESHOLD_NS,+ JarvisBarOverlay,+)+++class _FakeRoot:+ pass+++def _bare_bar(*, heartbeat_age_ns: int | None) -> tuple[JarvisBarOverlay, list[int]]:+ """A bar built without __init__ (the file's own test convention) whose+ wake-up call is recorded instead of hitting the OS."""+ bar = JarvisBarOverlay.__new__(JarvisBarOverlay)+ bar._running = True+ bar._root = _FakeRoot()+ bar._mode = "idle"+ bar._persistent = True+ bar._startup_gated = False+ bar._tk_native_thread_id = 4242+ bar._last_wake_ns = 0+ bar._sleep_kicks = 0+ now = time.monotonic_ns()+ bar._last_frame_ns = 0 if heartbeat_age_ns is None else now - heartbeat_age_ns+ kicks: list[int] = []+ bar._wake_tk_loop = lambda: kicks.append(1) or True # type: ignore[method-assign]+ bar._enqueue_ui = lambda fn: None # type: ignore[method-assign]+ return bar, kicks+++def test_waker_kicks_a_sleeping_loop():+ bar, kicks = _bare_bar(heartbeat_age_ns=LOOP_ASLEEP_THRESHOLD_NS * 2)++ assert bar._kick_if_asleep() is True+ assert kicks == [1], "a stale heartbeat did not post a wake-up"+ assert bar._sleep_kicks == 1+++def test_waker_leaves_a_ticking_loop_alone():+ bar, kicks = _bare_bar(heartbeat_age_ns=0)++ assert bar._kick_if_asleep() is False+ assert kicks == [], "a fresh heartbeat must never be kicked"+++def test_waker_holds_off_before_the_first_frame():+ """0 = no frame has run yet: the loop is booting, not asleep."""+ bar, kicks = _bare_bar(heartbeat_age_ns=None)++ assert bar._kick_if_asleep() is False+ assert kicks == []+++def test_waker_posts_at_most_one_wake_per_window():+ """A thread that is busy rather than waiting gets one nudge per threshold+ window, not one per poll — the message queue must not fill with no-ops."""+ bar, kicks = _bare_bar(heartbeat_age_ns=LOOP_ASLEEP_THRESHOLD_NS * 2)+ now = time.monotonic_ns()++ assert bar._kick_if_asleep(now_ns=now) is True+ assert bar._kick_if_asleep(now_ns=now + LOOP_ASLEEP_THRESHOLD_NS // 2) is False+ assert bar._kick_if_asleep(now_ns=now + LOOP_ASLEEP_THRESHOLD_NS + 1) is True+ assert kicks == [1, 1]+++def test_waker_closes_the_sleep_once_the_heartbeat_returns():+ bar, kicks = _bare_bar(heartbeat_age_ns=LOOP_ASLEEP_THRESHOLD_NS * 2)+ bar._kick_if_asleep()+ assert bar._sleep_kicks == 1++ bar._last_frame_ns = time.monotonic_ns() # the loop ticked again+ assert bar._kick_if_asleep() is False+ assert bar._sleep_kicks == 0, "a recovered loop must reset the sleep counter"+ assert kicks == [1]+++def test_waker_does_nothing_once_stopped():+ bar, kicks = _bare_bar(heartbeat_age_ns=LOOP_ASLEEP_THRESHOLD_NS * 2)+ bar._running = False++ assert bar._kick_if_asleep() is False+ assert kicks == []+++def test_show_wakes_a_sleeping_loop_at_once():+ """The reveal is the moment the user looks: ``show()`` must not wait for the+ waker's next poll. Its own threshold is far below the poll threshold."""+ assert SHOW_WAKE_THRESHOLD_NS < LOOP_ASLEEP_THRESHOLD_NS+ bar, kicks = _bare_bar(heartbeat_age_ns=SHOW_WAKE_THRESHOLD_NS * 2)++ bar.show("listen")++ assert bar._mode == "listen"+ assert kicks == [1], "show() on a quiet loop did not post a wake-up"+++def test_show_on_a_ticking_loop_posts_nothing():+ bar, kicks = _bare_bar(heartbeat_age_ns=0)++ bar.show("listen")++ assert bar._mode == "listen"+ assert kicks == []+++def test_wake_helper_is_a_quiet_no_op_off_windows(monkeypatch):+ """Cross-platform rule: OS-specific code sits behind a capability check+ and degrades to a quiet no-op elsewhere — no thread, no exception."""+ monkeypatch.setattr(sys, "platform", "linux")++ assert process_utils.thread_message_loop_wake_supported() is False+ assert process_utils.wake_thread_message_loop(4242) is False+++def test_waker_thread_is_not_started_without_a_message_queue(monkeypatch):+ monkeypatch.setattr(sys, "platform", "darwin")+ bar, _kicks = _bare_bar(heartbeat_age_ns=0)+ started: list[str] = []++ import threading++ class _NoThread:+ def __init__(self, *a: object, **k: object) -> None:+ started.append(str(k.get("name")))++ def start(self) -> None: # pragma: no cover - must never run+ raise AssertionError("waker thread started on a platform without a queue")++ monkeypatch.setattr(threading, "Thread", _NoThread)+ bar._start_loop_waker()++ assert started == []+++def test_wake_helper_rejects_a_dead_thread_on_windows():+ """On Windows a thread id nobody owns has no queue: the call reports False+ and raises nothing."""+ if sys.platform != "win32":+ return+ assert process_utils.thread_message_loop_wake_supported() is True+ assert process_utils.wake_thread_message_loop(0x7FFFFFFF) is False