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(ui): show the JarvisBar on macOS via an own-process Tk host (BUG-057 follow-up)
Ruben Lütkea4870effcbe0
diff --git a/docs/plans/cross-platform-mac-linux/FIX-TRACKER.md b/docs/plans/cross-platform-mac-linux/FIX-TRACKER.mdindex 778c59ceff..09e744155a 100644--- a/docs/plans/cross-platform-mac-linux/FIX-TRACKER.md+++ b/docs/plans/cross-platform-mac-linux/FIX-TRACKER.md@@ -103,3 +103,17 @@ creators on darwin (bar, mascot orb, virtual cursor, `make_overlay_surface`Commit `b82d821a`, shipped public same day. The follow-up above thereforegrows: main-thread/own-process hosting is needed for the menu-bar icon ANDthe bar/orb before macOS gets any on-screen overlay.++**Own-process bar host (2026-07-14, this session).** The BUG-057 follow-up+for the bar landed: `jarvis.ui.jarvisbar.host` is a companion process whose+MAIN thread runs the bar's Tk mainloop (legal on Aqua-Tk), remote-driven by+`SubprocessBarOverlay` over a JSON-per-line stdio protocol (stdin EOF =+parent died → host exits; events like mute-toggle stream back on stdout).+`_build_overlay_surface` on darwin now returns the proxy for+`style == "jarvis_bar"` (NullOverlay stays the fallback + the mascot's+surface). macOS transparency: no color key there — the root sets+`-transparent` + `systemTransparent` and frames carry a real alpha channel+(`renderer.key_to_alpha`).+- [ ] **Verify on real Mac hardware:** bar visible, transparent (no magenta+ rectangle), draggable, mute/hang-up clicks round-trip, no Dock icon for+ the host (pyobjc accessory policy is best-effort), clean exit on quit.diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex e257775d83..4e13f68273 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -1964,21 +1964,45 @@ class DesktopApp:"""if sys.platform == "darwin":# This runs on the jarvis-backend worker thread; Aqua-Tk (like- # AppKit) is main-thread-only on macOS, so a bar/mascot Tk root- # here aborts the WHOLE process natively — the second macOS- # first-boot crash (BUG-057; the first was the BUG-056 tray).- # NullOverlay keeps the bridge wiring intact; the desktop window- # + Dock icon remain the macOS surface until the overlay is- # hosted in its own process.+ # AppKit) is main-thread-only on macOS, so an in-process bar or+ # mascot Tk root here aborts the WHOLE process natively — the+ # second macOS first-boot crash (BUG-057; the first was the+ # BUG-056 tray). The bar therefore lives in its own companion+ # process whose MAIN thread owns the Tk mainloop+ # (jarvis.ui.jarvisbar.host), remote-driven over stdio. The+ # mascot orb has no host yet and stays a no-op surface.from loguru import logger+ if style == "jarvis_bar":+ try:+ from jarvis.ui.jarvisbar.subprocess_overlay import (+ SubprocessBarOverlay,+ )++ surface = SubprocessBarOverlay(+ persistent=self.cfg.ui.bar_persistent,+ accent=self.cfg.ui.bar_accent,+ startup_gated=gate_until_voice_ready,+ )+ surface.start_in_thread()+ logger.info(+ "JarvisBar hosted out-of-process on macOS "+ "(jarvis.ui.jarvisbar.host)."+ )+ return surface+ except Exception: # noqa: BLE001 — cosmetic; never block boot+ logger.opt(exception=True).warning(+ "macOS JarvisBar host failed to start — falling back "+ "to the no-op surface."+ )from jarvis.ui.jarvisbar import NullOverlay- logger.info(- "On-screen overlay disabled on macOS (style={}): Tk windows "- "are main-thread-only there — using the no-op surface.",- style,- )+ if style not in ("jarvis_bar", "none"):+ logger.info(+ "On-screen mascot disabled on macOS (style={}): Tk windows "+ "are main-thread-only there — using the no-op surface.",+ style,+ )return NullOverlay()if style == "none":from jarvis.ui.jarvisbar import NullOverlaydiff --git a/jarvis/ui/jarvisbar/host.py b/jarvis/ui/jarvisbar/host.pynew file mode 100644index 0000000000..472be4acf6--- /dev/null+++ b/jarvis/ui/jarvisbar/host.py@@ -0,0 +1,266 @@+"""Standalone Jarvis Bar host process — main-thread Tk hosting (BUG-057 fix).++Aqua-Tk (like AppKit) is main-thread-only on macOS: a Tk root created on any+worker thread aborts the WHOLE process with a native, uncatchable assertion+(BUG-057, same class as the BUG-056 tray). The desktop app cannot host the+bar in-process there — its main thread belongs to pywebview/Cocoa. This+module is the documented fix ("hosted in its own process"): a minimal+companion process whose MAIN thread runs the bar's Tk mainloop, remote-driven+by the parent app over a line-oriented JSON protocol.++Protocol (UTF-8, one JSON object per line):++- parent → child (stdin): the first line is the init object+ ``{"op": "init", "persistent": ..., "accent": ..., "startup_gated": ...}``+ (optional ``opacity``); every further line is a surface command mirroring+ the ``OrbBusBridge`` surface API (``show``, ``hide``, ``set_level``, ...).+ stdin EOF means the parent died or shut down → the host stops the bar and+ exits, so no ownerless bar can linger on the user's desktop.+- child → parent (stdout): events — ``{"event": "ready"}`` once the Tk root+ is initialized, plus user interactions (``mute_toggle``, ``feedback``,+ ``show_window``). Logging goes to stderr so stdout stays pure protocol.++The host works on every OS (the parent simply only uses it where in-process+hosting is impossible). ``JARVIS_BAR_HOST_FAKE=1`` swaps the Tk bar for an+echo double so the full cross-process pipeline is testable without a display.+"""+from __future__ import annotations++import contextlib+import json+import logging+import os+import sys+import threading+from collections.abc import Callable+from typing import Any, TextIO++log = logging.getLogger("jarvis.ui.jarvisbar.host")++READY_TIMEOUT_S = 30.0+# After stdin EOF the Tk mainloop should unwind via bar.stop(); if Tk wedges,+# this backstop hard-exits so the orphaned host can never outlive its parent.+HARD_EXIT_GRACE_S = 5.0+++def emit(event: str, **payload: Any) -> None:+ """Write one child→parent event line to stdout (thread-safe)."""+ line = json.dumps({"event": event, **payload}, ensure_ascii=False)+ with _STDOUT_LOCK:+ try:+ sys.stdout.write(line + "\n")+ sys.stdout.flush()+ except Exception: # noqa: BLE001 — parent gone; reader loop sees EOF too+ log.debug("bar-host event write failed", exc_info=True)+++_STDOUT_LOCK = threading.Lock()+++def dispatch(bar: Any, msg: dict[str, Any]) -> bool:+ """Apply one parent command to the bar. Returns ``False`` for ``stop``.++ Every method called here is documented thread-safe on the bar (enqueue+ onto the Tk UI queue or an atomic write), so the stdin reader thread may+ call them directly.+ """+ op = msg.get("op")+ if op == "stop":+ return False+ if op == "show":+ bar.show(str(msg.get("mode", "listen")))+ elif op == "hide":+ bar.hide()+ elif op == "set_level":+ bar.set_level(float(msg.get("level", 0.0)))+ elif op == "set_muted":+ bar.set_muted(bool(msg.get("muted", False)))+ elif op == "set_persistent":+ # Live flag flip — the same plain attribute write the in-process+ # set_bar_persistent path performs (no Tk marshal needed).+ bar._persistent = bool(msg.get("enabled", True)) # noqa: SLF001+ elif op == "release_startup_gate":+ bar.release_startup_gate()+ elif op == "reassert_z_order":+ bar.reassert_z_order()+ elif op == "play_animation":+ bar.play_animation(str(msg.get("name", "")), **dict(msg.get("params") or {}))+ elif op == "stop_animation":+ bar.stop_animation(str(msg.get("name", "")))+ elif op == "show_listening_transcript":+ bar.show_listening_transcript(+ str(msg.get("text", "")), int(msg.get("duration_ms", 30000))+ )+ elif op == "hide_comment":+ bar.hide_comment()+ elif op == "start_mouth_animation":+ bar.start_mouth_animation(int(msg.get("duration_ms", 60000)))+ elif op == "stop_mouth_animation":+ bar.stop_mouth_animation()+ elif op == "reset_position":+ bar._on_reset_double_click() # noqa: SLF001 — the double-click reset seam+ else:+ log.warning("bar-host: unknown op %r", op)+ return True+++def reader_loop(+ bar: Any,+ stream: TextIO,+ *,+ hard_exit: Callable[[int], Any] | None = None,+) -> None:+ """Drain parent commands until EOF or ``stop``, then stop the bar.++ ``hard_exit`` (production: ``os._exit``) is the anti-linger backstop for+ a Tk mainloop that refuses to unwind; injectable so tests never arm it.+ """+ try:+ for raw in stream:+ line = raw.strip()+ if not line:+ continue+ try:+ msg = json.loads(line)+ except ValueError:+ log.warning("bar-host: dropping non-JSON line: %.120r", line)+ continue+ try:+ if not dispatch(bar, msg):+ break+ except Exception: # noqa: BLE001 — one bad command must not kill the bar+ log.exception("bar-host command failed: %r", msg.get("op"))+ finally:+ # EOF = the parent died or closed us deliberately; either way the bar+ # has no owner anymore. Arm the anti-linger backstop BEFORE stopping+ # the bar: stop() lets the main thread's mainloop return immediately,+ # and starting a thread while the interpreter is already shutting+ # down is a fatal error (0xC0000409 on Windows).+ if hard_exit is not None:+ killer = threading.Timer(HARD_EXIT_GRACE_S, hard_exit, args=(0,))+ killer.daemon = True+ killer.start()+ # stop() marshals destroy onto the Tk thread.+ try:+ bar.stop()+ except Exception: # noqa: BLE001+ log.debug("bar-host stop failed", exc_info=True)+++class _EchoBar:+ """No-Tk protocol double (``JARVIS_BAR_HOST_FAKE=1``).++ Satisfies the lifecycle contract (``_started`` + a blocking ``start()``)+ and echoes every surface call back as an ``op`` event, so tests exercise+ the real pipes, threads, EOF and shutdown paths without a display.+ """++ def __init__(self, **_: Any) -> None:+ self._persistent = True+ self._started = threading.Event()+ self._stop_evt = threading.Event()++ def start(self) -> None:+ self._started.set()+ self._stop_evt.wait()++ def stop(self) -> None:+ self._stop_evt.set()++ def set_on_mute_toggle(self, cb: Any) -> None: ...+ def set_feedback_publisher(self, cb: Any) -> None: ...+ def set_on_show_window(self, cb: Any) -> None: ...++ def __getattr__(self, name: str) -> Any:+ if name.startswith("__"):+ raise AttributeError(name)++ def _echo(*args: Any, **kwargs: Any) -> None:+ emit("op", op=name, args=list(args), kwargs=kwargs)++ return _echo+++def _hide_dock_icon() -> None:+ """Best-effort: run as a Dock-less accessory app (macOS only).++ Without this the bar host would add a second python rocket to the Dock.+ pyobjc may be absent — purely cosmetic, never blocks the bar.+ """+ try:+ from AppKit import NSApplication # type: ignore[import-not-found]++ # 1 = NSApplicationActivationPolicyAccessory: windows allowed, no+ # Dock icon, no menu bar takeover — exactly a floating overlay.+ NSApplication.sharedApplication().setActivationPolicy_(1)+ except Exception: # noqa: BLE001+ log.debug("Dock-icon hide skipped (pyobjc unavailable?)", exc_info=True)+++def _build_bar(cfg: dict[str, Any]) -> Any:+ if os.environ.get("JARVIS_BAR_HOST_FAKE") == "1":+ return _EchoBar()+ if sys.platform == "darwin":+ _hide_dock_icon()+ from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay++ kwargs = {+ key: cfg[key]+ for key in ("persistent", "accent", "opacity", "startup_gated")+ if key in cfg+ }+ return JarvisBarOverlay(**kwargs)+++def main() -> int:+ logging.basicConfig(+ stream=sys.stderr,+ level=logging.INFO,+ format="%(levelname)s %(name)s: %(message)s",+ )+ # UTF-8 pipes on every OS (Windows would otherwise default to cp1252).+ for stream in (sys.stdin, sys.stdout):+ with contextlib.suppress(Exception):+ stream.reconfigure(encoding="utf-8") # type: ignore[union-attr]++ init_raw = sys.stdin.readline()+ try:+ cfg = json.loads(init_raw)+ if cfg.get("op") != "init":+ raise ValueError(f"expected init, got {cfg.get('op')!r}")+ except ValueError:+ log.error("bar-host: invalid init line %.200r — exiting", init_raw)+ return 2++ bar = _build_bar(cfg)+ bar.set_on_mute_toggle(lambda: emit("mute_toggle"))+ bar.set_feedback_publisher(+ lambda kind, payload: emit("feedback", kind=kind, payload=payload)+ )+ bar.set_on_show_window(lambda: emit("show_window"))++ def _announce_ready() -> None:+ if bar._started.wait(timeout=READY_TIMEOUT_S): # noqa: SLF001+ emit("ready")+ else:+ log.error("bar-host: bar did not initialize within %ss", READY_TIMEOUT_S)++ threading.Thread(+ target=_announce_ready, name="barhost-ready", daemon=True+ ).start()+ threading.Thread(+ target=reader_loop,+ args=(bar, sys.stdin),+ kwargs={"hard_exit": os._exit},+ name="barhost-stdin",+ daemon=True,+ ).start()++ # THE point of this process: the Tk mainloop runs on the MAIN thread, the+ # only thread Aqua-Tk accepts on macOS.+ bar.start()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.pyindex 87fc7bccbf..f1ce872a25 100644--- a/jarvis/ui/jarvisbar/overlay.py+++ b/jarvis/ui/jarvisbar/overlay.py@@ -348,6 +348,9 @@ class JarvisBarOverlay:self._feedback_publisher: Callable[[str, dict], None] | None = Noneself._on_show_window: Callable[[], None] | None = Noneself._hovered = False # mouse over the bar → reveal the close cross+ # True only on a macOS root whose "-transparent" attribute took; the+ # frame loop then converts frames to RGBA (renderer.key_to_alpha).+ self._mac_transparent = Falseself._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@@ -554,11 +557,30 @@ class JarvisBarOverlay:log.debug("jarvisbar icon setup skipped", exc_info=True)root.overrideredirect(True)root.wm_attributes("-topmost", True)- try:- root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)- except tk.TclError:- log.warning("transparentcolor unsupported — bar will show its key colour")- root.configure(bg=COLOR_KEY_HEX)+ # Per-pixel transparency, per platform: Windows keys out the magenta+ # color key on the layered window; macOS has no color key, so there+ # the WINDOW itself becomes transparent (Aqua-Tk's "-transparent" ++ # the systemTransparent background) and every frame carries a real+ # alpha channel instead (renderer.key_to_alpha in the frame loop).+ self._mac_transparent = False+ if sys.platform == "darwin":+ try:+ root.wm_attributes("-transparent", True)+ root.configure(bg="systemTransparent")+ self._mac_transparent = True+ except tk.TclError:+ log.warning(+ "macOS -transparent unsupported — bar will show its key colour"+ )+ root.configure(bg=COLOR_KEY_HEX)+ else:+ try:+ root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)+ except tk.TclError:+ log.warning(+ "transparentcolor unsupported — bar will show its key colour"+ )+ root.configure(bg=COLOR_KEY_HEX)# Window-level alpha ON TOP of the color key: the magenta stays fully# keyed out (verified — no bleed) while the pill itself goes# semi-transparent, so the desktop shows through it (a dictation app-like).@@ -574,7 +596,7 @@ class JarvisBarOverlay:root,width=renderer.WIN_W,height=renderer.WIN_H,- bg=COLOR_KEY_HEX,+ bg="systemTransparent" if self._mac_transparent else COLOR_KEY_HEX,highlightthickness=0,borderwidth=0,)@@ -728,10 +750,16 @@ class JarvisBarOverlay:"""Best-effort color-key + opacity application on the Tk thread."""if self._root is None:return- try:- self._root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)- except Exception: # noqa: BLE001- log.debug("jarvisbar transparentcolor re-assert failed", exc_info=True)+ if sys.platform != "darwin":+ # The color key is a Windows layered-window concept (BUG-030+ # re-assert); macOS transparency is the immutable "-transparent"+ # attribute set at creation — nothing to re-assert there.+ try:+ self._root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)+ except Exception: # noqa: BLE001+ log.debug(+ "jarvisbar transparentcolor re-assert failed", exc_info=True+ )try:self._root.wm_attributes("-alpha", opacity)except Exception: # noqa: BLE001@@ -896,6 +924,9 @@ class JarvisBarOverlay:t, effective_mode, self._ext_level,hovered=self._hovered, muted=self._muted,)+ if getattr(self, "_mac_transparent", False):+ # macOS: no color key — carry real per-pixel alpha instead.+ img = renderer.key_to_alpha(img)# PhotoImage must be retained on self, else Tk GCs it before# drawing.self._photo = ImageTk.PhotoImage(img)diff --git a/jarvis/ui/jarvisbar/renderer.py b/jarvis/ui/jarvisbar/renderer.pyindex 1fcc57b359..8b1e73c8dc 100644--- a/jarvis/ui/jarvisbar/renderer.py+++ b/jarvis/ui/jarvisbar/renderer.py@@ -24,6 +24,23 @@ import numpy as npfrom PIL import Image, ImageDrawCOLOR_KEY_RGB = (255, 0, 255)+++def key_to_alpha(img: Image.Image) -> Image.Image:+ """RGB frame → RGBA with the magenta color key mapped to full transparency.++ Windows keys the magenta out natively (layered-window color key); macOS+ has no color-key concept, so the Tk surface there shows RGBA frames on a+ ``-transparent`` root instead. Exact-match keying mirrors the Windows+ contract: only pure ``COLOR_KEY_RGB`` pixels vanish.+ """+ arr = np.asarray(img, dtype=np.uint8)+ alpha = np.where(+ (arr == COLOR_KEY_RGB).all(axis=-1), 0, 255+ ).astype(np.uint8)+ return Image.fromarray(np.dstack((arr, alpha)), "RGBA")++PILL_BG = (14, 13, 12)# Bright gold rim: the only thing that reads when the pill is slim AND# semi-transparent (window -alpha). Dark fill + glowing gold edge = glass look.diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.pynew file mode 100644index 0000000000..91c915d729--- /dev/null+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py@@ -0,0 +1,278 @@+"""Out-of-process Jarvis Bar surface — the macOS hosting fix (BUG-057).++``SubprocessBarOverlay`` implements the duck-typed surface API+``OrbBusBridge`` drives, but renders nothing itself: it spawns+``python -m jarvis.ui.jarvisbar.host`` — whose MAIN thread may legally own+Aqua-Tk — and forwards every surface call as one JSON line on the child's+stdin. Child events (mute toggle, feedback, show-window) stream back on+stdout and are dispatched to the callbacks the bridge registered, so the+bridge wiring is reused unchanged.++Failure contract: if the host cannot spawn or dies, every method degrades to+a one-log no-op (``NullOverlay`` behavior) — the bar is cosmetic and must+never take the app down with it. No auto-restart in this first cut; a dead+host stays down until the next overlay swap / app restart. Deliberately+defines no ``_root`` attribute so the bridge's reset path early-returns+(same contract as ``NullOverlay``).+"""+from __future__ import annotations++import json+import logging+import subprocess+import sys+import threading+from collections.abc import Callable+from typing import IO, Any++log = logging.getLogger("jarvis.ui.jarvisbar")++# Kept in sync with renderer.MODES without importing numpy/PIL into the+# parent for a pure IPC proxy; the host-side bar re-validates every mode.+_MODES = ("idle", "listen", "speak", "think")++_HOST_MODULE = "jarvis.ui.jarvisbar.host"+++class SubprocessBarOverlay:+ """Surface proxy driving a bar hosted in its own companion process."""++ def __init__(+ self,+ persistent: bool = True,+ accent: str = "#e7c46e",+ opacity: float | None = None,+ startup_gated: bool = False,+ ) -> None:+ self._persistent_flag = bool(persistent)+ self._accent = accent+ self._opacity = opacity+ self._startup_gated = bool(startup_gated)+ self._mode = "idle"+ self._muted = False+ self._proc: subprocess.Popen[str] | None = None+ self._send_lock = threading.Lock()+ self._ready = threading.Event()+ self._stopping = False+ self._dead_logged = False+ self._on_mute_toggle: Callable[[], None] | None = None+ self._feedback_publisher: Callable[[str, dict], None] | None = None+ self._on_show_window: Callable[[], None] | None = None++ # ------------------------------------------------------------------ #+ # Lifecycle #+ # ------------------------------------------------------------------ #+ def start_in_thread(self, timeout: float = 3.0) -> None:+ """Spawn the bar host process (name kept for the surface contract)."""+ if self._proc is not None and self._proc.poll() is None:+ return+ try:+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ self._proc = subprocess.Popen( # noqa: S603 — fixed argv, own venv+ [sys.executable, "-m", _HOST_MODULE],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ encoding="utf-8",+ errors="replace",+ bufsize=1,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except Exception: # noqa: BLE001 — cosmetic surface; degrade, never raise+ log.exception("JarvisBar host spawn failed — bar runs as a no-op")+ self._proc = None+ return++ init: dict[str, Any] = {+ "op": "init",+ "persistent": self._persistent_flag,+ "accent": self._accent,+ "startup_gated": self._startup_gated,+ }+ if self._opacity is not None:+ init["opacity"] = float(self._opacity)+ self._write_line(init)++ threading.Thread(+ target=self._pump_events,+ args=(self._proc.stdout,),+ name="jarvisbar-host-events",+ daemon=True,+ ).start()+ threading.Thread(+ target=self._pump_stderr,+ args=(self._proc.stderr,),+ name="jarvisbar-host-stderr",+ daemon=True,+ ).start()++ if not self._ready.wait(timeout=timeout):+ log.error("JarvisBar host not ready within %.1fs", timeout)++ def stop(self) -> None:+ proc = self._proc+ if proc is None:+ return+ self._stopping = True+ try:+ self._send({"op": "stop"})+ if proc.stdin is not None:+ proc.stdin.close()+ except Exception: # noqa: BLE001+ log.debug("JarvisBar host stop write failed", exc_info=True)+ try:+ proc.wait(timeout=3.0)+ except Exception: # noqa: BLE001+ try:+ proc.kill()+ except Exception: # noqa: BLE001+ log.debug("JarvisBar host kill failed", exc_info=True)+ self._proc = None++ # ------------------------------------------------------------------ #+ # Surface API consumed by OrbBusBridge #+ # ------------------------------------------------------------------ #+ def show(self, mode: str = "listen") -> None:+ if mode not in _MODES:+ return+ self._mode = mode+ self._send({"op": "show", "mode": mode})++ def hide(self) -> None:+ self._send({"op": "hide"})++ def reassert_z_order(self) -> None:+ self._send({"op": "reassert_z_order"})++ def release_startup_gate(self) -> bool:+ released = self._startup_gated+ self._startup_gated = False+ if released:+ self._send({"op": "release_startup_gate"})+ return released++ def set_level(self, level: float) -> None:+ self._send({"op": "set_level", "level": float(level)})++ def set_muted(self, muted: bool) -> None:+ self._muted = bool(muted)+ self._send({"op": "set_muted", "muted": self._muted})++ # The bar draws no text bubble and no mouth — the real surface no-ops+ # these, so the proxy saves the IPC round-trip and no-ops locally too.+ def play_animation(self, name: str, **params: Any) -> None: ...+ def stop_animation(self, name: str) -> None: ...+ def show_listening_transcript(+ self, text: str = "", duration_ms: int = 30000+ ) -> None: ...+ def hide_comment(self) -> None: ...+ def start_mouth_animation(self, duration_ms: int = 60000) -> None: ...+ def stop_mouth_animation(self) -> None: ...++ def set_on_mute_toggle(self, callback: Callable[[], None] | None) -> None:+ self._on_mute_toggle = callback++ def set_feedback_publisher(+ self, callback: Callable[[str, dict], None] | None+ ) -> None:+ self._feedback_publisher = callback++ def set_on_show_window(self, callback: Callable[[], None] | None) -> None:+ self._on_show_window = callback++ def _on_reset_double_click(self, _event: Any = None) -> None:+ self._send({"op": "reset_position"})++ # ``set_bar_persistent`` live-flips ``bar._persistent`` directly; keep+ # that contract while forwarding the flip to the host process.+ @property+ def _persistent(self) -> bool:+ return self._persistent_flag++ @_persistent.setter+ def _persistent(self, enabled: bool) -> None:+ self._persistent_flag = bool(enabled)+ self._send({"op": "set_persistent", "enabled": self._persistent_flag})++ # ------------------------------------------------------------------ #+ # IPC plumbing #+ # ------------------------------------------------------------------ #+ def _send(self, msg: dict[str, Any]) -> None:+ proc = self._proc+ if proc is None or proc.poll() is not None or proc.stdin is None:+ self._log_dead_once()+ return+ self._write_line(msg)++ def _write_line(self, msg: dict[str, Any]) -> None:+ proc = self._proc+ if proc is None or proc.stdin is None:+ return+ try:+ line = json.dumps(msg, ensure_ascii=False)+ with self._send_lock:+ proc.stdin.write(line + "\n")+ proc.stdin.flush()+ except Exception: # noqa: BLE001 — broken pipe = dead host; degrade+ self._log_dead_once()++ def _log_dead_once(self) -> None:+ if self._stopping or self._dead_logged:+ return+ self._dead_logged = True+ log.warning(+ "JarvisBar host process is gone — the bar stays hidden until the "+ "next overlay swap or app restart."+ )++ def _pump_events(self, stream: IO[str] | None) -> None:+ if stream is None:+ return+ try:+ for raw in stream:+ line = raw.strip()+ if not line:+ continue+ try:+ msg = json.loads(line)+ except ValueError:+ log.debug("bar host non-JSON stdout line: %.120r", line)+ continue+ self._dispatch_event(msg)+ except Exception: # noqa: BLE001+ log.debug("bar host event pump failed", exc_info=True)+ finally:+ if not self._stopping:+ self._log_dead_once()++ def _dispatch_event(self, msg: dict[str, Any]) -> None:+ event = msg.get("event")+ try:+ if event == "ready":+ self._ready.set()+ elif event == "mute_toggle":+ cb = self._on_mute_toggle+ if cb is not None:+ cb()+ elif event == "feedback":+ pub = self._feedback_publisher+ if pub is not None:+ pub(str(msg.get("kind", "")), dict(msg.get("payload") or {}))+ elif event == "show_window":+ cb_show = self._on_show_window+ if cb_show is not None:+ cb_show()+ except Exception: # noqa: BLE001 — a bad callback must not kill the pump+ log.exception("bar host event callback failed: %r", event)++ def _pump_stderr(self, stream: IO[str] | None) -> None:+ if stream is None:+ return+ try:+ for raw in stream:+ text = raw.rstrip()+ if text:+ log.info("bar host: %s", text)+ except Exception: # noqa: BLE001+ log.debug("bar host stderr pump failed", exc_info=True)diff --git a/tests/unit/ui/jarvisbar/__init__.py b/tests/unit/ui/jarvisbar/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/ui/jarvisbar/test_host_protocol.py b/tests/unit/ui/jarvisbar/test_host_protocol.pynew file mode 100644index 0000000000..66bd69e26a--- /dev/null+++ b/tests/unit/ui/jarvisbar/test_host_protocol.py@@ -0,0 +1,170 @@+"""Bar host process protocol (jarvis.ui.jarvisbar.host).++The host lets the bar's Tk mainloop run on a companion process's MAIN thread+(the only thread Aqua-Tk accepts on macOS, BUG-057). These tests drive the+dispatch/reader seams in-process with a recording bar, plus one real+cross-process round-trip using the echo double (JARVIS_BAR_HOST_FAKE=1) so+the pipes, EOF shutdown and ready handshake are proven without a display.+"""+from __future__ import annotations++import io+import json+import os+import subprocess+import sys++import pytest++from jarvis.ui.jarvisbar import host+++class _RecordingBar:+ def __init__(self) -> None:+ self.calls: list[tuple] = []+ self._persistent = True++ def show(self, mode: str = "listen") -> None:+ self.calls.append(("show", mode))++ def hide(self) -> None:+ self.calls.append(("hide",))++ def set_level(self, level: float) -> None:+ self.calls.append(("set_level", level))++ def set_muted(self, muted: bool) -> None:+ self.calls.append(("set_muted", muted))++ def release_startup_gate(self) -> bool:+ self.calls.append(("release_startup_gate",))+ return True++ def reassert_z_order(self) -> None:+ self.calls.append(("reassert_z_order",))++ def play_animation(self, name: str, **params) -> None:+ self.calls.append(("play_animation", name, params))++ def stop_animation(self, name: str) -> None:+ self.calls.append(("stop_animation", name))++ def show_listening_transcript(self, text: str = "", duration_ms: int = 0) -> None:+ self.calls.append(("show_listening_transcript", text, duration_ms))++ def hide_comment(self) -> None:+ self.calls.append(("hide_comment",))++ def start_mouth_animation(self, duration_ms: int = 0) -> None:+ self.calls.append(("start_mouth_animation", duration_ms))++ def stop_mouth_animation(self) -> None:+ self.calls.append(("stop_mouth_animation",))++ def _on_reset_double_click(self, _event=None) -> None:+ self.calls.append(("reset_position",))++ def stop(self) -> None:+ self.calls.append(("stop",))+++def test_dispatch_maps_every_op_onto_the_surface() -> None:+ bar = _RecordingBar()+ ops = [+ {"op": "show", "mode": "listen"},+ {"op": "hide"},+ {"op": "set_level", "level": 0.5},+ {"op": "set_muted", "muted": True},+ {"op": "set_persistent", "enabled": False},+ {"op": "release_startup_gate"},+ {"op": "reassert_z_order"},+ {"op": "play_animation", "name": "wave", "params": {"x": 1}},+ {"op": "stop_animation", "name": "wave"},+ {"op": "show_listening_transcript", "text": "hi", "duration_ms": 9},+ {"op": "hide_comment"},+ {"op": "start_mouth_animation", "duration_ms": 7},+ {"op": "stop_mouth_animation"},+ {"op": "reset_position"},+ ]+ for msg in ops:+ assert host.dispatch(bar, msg) is True+ assert bar._persistent is False+ assert ("show", "listen") in bar.calls+ assert ("set_level", 0.5) in bar.calls+ assert ("set_muted", True) in bar.calls+ assert ("play_animation", "wave", {"x": 1}) in bar.calls+ assert ("show_listening_transcript", "hi", 9) in bar.calls+ assert ("reset_position",) in bar.calls+++def test_dispatch_stop_returns_false_and_unknown_is_tolerated() -> None:+ bar = _RecordingBar()+ assert host.dispatch(bar, {"op": "stop"}) is False+ assert host.dispatch(bar, {"op": "definitely-not-a-real-op"}) is True+++def test_reader_loop_survives_junk_and_stops_bar_on_eof() -> None:+ bar = _RecordingBar()+ stream = io.StringIO(+ "\n"+ "this is not json\n"+ '{"op": "show", "mode": "speak"}\n'+ '{"op": "set_level", "level": 1.0}\n'+ )+ host.reader_loop(bar, stream) # hard_exit stays None in tests+ assert ("show", "speak") in bar.calls+ assert ("set_level", 1.0) in bar.calls+ assert bar.calls[-1] == ("stop",) # EOF → the bar is stopped+++def test_reader_loop_stop_command_stops_bar_without_draining_rest() -> None:+ bar = _RecordingBar()+ stream = io.StringIO('{"op": "stop"}\n{"op": "hide"}\n')+ host.reader_loop(bar, stream)+ assert ("hide",) not in bar.calls+ assert bar.calls[-1] == ("stop",)+++def test_one_failing_command_does_not_kill_the_loop() -> None:+ class _ExplodingBar(_RecordingBar):+ def hide(self) -> None: # type: ignore[override]+ raise RuntimeError("boom")++ bar = _ExplodingBar()+ stream = io.StringIO('{"op": "hide"}\n{"op": "show", "mode": "idle"}\n')+ host.reader_loop(bar, stream)+ assert ("show", "idle") in bar.calls+++def test_host_process_round_trip_with_echo_bar() -> None:+ """Real subprocess: init → ready, op echo, clean stop-driven exit."""+ env = dict(os.environ)+ env["JARVIS_BAR_HOST_FAKE"] = "1"+ proc = subprocess.Popen(+ [sys.executable, "-m", "jarvis.ui.jarvisbar.host"],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ encoding="utf-8",+ env=env,+ cwd=os.getcwd(),+ )+ try:+ assert proc.stdin is not None and proc.stdout is not None+ proc.stdin.write('{"op": "init", "persistent": true}\n')+ proc.stdin.write('{"op": "show", "mode": "listen"}\n')+ proc.stdin.write('{"op": "stop"}\n')+ proc.stdin.flush()+ out, _err = proc.communicate(timeout=30)+ events = [json.loads(line) for line in out.splitlines() if line.strip()]+ kinds = [e.get("event") for e in events]+ assert "ready" in kinds+ echoed = [e for e in events if e.get("event") == "op"]+ assert any(+ e.get("op") == "show" and e.get("args") == ["listen"] for e in echoed+ )+ assert proc.returncode == 0+ finally:+ if proc.poll() is None:+ proc.kill()diff --git a/tests/unit/ui/jarvisbar/test_key_to_alpha.py b/tests/unit/ui/jarvisbar/test_key_to_alpha.pynew file mode 100644index 0000000000..1d75a21fc8--- /dev/null+++ b/tests/unit/ui/jarvisbar/test_key_to_alpha.py@@ -0,0 +1,38 @@+"""renderer.key_to_alpha — the macOS per-pixel transparency translation.++macOS has no layered-window color key, so the bar's frames must carry a real+alpha channel there: exactly the magenta key pixels become fully transparent,+everything else stays fully opaque (mirroring the Windows color-key contract).+"""+from __future__ import annotations++import numpy as np+from PIL import Image++from jarvis.ui.jarvisbar.renderer import COLOR_KEY_RGB, key_to_alpha+++def test_key_pixels_become_transparent_and_content_stays_opaque() -> None:+ arr = np.zeros((4, 4, 3), dtype=np.uint8)+ arr[:, :] = COLOR_KEY_RGB+ arr[1, 2] = (10, 20, 30) # one content pixel+ arr[3, 0] = (255, 0, 254) # near-key must NOT be keyed (exact match only)++ out = key_to_alpha(Image.fromarray(arr, "RGB"))+ assert out.mode == "RGBA"+ result = np.asarray(out)++ assert result[0, 0, 3] == 0 # key pixel → fully transparent+ assert result[1, 2, 3] == 255 # content pixel → fully opaque+ assert tuple(result[1, 2, :3]) == (10, 20, 30) # colors untouched+ assert result[3, 0, 3] == 255 # near-key stays visible+++def test_real_rendered_frame_keys_out_only_the_background() -> None:+ from jarvis.ui.jarvisbar.renderer import JarvisBarRenderer++ frame = JarvisBarRenderer(accent="#e7c46e").render(0.5, "listen", 0.8)+ out = np.asarray(key_to_alpha(frame))+ # A real frame has both: transparent background and an opaque pill.+ assert (out[..., 3] == 0).any()+ assert (out[..., 3] == 255).any()diff --git a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py b/tests/unit/ui/jarvisbar/test_subprocess_overlay.pynew file mode 100644index 0000000000..fc71a9e63d--- /dev/null+++ b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py@@ -0,0 +1,192 @@+"""SubprocessBarOverlay — the out-of-process bar surface (BUG-057 fix).++Drives the proxy against a fake Popen so every surface call's wire format,+the local mirrors (_mode/_persistent/_muted), the ready handshake, event →+callback dispatch, and the dead-host degrade are proven without spawning a+process. The real cross-process path is covered in test_host_protocol.py.+"""+from __future__ import annotations++import io+import json+import threading++from jarvis.ui.jarvisbar import subprocess_overlay as mod+from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessBarOverlay+++class _FakeStdin:+ def __init__(self) -> None:+ self.lines: list[str] = []+ self.closed = False++ def write(self, text: str) -> None:+ self.lines.append(text)++ def flush(self) -> None: ...++ def close(self) -> None:+ self.closed = True+++class _FakePopen:+ """Records stdin writes; serves scripted stdout events; never a process."""++ last: _FakePopen | None = None++ def __init__(self, *_args, **_kwargs) -> None:+ self.stdin = _FakeStdin()+ self.stdout = io.StringIO('{"event": "ready"}\n')+ self.stderr = io.StringIO("")+ self._returncode: int | None = None+ _FakePopen.last = self++ def poll(self) -> int | None:+ return self._returncode++ def wait(self, timeout: float | None = None) -> int:+ self._returncode = 0+ return 0++ def kill(self) -> None:+ self._returncode = -9++ def sent(self) -> list[dict]:+ return [json.loads(line) for line in self.stdin.lines]+++def _started_proxy(monkeypatch, **kwargs) -> tuple[SubprocessBarOverlay, _FakePopen]:+ monkeypatch.setattr(mod.subprocess, "Popen", _FakePopen)+ surface = SubprocessBarOverlay(**kwargs)+ surface.start_in_thread(timeout=2.0)+ proc = _FakePopen.last+ assert proc is not None+ return surface, proc+++def test_init_line_carries_the_constructor_config(monkeypatch) -> None:+ surface, proc = _started_proxy(+ monkeypatch, persistent=False, accent="#123456", startup_gated=True+ )+ init = proc.sent()[0]+ assert init == {+ "op": "init",+ "persistent": False,+ "accent": "#123456",+ "startup_gated": True,+ }+ assert surface._ready.is_set() # scripted ready event consumed+++def test_surface_calls_become_wire_ops_and_mirror_locally(monkeypatch) -> None:+ surface, proc = _started_proxy(monkeypatch)+ surface.show("speak")+ surface.show("bogus") # invalid mode → ignored, not sent+ surface.hide()+ surface.set_level(0.75)+ surface.set_muted(True)+ surface.reassert_z_order()+ surface._on_reset_double_click()+ ops = [m["op"] for m in proc.sent()[1:]]+ assert ops == [+ "show",+ "hide",+ "set_level",+ "set_muted",+ "reassert_z_order",+ "reset_position",+ ]+ assert surface._mode == "speak"+ assert surface._muted is True+++def test_text_and_mouth_methods_are_local_noops(monkeypatch) -> None:+ surface, proc = _started_proxy(monkeypatch)+ surface.play_animation("wave", x=1)+ surface.stop_animation("wave")+ surface.show_listening_transcript("hi", 5)+ surface.hide_comment()+ surface.start_mouth_animation(5)+ surface.stop_mouth_animation()+ assert len(proc.sent()) == 1 # only the init line went out+++def test_release_startup_gate_semantics_match_the_real_bar(monkeypatch) -> None:+ surface, proc = _started_proxy(monkeypatch, startup_gated=True)+ assert surface.release_startup_gate() is True+ assert surface.release_startup_gate() is False # released exactly once+ assert [m["op"] for m in proc.sent()[1:]] == ["release_startup_gate"]+++def test_persistent_attribute_flip_is_forwarded(monkeypatch) -> None:+ surface, proc = _started_proxy(monkeypatch, persistent=True)+ surface._persistent = False # the set_bar_persistent live-flip contract+ assert surface._persistent is False+ flips = [m for m in proc.sent() if m["op"] == "set_persistent"]+ assert flips == [{"op": "set_persistent", "enabled": False}]+++def test_child_events_dispatch_to_bridge_callbacks(monkeypatch) -> None:+ monkeypatch.setattr(mod.subprocess, "Popen", _FakePopen)+ surface = SubprocessBarOverlay()+ fired: list[tuple] = []+ done = threading.Event()+ surface.set_on_mute_toggle(lambda: fired.append(("mute",)))+ surface.set_feedback_publisher(lambda k, d: fired.append(("feedback", k, d)))+ surface.set_on_show_window(lambda: (fired.append(("show_window",)), done.set()))++ events = (+ '{"event": "ready"}\n'+ '{"event": "mute_toggle"}\n'+ '{"event": "feedback", "kind": "bar", "payload": {"a": 1}}\n'+ "not json\n"+ '{"event": "show_window"}\n'+ )++ class _EventPopen(_FakePopen):+ def __init__(self, *args, **kwargs) -> None:+ super().__init__(*args, **kwargs)+ self.stdout = io.StringIO(events)++ monkeypatch.setattr(mod.subprocess, "Popen", _EventPopen)+ surface.start_in_thread(timeout=2.0)+ assert done.wait(timeout=2.0)+ assert ("mute",) in fired+ assert ("feedback", "bar", {"a": 1}) in fired+ assert ("show_window",) in fired+++def test_dead_host_degrades_to_noop_without_raising(monkeypatch) -> None:+ surface, proc = _started_proxy(monkeypatch)+ proc._returncode = 1 # the host died+ surface.show("listen") # must not raise+ surface.set_level(0.3)+ assert [m["op"] for m in proc.sent()[1:]] == [] # nothing reached the wire+++def test_spawn_failure_leaves_a_noop_surface(monkeypatch) -> None:+ def _boom(*_a, **_k):+ raise OSError("no python")++ monkeypatch.setattr(mod.subprocess, "Popen", _boom)+ surface = SubprocessBarOverlay()+ surface.start_in_thread(timeout=0.1)+ surface.show("listen") # every call is a safe no-op+ surface.stop()+++def test_stop_sends_stop_closes_stdin_and_waits(monkeypatch) -> None:+ surface, proc = _started_proxy(monkeypatch)+ surface.stop()+ assert proc.sent()[-1] == {"op": "stop"}+ assert proc.stdin.closed is True+ assert surface._proc is None+++def test_surface_contract_exposes_every_bridge_method() -> None:+ from tests.unit.ui.jarvisbar.test_surface_contract import REQUIRED++ for name in REQUIRED:+ assert getattr(SubprocessBarOverlay, name, None) is not None, name+ # Same reset-path contract as NullOverlay: no _root instance attribute.+ assert not hasattr(SubprocessBarOverlay(), "_root")diff --git a/tests/unit/ui/test_macos_ui_main_thread_gates.py b/tests/unit/ui/test_macos_ui_main_thread_gates.pyindex bb7b41eae1..fac4c2dab4 100644--- a/tests/unit/ui/test_macos_ui_main_thread_gates.py+++ b/tests/unit/ui/test_macos_ui_main_thread_gates.py@@ -68,14 +68,53 @@ def test_virtual_cursor_start_returns_false_on_macos(monkeypatch, caplog) -> Nonassert recorder.spawned == []-def test_desktop_build_overlay_surface_returns_nulloverlay_on_macos(+def test_desktop_build_overlay_surface_on_macos(monkeypatch) -> None:+ # The bar gets the own-process host (its Tk mainloop runs on the CHILD's+ # main thread — legal on Aqua-Tk); the mascot has no host yet and stays+ # the no-op surface. Neither path may create an in-process Tk root.+ from jarvis.ui.desktop_app import DesktopApp+ from jarvis.ui.jarvisbar.null_overlay import NullOverlay+ from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessBarOverlay++ monkeypatch.setattr("sys.platform", "darwin")+ spawned: list[float] = []+ monkeypatch.setattr(+ SubprocessBarOverlay,+ "start_in_thread",+ lambda self, timeout=3.0: spawned.append(timeout),+ )+ app = DesktopApp.__new__(DesktopApp) # bypass heavy __init__+ app.cfg = SimpleNamespace(+ ui=SimpleNamespace(+ orb_style="jarvis_bar",+ bar_persistent=True,+ bar_accent="#e7c46e",+ orb_mascot_path="",+ )+ )+ surface = app._build_overlay_surface("jarvis_bar")+ assert isinstance(surface, SubprocessBarOverlay)+ assert surface._persistent is True+ assert spawned # the companion process spawn was requested+ assert isinstance(app._build_overlay_surface("mascot"), NullOverlay)+++def test_desktop_build_overlay_surface_macos_bar_falls_back_to_null(monkeypatch,) -> None:+ # Fail-safe: a broken host spawn must never block the boot (BUG-057+ # class) — the bar degrades to the no-op surface instead.from jarvis.ui.desktop_app import DesktopAppfrom jarvis.ui.jarvisbar.null_overlay import NullOverlay+ from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessBarOverlaymonkeypatch.setattr("sys.platform", "darwin")- app = DesktopApp.__new__(DesktopApp) # bypass heavy __init__++ def _boom(self, timeout=3.0):+ raise RuntimeError("spawn failed")++ monkeypatch.setattr(SubprocessBarOverlay, "start_in_thread", _boom)+ app = DesktopApp.__new__(DesktopApp)app.cfg = SimpleNamespace(ui=SimpleNamespace(orb_style="jarvis_bar",@@ -84,9 +123,7 @@ def test_desktop_build_overlay_surface_returns_nulloverlay_on_macos(orb_mascot_path="",))- for style in ("jarvis_bar", "mascot"):- surface = app._build_overlay_surface(style)- assert isinstance(surface, NullOverlay), style+ assert isinstance(app._build_overlay_surface("jarvis_bar"), NullOverlay)def test_overlay_factory_selects_tray_floor_on_macos() -> None: