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
feat(macos): visible mascot/orb via subprocess host + real menu-bar tray icon
Joana Lütke2c7ab46460b4
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex cd2a6e9fb9..0d47f789bd 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2034,10 +2034,10 @@ class DesktopApp:# 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.+ # BUG-056 tray). Both surfaces therefore live in their own+ # companion process whose MAIN thread owns the Tk mainloop+ # (jarvis.ui.jarvisbar.host), remote-driven over stdio; the init+ # line's "surface" key selects bar vs. mascot.from loguru import loggerif style == "jarvis_bar":@@ -2062,14 +2062,28 @@ class DesktopApp:"macOS JarvisBar host failed to start — falling back ""to the no-op surface.")+ elif style != "none":+ try:+ from jarvis.ui.jarvisbar.subprocess_overlay import (+ SubprocessMascotOverlay,+ )++ surface = SubprocessMascotOverlay(+ mascot_path=self.cfg.ui.orb_mascot_path or None,+ )+ surface.start_in_thread()+ logger.info(+ "Mascot orb 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 mascot host failed to start — falling back "+ "to the no-op surface."+ )from jarvis.ui.jarvisbar import NullOverlay- 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.pyindex 472be4acf6..dd84319b49 100644--- a/jarvis/ui/jarvisbar/host.py+++ b/jarvis/ui/jarvisbar/host.py@@ -14,6 +14,9 @@ Protocol (UTF-8, one JSON object per line):``{"op": "init", "persistent": ..., "accent": ..., "startup_gated": ...}``(optional ``opacity``); every further line is a surface command mirroringthe ``OrbBusBridge`` surface API (``show``, ``hide``, ``set_level``, ...).+ An optional ``"surface"`` key selects what the host renders:+ ``"jarvis_bar"`` (default) or ``"mascot"`` (the OrbOverlay mascot, with an+ optional ``"mascot_path"`` passthrough).stdin EOF means the parent died or shut down → the host stops the bar andexits, so no ownerless bar can linger on the user's desktop.- child → parent (stdout): events — ``{"event": "ready"}`` once the Tk root@@ -57,60 +60,83 @@ def emit(event: str, **payload: Any) -> None:_STDOUT_LOCK = threading.Lock()-def dispatch(bar: Any, msg: dict[str, Any]) -> bool:- """Apply one parent command to the bar. Returns ``False`` for ``stop``.+def _call(surface: Any, name: str, *args: Any, **kwargs: Any) -> None:+ """Invoke ``surface.<name>(...)`` if present; a missing method is a no-op.- 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.+ The host now fronts more than one surface class (JarvisBarOverlay has+ every op; the mascot OrbOverlay lacks a few bar-only ones), so an op the+ current surface does not implement degrades to a debug-logged no-op.+ """+ method = getattr(surface, name, None)+ if method is None:+ log.debug("bar-host: surface has no %r — op ignored", name)+ return+ method(*args, **kwargs)+++def dispatch(surface: Any, msg: dict[str, Any]) -> bool:+ """Apply one parent command to the surface. Returns ``False`` for ``stop``.++ Every method called here is documented thread-safe on the surface+ (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 Falseif op == "show":- bar.show(str(msg.get("mode", "listen")))+ _call(surface, "show", str(msg.get("mode", "listen")))elif op == "hide":- bar.hide()+ _call(surface, "hide")elif op == "set_level":- bar.set_level(float(msg.get("level", 0.0)))+ _call(surface, "set_level", float(msg.get("level", 0.0)))elif op == "set_muted":- bar.set_muted(bool(msg.get("muted", False)))+ _call(surface, "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+ surface._persistent = bool(msg.get("enabled", True)) # noqa: SLF001elif op == "release_startup_gate":- bar.release_startup_gate()+ _call(surface, "release_startup_gate")elif op == "reassert_z_order":- bar.reassert_z_order()+ _call(surface, "reassert_z_order")elif op == "play_animation":- bar.play_animation(str(msg.get("name", "")), **dict(msg.get("params") or {}))+ _call(+ surface,+ "play_animation",+ str(msg.get("name", "")),+ **dict(msg.get("params") or {}),+ )elif op == "stop_animation":- bar.stop_animation(str(msg.get("name", "")))+ _call(surface, "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))+ _call(+ surface,+ "show_listening_transcript",+ str(msg.get("text", "")),+ int(msg.get("duration_ms", 30000)),)elif op == "hide_comment":- bar.hide_comment()+ _call(surface, "hide_comment")elif op == "start_mouth_animation":- bar.start_mouth_animation(int(msg.get("duration_ms", 60000)))+ _call(surface, "start_mouth_animation", int(msg.get("duration_ms", 60000)))elif op == "stop_mouth_animation":- bar.stop_mouth_animation()+ _call(surface, "stop_mouth_animation")elif op == "reset_position":- bar._on_reset_double_click() # noqa: SLF001 — the double-click reset seam+ # The double-click reset seam.+ _call(surface, "_on_reset_double_click")else:log.warning("bar-host: unknown op %r", op)return Truedef reader_loop(- bar: Any,+ surface: Any,stream: TextIO,*,hard_exit: Callable[[int], Any] | None = None,) -> None:- """Drain parent commands until EOF or ``stop``, then stop the bar.+ """Drain parent commands until EOF or ``stop``, then stop the surface.``hard_exit`` (production: ``os._exit``) is the anti-linger backstop fora Tk mainloop that refuses to unwind; injectable so tests never arm it.@@ -126,23 +152,23 @@ def reader_loop(log.warning("bar-host: dropping non-JSON line: %.120r", line)continuetry:- if not dispatch(bar, msg):+ if not dispatch(surface, msg):breakexcept Exception: # noqa: BLE001 — one bad command must not kill the barlog.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).+ # EOF = the parent died or closed us deliberately; either way the+ # surface has no owner anymore. Arm the anti-linger backstop BEFORE+ # stopping the surface: 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 = Truekiller.start()# stop() marshals destroy onto the Tk thread.try:- bar.stop()+ surface.stop()except Exception: # noqa: BLE001log.debug("bar-host stop failed", exc_info=True)@@ -197,11 +223,53 @@ def _hide_dock_icon() -> None:log.debug("Dock-icon hide skipped (pyobjc unavailable?)", exc_info=True)-def _build_bar(cfg: dict[str, Any]) -> Any:+def _import_orb_overlay() -> Any:+ """Import the mascot ``OrbOverlay`` — wheel-robust.++ The top-level ``ui`` package ships with the source tree but not the+ wheel; when ``import ui`` fails, retry with the ``jarvis`` package's+ parent directory (the source checkout root) on ``sys.path``. A final+ failure exits the host non-zero with an honest stderr line so the+ parent can degrade.+ """+ try:+ import ui # noqa: F401+ except ImportError:+ try:+ from pathlib import Path++ import jarvis++ root = str(Path(jarvis.__file__).resolve().parent.parent)+ if root not in sys.path:+ sys.path.insert(0, root)+ except Exception: # noqa: BLE001 — the import below reports the failure+ log.debug("mascot-host: sys.path fallback failed", exc_info=True)+ try:+ from ui.orb.overlay import OrbOverlay+ except Exception as exc: # noqa: BLE001+ log.error(+ "mascot-host: cannot import OrbOverlay (%s) — exiting so the "+ "parent can degrade",+ exc,+ )+ raise SystemExit(3) from exc+ return OrbOverlay+++def _build_surface(cfg: dict[str, Any]) -> Any:if os.environ.get("JARVIS_BAR_HOST_FAKE") == "1":return _EchoBar()if sys.platform == "darwin":_hide_dock_icon()+ if str(cfg.get("surface", "jarvis_bar")) == "mascot":+ orb_overlay_cls = _import_orb_overlay()+ return orb_overlay_cls(+ sticky=False,+ mic_reactive=False,+ style="mascot",+ mascot_path=cfg.get("mascot_path") or None,+ )from jarvis.ui.jarvisbar.overlay import JarvisBarOverlaykwargs = {@@ -232,25 +300,27 @@ def main() -> int: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(+ surface = _build_surface(cfg)+ surface.set_on_mute_toggle(lambda: emit("mute_toggle"))+ surface.set_feedback_publisher(lambda kind, payload: emit("feedback", kind=kind, payload=payload))- bar.set_on_show_window(lambda: emit("show_window"))+ surface.set_on_show_window(lambda: emit("show_window"))def _announce_ready() -> None:- if bar._started.wait(timeout=READY_TIMEOUT_S): # noqa: SLF001+ if surface._started.wait(timeout=READY_TIMEOUT_S): # noqa: SLF001emit("ready")else:- log.error("bar-host: bar did not initialize within %ss", READY_TIMEOUT_S)+ log.error(+ "bar-host: surface 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),+ args=(surface, sys.stdin),kwargs={"hard_exit": os._exit},name="barhost-stdin",daemon=True,@@ -258,7 +328,7 @@ def main() -> int:# THE point of this process: the Tk mainloop runs on the MAIN thread, the# only thread Aqua-Tk accepts on macOS.- bar.start()+ surface.start()return 0diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.pyindex 91c915d729..9fc1e466ce 100644--- a/jarvis/ui/jarvisbar/subprocess_overlay.py+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py@@ -37,6 +37,10 @@ _HOST_MODULE = "jarvis.ui.jarvisbar.host"class SubprocessBarOverlay:"""Surface proxy driving a bar hosted in its own companion process."""+ # Overridable per surface so a host's pump threads are identifiable.+ _EVENTS_THREAD_NAME = "jarvisbar-host-events"+ _STDERR_THREAD_NAME = "jarvisbar-host-stderr"+def __init__(self,persistent: bool = True,@@ -84,26 +88,18 @@ class SubprocessBarOverlay:self._proc = Nonereturn- 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)+ self._write_line(self._init_payload())threading.Thread(target=self._pump_events,args=(self._proc.stdout,),- name="jarvisbar-host-events",+ name=self._EVENTS_THREAD_NAME,daemon=True,).start()threading.Thread(target=self._pump_stderr,args=(self._proc.stderr,),- name="jarvisbar-host-stderr",+ name=self._STDERR_THREAD_NAME,daemon=True,).start()@@ -130,6 +126,18 @@ class SubprocessBarOverlay:log.debug("JarvisBar host kill failed", exc_info=True)self._proc = None+ def _init_payload(self) -> dict[str, Any]:+ """First protocol line sent to the freshly spawned host."""+ 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)+ return init+# ------------------------------------------------------------------ ## Surface API consumed by OrbBusBridge ## ------------------------------------------------------------------ #@@ -276,3 +284,56 @@ class SubprocessBarOverlay:log.info("bar host: %s", text)except Exception: # noqa: BLE001log.debug("bar host stderr pump failed", exc_info=True)+++class SubprocessMascotOverlay(SubprocessBarOverlay):+ """Surface proxy driving the mascot ``OrbOverlay`` in the same host.++ Same spawn / ready / EOF-degrade plumbing as the bar proxy — the host+ process picks the surface from the init line's ``"surface"`` key. Unlike+ the bar (which draws no text bubble and no mouth), the mascot renders+ all of them, so the text/mouth/animation ops are FORWARDED over stdio+ instead of no-opped locally.+ """++ _EVENTS_THREAD_NAME = "orb-host-events"+ _STDERR_THREAD_NAME = "orb-host-stderr"++ def __init__(self, mascot_path: str | None = None) -> None:+ super().__init__()+ self._mascot_path = mascot_path++ def _init_payload(self) -> dict[str, Any]:+ return {+ "op": "init",+ "surface": "mascot",+ "mascot_path": self._mascot_path,+ }++ # The mascot draws the comment bubble and the mouth — forward the ops the+ # bar proxy no-ops locally (wire shapes match host.dispatch()).+ def play_animation(self, name: str, **params: Any) -> None:+ self._send({"op": "play_animation", "name": str(name), "params": params})++ def stop_animation(self, name: str) -> None:+ self._send({"op": "stop_animation", "name": str(name)})++ def show_listening_transcript(+ self, text: str = "", duration_ms: int = 30000+ ) -> None:+ self._send(+ {+ "op": "show_listening_transcript",+ "text": str(text),+ "duration_ms": int(duration_ms),+ }+ )++ def hide_comment(self) -> None:+ self._send({"op": "hide_comment"})++ def start_mouth_animation(self, duration_ms: int = 60000) -> None:+ self._send({"op": "start_mouth_animation", "duration_ms": int(duration_ms)})++ def stop_mouth_animation(self) -> None:+ self._send({"op": "stop_mouth_animation"})diff --git a/jarvis/ui/tray.py b/jarvis/ui/tray.pyindex 7b20248209..3cf9e5e03f 100644--- a/jarvis/ui/tray.py+++ b/jarvis/ui/tray.py@@ -5,8 +5,10 @@ Higher-quality .ico files can later be placed under assets/icons/.Threading: pystray runs on its own thread (not asyncio-capable).It communicates with the event loop via a thread-safe queue.-macOS: AppKit forbids that worker thread (main-thread-only UI), so start()-is a logged no-op there until the icon is hosted on the main thread.+macOS: AppKit forbids that worker thread (main-thread-only UI). A main-thread+start() hosts the icon on the pywebview NSApplication via run_detached();+off-main callers keep the logged no-op (BUG-056). Icon mutations from worker+threads are marshaled to the main thread via PyObjCTools.AppHelper.callAfter."""from __future__ import annotations@@ -99,6 +101,9 @@ class JarvisTray:self._icon: Any = Noneself._thread: threading.Thread | None = Noneself._command_queue: queue.Queue[TrayCommand] = queue.Queue()+ # True when the darwin icon runs detached on the AppKit main thread;+ # icon mutations must then be marshaled via _call_on_main (BUG-056).+ self._darwin_detached = Falsedef _build_menu(self) -> Any:from pystray import Menu, MenuItem # type: ignore[import-untyped]@@ -159,18 +164,47 @@ class JarvisTray:returnif sys.platform == "darwin":# pystray's darwin backend builds an NSStatusItem in Icon.__init__;- # AppKit allows UI objects on the MAIN thread only. Created from- # this worker thread, the first real-Mac boot died with a native- # AppKit assertion (NSInternalInconsistencyException → process- # abort, "Python quit unexpectedly") that no try/except can catch.- # Degrade to a logged no-op (AD-6): the desktop window + Dock icon- # remain. A real menu-bar icon needs main-thread hosting- # (pystray run_detached + the pywebview NSApplication) — tracked- # in docs/plans/cross-platform-mac-linux/FIX-TRACKER.md.- log.info(- "Tray not started: macOS allows status items on the main "- "thread only — running without a menu-bar icon."- )+ # AppKit allows UI objects on the MAIN thread only. Created from a+ # worker thread, the first real-Mac boot died with a native AppKit+ # assertion (NSInternalInconsistencyException → process abort,+ # "Python quit unexpectedly") that no try/except can catch+ # (BUG-056). Main-thread callers host the icon detached on the+ # shared NSApplication; off-main callers keep the logged no-op+ # floor (AD-6) — the desktop window + Dock icon remain.+ if threading.current_thread() is not threading.main_thread():+ log.info(+ "Tray not started: macOS allows status items on the main "+ "thread only — running without a menu-bar icon."+ )+ return+ if self._darwin_detached and self._icon is not None:+ # Already hosted detached — a second start() must not build a+ # duplicate status item (the thread guard above only covers+ # the worker-thread backends).+ return+ try:+ from AppKit import NSApplication # type: ignore[import-not-found]+ from pystray import Icon # type: ignore[import-untyped]++ nsapp = NSApplication.sharedApplication()+ icon_image = _make_icon(self._state)+ self._icon = Icon(+ "jarvis",+ icon=icon_image,+ title="Jarvis — idle",+ menu=self._build_menu(),+ darwin_nsapplication=nsapp,+ )+ self._icon.run_detached()+ self._darwin_detached = True+ except Exception: # noqa: BLE001 — a broken menu-bar host must not crash boot (AD-6)+ log.warning(+ "Tray not started: macOS menu-bar icon could not be "+ "created — running without a menu-bar icon.",+ exc_info=True,+ )+ self._icon = None+ self._darwin_detached = Falsereturnif not display_present():# Headless, or a Linux/Wayland session without an AppIndicator /@@ -185,13 +219,37 @@ class JarvisTray:self._thread = threading.Thread(target=self._run, name="jarvis-tray", daemon=True)self._thread.start()+ def _call_on_main(self, fn: Callable[[], None]) -> None:+ """Runs fn on the AppKit main thread for the detached darwin icon.++ macOS drives the NSStatusItem behind the icon on the main thread only+ (BUG-056), so mutations from worker threads are marshaled through+ PyObjCTools.AppHelper.callAfter. Everywhere else (and as a last+ resort when the marshal itself is unavailable) fn runs directly.+ """+ if not self._darwin_detached:+ fn()+ return+ try:+ from PyObjCTools import AppHelper # type: ignore[import-not-found]++ AppHelper.callAfter(fn)+ except Exception: # noqa: BLE001 — AD-6: degrade to a direct call+ fn()+def stop(self) -> None:if self._icon is not None:- try:- self._icon.stop()- except Exception: # noqa: BLE001- pass+ icon = self._icon++ def _do_stop() -> None:+ try:+ icon.stop()+ except Exception: # noqa: BLE001+ pass++ self._call_on_main(_do_stop)self._icon = None+ self._darwin_detached = Falsedef set_state(self, state: JarvisState) -> None:"""Thread-safe state update — re-renders the icon and tooltip."""@@ -200,20 +258,30 @@ class JarvisTray:self._state = stateif self._icon is None:return- try:- self._icon.icon = _make_icon(state)- self._icon.title = f"Jarvis — {state.value}"- except Exception: # noqa: BLE001- pass+ icon = self._icon- def set_error(self, message: str) -> None:- self.set_state(JarvisState.ERROR)- if self._icon is not None:+ def _apply() -> None:try:- self._icon.title = f"Jarvis — Error: {message[:60]}"+ icon.icon = _make_icon(state)+ icon.title = f"Jarvis — {state.value}"except Exception: # noqa: BLE001pass+ self._call_on_main(_apply)++ def set_error(self, message: str) -> None:+ self.set_state(JarvisState.ERROR)+ if self._icon is not None:+ icon = self._icon++ def _apply() -> None:+ try:+ icon.title = f"Jarvis — Error: {message[:60]}"+ except Exception: # noqa: BLE001+ pass++ self._call_on_main(_apply)+async def command_stream(self) -> asyncio.Queue[TrayCommand]:"""Async bridge: yields tray commands as an asyncio queue.diff --git a/tests/unit/ui/jarvisbar/test_host_protocol.py b/tests/unit/ui/jarvisbar/test_host_protocol.pyindex 66bd69e26a..d53f868ef6 100644--- a/tests/unit/ui/jarvisbar/test_host_protocol.py+++ b/tests/unit/ui/jarvisbar/test_host_protocol.py@@ -103,6 +103,64 @@ def test_dispatch_stop_returns_false_and_unknown_is_tolerated() -> None:assert host.dispatch(bar, {"op": "definitely-not-a-real-op"}) is True+class _SparseSurface:+ """A surface missing several ops (like the mascot OrbOverlay)."""++ def __init__(self) -> None:+ self.calls: list[tuple] = []++ def show(self, mode: str = "listen") -> None:+ self.calls.append(("show", mode))++ def stop(self) -> None:+ self.calls.append(("stop",))+++def test_dispatch_missing_surface_method_is_a_noop() -> None:+ surface = _SparseSurface()+ # OrbOverlay lacks e.g. set_muted/release_startup_gate/reassert_z_order —+ # a missing method must degrade to a no-op, never raise.+ assert host.dispatch(surface, {"op": "set_muted", "muted": True}) is True+ assert host.dispatch(surface, {"op": "release_startup_gate"}) is True+ assert host.dispatch(surface, {"op": "reassert_z_order"}) is True+ assert surface.calls == []+++def test_reader_loop_survives_ops_the_surface_lacks() -> None:+ surface = _SparseSurface()+ stream = io.StringIO(+ '{"op": "set_muted", "muted": true}\n{"op": "show", "mode": "idle"}\n'+ )+ host.reader_loop(surface, stream)+ assert ("show", "idle") in surface.calls+ assert surface.calls[-1] == ("stop",)+++def test_build_surface_mascot_builds_an_orb_overlay(monkeypatch) -> None:+ from ui.orb.overlay import OrbOverlay++ monkeypatch.delenv("JARVIS_BAR_HOST_FAKE", raising=False)+ monkeypatch.setattr(host, "_hide_dock_icon", lambda: None)+ surface = host._build_surface(+ {"op": "init", "surface": "mascot", "mascot_path": None}+ )+ assert isinstance(surface, OrbOverlay)+++def test_build_surface_defaults_to_the_jarvis_bar(monkeypatch) -> None:+ """Regression: an init line without "surface" still builds the bar."""+ from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay++ monkeypatch.delenv("JARVIS_BAR_HOST_FAKE", raising=False)+ monkeypatch.setattr(host, "_hide_dock_icon", lambda: None)+ surface = host._build_surface(+ {"op": "init", "persistent": False, "accent": "#123456"}+ )+ assert isinstance(surface, JarvisBarOverlay)+ assert surface._persistent is False+ assert surface._accent == "#123456"++def test_reader_loop_survives_junk_and_stops_bar_on_eof() -> None:bar = _RecordingBar()stream = io.StringIO(@@ -153,13 +211,17 @@ def test_host_process_round_trip_with_echo_bar() -> None:try:assert proc.stdin is not None and proc.stdout is not Noneproc.stdin.write('{"op": "init", "persistent": true}\n')+ proc.stdin.flush()+ # Wait for the ready handshake before sending ops — otherwise the+ # stop below can end the host before the daemon ready-announce+ # thread ever gets to emit its event.+ ready = json.loads(proc.stdout.readline())+ assert ready.get("event") == "ready"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 kindsechoed = [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@@ -168,3 +230,56 @@ def test_host_process_round_trip_with_echo_bar() -> None:finally:if proc.poll() is None:proc.kill()+++def test_host_process_round_trip_with_mascot_surface() -> None:+ """Real subprocess, surface "mascot": forwarded ops reach the surface."""+ 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", "surface": "mascot", "mascot_path": "assets/m.png"}\n'+ )+ proc.stdin.flush()+ # Wait for the ready handshake before sending ops — otherwise the+ # stop below can end the host before the daemon ready-announce+ # thread ever gets to emit its event.+ ready = json.loads(proc.stdout.readline())+ assert ready.get("event") == "ready"+ proc.stdin.write(+ '{"op": "play_animation", "name": "wave", "params": {"x": 1}}\n'+ )+ proc.stdin.write(+ '{"op": "show_listening_transcript", "text": "hi", "duration_ms": 9}\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()]+ echoed = [e for e in events if e.get("event") == "op"]+ assert any(+ e.get("op") == "play_animation"+ and e.get("args") == ["wave"]+ and e.get("kwargs") == {"x": 1}+ for e in echoed+ )+ assert any(+ e.get("op") == "show_listening_transcript"+ and e.get("args") == ["hi", 9]+ for e in echoed+ )+ assert proc.returncode == 0+ finally:+ if proc.poll() is None:+ proc.kill()diff --git a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py b/tests/unit/ui/jarvisbar/test_subprocess_overlay.pyindex fc71a9e63d..8d041bf586 100644--- a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py+++ b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py@@ -12,7 +12,10 @@ import jsonimport threadingfrom jarvis.ui.jarvisbar import subprocess_overlay as mod-from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessBarOverlay+from jarvis.ui.jarvisbar.subprocess_overlay import (+ SubprocessBarOverlay,+ SubprocessMascotOverlay,+)class _FakeStdin:@@ -190,3 +193,88 @@ def test_surface_contract_exposes_every_bridge_method() -> None:assert getattr(SubprocessBarOverlay, name, None) is not None, name# Same reset-path contract as NullOverlay: no _root instance attribute.assert not hasattr(SubprocessBarOverlay(), "_root")+++# --------------------------------------------------------------------- #+# SubprocessMascotOverlay — the mascot flavor of the same host proxy #+# --------------------------------------------------------------------- #+def _started_mascot(+ monkeypatch, **kwargs+) -> tuple[SubprocessMascotOverlay, _FakePopen]:+ monkeypatch.setattr(mod.subprocess, "Popen", _FakePopen)+ surface = SubprocessMascotOverlay(**kwargs)+ surface.start_in_thread(timeout=2.0)+ proc = _FakePopen.last+ assert proc is not None+ return surface, proc+++def test_mascot_init_line_declares_surface_and_mascot_path(monkeypatch) -> None:+ surface, proc = _started_mascot(monkeypatch, mascot_path="assets/m.png")+ init = proc.sent()[0]+ assert init == {"op": "init", "surface": "mascot", "mascot_path": "assets/m.png"}+ assert surface._ready.is_set() # scripted ready event consumed+++def test_bar_init_payload_is_unchanged_by_the_mascot_variant(monkeypatch) -> None:+ """Regression: the bar proxy's init line keeps its exact pre-mascot shape."""+ surface, proc = _started_proxy(+ monkeypatch, persistent=True, accent="#e7c46e", startup_gated=False+ )+ assert proc.sent()[0] == {+ "op": "init",+ "persistent": True,+ "accent": "#e7c46e",+ "startup_gated": False,+ }+ assert not isinstance(surface, SubprocessMascotOverlay)+++def test_mascot_forwards_text_and_mouth_ops_over_the_wire(monkeypatch) -> None:+ surface, proc = _started_mascot(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()+ sent = proc.sent()[1:]+ assert sent == [+ {"op": "play_animation", "name": "wave", "params": {"x": 1}},+ {"op": "stop_animation", "name": "wave"},+ {"op": "show_listening_transcript", "text": "hi", "duration_ms": 5},+ {"op": "hide_comment"},+ {"op": "start_mouth_animation", "duration_ms": 5},+ {"op": "stop_mouth_animation"},+ ]+++def test_mascot_pump_threads_use_orb_host_names(monkeypatch) -> None:+ names: list[str | None] = []+ real_thread = mod.threading.Thread++ class _NamedThread(real_thread): # type: ignore[misc, valid-type]+ def __init__(self, *args, **kwargs) -> None:+ names.append(kwargs.get("name"))+ super().__init__(*args, **kwargs)++ monkeypatch.setattr(mod.threading, "Thread", _NamedThread)+ _started_mascot(monkeypatch)+ assert names == ["orb-host-events", "orb-host-stderr"]+++def test_mascot_dead_host_degrades_to_noop_without_raising(monkeypatch) -> None:+ surface, proc = _started_mascot(monkeypatch)+ proc._returncode = 1 # the host died+ surface.play_animation("wave") # must not raise+ surface.show_listening_transcript("hi", 5)+ assert proc.sent()[1:] == [] # nothing reached the wire+++def test_mascot_surface_contract_matches_the_bar_proxy() -> None:+ from tests.unit.ui.jarvisbar.test_surface_contract import REQUIRED++ for name in REQUIRED:+ assert getattr(SubprocessMascotOverlay, name, None) is not None, name+ # Same reset-path contract as NullOverlay: no _root instance attribute.+ assert not hasattr(SubprocessMascotOverlay(), "_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 fac4c2dab4..5c933f1813 100644--- a/tests/unit/ui/test_macos_ui_main_thread_gates.py+++ b/tests/unit/ui/test_macos_ui_main_thread_gates.py@@ -69,12 +69,15 @@ def test_virtual_cursor_start_returns_false_on_macos(monkeypatch, caplog) -> Nondef 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.+ # Both surfaces get an own-process host (their Tk mainloop runs on the+ # CHILD's main thread — legal on Aqua-Tk): the bar via+ # SubprocessBarOverlay, the mascot via SubprocessMascotOverlay. 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+ from jarvis.ui.jarvisbar.subprocess_overlay import (+ SubprocessBarOverlay,+ SubprocessMascotOverlay,+ )monkeypatch.setattr("sys.platform", "darwin")spawned: list[float] = []@@ -94,9 +97,15 @@ def test_desktop_build_overlay_surface_on_macos(monkeypatch) -> None:)surface = app._build_overlay_surface("jarvis_bar")assert isinstance(surface, SubprocessBarOverlay)+ assert not isinstance(surface, SubprocessMascotOverlay)assert surface._persistent is Trueassert spawned # the companion process spawn was requested- assert isinstance(app._build_overlay_surface("mascot"), NullOverlay)++ spawned.clear()+ mascot = app._build_overlay_surface("mascot")+ assert isinstance(mascot, SubprocessMascotOverlay)+ assert mascot._mascot_path is None # empty config path → host default+ assert spawned # the mascot host spawn was requesteddef test_desktop_build_overlay_surface_macos_bar_falls_back_to_null(@@ -126,6 +135,62 @@ def test_desktop_build_overlay_surface_macos_bar_falls_back_to_null(assert isinstance(app._build_overlay_surface("jarvis_bar"), NullOverlay)+def test_desktop_build_overlay_surface_macos_mascot_falls_back_to_null(+ monkeypatch,+) -> None:+ # Fail-safe: a broken mascot host spawn must never block the boot+ # (BUG-057 class) — the mascot degrades to the no-op surface instead.+ from jarvis.ui.desktop_app import DesktopApp+ from jarvis.ui.jarvisbar.null_overlay import NullOverlay+ from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessMascotOverlay++ monkeypatch.setattr("sys.platform", "darwin")++ def _boom(self, timeout=3.0):+ raise RuntimeError("spawn failed")++ monkeypatch.setattr(SubprocessMascotOverlay, "start_in_thread", _boom)+ app = DesktopApp.__new__(DesktopApp)+ app.cfg = SimpleNamespace(+ ui=SimpleNamespace(+ orb_style="mascot",+ bar_persistent=True,+ bar_accent="#e7c46e",+ orb_mascot_path="",+ )+ )+ assert isinstance(app._build_overlay_surface("mascot"), NullOverlay)+++def test_desktop_build_overlay_surface_windows_mascot_stays_in_process(+ monkeypatch,+) -> None:+ # AD-7 guard: off macOS the mascot keeps its in-process OrbOverlay — the+ # darwin subprocess host must not leak onto other platforms.+ from jarvis.ui.desktop_app import DesktopApp+ from ui.orb.overlay import OrbOverlay++ monkeypatch.setattr("sys.platform", "win32")+ started: list[bool] = []+ monkeypatch.setattr(+ OrbOverlay,+ "start_in_thread",+ lambda self, *args, **kwargs: started.append(True),+ )+ app = DesktopApp.__new__(DesktopApp)+ app.cfg = SimpleNamespace(+ ui=SimpleNamespace(+ orb_style="mascot",+ bar_persistent=True,+ bar_accent="#e7c46e",+ orb_mascot_path="",+ )+ )+ surface = app._build_overlay_surface("mascot")+ assert isinstance(surface, OrbOverlay)+ assert started # the in-process Tk thread spawn was requested (AD-7)++def test_overlay_factory_selects_tray_floor_on_macos() -> None:# make_overlay_surface runs on the desktop backend WORKER thread; a Tk# surface on darwin would abort the process natively. The tray floor isdiff --git a/tests/unit/ui/test_tray.py b/tests/unit/ui/test_tray.pyindex 9dc6c2a459..3656ef9c31 100644--- a/tests/unit/ui/test_tray.py+++ b/tests/unit/ui/test_tray.py@@ -8,6 +8,9 @@ host without a real Linux/headless session.from __future__ import annotationsimport logging+import sys+import threading+import typesfrom pathlib import Pathfrom jarvis.ui import tray as tray_mod@@ -15,6 +18,9 @@ from jarvis.ui.tray import JarvisTraydef test_tray_start_is_noop_without_display(monkeypatch, caplog) -> None:+ # Pinned to linux: the display gate sits after the darwin branch, so on a+ # macOS dev host the test would otherwise assert the wrong path.+ monkeypatch.setattr("sys.platform", "linux")monkeypatch.setattr(tray_mod, "display_present", lambda: False, raising=False)# If the gate works, _run is never reached; the no-op keeps RED from launching# a real pystray icon.@@ -26,25 +32,128 @@ def test_tray_start_is_noop_without_display(monkeypatch, caplog) -> None:assert "tray not started" in caplog.text.lower()-def test_tray_start_is_noop_on_macos(monkeypatch, caplog) -> None:- # AppKit allows UI objects (the NSStatusItem behind pystray's darwin- # backend) on the main thread ONLY; created from the tray worker thread+class _FakeDetachedIcon:+ """Records the ctor kwargs + run_detached()/stop() calls."""++ def __init__(self, name: str, **kwargs) -> None:+ self.name = name+ self.kwargs = kwargs+ self.run_detached_calls = 0+ self.stop_calls = 0++ def run_detached(self) -> None:+ self.run_detached_calls += 1++ def stop(self) -> None:+ self.stop_calls += 1+++class _FakeMenu:+ SEPARATOR = object()++ def __init__(self, *items) -> None:+ self.items = items+++def _install_fake_darwin_modules(monkeypatch, icon_cls) -> object:+ """Injects fake pystray + AppKit modules; returns the fake NSApplication."""+ fake_pystray = types.SimpleNamespace(+ Icon=icon_cls,+ Menu=_FakeMenu,+ MenuItem=lambda *args, **kwargs: (args, kwargs),+ )+ monkeypatch.setitem(sys.modules, "pystray", fake_pystray)+ nsapp = object()+ fake_appkit = types.SimpleNamespace(+ NSApplication=types.SimpleNamespace(sharedApplication=lambda: nsapp),+ )+ monkeypatch.setitem(sys.modules, "AppKit", fake_appkit)+ # Synchronous callAfter: runs the marshaled fn immediately, so the tests+ # observe the mutation without a live AppKit run loop.+ fake_pyobjctools = types.SimpleNamespace(+ AppHelper=types.SimpleNamespace(callAfter=lambda fn, *args: fn(*args)),+ )+ monkeypatch.setitem(sys.modules, "PyObjCTools", fake_pyobjctools)+ return nsapp+++def test_tray_start_is_noop_on_macos_off_main_thread(monkeypatch, caplog) -> None:+ # BUG-056: AppKit allows UI objects (the NSStatusItem behind pystray's+ # darwin backend) on the main thread ONLY; created from a worker thread# the process dies with a native, uncatchable AppKit assertion — the# first real-Mac boot aborted exactly there ("Python quit unexpectedly").- # start() must degrade to a logged no-op instead of spawning the thread.+ # An off-main start() must stay a logged no-op (the tray floor used by+ # TrayOnlySurface, whose start() runs on the backend worker thread).monkeypatch.setattr("sys.platform", "darwin")monkeypatch.setattr(tray_mod, "display_present", lambda: True, raising=False)- monkeypatch.setattr(JarvisTray, "_run", lambda self: None)+ monkeypatch.setattr(+ JarvisTray, "_run", lambda self: (_ for _ in ()).throw(AssertionError)+ )+ # Pretend the caller is NOT the main thread (deterministic, no worker+ # thread needed for the assertion).+ fake_main = threading.Thread(name="fake-main")+ monkeypatch.setattr(threading, "main_thread", lambda: fake_main)t = JarvisTray()with caplog.at_level(logging.INFO):t.start()assert t._thread is None # gated: no tray thread spawned+ assert t._icon is None # no icon built off-main either+ assert "tray not started" in caplog.text.lower()+ assert "main thread" in caplog.text.lower()+++def test_tray_start_on_macos_main_thread_runs_detached(monkeypatch) -> None:+ # BUG-056 follow-up: a MAIN-thread start() on macOS hosts a real menu-bar+ # icon — pystray.Icon built with the shared NSApplication+ # (darwin_nsapplication=...) + run_detached(); no jarvis-tray worker+ # thread is ever spawned.+ monkeypatch.setattr("sys.platform", "darwin")+ monkeypatch.setattr(tray_mod, "display_present", lambda: True, raising=False)+ monkeypatch.setattr(tray_mod, "_make_icon", lambda state, size=64: object())+ nsapp = _install_fake_darwin_modules(monkeypatch, _FakeDetachedIcon)+ t = JarvisTray()+ t.start()+ assert t._thread is None # no jarvis-tray worker thread on darwin+ icon = t._icon+ assert isinstance(icon, _FakeDetachedIcon)+ assert icon.kwargs["darwin_nsapplication"] is nsapp+ assert icon.run_detached_calls == 1+ assert t._darwin_detached is True+ # stop() must reach the detached icon through the main-thread marshal.+ t.stop()+ assert icon.stop_calls == 1+ assert t._icon is None+ assert t._darwin_detached is False+++def test_tray_start_on_macos_main_thread_degrades_when_icon_ctor_raises(+ monkeypatch, caplog+) -> None:+ # AD-6: a broken menu-bar host (Icon ctor raising) must degrade to a+ # logged no-op — never an exception out of start().+ monkeypatch.setattr("sys.platform", "darwin")+ monkeypatch.setattr(tray_mod, "display_present", lambda: True, raising=False)+ monkeypatch.setattr(tray_mod, "_make_icon", lambda state, size=64: object())++ class _BoomIcon:+ def __init__(self, *args, **kwargs) -> None:+ raise RuntimeError("no status bar host")++ _install_fake_darwin_modules(monkeypatch, _BoomIcon)+ t = JarvisTray()+ with caplog.at_level(logging.INFO):+ t.start() # must not raise+ assert t._thread is None+ assert t._icon is None+ assert t._darwin_detached is Falseassert "tray not started" in caplog.text.lower()def test_tray_start_spawns_thread_with_display(monkeypatch) -> None:# AD-7: with a display present (Windows/Linux-X11) the tray still starts.- # (macOS is gated separately — see test_tray_start_is_noop_on_macos.)+ # (macOS is gated separately — see the darwin tests above.) Pinned to+ # win32 so the test asserts the same path on every dev/CI host.+ monkeypatch.setattr("sys.platform", "win32")monkeypatch.setattr(tray_mod, "display_present", lambda: True, raising=False)ran: list[bool] = []monkeypatch.setattr(JarvisTray, "_run", lambda self: ran.append(True))diff --git a/ui/orb/overlay.py b/ui/orb/overlay.pyindex 245b58f0cb..3ad572b4b6 100644--- a/ui/orb/overlay.py+++ b/ui/orb/overlay.py@@ -150,10 +150,26 @@ TRANSCRIPT_MAX_VISIBLE_LINES = 4# Min on-screen time so fast LISTENING→THINKING bounces are still readable.BUBBLE_MIN_SHOW_S = 1.1-# Magenta als Color-Key — Tkinter macht diese Farbe pixel-perfect transparent+# Magenta color key — Tkinter renders this color pixel-perfect transparentCOLOR_KEY_HEX = "#FF00FF"COLOR_KEY_RGB = np.array([255, 0, 255], dtype=np.uint8)++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")++_GWL_EXSTYLE = -20_WS_EX_APPWINDOW = 0x00040000_WS_EX_TOOLWINDOW = 0x00000080@@ -922,12 +938,35 @@ class OrbCommentBubble:top = tk.Toplevel(self._parent)top.overrideredirect(True)top.wm_attributes("-topmost", True)- top.wm_attributes("-transparentcolor", COLOR_KEY_HEX)- top.configure(bg=COLOR_KEY_HEX)+ # Same per-platform transparency split as the main orb root: macOS+ # has no color key, so the bubble Toplevel itself goes transparent;+ # a TclError degrades to an opaque (key-coloured) bubble.+ self._mac_transparent = False+ if sys.platform == "darwin":+ try:+ top.wm_attributes("-transparent", True)+ top.configure(bg="systemTransparent")+ self._mac_transparent = True+ except tk.TclError:+ import logging++ logging.getLogger("jarvis.orb").warning(+ "macOS -transparent unsupported — the comment bubble "+ "renders opaque"+ )+ top.configure(bg=COLOR_KEY_HEX)+ else:+ top.wm_attributes("-transparentcolor", COLOR_KEY_HEX)+ top.configure(bg=COLOR_KEY_HEX)_hide_tk_window_from_task_switcher(top)top.withdraw()- canvas = tk.Canvas(top, bg=COLOR_KEY_HEX, highlightthickness=0, borderwidth=0)+ canvas = tk.Canvas(+ top,+ bg="systemTransparent" if self._mac_transparent else COLOR_KEY_HEX,+ highlightthickness=0,+ borderwidth=0,+ )canvas.pack(fill="both", expand=True)self._top = top@@ -1303,8 +1342,28 @@ class OrbOverlay:self._root.title("JarvisOrb")self._root.overrideredirect(True) # Frameless, no drop shadowself._root.wm_attributes("-topmost", True)- self._root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)- self._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 (key_to_alpha in the frame loop).+ self._mac_transparent = False+ if sys.platform == "darwin":+ try:+ self._root.wm_attributes("-transparent", True)+ self._root.configure(bg="systemTransparent")+ self._mac_transparent = True+ except tk.TclError:+ import logging++ logging.getLogger("jarvis.orb").warning(+ "macOS -transparent unsupported — the mascot will show "+ "its key colour"+ )+ self._root.configure(bg=COLOR_KEY_HEX)+ else:+ self._root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)+ self._root.configure(bg=COLOR_KEY_HEX)# Apply the Jarvis icon BEFORE hiding from the task switcher: Windows# caches the taskbar entry on first show, so even a brief flash with# the default pythonw icon sticks. Belt-and-suspenders: stable AppID@@ -1398,7 +1457,7 @@ class OrbOverlay:self._root,width=WIN_W,height=WIN_H,- bg=COLOR_KEY_HEX,+ bg="systemTransparent" if self._mac_transparent else COLOR_KEY_HEX,highlightthickness=0,borderwidth=0,)@@ -2225,6 +2284,10 @@ class OrbOverlay:returnt = time.perf_counter() - self._t0img = self._renderer.render(t, self._mode, self._ext_level)+ if self._mac_transparent:+ # macOS has no color key — the frame carries a real alpha+ # channel instead (magenta → fully transparent).+ img = key_to_alpha(img)# The PhotoImage must be kept as self._photo — otherwise Tkinter# garbage-collects the image before it gets rendered.