Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(macos): repair companion overlay rendering and input

Ruben Lütke4c9c7d11641a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5014985e79..ef9b9b8896 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,16 @@ versioning per [SemVer](https://semver.org/lang/de/).
### Fixed
+- **macOS: the Jarvis Bar is transparent and animation frames no longer pile
+ up.** Aqua-Tk 9 kept an opaque black Canvas backing and composited every new
+ RGBA frame over the old one, producing a rectangle at rest and concentric
+ red/green/gold outlines while speaking. The macOS companion now uses Qt's
+ translucent surface with full-frame alpha replacement; Windows and Linux
+ keep the established Tk color-key path unchanged. Bar clicks are also
+ executed in the parent process again, transparent window padding passes
+ clicks through to the app underneath, the companion no longer steals macOS
+ foreground focus every 500 ms, and parent TTS loudness now reaches the
+ companion equalizer (BUG-093).
- **macOS: the repeated Keychain password-dialog storm is stopped.** A Control
key created by an older direct Python launch could make macOS ask for the
login-keychain password again on every protected request — often dozens of
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 2d8c70d3c6..9d3701692d 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -6402,3 +6402,90 @@ model Keychain as one global permission: ownership is per item and anchored to
the caller's designated requirement. Repair legacy ownership only after one
user-approved read and only from the verified canonical app; never solve a
prompt by broadening an ACL to unsigned tools or all applications.
+
+---
+
+## BUG-093: macOS Jarvis Bar has a black rectangle and retains every speaking frame (HIGH, FIXED 2026-07-19)
+
+**Symptom (physical-Mac field report).** Once the missing-image error was fixed,
+the idle pill appeared inside a black rectangular window. Entering an active
+voice state made every eased pill size remain on screen: old outlines formed
+larger concentric red/green/gold capsules around the current frame. The
+rectangle was the fixed `83x37` bar surface; the nested sizes exactly matched
+the renderer's `36x6 -> 53.5x15.5 -> 62.25x20.25 -> ... -> 71x25` transition.
+After the Qt surface removed those visual artifacts, clicks over transparent
+padding around the pill were still swallowed instead of reaching the browser
+or other window underneath. Worse, the companion became macOS' frontmost
+application. Its 500 ms Z-order guard repeatedly reclaimed foreground status,
+so ordinary browser/editor clicks were consumed merely to reactivate that app
+and appeared globally unreliable even when the pointer was nowhere near the
+bar.
+
+**Root cause.** The PIL renderer was correct and returned a complete fresh
+frame each tick. The failure was Aqua-Tk 9's layer-backed Canvas composition:
+an RGBA `PhotoImage` update used source-over behavior, so source pixels with
+alpha zero were no-ops rather than replacements. They could neither erase the
+initial opaque Canvas backing nor clear pixels occupied only by the preceding
+larger frame. Reusing a PhotoImage, deleting/recreating the Canvas item, and
+clearing the `NSWindow` all left the same retained pixels.
+
+BUG-075's AppKit pass was therefore insufficient. The target `NSWindow`, its
+`TKContentView`, and its backing layer were already non-opaque with a clear
+background; the unwanted pixels lived in the Canvas backing store above that
+window background. The separate `master=self._root` fix remains necessary for
+BUG-074's two Tcl interpreters, but it only makes the frames visible and cannot
+change their composition semantics.
+
+**Fix (platform split).** The companion host now selects
+`QtJarvisBarOverlay` on Darwin. It keeps the existing deterministic PIL
+renderer, geometry, modes, startup gate, drag/persistence, opacity, and JSON
+host protocol, but presents each RGBA image on a `WA_TranslucentBackground`
+Qt tool window. Every paint first clears the complete destination under
+`QPainter.CompositionMode_Source`, then draws the new frame. Transparent pixels
+therefore replace old alpha instead of blending over it. Windows and Linux
+still instantiate `JarvisBarOverlay`; their proven Tk color-key/DWM path is not
+changed. The Qt application is created before the host enters macOS accessory
+mode, so no Tk bootstrap is mixed into its Cocoa lifecycle and no extra Dock
+icon is required. Each complete RGBA frame also supplies the top-level Qt
+window's native input mask. Only non-transparent pixels participate in hit
+testing, so the visible pill remains interactive while its rectangular clear
+padding passes mouse events through to the app below. Before `QApplication`
+starts, the companion disables Qt's foreground-application transform. The
+native window is marked as a non-activating `NSPanel`, and the Z-order guard
+uses AppKit's `orderFrontRegardless` instead of `QWidget.raise_()`. This keeps
+the bar above normal windows without making the helper process active; if the
+native bridge is unavailable, the guard skips its cosmetic raise rather than
+stealing focus through the Qt fallback.
+
+**Adjacent subprocess fixes.** The audit found two bugs hidden by the missing
+image. Talk/hang-up/mute clicks were resolved in the child, whose
+`runtime_refs` can never contain the parent SpeechPipeline; they now cross the
+host protocol and execute against the authoritative parent pipeline, including
+the stuck-active recovery guard. `level_tap` is process-local too, so the bus
+bridge now forwards live parent TTS levels through `set_level`; Jarvis' speaking
+bars react to actual output instead of remaining flat.
+
+**Guards.** A headless `QImage` regression starts with an opaque black backing,
+paints a larger shape, then a fully transparent frame, asserting both the black
+corner and old-only shape pixels return to alpha zero. Input-mask regressions
+assert opaque bar pixels remain clickable, clear corners are excluded, and
+every newly rendered eased frame updates the window mask. Z-order regressions
+prove Darwin uses native non-activating ordering and never falls back to Qt's
+focus-stealing raise. A physical-Mac trace activates Finder, waits across
+multiple guard intervals, and confirms Finder remains frontmost while the bar
+stays onscreen. Host-selection tests prove Darwin uses Qt without calling the
+Tk bootstrap and non-Darwin keeps Tk. Interaction tests cover child events
+through parent pipeline actions, and a real `QT_QPA_PLATFORM=offscreen`
+subprocess smoke covers init, ready, state, level, hide, stop, and clean exit.
+The full Jarvis Bar unit suite passes on the physical Mac.
+
+**Class rule.** Window transparency and animated-frame replacement are separate
+contracts, and visual transparency is separate again from input transparency.
+A clear/non-opaque native window does not prove that a child Canvas will erase
+its own backing store or that alpha-zero pixels pass clicks through. For dynamic
+RGBA overlays, test a large frame followed by a smaller or transparent one,
+assert old-only pixels return to alpha zero, and constrain the native hit-test
+region to the visible content. An always-on-top helper must also prove that its
+periodic ordering operation does not activate the helper application. Keep
+compositor workarounds behind a platform backend instead of changing a
+rendering path already proven on another OS.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 78e19a9531..5e57af20fa 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -15,6 +15,11 @@ P-02/P-03 implemented for macOS + X11 Linux (rows narrowed to the Wayland
residual); P-10 fixed on Linux via `PR_SET_PDEATHSIG` (row narrowed to
macOS). Git history of this file keeps the original entries.
+**Fix pass 2026-07-19:** P-01 fixed and removed. Both the Jarvis Bar and the
+mascot now use a main-thread companion-process host on macOS; rendered images
+and bubble fonts are explicitly bound to the overlay's Tcl interpreter so the
+host's Tk bootstrap root cannot steal them.
+
## Audit verdict summary
**No hard breakers found.** No feature crashes on macOS or headless Linux;
@@ -39,7 +44,6 @@ experiences today.
| # | Impact | Area | Gap | Evidence | Behavior off-Windows |
|---|---|---|---|---|---|
-| P-01 | Medium | Orb/UI | macOS has no floating mascot orb — Aqua-Tk is main-thread-only (BUG-057). The Jarvis BAR works on macOS since v1.0.8 via an own-process Tk host (`jarvis/ui/jarvisbar/host.py`, 2026-07-14); the mascot orb has no such host yet | `jarvis/overlay/surface.py:177-229`, `jarvis/ui/desktop_app.py:2032-2073` | `overlay_style=jarvis_bar`: bar shows (after voice-usable releases the startup gate; needs tkinter in the running Python). Mascot styles: no-op surface |
| P-02 | Low | Awareness | Idle detection has no Wayland backend (Windows GetLastInputInfo, macOS Quartz, Linux X11 `xprintidle` all exist since 2026-07-16); Wayland exposes no global idle time without portal support | `jarvis/awareness/watchers/idle.py` | Wayland: one honest log line, watcher does not start |
| P-03 | Low | Awareness | Window-focus watcher has no Wayland backend (Windows event hook, macOS NSWorkspace, Linux X11 polling all exist since 2026-07-16); Wayland hides the foreground window by design | `jarvis/awareness/watchers/window.py` | Wayland: one honest log line, watcher does not start |
| P-04 | Medium | CU typing | Linux non-ASCII typing (umlauts, CJK, emoji) requires `xdotool`; pyautogui silently drops those chars without it | `jarvis/cu/actuate/posix.py:387-438` | With `xdotool` (installer provisions it since 2026-07-15): fine. Without: warning + silent char loss |
diff --git a/docs/product/personalize-and-connect/settings-and-appearance.md b/docs/product/personalize-and-connect/settings-and-appearance.md
index 18fc62c71f..20d0d872d6 100644
--- a/docs/product/personalize-and-connect/settings-and-appearance.md
+++ b/docs/product/personalize-and-connect/settings-and-appearance.md
@@ -77,7 +77,7 @@ Under **Bar & Overlay > Appearance**, choose one of these display styles:
| Style | What you see | Important limit |
|---|---|---|
| **Bar (default)** | A slim status bar for idle, listening, thinking, and speaking states | Available on a supported graphical desktop |
-| **Mascot orb** | The classic on-screen mascot during voice activity | Not available on macOS; a change from another real style normally needs a restart |
+| **Mascot orb** | The classic on-screen mascot during voice activity | Available on a supported graphical desktop; a change from another real style normally needs a restart |
| **None (hidden)** | No on-screen voice surface | Hiding the current surface can usually apply live |
1. Select the preview card for the style you want.
@@ -87,9 +87,9 @@ Under **Bar & Overlay > Appearance**, choose one of these display styles:
4. If the restart is refused because missions are running, wait for them to
finish. Use a forced restart only when you accept that those runs will stop.
-On macOS, the Jarvis Bar runs in a separate desktop companion process, while
-the Mascot option falls back to no visible surface. On a machine without a
-display, all styles are saved for a later graphical start but cannot appear
+On macOS, both the Jarvis Bar and the Mascot run in a separate desktop
+companion process so Aqua-Tk owns the process main thread. On a machine without
+a display, all styles are saved for a later graphical start but cannot appear
immediately.
### Adjust Bar and Sound Behavior
diff --git a/jarvis/ui/jarvisbar/host.py b/jarvis/ui/jarvisbar/host.py
index 6f1999b8af..d25cc9c686 100644
--- a/jarvis/ui/jarvisbar/host.py
+++ b/jarvis/ui/jarvisbar/host.py
@@ -19,14 +19,16 @@ Protocol (UTF-8, one JSON object per line):
optional ``"mascot_path"`` passthrough).
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.
+- child → parent (stdout): events — ``{"event": "ready"}`` once the surface
+ is initialized, plus user interactions (``talk``, ``hangup``,
+ ``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
@@ -194,6 +196,9 @@ class _EchoBar:
self._stop_evt.set()
def set_on_mute_toggle(self, cb: Any) -> None: ...
+ def set_on_voice_action(self, cb: Any) -> None: ...
+ def set_on_talk(self, cb: Any) -> None: ...
+ def set_on_hangup(self, cb: Any) -> None: ...
def set_feedback_publisher(self, cb: Any) -> None: ...
def set_on_show_window(self, cb: Any) -> None: ...
@@ -274,8 +279,7 @@ def _import_orb_overlay() -> Any:
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",
+ "mascot-host: cannot import OrbOverlay (%s) — exiting so the parent can degrade",
exc,
)
raise SystemExit(3) from exc
@@ -285,9 +289,13 @@ def _import_orb_overlay() -> Any:
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":
+ surface_name = str(cfg.get("surface", "jarvis_bar"))
+ if surface_name == "mascot":
+ if sys.platform == "darwin":
+ # The mascot still uses Aqua-Tk, whose TKApplication bootstrap
+ # must precede AppKit (BUG-074). The Qt bar below deliberately
+ # skips this: QApplication must own its own Cocoa lifecycle.
+ _hide_dock_icon()
orb_overlay_cls = _import_orb_overlay()
return orb_overlay_cls(
sticky=False,
@@ -295,16 +303,55 @@ def _build_surface(cfg: dict[str, Any]) -> Any:
style="mascot",
mascot_path=cfg.get("mascot_path") or None,
)
- from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
-
kwargs = {
- key: cfg[key]
- for key in ("persistent", "accent", "opacity", "startup_gated")
- if key in cfg
+ key: cfg[key] for key in ("persistent", "accent", "opacity", "startup_gated") if key in cfg
}
+ if sys.platform == "darwin":
+ # Aqua-Tk 9 composites RGBA Canvas images with SourceOver semantics:
+ # transparent pixels neither clear its black backing nor erase the
+ # previous animation frame. Use Qt's real translucent backing and
+ # full-frame CompositionMode_Source replacement on macOS only.
+ # Windows/Linux retain their proven Tk color-key implementation.
+ from jarvis.ui.jarvisbar.qt_overlay import QtJarvisBarOverlay
+
+ return QtJarvisBarOverlay(**kwargs)
+
+ from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
return JarvisBarOverlay(**kwargs)
+def _wire_surface_events(surface: Any) -> None:
+ """Forward child-owned UI actions to the parent over stdout.
+
+ Talk and hang-up cannot use ``runtime_refs`` in this process: the live
+ SpeechPipeline is registered in the parent desktop process. ``_call``
+ keeps mascot and protocol-double surfaces that lack a bar-only setter
+ compatible with the shared host.
+ """
+
+ def _emit_voice_action(action: str) -> None:
+ normalized = str(action).strip().lower()
+ if normalized in {"talk", "hangup"}:
+ emit(normalized)
+ else:
+ log.warning("bar-host: dropping unknown voice action %r", action)
+
+ # Qt exposes the compact action callback; Tk keeps the two explicit
+ # setters. Wiring both is safe because each surface invokes only the
+ # callback contract it implements.
+ _call(surface, "set_on_voice_action", _emit_voice_action)
+ _call(surface, "set_on_talk", lambda: emit("talk"))
+ _call(surface, "set_on_hangup", lambda: emit("hangup"))
+ _call(surface, "set_on_mute_toggle", lambda: emit("mute_toggle"))
+ _call(
+ surface,
+ "set_feedback_publisher",
+ lambda kind, payload: emit("feedback", kind=kind, payload=payload),
+ )
+ _call(surface, "set_on_show_window", lambda: emit("show_window"))
+
+
def main() -> int:
logging.basicConfig(
stream=sys.stderr,
@@ -326,23 +373,15 @@ def main() -> int:
return 2
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)
- )
- surface.set_on_show_window(lambda: emit("show_window"))
+ _wire_surface_events(surface)
def _announce_ready() -> None:
if surface._started.wait(timeout=READY_TIMEOUT_S): # noqa: SLF001
emit("ready")
else:
- log.error(
- "bar-host: surface 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=_announce_ready, name="barhost-ready", daemon=True).start()
threading.Thread(
target=reader_loop,
args=(surface, sys.stdin),
@@ -351,8 +390,8 @@ def main() -> int:
daemon=True,
).start()
- # THE point of this process: the Tk mainloop runs on the MAIN thread, the
- # only thread Aqua-Tk accepts on macOS.
+ # THE point of this process: the platform GUI loop runs on the MAIN thread
+ # (Qt for the macOS bar, Aqua-Tk for the macOS mascot).
surface.start()
return 0
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index 384ef1e019..0bb57e1f1e 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -24,6 +24,7 @@ configured opacity. This keeps Tk's opaque backing surface off-screen even
when the bar spent long enough withdrawn for the idle renderer to stop
repainting.
"""
+
from __future__ import annotations
import logging
@@ -71,9 +72,7 @@ _SWP_NOOWNERZORDER = 0x0200
_GW_HWNDPREV = 3
_GWL_EXSTYLE = -20
_WS_EX_TOPMOST = 0x00000008
-_WIN32_TOPMOST_FLAGS = (
- _SWP_NOSIZE | _SWP_NOMOVE | _SWP_NOACTIVATE | _SWP_NOOWNERZORDER
-)
+_WIN32_TOPMOST_FLAGS = _SWP_NOSIZE | _SWP_NOMOVE | _SWP_NOACTIVATE | _SWP_NOOWNERZORDER
# Sound-driven look. The bar shows the speaking equalizer (bars) ONLY while real
# audio is present — mic input while you speak, or TTS output while Jarvis speaks
@@ -171,9 +170,7 @@ def _primary_work_area() -> tuple[int, int, int, int] | None:
SPI_GETWORKAREA = 0x0030
rect = wintypes.RECT()
- ok = ctypes.windll.user32.SystemParametersInfoW(
- SPI_GETWORKAREA, 0, ctypes.byref(rect), 0
- )
+ ok = ctypes.windll.user32.SystemParametersInfoW(SPI_GETWORKAREA, 0, ctypes.byref(rect), 0)
if not ok:
return None
return (int(rect.left), int(rect.top), int(rect.right), int(rect.bottom))
@@ -289,9 +286,7 @@ def _win32_force_topmost(root: Any, *, user32: Any | None = None) -> bool:
return False
-def _win32_topmost_band_is_healthy(
- root: Any, *, user32: Any | None = None
-) -> bool | None:
+def _win32_topmost_band_is_healthy(root: Any, *, user32: Any | None = None) -> bool | None:
"""Check whether any ordinary visible HWND sits above the Jarvis Bar.
``WS_EX_TOPMOST`` on the bar itself cannot answer this: the reported bug
@@ -393,6 +388,12 @@ class JarvisBarOverlay:
self._drag: dict | None = None
self._level_unsub: Callable[[], None] | None = None
self._on_mute_toggle: Callable[[], None] | None = None
+ # Interaction callbacks let the macOS companion host forward actions
+ # to the parent process, where the live SpeechPipeline is registered.
+ # They stay optional so Windows/Linux keep their existing in-process
+ # runtime_refs fallback when no callback is installed.
+ self._on_talk: Callable[[], None] | None = None
+ self._on_hangup: Callable[[], None] | None = None
self._feedback_publisher: Callable[[str, dict], None] | None = None
self._on_show_window: Callable[[], None] | None = None
self._hovered = False # mouse over the bar → reveal the close cross
@@ -500,6 +501,14 @@ class JarvisBarOverlay:
def set_on_mute_toggle(self, callback: Callable[[], None] | None) -> None:
self._on_mute_toggle = callback
+ def set_on_talk(self, callback: Callable[[], None] | None) -> None:
+ """Register the idle-body click action for an external host."""
+ self._on_talk = callback
+
+ def set_on_hangup(self, callback: Callable[[], None] | None) -> None:
+ """Register the active close-X action for an external host."""
+ self._on_hangup = callback
+
def set_feedback_publisher(self, callback: Callable[[str, dict], None] | None) -> None:
self._feedback_publisher = callback
@@ -639,17 +648,13 @@ class JarvisBarOverlay:
root.configure(bg="systemTransparent")
self._mac_transparent = True
except tk.TclError:
- log.warning(
- "macOS -transparent unsupported — bar will show its key colour"
- )
+ 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"
- )
+ 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
@@ -754,8 +759,13 @@ class JarvisBarOverlay:
pos = None
if pos is not None:
self._x, self._y = interaction.clamp_to_screen(
- pos[0], pos[1], screen_w=sw, screen_h=sh,
- bar_w=renderer.WIN_W, bar_h=renderer.WIN_H, margin=MARGIN_PX,
+ pos[0],
+ pos[1],
+ screen_w=sw,
+ screen_h=sh,
+ bar_w=renderer.WIN_W,
+ bar_h=renderer.WIN_H,
+ margin=MARGIN_PX,
)
else:
# Anchor just ABOVE the taskbar (work area), exactly centered —
@@ -768,8 +778,11 @@ class JarvisBarOverlay:
self._y = wb - renderer.WIN_H - TASKBAR_GAP_PX
else:
self._x, self._y = interaction.default_bottom_center(
- screen_w=sw, screen_h=sh,
- bar_w=renderer.WIN_W, bar_h=renderer.WIN_H, margin=MARGIN_PX,
+ screen_w=sw,
+ screen_h=sh,
+ bar_w=renderer.WIN_W,
+ bar_h=renderer.WIN_H,
+ margin=MARGIN_PX,
)
def _do_show(self) -> None:
@@ -838,9 +851,7 @@ class JarvisBarOverlay:
try:
self._root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)
except Exception: # noqa: BLE001
- log.debug(
- "jarvisbar transparentcolor re-assert failed", exc_info=True
- )
+ log.debug("jarvisbar transparentcolor re-assert failed", exc_info=True)
try:
self._root.wm_attributes("-alpha", opacity)
except Exception: # noqa: BLE001
@@ -879,9 +890,7 @@ class JarvisBarOverlay:
# exactly as set at creation so a dropped attribute self-heals on the
# very next reveal instead of needing an app restart. Guarded
# separately so a failure here can never undo the topmost re-assert.
- self._apply_layered_attributes(
- opacity=self._opacity if opacity is None else opacity
- )
+ self._apply_layered_attributes(opacity=self._opacity if opacity is None else opacity)
# A long-withdrawn idle bar may already be in the static-frame fast
# path. Native style/map changes require one fresh canvas submission so
# DWM cannot keep a stale backing surface indefinitely.
@@ -991,8 +1000,7 @@ class JarvisBarOverlay:
else:
self._static_tick_count += 1
is_settled_idle = (
- effective_mode == "idle"
- and self._static_tick_count >= _IDLE_SETTLE_TICKS
+ effective_mode == "idle" and self._static_tick_count >= _IDLE_SETTLE_TICKS
)
if not is_settled_idle:
@@ -1002,19 +1010,28 @@ class JarvisBarOverlay:
# your mic. No synthetic floor (that made the bars look
# uniformly blocky).
img = self._renderer.render(
- t, effective_mode, self._ext_level,
- hovered=self._hovered, muted=self._muted,
+ 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)
+ # drawing. The explicit master is equally load-bearing on
+ # macOS: the companion host owns a withdrawn bootstrap Tk root
+ # (so Tk, not pyobjc, creates NSApp) and this overlay owns a
+ # second Tcl interpreter. Pillow otherwise binds the image to
+ # the bootstrap interpreter, and this canvas rejects it with
+ # ``TclError: image \"pyimageN\" does not exist`` — leaving only
+ # the empty backing rectangle on screen. Supplying the actual
+ # consumer also stays correct for the single-root Windows/Linux
+ # paths.
+ self._photo = ImageTk.PhotoImage(img, master=self._root)
if self._image_id is None:
- self._image_id = self._canvas.create_image(
- 0, 0, anchor="nw", image=self._photo
- )
+ self._image_id = self._canvas.create_image(0, 0, anchor="nw", image=self._photo)
else:
self._canvas.itemconfig(self._image_id, image=self._photo)
except Exception: # noqa: BLE001 — one bad frame must never freeze the bar
@@ -1057,9 +1074,7 @@ class JarvisBarOverlay:
last = self._last_frame_ns
if last and (time.monotonic_ns() - last) > FRAME_STALL_THRESHOLD_NS:
stalled_s = (time.monotonic_ns() - last) / 1e9
- log.warning(
- "JarvisBar frame loop stalled %.1fs — reviving it", stalled_s
- )
+ log.warning("JarvisBar frame loop stalled %.1fs — reviving it", stalled_s)
# Pre-stamp so a false alarm (a still-live loop) doesn't make us
# re-kick every tick; the revived loop immediately re-stamps.
self._last_frame_ns = time.monotonic_ns()
@@ -1069,13 +1084,9 @@ class JarvisBarOverlay:
finally:
if self._running and self._root is not None:
try:
- self._root.after(
- WATCHDOG_INTERVAL_MS, self._schedule_frame_watchdog
- )
+ self._root.after(WATCHDOG_INTERVAL_MS, self._schedule_frame_watchdog)
except Exception: # noqa: BLE001
- log.warning(
- "JarvisBar frame watchdog re-arm skipped", exc_info=True
- )
+ log.warning("JarvisBar frame watchdog re-arm skipped", exc_info=True)
def _schedule_z_order_guard(self) -> None:
"""Keep a mapped bar above apps that are opened after it.
@@ -1107,13 +1118,9 @@ class JarvisBarOverlay:
finally:
if self._running and self._root is not None:
try:
- self._root.after(
- Z_ORDER_GUARD_INTERVAL_MS, self._schedule_z_order_guard
- )
+ self._root.after(Z_ORDER_GUARD_INTERVAL_MS, self._schedule_z_order_guard)
except Exception: # noqa: BLE001
- log.warning(
- "JarvisBar Z-order guard re-arm skipped", exc_info=True
- )
+ log.warning("JarvisBar Z-order guard re-arm skipped", exc_info=True)
# ------------------------------------------------------------------ #
# Drag (reposition) + click (start a voice session) #
@@ -1177,8 +1184,13 @@ class JarvisBarOverlay:
sw = int(self._root.winfo_screenwidth())
sh = int(self._root.winfo_screenheight())
self._x, self._y = interaction.clamp_to_screen(
- self._x, self._y, screen_w=sw, screen_h=sh,
- bar_w=renderer.WIN_W, bar_h=renderer.WIN_H, margin=MARGIN_PX,
+ self._x,
+ self._y,
+ screen_w=sw,
+ screen_h=sh,
+ bar_w=renderer.WIN_W,
+ bar_h=renderer.WIN_H,
+ margin=MARGIN_PX,
)
self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")
from jarvis.core.config_writer import DEFAULT_CONFIG_FILE
@@ -1246,20 +1258,14 @@ class JarvisBarOverlay:
if time.monotonic() < self._hangup_click_block_until:
return
try:
- from jarvis.core.runtime_refs import get_speech_pipeline
-
- pipeline = get_speech_pipeline()
- if pipeline is None:
- return
- # Hang-up must be a deliberate click on the VISIBLE close-X glyph
- # (the X is only drawn while hovered), never the wide left dead-zone
- # — see interaction.resolve_click + the silent-hangup forensic. The
- # active pill is ACTIVE_W, so the X glyph sits at WIN_W/2-0.42*pw.
active = self._mode in ("listen", "think", "speak")
pill_w = renderer.ACTIVE_W if active else None
action = interaction.resolve_click(
- click_x, renderer.WIN_W, self._mode,
- hovered=hovered, pill_w=pill_w,
+ click_x,
+ renderer.WIN_W,
+ self._mode,
+ hovered=hovered,
+ pill_w=pill_w,
)
if action == "mute":
# The mic button toggles voice mute via the bridge-wired
@@ -1274,6 +1280,21 @@ class JarvisBarOverlay:
cb()
self._muted = not self._muted
elif action == "hangup":
+ callback = self._on_hangup
+ if callback is not None:
+ # The macOS child cannot inspect the parent's live session.
+ # It emits the resolved action; SubprocessBarOverlay applies
+ # the same active/stuck-active guard in the parent process.
+ callback()
+ self._mode = "idle"
+ self._hangup_click_block_until = time.monotonic() + HANGUP_CLICK_GUARD_S
+ return
+
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ if pipeline is None:
+ return
# Only a LIVE session is hung up. If the bar is stuck in an
# active "listen/think/speak" look with NO session behind it
# (a wake confirmed then swallowed by the post-hangup wake-lock,
@@ -1295,11 +1316,18 @@ class JarvisBarOverlay:
# round-trip. The authoritative bridge state will
# reconcile the same value when teardown completes.
self._mode = "idle"
- self._hangup_click_block_until = (
- time.monotonic() + HANGUP_CLICK_GUARD_S
- )
+ self._hangup_click_block_until = time.monotonic() + HANGUP_CLICK_GUARD_S
elif action == "talk":
- pipeline.request_voice_session()
+ callback = self._on_talk
+ if callback is not None:
+ callback()
+ return
+
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ if pipeline is not None:
+ pipeline.request_voice_session()
# "none" → nothing
except Exception: # noqa: BLE001
log.debug("jarvisbar click action failed", exc_info=True)
@@ -1317,8 +1345,11 @@ class JarvisBarOverlay:
sw = int(self._root.winfo_screenwidth())
sh = int(self._root.winfo_screenheight())
self._x, self._y = interaction.default_bottom_center(
- screen_w=sw, screen_h=sh,
- bar_w=renderer.WIN_W, bar_h=renderer.WIN_H, margin=MARGIN_PX,
+ screen_w=sw,
+ screen_h=sh,
+ bar_w=renderer.WIN_W,
+ bar_h=renderer.WIN_H,
+ margin=MARGIN_PX,
)
self._root.geometry(f"{renderer.WIN_W}x{renderer.WIN_H}+{self._x}+{self._y}")
from jarvis.core.config_writer import DEFAULT_CONFIG_FILE
diff --git a/jarvis/ui/jarvisbar/qt_overlay.py b/jarvis/ui/jarvisbar/qt_overlay.py
new file mode 100644
index 0000000000..60acbff357
--- /dev/null
+++ b/jarvis/ui/jarvisbar/qt_overlay.py
@@ -0,0 +1,829 @@
+"""Darwin Qt surface for the Jarvis Bar.
+
+This module is intentionally separate from :mod:`jarvis.ui.jarvisbar.overlay`.
+The Windows/Linux Tk surface has platform-specific behavior which must not be
+disturbed, while Aqua-Tk 9 currently cannot clear a ``systemTransparent``
+canvas reliably: its native ``NSWindow`` is non-opaque, but the Tk content
+view still leaves an opaque black backing store and retains pixels from older
+animation frames.
+
+The companion process may select :class:`QtJarvisBarOverlay` on macOS. It
+reuses the deterministic Pillow renderer and the existing surface API, but
+uses a Qt top-level window with a real alpha channel. Every paint replaces
+the complete backing image with ``CompositionMode_Source`` before drawing the
+new RGBA frame. Transparent pixels therefore clear both the initial backing
+and the previous animation frame instead of blending over them.
+
+PySide6 is imported lazily. Importing this module remains safe in the base or
+headless installation; only ``start()`` requires the desktop extra and a
+usable display. ``start()`` must run on the companion process's main thread.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import queue
+import sys
+import threading
+import time
+from collections.abc import Callable
+from types import SimpleNamespace
+from typing import Any
+
+from PIL import Image
+
+from jarvis.ui.jarvisbar import interaction, renderer
+
+log = logging.getLogger("jarvis.ui.jarvisbar.qt")
+
+# Keep the visual contract identical to the established Tk bar. These values
+# are local so importing the macOS surface never imports tkinter.
+BAR_ALPHA = 0.6
+AUDIBLE_LEVEL = 0.06
+AUDIBLE_HOLD_S = 0.5
+TARGET_FRAME_MS = 16
+UI_QUEUE_INTERVAL_MS = 20
+Z_ORDER_GUARD_INTERVAL_MS = 500
+DRAG_THRESHOLD_PX = 16
+MARGIN_PX = 12
+TASKBAR_GAP_PX = 8
+HANGUP_CLICK_GUARD_S = 1.0
+_IDLE_SETTLE_TICKS = 30
+
+_QT: SimpleNamespace | None = None
+
+
+def _prepare_macos_qt_process() -> None:
+ """Keep the companion from becoming macOS' foreground application.
+
+ Qt's Cocoa plugin normally activates a command-line ``QApplication`` when
+ launch finishes. That is correct for a regular app, but an overlay helper
+ becoming active makes macOS consume the user's next browser/editor click
+ merely to reactivate that app. This process owns no normal application
+ window, so disable the transform before constructing ``QApplication``.
+ """
+ if sys.platform == "darwin":
+ os.environ["QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM"] = "1"
+
+
+def _qt() -> SimpleNamespace:
+ """Return the lazily imported Qt modules.
+
+ Keeping this behind a function preserves the torch-/GUI-free base import
+ floor. The caller owns the honest missing-desktop-extra diagnostic.
+ """
+ global _QT
+ if _QT is None:
+ from PySide6 import QtCore, QtGui, QtWidgets # noqa: PLC0415
+
+ _QT = SimpleNamespace(
+ QtCore=QtCore,
+ QtGui=QtGui,
+ QtWidgets=QtWidgets,
+ Qt=QtCore.Qt,
+ )
+ return _QT
+
+
+def _qimage_from_pil(image: Image.Image) -> Any:
+ """Copy a Pillow RGBA image into an owning ``QImage``."""
+ q = _qt()
+ rgba = image.convert("RGBA")
+ width, height = rgba.size
+ raw = rgba.tobytes("raw", "RGBA")
+ wrapped = q.QtGui.QImage(
+ raw,
+ width,
+ height,
+ width * 4,
+ q.QtGui.QImage.Format.Format_RGBA8888,
+ )
+ # The wrapper above borrows ``raw``. A detached copy is load-bearing:
+ # Pillow/bytes may be released before Qt services the asynchronous paint.
+ return wrapped.copy()
+
+
+def _paint_transparent_frame(
+ painter: Any,
+ rect: Any,
+ image: Any | None,
+) -> None:
+ """Replace a complete paint device with one transparent RGBA frame.
+
+ ``SourceOver`` cannot clear pixels left by a prior frame: an alpha-zero
+ source is a no-op. First filling with transparent black under ``Source``
+ replaces every destination pixel, including its alpha. Drawing the new
+ image afterwards gives the compositor a fresh frame with no black backing
+ and no animation trails.
+ """
+ q = _qt()
+ painter.setCompositionMode(q.QtGui.QPainter.CompositionMode.CompositionMode_Source)
+ painter.fillRect(rect, q.QtGui.QColor(0, 0, 0, 0))
+ if image is None:
+ return
+ painter.setCompositionMode(q.QtGui.QPainter.CompositionMode.CompositionMode_SourceOver)
+ painter.drawImage(rect, image)
+
+
+def _input_mask_from_frame(image: Any) -> Any:
+ """Return a native input mask containing only non-transparent pixels.
+
+ A translucent top-level window still owns its complete rectangular mouse
+ region on macOS. Without an explicit mask, the invisible padding around
+ the pill consumes clicks intended for the app underneath it. The renderer
+ produces binary alpha (fully clear key pixels, fully opaque bar pixels), so
+ its alpha mask is also the exact hit-test shape we need.
+ """
+ q = _qt()
+ bitmap = q.QtGui.QBitmap.fromImage(image.createAlphaMask())
+ return q.QtGui.QRegion(bitmap)
+
+
+def _window_class() -> type:
+ """Build the QWidget subclass after the lazy PySide6 import."""
+ q = _qt()
+
+ class _QtBarWindow(q.QtWidgets.QWidget):
+ def __init__(self, owner: QtJarvisBarOverlay) -> None:
+ super().__init__(None)
+ self._owner = owner
+ flags = (
+ q.Qt.WindowType.FramelessWindowHint
+ | q.Qt.WindowType.WindowStaysOnTopHint
+ | q.Qt.WindowType.Tool
+ | q.Qt.WindowType.NoDropShadowWindowHint
+ | q.Qt.WindowType.WindowDoesNotAcceptFocus
+ )
+ self.setWindowFlags(flags)
+ self.setAttribute(q.Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setAttribute(q.Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ # A macOS Qt::Tool is an NSPanel and normally disappears while its
+ # process is inactive. The companion is intentionally an accessory
+ # process, so the overlay must remain visible above the active app.
+ mac_always_show = getattr(q.Qt.WidgetAttribute, "WA_MacAlwaysShowToolWindow", None)
+ if mac_always_show is not None:
+ self.setAttribute(mac_always_show)
+ self.setMouseTracking(True)
+ self.setFixedSize(renderer.WIN_W, renderer.WIN_H)
+ self.setWindowOpacity(owner._opacity)
+
+ def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ del event
+ painter = q.QtGui.QPainter(self)
+ try:
+ _paint_transparent_frame(painter, self.rect(), self._owner._qimage)
+ finally:
+ painter.end()
+
+ def enterEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ self._owner._hovered = True
+ self._owner._invalidate_static_frame()
+ self.update()
+ super().enterEvent(event)
+
+ def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ self._owner._hovered = False
+ self._owner._invalidate_static_frame()
+ self.update()
+ super().leaveEvent(event)
+
+ def mousePressEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ if self._owner._mouse_press_ui(event):
+ event.accept()
+ return
+ super().mousePressEvent(event)
+
+ def mouseMoveEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ if self._owner._mouse_move_ui(event):
+ event.accept()
+ return
+ super().mouseMoveEvent(event)
+
+ def mouseReleaseEvent(self, event: Any) -> None: # noqa: N802 - Qt override
+ if self._owner._mouse_release_ui(event):
+ event.accept()
+ return
+ super().mouseReleaseEvent(event)
+
+ return _QtBarWindow
+
+
+class QtJarvisBarOverlay:
+ """Main-thread Qt implementation of the Jarvis Bar surface contract.
+
+ The class is constructed before a ``QApplication`` exists. All Qt objects
+ are created inside ``start()``, which lets the existing companion-host
+ lifecycle instantiate and wire callbacks first. Public methods may be
+ called from the host's stdin-reader thread; widget mutations are queued and
+ drained by a timer on the Qt main thread.
+ """
+
+ def __init__(
+ self,
+ persistent: bool = True,
+ accent: str = "#e7c46e",
+ opacity: float = BAR_ALPHA,
+ startup_gated: bool = False,
+ ) -> None:
+ self._persistent_flag = bool(persistent)
+ self._accent = accent
+ self._opacity = max(0.2, min(1.0, float(opacity)))
+ self._startup_gated = bool(startup_gated)
+ self._mode = "idle"
+ self._ext_level = 0.0
+ self._last_audible_t = 0.0
+ self._muted = False
+ self._hovered = False
+ self._static_tick_key: tuple[str, bool, bool] | None = None
+ self._static_tick_count = 0
+ self._hangup_click_block_until = 0.0
+
+ self._ui_queue: queue.Queue[Callable[[], None]] = queue.Queue()
+ self._started = threading.Event()
+ self._running = False
+ self._stop_requested = False
+ self._desired_visible = self._persistent_flag and not self._startup_gated
+ self._t0 = 0.0
+ self._last_frame_ns = 0
+
+ self._app: Any = None
+ self._window: Any = None
+ # Kept for duck-typed code which probes Tk surfaces. A Qt host has no
+ # Tk root; reset remains available through ``_on_reset_double_click``.
+ self._root: Any = None
+ self._renderer: renderer.JarvisBarRenderer | None = None
+ self._qimage: Any = None
+ self._input_mask: Any = None
+ self._input_mask_key: bytes | None = None
+ self._frame_timer: Any = None
+ self._queue_timer: Any = None
+ self._z_timer: Any = None
+ self._native_window: Any = None
+ self._x = 0
+ self._y = 0
+ self._drag: dict[str, Any] | None = None
+
+ 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
+ # The companion has no SpeechPipeline of its own. The host should map
+ # this callback to an IPC event and let the parent perform the action.
+ self._on_voice_action: Callable[[str], None] | None = None
+
+ # ------------------------------------------------------------------
+ # Surface API consumed by OrbBusBridge / the companion host
+ # ------------------------------------------------------------------
+ @property
+ def _persistent(self) -> bool:
+ return self._persistent_flag
+
+ @_persistent.setter
+ def _persistent(self, enabled: bool) -> None:
+ self._persistent_flag = bool(enabled)
+ self._desired_visible = not self._startup_gated and (
+ self._persistent_flag or self._mode != "idle"
+ )
+ self._enqueue_if_started(self._sync_visibility_ui)
+
+ def show(self, mode: str = "listen") -> None:
+ if mode not in renderer.MODES:
+ return
+ self._mode = mode
+ self._desired_visible = not self._startup_gated and (
+ self._persistent_flag or mode != "idle"
+ )
+ self._invalidate_static_frame()
+ self._enqueue_if_started(self._sync_visibility_ui)
+
+ def hide(self) -> None:
+ self._desired_visible = False
+ self._enqueue_if_started(self._sync_visibility_ui)
+
+ def reassert_z_order(self) -> None:
+ if self._startup_gated:
+ return
+ self._enqueue_if_started(self._raise_ui)
+
+ def release_startup_gate(self) -> bool:
+ if not self._startup_gated:
+ return False
+ self._startup_gated = False
+ self._desired_visible = self._persistent_flag or self._mode != "idle"
+ self._enqueue_if_started(self._sync_visibility_ui)
+ return True
+
+ def set_level(self, level: float) -> None:
+ lv = max(0.0, min(1.0, float(level)))
+ self._ext_level = lv
+ if lv >= AUDIBLE_LEVEL:
+ self._last_audible_t = time.perf_counter()
+
+ def set_muted(self, muted: bool) -> None:
+ self._muted = bool(muted)
+ self._invalidate_static_frame()
+
+ 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 set_on_voice_action(self, callback: Callable[[str], None] | None) -> None:
+ """Register parent-owned handling for ``"talk"`` and ``"hangup"``.
+
+ The macOS surface lives in a companion process, so importing
+ ``runtime_refs.get_speech_pipeline`` here would always return ``None``.
+ Keeping the action opaque lets the host forward it to the parent where
+ the authoritative SpeechPipeline lives.
+ """
+ self._on_voice_action = callback
+
+ # The bar has no comment bubble or mouth animation.
+ 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: ...
+
+ # ------------------------------------------------------------------
+ # Lifecycle
+ # ------------------------------------------------------------------
+ def start_in_thread(self, timeout: float = 3.0) -> None:
+ """Reject in-process threaded use; the companion must call ``start``.
+
+ Qt/Cocoa windows share AppKit's main-thread rule. The method exists to
+ preserve the surface contract, but deliberately creates no GUI thread.
+ """
+ del timeout
+ log.info(
+ "Qt Jarvis Bar requires the companion process main thread; start_in_thread is a no-op."
+ )
+
+ def start(self) -> None:
+ """Create the transparent window and run the Qt event loop."""
+ _prepare_macos_qt_process()
+ q = _qt()
+ app = q.QtWidgets.QApplication.instance()
+ if app is None:
+ q.QtGui.QGuiApplication.setHighDpiScaleFactorRoundingPolicy(
+ q.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
+ )
+ app = q.QtWidgets.QApplication(sys.argv[:1] or ["jarvisbar-qt"])
+ app.setQuitOnLastWindowClosed(False)
+ self._app = app
+
+ # QApplication must create NSApp first. Only then turn the companion
+ # into an accessory process so it owns windows without adding a second
+ # Python icon or menu bar. This is the Qt equivalent of the old Tk
+ # bootstrap ordering rule, without mixing the two GUI toolkits.
+ if sys.platform == "darwin":
+ try:
+ from AppKit import NSApplication # type: ignore[import-not-found] # noqa: PLC0415
+
+ NSApplication.sharedApplication().setActivationPolicy_(1)
+ except Exception: # noqa: BLE001 - cosmetic; never block the bar
+ log.warning(
+ "Qt Jarvis Bar could not enter macOS accessory mode; "
+ "a companion Dock icon may remain",
+ exc_info=True,
+ )
+
+ screen = app.primaryScreen()
+ if screen is not None:
+ geometry = screen.geometry()
+ renderer.apply_display_scale(
+ renderer.compute_display_scale(geometry.width(), geometry.height())
+ )
+ self._renderer = renderer.JarvisBarRenderer(accent=self._accent)
+
+ window_type = _window_class()
+ self._window = window_type(self)
+ self._configure_macos_nonactivating_window_ui()
+ self._resolve_position_ui()
+ self._window.move(self._x, self._y)
+
+ self._running = True
+ self._t0 = time.perf_counter()
+
+ self._frame_timer = q.QtCore.QTimer(self._window)
+ self._frame_timer.setTimerType(q.Qt.TimerType.PreciseTimer)
+ self._frame_timer.setInterval(TARGET_FRAME_MS)
+ self._frame_timer.timeout.connect(self._render_frame_ui)
+ self._frame_timer.start()
+
+ self._queue_timer = q.QtCore.QTimer(self._window)
+ self._queue_timer.setInterval(UI_QUEUE_INTERVAL_MS)
+ self._queue_timer.timeout.connect(self._drain_ui_queue)
+ self._queue_timer.start()
+
+ self._z_timer = q.QtCore.QTimer(self._window)
+ self._z_timer.setInterval(Z_ORDER_GUARD_INTERVAL_MS)
+ self._z_timer.timeout.connect(self._z_order_guard_ui)
+ self._z_timer.start()
+
+ # Submit a complete RGBA frame before the first map. Qt's translucent
+ # backing already starts clear, and paintEvent replaces it atomically.
+ self._render_frame_ui()
+ self._sync_visibility_ui()
+ self._started.set()
+
+ if self._stop_requested:
+ self._stop_ui()
+ return
+ try:
+ app.exec()
+ finally:
+ self._running = False
+
+ def stop(self) -> None:
+ self._stop_requested = True
+ self._running = False
+ if self._window is not None:
+ self._ui_queue.put(self._stop_ui)
+
+ # ------------------------------------------------------------------
+ # Qt-main-thread rendering and commands
+ # ------------------------------------------------------------------
+ def _enqueue_if_started(self, callback: Callable[[], None]) -> None:
+ if self._window is not None:
+ self._ui_queue.put(callback)
+
+ def _drain_ui_queue(self) -> None:
+ while True:
+ try:
+ callback = self._ui_queue.get_nowait()
+ except queue.Empty:
+ return
+ try:
+ callback()
+ except Exception: # noqa: BLE001 - one command must not kill the loop
+ log.exception("Qt Jarvis Bar UI command failed")
+
+ def _render_frame_ui(self) -> None:
+ window = self._window
+ bar_renderer = self._renderer
+ if window is None or bar_renderer is None:
+ return
+ try:
+ now = time.perf_counter()
+ effective_mode = renderer.visual_mode(
+ self._mode,
+ now - self._last_audible_t,
+ hold_s=AUDIBLE_HOLD_S,
+ # The authoritative audio process forwards level samples over
+ # IPC. Its process-local playback_active flag is unavailable
+ # here, so recent real level samples are the truthful signal.
+ playback_active=False,
+ )
+ tick_key = (effective_mode, self._hovered, self._muted)
+ if tick_key != self._static_tick_key:
+ self._static_tick_key = tick_key
+ self._static_tick_count = 0
+ else:
+ self._static_tick_count += 1
+ settled_idle = (
+ effective_mode == "idle" and self._static_tick_count >= _IDLE_SETTLE_TICKS
+ )
+ if settled_idle:
+ return
+
+ pil_frame = bar_renderer.render(
+ now - self._t0,
+ effective_mode,
+ self._ext_level,
+ hovered=self._hovered,
+ muted=self._muted,
+ )
+ rgba_frame = renderer.key_to_alpha(pil_frame)
+ input_mask_key = rgba_frame.getchannel("A").tobytes()
+ self._qimage = _qimage_from_pil(rgba_frame)
+ # Visual transparency does not imply mouse transparency on macOS:
+ # an unmasked Qt window intercepts clicks across its full WIN_W x
+ # WIN_H rectangle, including every alpha-zero pixel. Keep the
+ # native window shape synchronized with the eased pill so only the
+ # visible bar is interactive and all clear padding clicks through.
+ if input_mask_key != self._input_mask_key:
+ input_mask = _input_mask_from_frame(self._qimage)
+ window.setMask(input_mask)
+ self._input_mask = input_mask
+ self._input_mask_key = input_mask_key
+ window.update()
+ except Exception: # noqa: BLE001 - one frame must never stop the timer
+ log.exception("Qt Jarvis Bar frame render failed; dropping one frame")
+ finally:
+ self._last_frame_ns = time.monotonic_ns()
+
+ def _invalidate_static_frame(self) -> None:
+ self._static_tick_key = None
+ self._static_tick_count = 0
+
+ def _sync_visibility_ui(self) -> None:
+ if self._window is None:
+ return
+ if self._desired_visible and not self._startup_gated:
+ self._do_show_ui()
+ else:
+ self._window.hide()
+
+ def _do_show_ui(self) -> None:
+ if self._window is None or self._startup_gated:
+ return
+ self._invalidate_static_frame()
+ self._render_frame_ui()
+ self._window.show()
+ self._raise_ui()
+ q = _qt()
+ mode = self._mode
+ q.QtCore.QTimer.singleShot(50, lambda: self._publish_visibility_ui(mode))
+
+ def _raise_ui(self) -> None:
+ window = self._window
+ if window is None or not window.isVisible() or self._startup_gated:
+ return
+ if sys.platform == "darwin":
+ # QWidget.raise_() activates the Cocoa application even though the
+ # QNSPanel cannot become key. The 500 ms Z-order guard then steals
+ # foreground status over and over, so clicks in every other app are
+ # consumed as activation clicks. Native orderFrontRegardless keeps
+ # the panel ordered above apps without activating this process.
+ if self._native_window is not None:
+ self._native_window.orderFrontRegardless()
+ return
+ window.raise_()
+
+ def _z_order_guard_ui(self) -> None:
+ if self._desired_visible:
+ self._raise_ui()
+
+ def _configure_macos_nonactivating_window_ui(self) -> None:
+ """Apply the native non-activating NSPanel contract after Qt starts."""
+ if sys.platform != "darwin" or self._window is None:
+ return
+ # ``winId()`` from Qt's offscreen/minimal test plugins is not an
+ # Objective-C NSView pointer. Handing it to pyobjc can spin inside the
+ # runtime instead of raising, so native bridging is Cocoa-only.
+ platform_name = str(self._app.platformName()).lower() if self._app is not None else ""
+ if platform_name and platform_name != "cocoa":
+ return
+ try:
+ from ctypes import c_void_p # noqa: PLC0415
+
+ import objc # type: ignore[import-not-found] # noqa: PLC0415
+ from AppKit import ( # type: ignore[import-not-found] # noqa: PLC0415
+ NSWindowStyleMaskNonactivatingPanel,
+ )
+
+ native_view = objc.objc_object(c_void_p=c_void_p(int(self._window.winId())))
+ native_window = native_view.window()
+ if native_window is None:
+ raise RuntimeError("Qt did not expose a native NSWindow")
+ native_window.setStyleMask_(
+ int(native_window.styleMask()) | int(NSWindowStyleMaskNonactivatingPanel)
+ )
+ native_window.setBecomesKeyOnlyIfNeeded_(True)
+ native_window.setHidesOnDeactivate_(False)
+ self._native_window = native_window
+ except Exception: # noqa: BLE001 - topmost is cosmetic; focus safety wins
+ # WindowStaysOnTopHint still supplies the normal ordering. Do not
+ # fall back to QWidget.raise_() on Darwin: foreground theft is much
+ # worse than a bar another app can temporarily cover.
+ self._native_window = None
+ log.warning(
+ "Qt Jarvis Bar could not configure its non-activating macOS panel; "
+ "periodic Z-order raises are disabled",
+ exc_info=True,
+ )
+
+ def _publish_visibility_ui(self, mode: str) -> None:
+ publisher = self._feedback_publisher
+ window = self._window
+ if publisher is None or window is None:
+ return
+ observed = {
+ "viewable": int(window.isVisible()),
+ "geometry": (f"{renderer.WIN_W}x{renderer.WIN_H}+{window.x()}+{window.y()}"),
+ "x": int(window.x()),
+ "y": int(window.y()),
+ }
+ try:
+ publisher(mode, observed)
+ except Exception: # noqa: BLE001 - feedback is diagnostic, never fatal
+ log.debug("Qt Jarvis Bar feedback publisher failed", exc_info=True)
+
+ def _stop_ui(self) -> None:
+ for timer in (self._frame_timer, self._queue_timer, self._z_timer):
+ if timer is not None:
+ timer.stop()
+ if self._window is not None:
+ self._window.hide()
+ self._window.close()
+ if self._app is not None:
+ self._app.quit()
+
+ # ------------------------------------------------------------------
+ # Position, drag, and gestures
+ # ------------------------------------------------------------------
+ def _primary_available_geometry_ui(self) -> Any:
+ app = self._app
+ if app is None:
+ return None
+ screen = app.primaryScreen()
+ return screen.availableGeometry() if screen is not None else None
+
+ def _screen_geometry_for_point_ui(self, x: int, y: int) -> Any:
+ q = _qt()
+ app = self._app
+ if app is None:
+ return None
+ screen = app.screenAt(q.QtCore.QPoint(int(x), int(y)))
+ if screen is None:
+ screen = app.primaryScreen()
+ return screen.availableGeometry() if screen is not None else None
+
+ def _clamp_to_geometry_ui(self, x: int, y: int, geometry: Any) -> tuple[int, int]:
+ if geometry is None:
+ return int(x), int(y)
+ local_x, local_y = interaction.clamp_to_screen(
+ int(x) - geometry.x(),
+ int(y) - geometry.y(),
+ screen_w=geometry.width(),
+ screen_h=geometry.height(),
+ bar_w=renderer.WIN_W,
+ bar_h=renderer.WIN_H,
+ margin=MARGIN_PX,
+ )
+ return local_x + geometry.x(), local_y + geometry.y()
+
+ def _default_position_ui(self) -> tuple[int, int]:
+ geometry = self._primary_available_geometry_ui()
+ if geometry is None:
+ return interaction.default_bottom_center(
+ screen_w=1920,
+ screen_h=1080,
+ bar_w=renderer.WIN_W,
+ bar_h=renderer.WIN_H,
+ margin=MARGIN_PX,
+ )
+ x = geometry.x() + (geometry.width() - renderer.WIN_W) // 2
+ y = geometry.y() + geometry.height() - renderer.WIN_H - TASKBAR_GAP_PX
+ return self._clamp_to_geometry_ui(x, y, geometry)
+
+ def _resolve_position_ui(self) -> None:
+ position: tuple[int, int] | None = None
+ try:
+ from jarvis.core.config_writer import DEFAULT_CONFIG_FILE # noqa: PLC0415
+
+ position = interaction.load_jarvisbar_position(DEFAULT_CONFIG_FILE)
+ except Exception: # noqa: BLE001 - placement degrades to the default
+ log.debug("Qt Jarvis Bar position load failed", exc_info=True)
+ if position is None:
+ self._x, self._y = self._default_position_ui()
+ return
+ geometry = self._screen_geometry_for_point_ui(
+ position[0] + renderer.WIN_W // 2,
+ position[1] + renderer.WIN_H // 2,
+ )
+ self._x, self._y = self._clamp_to_geometry_ui(position[0], position[1], geometry)
+
+ def _mouse_press_ui(self, event: Any) -> bool:
+ q = _qt()
+ button = event.button()
+ if button == q.Qt.MouseButton.RightButton:
+ self._invoke_callback(self._on_show_window, "show-window")
+ return True
+ if button == q.Qt.MouseButton.MiddleButton:
+ self._reset_position_ui()
+ return True
+ if button != q.Qt.MouseButton.LeftButton or self._window is None:
+ return False
+ global_pos = event.globalPosition().toPoint()
+ self._hovered = True
+ self._drag = {
+ "sx": int(global_pos.x()),
+ "sy": int(global_pos.y()),
+ "ox": int(global_pos.x()) - int(self._window.x()),
+ "oy": int(global_pos.y()) - int(self._window.y()),
+ "cx": float(event.position().x()),
+ "hovered": True,
+ "moved": False,
+ }
+ self._invalidate_static_frame()
+ return True
+
+ def _mouse_move_ui(self, event: Any) -> bool:
+ q = _qt()
+ drag = self._drag
+ window = self._window
+ if drag is None or window is None or not event.buttons() & q.Qt.MouseButton.LeftButton:
+ return False
+ global_pos = event.globalPosition().toPoint()
+ dx = int(global_pos.x()) - drag["sx"]
+ dy = int(global_pos.y()) - drag["sy"]
+ if not drag["moved"] and not interaction.is_drag(dx, dy, DRAG_THRESHOLD_PX):
+ return True
+ drag["moved"] = True
+ self._x = int(global_pos.x()) - drag["ox"]
+ self._y = int(global_pos.y()) - drag["oy"]
+ window.move(self._x, self._y)
+ return True
+
+ def _mouse_release_ui(self, event: Any) -> bool:
+ q = _qt()
+ if event.button() != q.Qt.MouseButton.LeftButton:
+ return False
+ drag = self._drag
+ self._drag = None
+ if drag is None:
+ return True
+ if not drag["moved"]:
+ self._dispatch_click_ui(float(event.position().x()), hovered=True)
+ return True
+
+ geometry = self._screen_geometry_for_point_ui(
+ self._x + renderer.WIN_W // 2,
+ self._y + renderer.WIN_H // 2,
+ )
+ self._x, self._y = self._clamp_to_geometry_ui(self._x, self._y, geometry)
+ if self._window is not None:
+ self._window.move(self._x, self._y)
+ self._persist_position_ui()
+ return True
+
+ def _dispatch_click_ui(self, click_x: float, *, hovered: bool | None = None) -> str:
+ if time.monotonic() < self._hangup_click_block_until:
+ return "none"
+ is_hovered = self._hovered if hovered is None else bool(hovered)
+ active = self._mode in ("listen", "think", "speak")
+ action = interaction.resolve_click(
+ click_x,
+ renderer.WIN_W,
+ self._mode,
+ hovered=is_hovered,
+ pill_w=renderer.ACTIVE_W if active else None,
+ )
+ if action == "mute":
+ callback = self._on_mute_toggle
+ if callback is not None:
+ self._invoke_callback(callback, "mute-toggle")
+ self._muted = not self._muted
+ self._invalidate_static_frame()
+ elif action in {"talk", "hangup"}:
+ callback = self._on_voice_action
+ if callback is None:
+ log.warning(
+ "Qt Jarvis Bar %s click has no parent voice-action callback",
+ action,
+ )
+ else:
+ self._invoke_callback(lambda: callback(action), f"voice-{action}")
+ if action == "hangup":
+ # Match the Tk surface's optimistic collapse while the
+ # authoritative parent tears the session down (or repairs
+ # a stuck active state). The next bus state reconciles it.
+ self._mode = "idle"
+ self._invalidate_static_frame()
+ self._hangup_click_block_until = time.monotonic() + HANGUP_CLICK_GUARD_S
+ return action
+
+ @staticmethod
+ def _invoke_callback(callback: Callable[[], None] | None, label: str) -> None:
+ if callback is None:
+ return
+ try:
+ callback()
+ except Exception: # noqa: BLE001 - a gesture must not kill the UI loop
+ log.warning("Qt Jarvis Bar %s callback failed", label, exc_info=True)
+
+ def _persist_position_ui(self) -> None:
+ try:
+ from jarvis.core.config_writer import DEFAULT_CONFIG_FILE # noqa: PLC0415
+
+ interaction.save_jarvisbar_position(DEFAULT_CONFIG_FILE, self._x, self._y)
+ except Exception: # noqa: BLE001 - position persistence is non-critical
+ log.debug("Qt Jarvis Bar position save failed", exc_info=True)
+
+ def _on_reset_double_click(self, _event: Any = None) -> None:
+ del _event
+ if self._window is None:
+ return
+ self._ui_queue.put(self._reset_position_ui)
+
+ def _reset_position_ui(self) -> None:
+ self._x, self._y = self._default_position_ui()
+ if self._window is not None:
+ self._window.move(self._x, self._y)
+ self._persist_position_ui()
+
+
+__all__ = [
+ "QtJarvisBarOverlay",
+ "_input_mask_from_frame",
+ "_paint_transparent_frame",
+ "_prepare_macos_qt_process",
+ "_qimage_from_pil",
+]
diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.py
index 7a70a252a3..71f50d15a4 100644
--- a/jarvis/ui/jarvisbar/subprocess_overlay.py
+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py
@@ -4,9 +4,9 @@
``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.
+stdin. Child events (talk, hang-up, mute toggle, feedback, show-window) stream
+back on stdout. Voice actions are executed against the live parent-process
+pipeline; bridge-owned actions are dispatched to its registered callbacks.
Failure contract: while the host is down, every method degrades to a one-log
no-op (``NullOverlay`` behavior) — the bar is cosmetic and must never take
@@ -71,7 +71,12 @@ class SubprocessBarOverlay:
self._startup_gated = bool(startup_gated)
self._mode = "idle"
self._muted = False
- self._visible = False
+ # Mirror what the real host does at construction time. A persistent,
+ # ungated bar maps itself immediately; a startup-gated or
+ # non-persistent bar starts withdrawn. This mirror is load-bearing for
+ # respawn: _reapply_desired_state must not hide a bar that the host just
+ # restored after a crash/reload.
+ self._visible = self._persistent_flag and not self._startup_gated
self._last_level: float | None = None
self._proc: subprocess.Popen[str] | None = None
self._send_lock = threading.Lock()
@@ -83,6 +88,8 @@ class SubprocessBarOverlay:
self._respawn_succeeded = threading.Event()
self._respawn_exhausted = threading.Event()
self._on_mute_toggle: Callable[[], None] | None = None
+ self._on_talk: Callable[[], None] | None = None
+ self._on_hangup: Callable[[], None] | None = None
self._feedback_publisher: Callable[[str, dict], None] | None = None
self._on_show_window: Callable[[], None] | None = None
@@ -198,7 +205,10 @@ class SubprocessBarOverlay:
if mode not in _MODES:
return
self._mode = mode
- self._visible = True
+ # Match JarvisBarOverlay.show(): a non-persistent idle bar withdraws
+ # instead of becoming visible. Active modes and every persistent mode
+ # are visible once the startup gate permits them.
+ self._visible = self._persistent_flag or mode != "idle"
self._send({"op": "show", "mode": mode})
def hide(self) -> None:
@@ -212,6 +222,10 @@ class SubprocessBarOverlay:
released = self._startup_gated
self._startup_gated = False
if released:
+ # The host maps a persistent bar immediately on gate release. Keep
+ # the proxy's desired-state mirror in lock-step so a later bounded
+ # respawn replays ``show`` rather than hiding the restored bar.
+ self._visible = self._persistent_flag or self._mode != "idle"
self._send({"op": "release_startup_gate"})
return released
@@ -235,6 +249,12 @@ class SubprocessBarOverlay:
def set_on_mute_toggle(self, callback: Callable[[], None] | None) -> None:
self._on_mute_toggle = callback
+ def set_on_talk(self, callback: Callable[[], None] | None) -> None:
+ self._on_talk = callback
+
+ def set_on_hangup(self, callback: Callable[[], None] | None) -> None:
+ self._on_hangup = callback
+
def set_feedback_publisher(self, callback: Callable[[str, dict], None] | None) -> None:
self._feedback_publisher = callback
@@ -407,6 +427,10 @@ class SubprocessBarOverlay:
try:
if event == "ready":
self._ready.set()
+ elif event == "talk":
+ self._dispatch_talk_action()
+ elif event == "hangup":
+ self._dispatch_hangup_action()
elif event == "mute_toggle":
cb = self._on_mute_toggle
if cb is not None:
@@ -422,6 +446,55 @@ class SubprocessBarOverlay:
except Exception: # noqa: BLE001 — a bad callback must not kill the pump
log.exception("bar host event callback failed: %r", event)
+ def _dispatch_talk_action(self) -> None:
+ """Start a voice session in the parent process.
+
+ An explicitly installed callback wins for embedders/tests. The normal
+ macOS desktop path falls through to ``runtime_refs``, which is populated
+ in this parent process (and deliberately empty in the Tk host child).
+ """
+ callback = self._on_talk
+ if callback is not None:
+ callback()
+ return
+
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ if pipeline is None:
+ return
+ start = getattr(pipeline, "request_voice_session", None)
+ if callable(start):
+ start()
+
+ def _dispatch_hangup_action(self) -> None:
+ """Apply the close-X active-session guard in the parent process."""
+ callback = self._on_hangup
+ if callback is not None:
+ callback()
+ return
+
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ if pipeline is None:
+ return
+
+ # Preserve the in-process bar contract: an active-looking bar with no
+ # live session is a stuck visual state, so the close click starts a
+ # session and lets the user escape. Pipelines without the probe retain
+ # the legacy fail-safe and receive a normal hang-up request.
+ active = getattr(pipeline, "is_session_active", None)
+ if callable(active) and not active():
+ start = getattr(pipeline, "request_voice_session", None)
+ if callable(start):
+ start()
+ return
+
+ hangup = getattr(pipeline, "request_hangup", None)
+ if callable(hangup):
+ hangup()
+
def _pump_stderr(self, stream: IO[str] | None) -> None:
if stream is None:
return
@@ -451,6 +524,9 @@ class SubprocessMascotOverlay(SubprocessBarOverlay):
def __init__(self, mascot_path: str | None = None) -> None:
super().__init__()
self._mascot_path = mascot_path
+ # OrbOverlay(sticky=False) always starts withdrawn. The base proxy's
+ # persistent-bar visibility default does not apply to this surface.
+ self._visible = False
def _init_payload(self) -> dict[str, Any]:
return {
diff --git a/tests/unit/ui/jarvisbar/test_boot_visibility.py b/tests/unit/ui/jarvisbar/test_boot_visibility.py
index 7567c30f84..74d41f89cd 100644
--- a/tests/unit/ui/jarvisbar/test_boot_visibility.py
+++ b/tests/unit/ui/jarvisbar/test_boot_visibility.py
@@ -9,10 +9,12 @@ The current contract separates initialization from visibility: boot creates a
fully painted, startup-gated bar; the bus bridge releases that gate directly on
the genuine ``VoiceBootStatus`` event. Runtime builds remain immediate.
"""
+
from __future__ import annotations
from types import SimpleNamespace
+import jarvis.ui.desktop_app as desktop_app_module
from jarvis.ui.desktop_app import DesktopApp
from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
@@ -31,9 +33,11 @@ def _app(*, bar_persistent: bool) -> DesktopApp:
def _disable_real_tk(monkeypatch) -> None:
- monkeypatch.setattr(
- JarvisBarOverlay, "start_in_thread", lambda self, timeout=3.0: None
- )
+ # These tests exercise the in-process Tk lifecycle specifically. The real
+ # macOS desktop selects SubprocessBarOverlay; its mirror/gate contract is
+ # covered in test_subprocess_overlay.py and the Qt host-selection tests.
+ monkeypatch.setattr(desktop_app_module.sys, "platform", "linux")
+ monkeypatch.setattr(JarvisBarOverlay, "start_in_thread", lambda self, timeout=3.0: None)
def test_boot_persistent_bar_is_initialized_but_startup_gated(monkeypatch) -> None:
diff --git a/tests/unit/ui/jarvisbar/test_click_no_session_guard.py b/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
index d3a2827d7d..357f6196ab 100644
--- a/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
+++ b/tests/unit/ui/jarvisbar/test_click_no_session_guard.py
@@ -10,6 +10,7 @@ no-op that just traps the user ("frozen, nothing works"). The bar must instead
treat a click as a session start whenever no session is live, so the user can
always escape the stuck state.
"""
+
from __future__ import annotations
from jarvis.ui.jarvisbar import renderer as R
@@ -44,9 +45,7 @@ def _x_glyph() -> int:
def _patch_pipeline(monkeypatch, fake) -> None:
# _on_click does `from jarvis.core.runtime_refs import get_speech_pipeline`
# at call time, so patching the module attribute is enough.
- monkeypatch.setattr(
- "jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake
- )
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake)
def test_stuck_active_bar_without_session_starts_session_not_hangup(monkeypatch):
@@ -57,7 +56,7 @@ def test_stuck_active_bar_without_session_starts_session_not_hangup(monkeypatch)
bar._on_click(_x_glyph(), hovered=True)
- assert fake.hangup_calls == 0 # never the useless trap-hangup
+ assert fake.hangup_calls == 0 # never the useless trap-hangup
assert fake.session_calls == 1 # the click escapes the stuck state
@@ -69,18 +68,16 @@ def test_live_session_close_x_still_hangs_up(monkeypatch):
bar._on_click(_x_glyph(), hovered=True)
- assert fake.hangup_calls == 1 # a genuine session is still hang-up-able
+ assert fake.hangup_calls == 1 # a genuine session is still hang-up-able
assert fake.session_calls == 0
- assert bar._mode == "idle" # immediate visual acknowledgement
+ assert bar._mode == "idle" # immediate visual acknowledgement
def test_repeated_close_click_does_not_reopen_session(monkeypatch):
"""A rapid second click lands where the X used to be after the optimistic
collapse; it must not be reinterpreted as an idle-body session start."""
now = [100.0]
- monkeypatch.setattr(
- "jarvis.ui.jarvisbar.overlay.time.monotonic", lambda: now[0]
- )
+ monkeypatch.setattr("jarvis.ui.jarvisbar.overlay.time.monotonic", lambda: now[0])
bar = JarvisBarOverlay()
bar._mode = "listen"
fake = _FakePipeline(session_active=True)
@@ -121,9 +118,7 @@ def test_missing_accessor_preserves_legacy_hangup(monkeypatch):
...
fake = _Legacy()
- monkeypatch.setattr(
- "jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake
- )
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake)
bar = JarvisBarOverlay()
bar._mode = "listen"
@@ -131,3 +126,36 @@ def test_missing_accessor_preserves_legacy_hangup(monkeypatch):
assert fake.hangup_calls == 1
assert fake.session_calls == 0
+
+
+def test_external_talk_callback_bypasses_child_runtime_refs(monkeypatch):
+ """The macOS host resolves the click, but the parent owns the pipeline."""
+ monkeypatch.setattr(
+ "jarvis.core.runtime_refs.get_speech_pipeline",
+ lambda: (_ for _ in ()).throw(AssertionError("child pipeline lookup")),
+ )
+ fired: list[str] = []
+ bar = JarvisBarOverlay()
+ bar.set_on_talk(lambda: fired.append("talk"))
+
+ bar._on_click(R.WIN_W / 2)
+
+ assert fired == ["talk"]
+
+
+def test_external_hangup_callback_bypasses_child_runtime_refs(monkeypatch):
+ """A hosted close click is forwarded and acknowledged locally."""
+ monkeypatch.setattr(
+ "jarvis.core.runtime_refs.get_speech_pipeline",
+ lambda: (_ for _ in ()).throw(AssertionError("child pipeline lookup")),
+ )
+ fired: list[str] = []
+ bar = JarvisBarOverlay()
+ bar._mode = "listen"
+ bar.set_on_hangup(lambda: fired.append("hangup"))
+
+ bar._on_click(_x_glyph(), hovered=True)
+
+ assert fired == ["hangup"]
+ assert bar._mode == "idle"
+ assert bar._hangup_click_block_until > 0.0
diff --git a/tests/unit/ui/jarvisbar/test_frame_pacing.py b/tests/unit/ui/jarvisbar/test_frame_pacing.py
index a87111e642..9ebcec2c89 100644
--- a/tests/unit/ui/jarvisbar/test_frame_pacing.py
+++ b/tests/unit/ui/jarvisbar/test_frame_pacing.py
@@ -20,6 +20,7 @@ constants' docstrings in ``overlay.py``):
These tests pin both contracts headless — a fake root/canvas/renderer, no
real Tk display, so they run on every OS including a headless CI box.
"""
+
from __future__ import annotations
import pytest
@@ -41,7 +42,7 @@ def _no_real_tk_photoimage(monkeypatch):
render()/re-arm CALL COUNTS, not actual Tk image objects. Patching the
real ``PIL.ImageTk`` module attribute (not ``overlay``'s local name)
because the import is re-resolved fresh inside the function body."""
- monkeypatch.setattr("PIL.ImageTk.PhotoImage", lambda img: img)
+ monkeypatch.setattr("PIL.ImageTk.PhotoImage", lambda img, **_kwargs: img)
class _FakeRoot:
@@ -240,9 +241,7 @@ def test_adaptive_pacing_shortens_the_next_delay_after_a_slow_tick(monkeypatch):
than a full extra TARGET_FRAME_MS later — otherwise a single slow render
compounds into an even longer visible gap (the old fixed-16ms behavior)."""
clock = [1000.0]
- monkeypatch.setattr(
- "jarvis.ui.jarvisbar.overlay.time.perf_counter", lambda: clock[0]
- )
+ monkeypatch.setattr("jarvis.ui.jarvisbar.overlay.time.perf_counter", lambda: clock[0])
slow_cost_s = (TARGET_FRAME_MS + 25) / 1000.0 # well past the target
bar, root, _canvas = _bare_bar(_SlowRenderer(clock, slow_cost_s), mode="think")
@@ -259,9 +258,7 @@ def test_adaptive_pacing_keeps_the_full_target_delay_for_a_fast_tick(monkeypatch
"""A negligible-cost tick must schedule (at, or very near) the full
TARGET_FRAME_MS — the adaptive math must not change normal-case behavior."""
clock = [1000.0]
- monkeypatch.setattr(
- "jarvis.ui.jarvisbar.overlay.time.perf_counter", lambda: clock[0]
- )
+ monkeypatch.setattr("jarvis.ui.jarvisbar.overlay.time.perf_counter", lambda: clock[0])
bar, root, _canvas = _bare_bar(_CountingRenderer(), mode="think")
bar._schedule_frame()
diff --git a/tests/unit/ui/jarvisbar/test_host_protocol.py b/tests/unit/ui/jarvisbar/test_host_protocol.py
index d53f868ef6..f8e9cb539a 100644
--- a/tests/unit/ui/jarvisbar/test_host_protocol.py
+++ b/tests/unit/ui/jarvisbar/test_host_protocol.py
@@ -6,8 +6,10 @@ 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 importlib.util
import io
import json
import os
@@ -23,6 +25,12 @@ class _RecordingBar:
def __init__(self) -> None:
self.calls: list[tuple] = []
self._persistent = True
+ self.on_voice_action = None
+ self.on_talk = None
+ self.on_hangup = None
+ self.on_mute_toggle = None
+ self.feedback_publisher = None
+ self.on_show_window = None
def show(self, mode: str = "listen") -> None:
self.calls.append(("show", mode))
@@ -64,6 +72,24 @@ class _RecordingBar:
def _on_reset_double_click(self, _event=None) -> None:
self.calls.append(("reset_position",))
+ def set_on_talk(self, callback) -> None:
+ self.on_talk = callback
+
+ def set_on_voice_action(self, callback) -> None:
+ self.on_voice_action = callback
+
+ def set_on_hangup(self, callback) -> None:
+ self.on_hangup = callback
+
+ def set_on_mute_toggle(self, callback) -> None:
+ self.on_mute_toggle = callback
+
+ def set_feedback_publisher(self, callback) -> None:
+ self.feedback_publisher = callback
+
+ def set_on_show_window(self, callback) -> None:
+ self.on_show_window = callback
+
def stop(self) -> None:
self.calls.append(("stop",))
@@ -103,6 +129,38 @@ def test_dispatch_stop_returns_false_and_unknown_is_tolerated() -> None:
assert host.dispatch(bar, {"op": "definitely-not-a-real-op"}) is True
+def test_surface_interactions_are_wired_to_child_events(monkeypatch) -> None:
+ bar = _RecordingBar()
+ emitted: list[tuple[str, dict]] = []
+ monkeypatch.setattr(
+ host,
+ "emit",
+ lambda event, **payload: emitted.append((event, payload)),
+ )
+
+ host._wire_surface_events(bar)
+ assert bar.on_voice_action is not None
+ assert bar.on_talk is not None
+ assert bar.on_hangup is not None
+ assert bar.on_mute_toggle is not None
+ assert bar.feedback_publisher is not None
+ assert bar.on_show_window is not None
+
+ bar.on_voice_action("talk")
+ bar.on_voice_action("hangup")
+ bar.on_mute_toggle()
+ bar.feedback_publisher("bar", {"value": 1})
+ bar.on_show_window()
+
+ assert emitted == [
+ ("talk", {}),
+ ("hangup", {}),
+ ("mute_toggle", {}),
+ ("feedback", {"kind": "bar", "payload": {"value": 1}}),
+ ("show_window", {}),
+ ]
+
+
class _SparseSurface:
"""A surface missing several ops (like the mascot OrbOverlay)."""
@@ -128,9 +186,7 @@ def test_dispatch_missing_surface_method_is_a_noop() -> None:
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'
- )
+ 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",)
@@ -141,33 +197,56 @@ def test_build_surface_mascot_builds_an_orb_overlay(monkeypatch) -> None:
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}
- )
+ 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."""
+def test_build_surface_defaults_to_the_tk_bar_off_macos(monkeypatch) -> None:
+ """Windows/Linux keep the established Tk color-key implementation."""
from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
monkeypatch.delenv("JARVIS_BAR_HOST_FAKE", raising=False)
- monkeypatch.setattr(host, "_hide_dock_icon", lambda: None)
+ monkeypatch.setattr(host.sys, "platform", "linux")
+ 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_build_surface_uses_qt_bar_on_macos_without_tk_bootstrap(
+ monkeypatch,
+) -> None:
+ """Darwin must never initialize Tk before the Qt Cocoa application."""
+ from jarvis.ui.jarvisbar.qt_overlay import QtJarvisBarOverlay
+
+ monkeypatch.delenv("JARVIS_BAR_HOST_FAKE", raising=False)
+ monkeypatch.setattr(host.sys, "platform", "darwin")
+
+ def fail_tk_bootstrap() -> None:
+ raise AssertionError("macOS Qt bar must not create a Tk bootstrap")
+
+ monkeypatch.setattr(host, "_hide_dock_icon", fail_tk_bootstrap)
surface = host._build_surface(
- {"op": "init", "persistent": False, "accent": "#123456"}
+ {
+ "op": "init",
+ "persistent": False,
+ "accent": "#123456",
+ "opacity": 0.8,
+ "startup_gated": True,
+ }
)
- assert isinstance(surface, JarvisBarOverlay)
+
+ assert isinstance(surface, QtJarvisBarOverlay)
assert surface._persistent is False
assert surface._accent == "#123456"
+ assert surface._opacity == 0.8
+ assert surface._startup_gated 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'
+ '\nthis 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
@@ -223,9 +302,7 @@ def test_host_process_round_trip_with_echo_bar() -> None:
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") == "show" and e.get("args") == ["listen"] for e in echoed
- )
+ 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:
@@ -248,21 +325,15 @@ def test_host_process_round_trip_with_mascot_surface() -> None:
)
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.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": "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)
@@ -275,11 +346,54 @@ def test_host_process_round_trip_with_mascot_surface() -> None:
for e in echoed
)
assert any(
- e.get("op") == "show_listening_transcript"
- and e.get("args") == ["hi", 9]
+ 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()
+
+
+ sys.platform != "darwin" or importlib.util.find_spec("PySide6") is None,
+ reason="real Darwin Qt host requires PySide6",
+)
+def test_host_process_round_trip_with_qt_bar_offscreen() -> None:
+ """Real macOS host: Qt initializes, renders commands, and exits cleanly."""
+ env = dict(os.environ)
+ env["QT_QPA_PLATFORM"] = "offscreen"
+ 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":false,"startup_gated":true}\n')
+ proc.stdin.flush()
+ ready = json.loads(proc.stdout.readline())
+ assert ready.get("event") == "ready"
+
+ for command in (
+ {"op": "release_startup_gate"},
+ {"op": "show", "mode": "speak"},
+ {"op": "set_level", "level": 0.72},
+ {"op": "hide"},
+ {"op": "stop"},
+ ):
+ proc.stdin.write(json.dumps(command) + "\n")
+ proc.stdin.flush()
+ _out, err = proc.communicate(timeout=30)
+
+ assert proc.returncode == 0, err
+ assert "pyimage" not in err.lower()
+ assert "tkinter" not in err.lower()
+ finally:
+ if proc.poll() is None:
+ proc.kill()
diff --git a/tests/unit/ui/jarvisbar/test_mute_button.py b/tests/unit/ui/jarvisbar/test_mute_button.py
index 4eee746177..f8cac477cf 100644
--- a/tests/unit/ui/jarvisbar/test_mute_button.py
+++ b/tests/unit/ui/jarvisbar/test_mute_button.py
@@ -6,6 +6,7 @@ OrbBusBridge points at ``VoiceMuteToggleRequested``) and optimistically flips
the local mirror so the slashed-mic icon shows on the very next frame. The
authoritative ``VoiceMuteChanged`` is reconciled via ``set_muted``.
"""
+
from __future__ import annotations
from jarvis.ui.jarvisbar import renderer as R
@@ -32,9 +33,7 @@ def _mic_x() -> int:
def _patch_pipeline(monkeypatch, fake) -> None:
- monkeypatch.setattr(
- "jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake
- )
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: fake)
def test_mic_click_fires_toggle_and_optimistically_mutes(monkeypatch):
@@ -53,6 +52,19 @@ def test_mic_click_fires_toggle_and_optimistically_mutes(monkeypatch):
assert bar._muted is False # toggles back
+def test_mic_callback_does_not_require_a_child_speech_pipeline(monkeypatch):
+ """The macOS host has no pipeline, but its mute IPC callback must fire."""
+ bar = JarvisBarOverlay()
+ fired: list[int] = []
+ bar.set_on_mute_toggle(lambda: fired.append(1))
+ _patch_pipeline(monkeypatch, None)
+
+ bar._on_click(_mic_x(), hovered=True)
+
+ assert fired == [1]
+ assert bar._muted is True
+
+
def test_mic_click_without_callback_is_noop(monkeypatch):
bar = JarvisBarOverlay()
bar._on_mute_toggle = None # boot race: bridge not wired yet
diff --git a/tests/unit/ui/jarvisbar/test_qt_overlay.py b/tests/unit/ui/jarvisbar/test_qt_overlay.py
new file mode 100644
index 0000000000..9def2054c6
--- /dev/null
+++ b/tests/unit/ui/jarvisbar/test_qt_overlay.py
@@ -0,0 +1,276 @@
+"""Focused regression tests for the Darwin Qt Jarvis Bar surface."""
+
+from __future__ import annotations
+
+import sys
+from typing import Any
+
+import pytest
+from PIL import Image, ImageDraw
+
+from jarvis.ui.jarvisbar import qt_overlay, renderer
+
+
+def test_surface_state_is_safe_before_qt_is_started(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Construction and pre-start bus updates must not import or touch Qt."""
+
+ def fail_qt_import() -> Any:
+ raise AssertionError("Qt was loaded before the surface started")
+
+ monkeypatch.setattr(qt_overlay, "_qt", fail_qt_import)
+ surface = qt_overlay.QtJarvisBarOverlay(
+ persistent=True,
+ startup_gated=True,
+ )
+
+ surface.show("think")
+ surface.set_level(2.0)
+ surface.set_muted(True)
+
+ assert surface._mode == "think" # noqa: SLF001
+ assert surface._ext_level == 1.0 # noqa: SLF001
+ assert surface._muted is True # noqa: SLF001
+ assert surface._desired_visible is False # noqa: SLF001
+ assert surface.release_startup_gate() is True
+ assert surface._desired_visible is True # noqa: SLF001
+ assert surface.release_startup_gate() is False
+
+
+def test_macos_qt_process_disables_foreground_activation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(qt_overlay.sys, "platform", "darwin")
+ monkeypatch.delenv("QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM", raising=False)
+
+ qt_overlay._prepare_macos_qt_process() # noqa: SLF001
+
+ assert qt_overlay.os.environ["QT_MAC_DISABLE_FOREGROUND_APPLICATION_TRANSFORM"] == "1"
+
+
+def test_macos_z_order_uses_native_nonactivating_raise(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _Window:
+ def __init__(self) -> None:
+ self.qt_raise_calls = 0
+
+ def isVisible(self) -> bool: # noqa: N802 - Qt-compatible double
+ return True
+
+ def raise_(self) -> None:
+ self.qt_raise_calls += 1
+
+ class _NativeWindow:
+ def __init__(self) -> None:
+ self.order_calls = 0
+
+ def orderFrontRegardless(self) -> None: # noqa: N802 - AppKit-compatible double
+ self.order_calls += 1
+
+ monkeypatch.setattr(qt_overlay.sys, "platform", "darwin")
+ surface = qt_overlay.QtJarvisBarOverlay(startup_gated=False)
+ window = _Window()
+ native_window = _NativeWindow()
+ surface._window = window # type: ignore[assignment] # noqa: SLF001
+ surface._native_window = native_window # noqa: SLF001
+
+ surface._raise_ui() # noqa: SLF001
+
+ assert native_window.order_calls == 1
+ assert window.qt_raise_calls == 0
+
+
+def test_macos_z_order_never_falls_back_to_focus_stealing_qt_raise(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _Window:
+ def __init__(self) -> None:
+ self.qt_raise_calls = 0
+
+ def isVisible(self) -> bool: # noqa: N802 - Qt-compatible double
+ return True
+
+ def raise_(self) -> None:
+ self.qt_raise_calls += 1
+
+ monkeypatch.setattr(qt_overlay.sys, "platform", "darwin")
+ surface = qt_overlay.QtJarvisBarOverlay(startup_gated=False)
+ window = _Window()
+ surface._window = window # type: ignore[assignment] # noqa: SLF001
+ surface._native_window = None # noqa: SLF001
+
+ surface._raise_ui() # noqa: SLF001
+
+ assert window.qt_raise_calls == 0
+
+
+def test_non_cocoa_qt_backend_never_enters_the_appkit_bridge(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _App:
+ @staticmethod
+ def platformName() -> str: # noqa: N802 - Qt-compatible double
+ return "offscreen"
+
+ class _Window:
+ @staticmethod
+ def winId() -> int: # noqa: N802 - Qt-compatible double
+ raise AssertionError("offscreen winId must not be treated as an NSView")
+
+ monkeypatch.setattr(qt_overlay.sys, "platform", "darwin")
+ surface = qt_overlay.QtJarvisBarOverlay()
+ surface._app = _App() # type: ignore[assignment] # noqa: SLF001
+ surface._window = _Window() # type: ignore[assignment] # noqa: SLF001
+
+ surface._configure_macos_nonactivating_window_ui() # noqa: SLF001
+
+ assert surface._native_window is None # noqa: SLF001
+
+
+def test_clicks_are_forwarded_to_parent_owned_callbacks() -> None:
+ """The companion surface must not look for a child-local speech pipeline."""
+ surface = qt_overlay.QtJarvisBarOverlay()
+ voice_actions: list[str] = []
+ mute_toggles: list[bool] = []
+ surface.set_on_voice_action(voice_actions.append)
+ surface.set_on_mute_toggle(lambda: mute_toggles.append(True))
+
+ surface._mode = "idle" # noqa: SLF001
+ assert surface._dispatch_click_ui(renderer.WIN_W / 2) == "talk" # noqa: SLF001
+
+ surface._mode = "listen" # noqa: SLF001
+ assert surface._dispatch_click_ui(renderer.WIN_W * 0.8) == "mute" # noqa: SLF001
+
+ close_x = renderer.WIN_W / 2 - 0.42 * renderer.ACTIVE_W
+ assert surface._dispatch_click_ui(close_x, hovered=True) == "hangup" # noqa: SLF001
+
+ assert voice_actions == ["talk", "hangup"]
+ assert mute_toggles == [True]
+ assert surface._muted is True # noqa: SLF001
+ assert surface._mode == "idle" # noqa: SLF001
+
+
+def test_full_frame_paint_clears_black_backing_and_previous_pixels() -> None:
+ """Transparent pixels must replace, rather than blend over, old content."""
+ pytest.importorskip("PySide6")
+ q = qt_overlay._qt() # noqa: SLF001
+ size = 16
+ target = q.QtGui.QImage(
+ size,
+ size,
+ q.QtGui.QImage.Format.Format_RGBA8888,
+ )
+ target.fill(q.QtGui.QColor(0, 0, 0, 255))
+
+ first = Image.new("RGBA", (size, size), (0, 0, 0, 0))
+ ImageDraw.Draw(first).rectangle((5, 5, 10, 10), fill=(231, 196, 110, 255))
+ painter = q.QtGui.QPainter(target)
+ qt_overlay._paint_transparent_frame( # noqa: SLF001
+ painter,
+ target.rect(),
+ qt_overlay._qimage_from_pil(first), # noqa: SLF001
+ )
+ painter.end()
+
+ assert target.pixelColor(0, 0).alpha() == 0
+ assert target.pixelColor(7, 7).alpha() == 255
+
+ second = Image.new("RGBA", (size, size), (0, 0, 0, 0))
+ painter = q.QtGui.QPainter(target)
+ qt_overlay._paint_transparent_frame( # noqa: SLF001
+ painter,
+ target.rect(),
+ qt_overlay._qimage_from_pil(second), # noqa: SLF001
+ )
+ painter.end()
+
+ assert target.pixelColor(0, 0).alpha() == 0
+ assert target.pixelColor(7, 7).alpha() == 0
+
+
[email protected](sys.platform != "darwin", reason="Darwin Qt input-mask regression")
+def test_transparent_frame_pixels_are_excluded_from_the_input_mask() -> None:
+ """Invisible window padding must pass clicks to the app underneath."""
+ pytest.importorskip("PySide6")
+ q = qt_overlay._qt() # noqa: SLF001
+ app = q.QtWidgets.QApplication.instance()
+ owns_app = app is None
+ if app is None:
+ app = q.QtWidgets.QApplication(["jarvisbar-input-mask-test"])
+
+ frame = Image.new("RGBA", (16, 12), (0, 0, 0, 0))
+ ImageDraw.Draw(frame).rectangle((5, 4, 10, 8), fill=(231, 196, 110, 255))
+ mask = qt_overlay._input_mask_from_frame( # noqa: SLF001
+ qt_overlay._qimage_from_pil(frame), # noqa: SLF001
+ )
+
+ assert mask.contains(q.QtCore.QPoint(5, 4))
+ assert mask.contains(q.QtCore.QPoint(10, 8))
+ assert not mask.contains(q.QtCore.QPoint(0, 0))
+ assert not mask.contains(q.QtCore.QPoint(15, 11))
+ if owns_app:
+ app.quit()
+
+
+def test_render_applies_the_frame_input_mask(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every eased geometry frame must update the native hit-test shape."""
+ surface = qt_overlay.QtJarvisBarOverlay()
+ surface._renderer = renderer.JarvisBarRenderer() # noqa: SLF001
+ surface._t0 = 0.0 # noqa: SLF001
+ qimage = object()
+ input_mask = object()
+
+ class _Window:
+ def __init__(self) -> None:
+ self.masks: list[object] = []
+ self.updates = 0
+
+ def setMask(self, mask: object) -> None: # noqa: N802 - Qt-compatible double
+ self.masks.append(mask)
+
+ def update(self) -> None:
+ self.updates += 1
+
+ window = _Window()
+ surface._window = window # type: ignore[assignment] # noqa: SLF001
+ monkeypatch.setattr(qt_overlay, "_qimage_from_pil", lambda _image: qimage)
+ monkeypatch.setattr(
+ qt_overlay,
+ "_input_mask_from_frame",
+ lambda image: input_mask if image is qimage else None,
+ )
+
+ surface._render_frame_ui() # noqa: SLF001
+ surface._render_frame_ui() # noqa: SLF001
+
+ assert window.masks == [input_mask]
+ assert window.updates == 2
+
+
+def test_qt_surface_preserves_the_overlay_contract() -> None:
+ surface = qt_overlay.QtJarvisBarOverlay()
+ methods = {
+ "hide",
+ "hide_comment",
+ "play_animation",
+ "reassert_z_order",
+ "release_startup_gate",
+ "set_feedback_publisher",
+ "set_level",
+ "set_muted",
+ "set_on_mute_toggle",
+ "set_on_show_window",
+ "set_on_voice_action",
+ "show",
+ "show_listening_transcript",
+ "start",
+ "start_in_thread",
+ "start_mouth_animation",
+ "stop",
+ "stop_animation",
+ "stop_mouth_animation",
+ }
+
+ assert all(callable(getattr(surface, name, None)) for name in methods)
diff --git a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
index ba34acffa4..7f7f123ebc 100644
--- a/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
+++ b/tests/unit/ui/jarvisbar/test_show_lifts_topmost.py
@@ -17,6 +17,7 @@ Repeated wake updates on an already-mapped persistent bar skip all of those
native style mutations, preventing the old default-size Tk backing surface from
flashing at the top-left of the screen.
"""
+
from __future__ import annotations
import jarvis.ui.jarvisbar.overlay as overlay_module
@@ -156,7 +157,10 @@ def test_do_show_mapped_window_skips_all_native_style_mutations() -> None:
assert bar._static_tick_count == 0 # noqa: SLF001
-def test_explicit_z_order_reassert_repins_an_already_mapped_window() -> None:
+def test_explicit_z_order_reassert_repins_an_already_mapped_window(
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(overlay_module.sys, "platform", "win32")
bar, root = _bar_with_fake_root(mapped=True)
bar._do_reassert_z_order() # noqa: SLF001
@@ -198,12 +202,7 @@ def test_win32_native_pin_uses_inner_handle_when_it_is_already_toplevel() -> Non
def test_win32_native_pin_failure_is_nonfatal() -> None:
- assert (
- _win32_force_topmost(
- _FakeNativeRoot(), user32=_FakeUser32(succeeds=False)
- )
- is False
- )
+ assert _win32_force_topmost(_FakeNativeRoot(), user32=_FakeUser32(succeeds=False)) is False
def test_win32_band_check_detects_visible_non_topmost_window_above_bar() -> None:
@@ -215,9 +214,7 @@ def test_win32_band_check_detects_visible_non_topmost_window_above_bar() -> None
ex_styles={normal: 0},
)
- assert _win32_topmost_band_is_healthy(
- _FakeNativeRoot(), user32=user32
- ) is False
+ assert _win32_topmost_band_is_healthy(_FakeNativeRoot(), user32=user32) is False
def test_win32_band_check_accepts_only_topmost_or_hidden_windows_above() -> None:
@@ -230,9 +227,7 @@ def test_win32_band_check_accepts_only_topmost_or_hidden_windows_above() -> None
ex_styles={topmost: 0x00000008, hidden_normal: 0},
)
- assert _win32_topmost_band_is_healthy(
- _FakeNativeRoot(), user32=user32
- ) is True
+ assert _win32_topmost_band_is_healthy(_FakeNativeRoot(), user32=user32) is True
def test_win32_pin_skips_tk_lift_that_can_leave_the_wrong_z_order_band(
@@ -263,9 +258,7 @@ def test_z_order_guard_repins_mapped_bar_and_rearms(monkeypatch) -> None:
bar._root = root # noqa: SLF001
bar._running = True # noqa: SLF001
calls: list[bool] = []
- monkeypatch.setattr(
- overlay_module, "_win32_topmost_band_is_healthy", lambda _root: False
- )
+ monkeypatch.setattr(overlay_module, "_win32_topmost_band_is_healthy", lambda _root: False)
monkeypatch.setattr(bar, "_do_pin_topmost", lambda: calls.append(True) or "native")
bar._schedule_z_order_guard() # noqa: SLF001
@@ -282,9 +275,7 @@ def test_z_order_guard_leaves_healthy_win32_band_untouched(monkeypatch) -> None:
bar._root = root # noqa: SLF001
bar._running = True # noqa: SLF001
monkeypatch.setattr(overlay_module.sys, "platform", "win32")
- monkeypatch.setattr(
- overlay_module, "_win32_topmost_band_is_healthy", lambda _root: True
- )
+ monkeypatch.setattr(overlay_module, "_win32_topmost_band_is_healthy", lambda _root: True)
monkeypatch.setattr(
bar,
"_do_pin_topmost",
@@ -312,10 +303,13 @@ def test_z_order_guard_never_maps_hidden_bar(monkeypatch) -> None:
assert root.after_calls
-def test_do_show_reapplies_transparentcolor_and_alpha_after_topmost() -> None:
+def test_do_show_reapplies_transparentcolor_and_alpha_after_topmost(
+ monkeypatch,
+) -> None:
"""BUG-030 guard: the topmost re-assert must not leave the layered
color-key/alpha attributes un-reapplied — else a Windows-side drop of
those attributes on the style mutation shows as a black flash."""
+ monkeypatch.setattr(overlay_module.sys, "platform", "win32")
bar, root = _bar_with_fake_root()
bar._do_show() # noqa: SLF001
@@ -342,8 +336,12 @@ def test_do_show_composes_at_zero_alpha_before_becoming_visible() -> None:
zero_alpha = root.calls.index("wm_attributes:-alpha=0.0")
mapped = root.calls.index("deiconify")
composed = root.calls.index("update_idletasks")
- visible_alpha = len(root.calls) - 1 - root.calls[::-1].index(
- f"wm_attributes:-alpha={bar._opacity}" # noqa: SLF001
+ visible_alpha = (
+ len(root.calls)
+ - 1
+ - root.calls[::-1].index(
+ f"wm_attributes:-alpha={bar._opacity}" # noqa: SLF001
+ )
)
assert zero_alpha < mapped < composed < visible_alpha
assert root.attrs["-alpha"] == bar._opacity # noqa: SLF001
@@ -371,8 +369,12 @@ def test_do_show_resubmits_prepared_frame_while_alpha_is_zero() -> None:
refreshed = root.calls.index(f"itemconfig:7:{id(photo)}")
composed = root.calls.index("update_idletasks")
- visible_alpha = len(root.calls) - 1 - root.calls[::-1].index(
- f"wm_attributes:-alpha={bar._opacity}" # noqa: SLF001
+ visible_alpha = (
+ len(root.calls)
+ - 1
+ - root.calls[::-1].index(
+ f"wm_attributes:-alpha={bar._opacity}" # noqa: SLF001
+ )
)
assert refreshed < composed < visible_alpha
diff --git a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
index 477e92e2b5..462c7f2502 100644
--- a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
+++ b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
@@ -139,11 +139,26 @@ def test_text_and_mouth_methods_are_local_noops(monkeypatch) -> None:
def test_release_startup_gate_semantics_match_the_real_bar(monkeypatch) -> None:
surface, proc = _started_proxy(monkeypatch, startup_gated=True)
+ assert surface._visible is False
assert surface.release_startup_gate() is True
+ assert surface._visible 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_visibility_mirror_matches_bar_start_and_idle_semantics() -> None:
+ assert SubprocessBarOverlay(persistent=True, startup_gated=False)._visible is True
+ assert SubprocessBarOverlay(persistent=True, startup_gated=True)._visible is False
+ non_persistent = SubprocessBarOverlay(persistent=False, startup_gated=False)
+ assert non_persistent._visible is False
+ non_persistent._send = lambda _msg: None # type: ignore[method-assign]
+
+ non_persistent.show("listen")
+ assert non_persistent._visible is True
+ non_persistent.show("idle")
+ assert non_persistent._visible is False
+
+
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
@@ -157,12 +172,16 @@ def test_child_events_dispatch_to_bridge_callbacks(monkeypatch) -> None:
surface = SubprocessBarOverlay()
fired: list[tuple] = []
done = threading.Event()
+ surface.set_on_talk(lambda: fired.append(("talk",)))
+ surface.set_on_hangup(lambda: fired.append(("hangup",)))
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": "talk"}\n'
+ '{"event": "hangup"}\n'
'{"event": "mute_toggle"}\n'
'{"event": "feedback", "kind": "bar", "payload": {"a": 1}}\n'
"not json\n"
@@ -177,11 +196,79 @@ def test_child_events_dispatch_to_bridge_callbacks(monkeypatch) -> None:
monkeypatch.setattr(mod.subprocess, "Popen", _EventPopen)
surface.start_in_thread(timeout=2.0)
assert done.wait(timeout=2.0)
+ assert ("talk",) in fired
+ assert ("hangup",) in fired
assert ("mute",) in fired
assert ("feedback", "bar", {"a": 1}) in fired
assert ("show_window",) in fired
+class _FakeSpeechPipeline:
+ def __init__(self, *, session_active: bool) -> None:
+ self.session_active = session_active
+ self.talk_calls = 0
+ self.hangup_calls = 0
+
+ def is_session_active(self) -> bool:
+ return self.session_active
+
+ def request_voice_session(self) -> None:
+ self.talk_calls += 1
+
+ def request_hangup(self) -> None:
+ self.hangup_calls += 1
+
+
+def test_talk_event_executes_the_parent_pipeline(monkeypatch) -> None:
+ pipeline = _FakeSpeechPipeline(session_active=False)
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline)
+ surface = SubprocessBarOverlay()
+
+ surface._dispatch_event({"event": "talk"})
+
+ assert pipeline.talk_calls == 1
+ assert pipeline.hangup_calls == 0
+
+
+def test_hangup_event_closes_a_live_parent_session(monkeypatch) -> None:
+ pipeline = _FakeSpeechPipeline(session_active=True)
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline)
+ surface = SubprocessBarOverlay()
+
+ surface._dispatch_event({"event": "hangup"})
+
+ assert pipeline.hangup_calls == 1
+ assert pipeline.talk_calls == 0
+
+
+def test_hangup_event_escapes_a_stuck_active_parent_state(monkeypatch) -> None:
+ pipeline = _FakeSpeechPipeline(session_active=False)
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline)
+ surface = SubprocessBarOverlay()
+
+ surface._dispatch_event({"event": "hangup"})
+
+ assert pipeline.hangup_calls == 0
+ assert pipeline.talk_calls == 1
+
+
+def test_hangup_event_preserves_legacy_parent_pipeline_behavior(monkeypatch) -> None:
+ class _LegacyPipeline:
+ def __init__(self) -> None:
+ self.hangup_calls = 0
+
+ def request_hangup(self) -> None:
+ self.hangup_calls += 1
+
+ pipeline = _LegacyPipeline()
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline)
+ surface = SubprocessBarOverlay()
+
+ surface._dispatch_event({"event": "hangup"})
+
+ assert pipeline.hangup_calls == 1
+
+
def test_dead_host_degrades_to_noop_without_raising(monkeypatch) -> None:
surface, proc = _started_proxy(monkeypatch)
proc._returncode = 1 # the host died
@@ -399,6 +486,7 @@ def test_mascot_init_line_declares_surface_and_mascot_path(monkeypatch) -> None:
init = proc.sent()[0]
assert init == {"op": "init", "surface": "mascot", "mascot_path": "assets/m.png"}
assert surface._ready.is_set() # scripted ready event consumed
+ assert surface._visible is False # sticky=False mascot starts withdrawn
def test_bar_init_payload_is_unchanged_by_the_mascot_variant(monkeypatch) -> None:
diff --git a/tests/unit/ui/jarvisbar/test_surface_contract.py b/tests/unit/ui/jarvisbar/test_surface_contract.py
index d1089a4e8d..974e0abd64 100644
--- a/tests/unit/ui/jarvisbar/test_surface_contract.py
+++ b/tests/unit/ui/jarvisbar/test_surface_contract.py
@@ -1,5 +1,6 @@
"""JarvisBarOverlay must expose the duck-typed surface OrbBusBridge drives,
and every method must be safe to call before/without a Tk window."""
+
from __future__ import annotations
from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
@@ -18,6 +19,8 @@ REQUIRED = [
"start_mouth_animation",
"stop_mouth_animation",
"set_on_mute_toggle",
+ "set_on_talk",
+ "set_on_hangup",
"set_feedback_publisher",
"set_on_show_window",
"start_in_thread",
@@ -77,8 +80,12 @@ def test_methods_safe_without_tk_window():
bar.stop_mouth_animation()
bar.set_on_mute_toggle(lambda: None)
+ bar.set_on_talk(lambda: None)
+ bar.set_on_hangup(lambda: None)
bar.set_feedback_publisher(lambda k, d: None)
assert bar._on_mute_toggle is not None
+ assert bar._on_talk is not None
+ assert bar._on_hangup is not None
assert bar._feedback_publisher is not None
bar._on_reset_double_click() # _root None → safe no-op
diff --git a/tests/unit/ui/test_orb_bus_bridge.py b/tests/unit/ui/test_orb_bus_bridge.py
index 2d98527169..98dd11cbae 100644
--- a/tests/unit/ui/test_orb_bus_bridge.py
+++ b/tests/unit/ui/test_orb_bus_bridge.py
@@ -79,9 +79,7 @@ class _FakeOrb:
def stop_animation(self, name: str) -> None:
self.calls.append(("stop_animation", name))
- def show_listening_transcript(
- self, text: str = "", duration_ms: int = 30000
- ) -> None:
+ def show_listening_transcript(self, text: str = "", duration_ms: int = 30000) -> None:
self.calls.append(("show_listening_transcript", text))
def hide_comment(self) -> None:
@@ -113,6 +111,17 @@ class _FakeStartupGatedBar(_FakeBarWithExplicitReassert):
return True
+def test_tts_level_is_forwarded_to_cross_process_surface() -> None:
+ """The macOS surface cannot subscribe to the parent's process-local tap."""
+ orb = _FakeOrb()
+ bridge = OrbBusBridge(bus=_FakeBus(), orb=orb, idle_animations_enabled=False) # type: ignore[arg-type]
+
+ bridge._note_tts_level(0.73) # noqa: SLF001
+
+ assert ("set_level", 0.73) in orb.calls
+ assert bridge._last_tts_level_t > 0.0 # noqa: SLF001
+
+
async def test_orb_is_shown_again_for_thinking_after_external_hide() -> None:
orb = _FakeOrb()
bridge = OrbBusBridge(bus=_FakeBus(), orb=orb, idle_animations_enabled=False) # type: ignore[arg-type]
@@ -279,7 +288,10 @@ async def test_broadcast_boilerplate_is_not_shown_in_listening_bubble() -> None:
TranscriptionUpdate(text="Eine Sendung des NDR, 2020", is_final=False) # i18n-allow
)
- assert ("show_listening_transcript", "Eine Sendung des NDR, 2020") not in orb.calls # i18n-allow
+ assert (
+ "show_listening_transcript",
+ "Eine Sendung des NDR, 2020", # i18n-allow
+ ) not in orb.calls # i18n-allow
assert ("show_listening_transcript", "") in orb.calls
@@ -299,7 +311,8 @@ async def test_listening_bubble_mirrors_accumulating_pipeline_snapshots() -> Non
await bridge._on_transcription_update( # noqa: SLF001
TranscriptionUpdate(
- text="Hallo ich moechte einen langen Prompt", is_final=False # i18n-allow
+ text="Hallo ich moechte einen langen Prompt",
+ is_final=False, # i18n-allow
)
)
await bridge._on_transcription_update( # noqa: SLF001
@@ -797,7 +810,7 @@ async def test_listening_bubble_mirrors_pipeline_snapshot_one_to_one() -> None:
"Hallo",
"Hallo wie",
"Eine Sendung Hallo wie geht es dir",
- "Hallo wie geht es dir", # downward correction
+ "Hallo wie geht es dir", # downward correction
"Hallo wie geht es dir heute",
]
for snapshot in snapshots:
@@ -1073,9 +1086,7 @@ async def test_delayed_hide_withdraws_non_persistent_bar() -> None:
real session is unchanged. The persistence gate only spares the always-on
bar."""
orb = _FakeOrb()
- bridge = OrbBusBridge(
- bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=True
- ) # type: ignore[arg-type]
+ bridge = OrbBusBridge(bus=_FakeBus(), orb=orb, idle_animations_enabled=False, hide_on_idle=True) # type: ignore[arg-type]
bridge._last_state = "IDLE" # noqa: SLF001
await bridge._delayed_hide(0.0) # noqa: SLF001
@@ -1124,6 +1135,7 @@ async def test_mute_toggle_publishes_voice_mute_request() -> None:
callback()
# Give the scheduled coro a tick to run.
import asyncio
+
await asyncio.sleep(0.05)
assert len(seen) == 1
@@ -1162,6 +1174,7 @@ from jarvis.core.events import ( # noqa: E402
async def test_attach_injects_feedback_publisher_into_orb() -> None:
"""The bridge must inject its publisher via ``set_feedback_publisher``
so the orb can call back from the Tk thread."""
+
class _OrbWithFeedback(_FakeOrb):
def __init__(self) -> None:
super().__init__()
@@ -1204,6 +1217,7 @@ async def test_visible_feedback_publish_emits_event_with_correlation_id() -> Non
# Drain any pending threadsafe publishes scheduled via asyncio.
import asyncio
+
await asyncio.sleep(0.05)
assert len(seen) >= 1
@@ -1217,6 +1231,7 @@ async def test_visible_feedback_publish_emits_event_with_correlation_id() -> Non
async def test_reset_requested_dispatches_to_tk_thread() -> None:
"""L2 wiring: an OrbResetRequested bus event must call into the
orb's ``_on_reset_double_click`` via ``root.after(0, ...)``."""
+
class _Root:
def __init__(self) -> None:
self.after_calls: list = []
@@ -1247,6 +1262,7 @@ async def test_reset_requested_dispatches_to_tk_thread() -> None:
async def test_reset_requested_with_no_root_logs_and_returns() -> None:
"""Defensive: when the orb has no Tk root yet (boot race), the reset
request must NOT crash — the handler logs and returns."""
+
class _OrbNoRoot(_FakeOrb):
_root = None
diff --git a/tests/unit/ui/test_overlay_tk_interpreter_binding.py b/tests/unit/ui/test_overlay_tk_interpreter_binding.py
new file mode 100644
index 0000000000..1e90195727
--- /dev/null
+++ b/tests/unit/ui/test_overlay_tk_interpreter_binding.py
@@ -0,0 +1,148 @@
+"""Overlay images/fonts must belong to the Tcl interpreter that consumes them.
+
+The macOS companion host first creates a withdrawn bootstrap ``Tk`` root so
+Tk's ``TKApplication`` owns NSApp, then the selected bar/mascot creates its own
+root. Those are separate Tcl interpreters. Pillow/tkinter resources created
+without an explicit master silently attach to the bootstrap interpreter; using
+them on the overlay canvas then raises ``image \"pyimageN\" does not exist``.
+
+These tests are headless and platform-neutral: the fakes prove that both frame
+loops and the mascot bubble pass their actual consumer as the resource master.
+That keeps the fix active on macOS without changing Windows/Linux behaviour.
+"""
+
+from __future__ import annotations
+
+from PIL import Image, ImageTk
+
+
+class _Root:
+ def __init__(self) -> None:
+ self.scheduled: list[tuple[int, object]] = []
+
+ def after(self, delay_ms: int, callback: object) -> None:
+ self.scheduled.append((delay_ms, callback))
+
+
+class _Canvas:
+ def __init__(self) -> None:
+ self.created_with: object | None = None
+
+ def create_image(self, *_args: object, **kwargs: object) -> int:
+ self.created_with = kwargs.get("image")
+ return 1
+
+ def itemconfig(self, *_args: object, **_kwargs: object) -> None: ...
+
+
+class _Renderer:
+ def render(self, *_args: object, **_kwargs: object) -> Image.Image:
+ return Image.new("RGB", (4, 4), "magenta")
+
+
+def test_jarvisbar_frame_binds_photo_to_its_overlay_root(monkeypatch) -> None:
+ from jarvis.ui.jarvisbar.overlay import JarvisBarOverlay
+
+ root = _Root()
+ canvas = _Canvas()
+ masters: list[object] = []
+
+ def _photo(image: Image.Image, **kwargs: object) -> object:
+ assert image.size == (4, 4)
+ masters.append(kwargs.get("master"))
+ return object()
+
+ monkeypatch.setattr(ImageTk, "PhotoImage", _photo)
+ monkeypatch.setattr("jarvis.audio.level_tap.playback_active", lambda: False)
+
+ bar = JarvisBarOverlay.__new__(JarvisBarOverlay)
+ bar._running = True
+ bar._root = root
+ bar._canvas = canvas
+ bar._renderer = _Renderer()
+ bar._mode = "think"
+ bar._ext_level = 0.0
+ bar._last_audible_t = 0.0
+ bar._t0 = 0.0
+ bar._hovered = False
+ bar._muted = False
+ bar._mac_transparent = False
+ bar._static_tick_key = None
+ bar._static_tick_count = 0
+ bar._image_id = None
+ bar._photo = None
+ bar._last_frame_ns = 0
+
+ bar._schedule_frame()
+
+ assert masters == [root]
+ assert canvas.created_with is bar._photo
+ assert root.scheduled, "the normal frame-loop re-arm must remain intact"
+
+
+def test_mascot_frame_binds_photo_to_its_overlay_root(monkeypatch) -> None:
+ from ui.orb.overlay import OrbOverlay
+
+ root = _Root()
+ canvas = _Canvas()
+ masters: list[object] = []
+
+ def _photo(image: Image.Image, **kwargs: object) -> object:
+ assert image.size == (4, 4)
+ masters.append(kwargs.get("master"))
+ return object()
+
+ monkeypatch.setattr(ImageTk, "PhotoImage", _photo)
+
+ mascot = OrbOverlay.__new__(OrbOverlay)
+ mascot._running = True
+ mascot._root = root
+ mascot._canvas = canvas
+ mascot._renderer = _Renderer()
+ mascot._mode = "listen"
+ mascot._ext_level = 0.0
+ mascot._t0 = 0.0
+ mascot._mac_transparent = False
+ mascot._image_id = None
+ mascot._photo = None
+
+ mascot._schedule_frame()
+
+ assert masters == [root]
+ assert canvas.created_with is mascot._photo
+ assert root.scheduled, "the mascot animation loop must remain intact"
+
+
+def test_mascot_bubble_binds_named_fonts_to_its_toplevel(monkeypatch) -> None:
+ from ui.orb import overlay as orb_mod
+
+ class _Top:
+ def overrideredirect(self, _enabled: bool) -> None: ...
+
+ def wm_attributes(self, *_args: object) -> None: ...
+
+ def configure(self, **_kwargs: object) -> None: ...
+
+ def withdraw(self) -> None: ...
+
+ class _BubbleCanvas:
+ def pack(self, **_kwargs: object) -> None: ...
+
+ top = _Top()
+ font_roots: list[object] = []
+
+ monkeypatch.setattr(orb_mod.sys, "platform", "linux")
+ monkeypatch.setattr(orb_mod.tk, "Toplevel", lambda _parent: top)
+ monkeypatch.setattr(orb_mod.tk, "Canvas", lambda *_args, **_kwargs: _BubbleCanvas())
+ monkeypatch.setattr(orb_mod, "_hide_tk_window_from_task_switcher", lambda _top: None)
+
+ def _font(**kwargs: object) -> object:
+ font_roots.append(kwargs.get("root"))
+ return object()
+
+ monkeypatch.setattr(orb_mod.tkfont, "Font", _font)
+
+ bubble = orb_mod.OrbCommentBubble(parent=object(), orb_x=0, orb_y=0, orb_w=108, screen_w=1440)
+
+ assert bubble._top is top
+ assert font_roots == [top, top]
diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.py
index bc4a54b3fc..9e88e2e50c 100644
--- a/ui/orb/bus_bridge.py
+++ b/ui/orb/bus_bridge.py
@@ -342,10 +342,12 @@ class OrbBusBridge:
self._mic_level_unsub = mic_level.subscribe(self._on_mic_level)
except Exception as exc: # noqa: BLE001
log.warning("OrbBridge mic_level subscribe failed: %s", exc)
- # Track TTS-output activity so the (silent) mic does not clobber
- # Jarvis's voice level on the shared set_level while TTS plays. The
- # surface's OWN level_tap subscription does the actual SPEAKING
- # set_level; here we only note the recency.
+ # Track AND forward TTS output. In-process surfaces also subscribe
+ # to level_tap themselves, so this is a harmless duplicate there;
+ # the macOS bar/mascot live in a companion process and cannot see
+ # this process-local signal at all. Forwarding here is therefore
+ # load-bearing for cross-process speaking animation, while the
+ # recency timestamp still prevents the mic from clobbering it.
try:
from jarvis.audio import level_tap
@@ -370,9 +372,7 @@ class OrbBusBridge:
root = getattr(self._orb, "_root", None)
reset_fn = getattr(self._orb, "_on_reset_double_click", None)
if root is None or reset_fn is None:
- log.warning(
- "OrbBridge: reset requested but orb has no _root / _on_reset"
- )
+ log.warning("OrbBridge: reset requested but orb has no _root / _on_reset")
return
try:
root.after(0, lambda: reset_fn(None))
@@ -421,9 +421,7 @@ class OrbBusBridge:
the real loop, raising "bound to a different event loop" and leaving the
mic muted with the voice session frozen in LISTENING (2026-06-28).
"""
- coro = self._bus.publish(
- VoiceMuteToggleRequested(source="orb_dblclick_double")
- )
+ coro = self._bus.publish(VoiceMuteToggleRequested(source="orb_dblclick_double"))
self._marshal_publish(coro, label="mute-toggle")
def _publish_show_window(self) -> None:
@@ -638,8 +636,7 @@ class OrbBusBridge:
# a no-op or cut that animation short. Suppressing the *show* is the
# whole job — the orb simply stays hidden.
log.info(
- "OrbBridge: stray %s outside live session suppressed — "
- "mascot stays hidden.",
+ "OrbBridge: stray %s outside live session suppressed — mascot stays hidden.",
state,
)
return
@@ -783,9 +780,7 @@ class OrbBusBridge:
"""
if self._last_state != "LISTENING":
return
- if self._listening_transcript_text and getattr(
- self, "_completion_continuation", False
- ):
+ if self._listening_transcript_text and getattr(self, "_completion_continuation", False):
return
self._listening_transcript_text = ""
self._last_response_text = ""
@@ -853,9 +848,7 @@ class OrbBusBridge:
if state == "LISTENING":
self._show_listening_transcript(self._listening_transcript_text)
elif state in ("THINKING", "SPEAKING"):
- self._show_listening_transcript(
- self._last_response_text or THINKING_BUBBLE_TEXT
- )
+ self._show_listening_transcript(self._last_response_text or THINKING_BUBBLE_TEXT)
def _show_listening_transcript(self, text: str) -> None:
show_transcript = getattr(self._orb, "show_listening_transcript", None)
@@ -953,7 +946,8 @@ class OrbBusBridge:
if self._idle_task and not self._idle_task.done():
return
self._idle_task = asyncio.create_task(
- self._idle_loop(), name="orb-idle-animation-scheduler",
+ self._idle_loop(),
+ name="orb-idle-animation-scheduler",
)
def _cancel_idle_scheduler(self) -> None:
@@ -979,12 +973,21 @@ class OrbBusBridge:
_TTS_OWNS_BARS_S = 0.5 # mic is muted this long after the last TTS level
- def _note_tts_level(self, _level: float) -> None:
- """Recency tracker only: TTS just produced an output level, so it is
- making sound now. The surface's own ``level_tap`` subscription does the
- actual SPEAKING ``set_level``; we just remember the time so the mic does
- not clobber it."""
+ def _note_tts_level(self, level: float) -> None:
+ """Forward live TTS loudness and remember that Jarvis owns the bars.
+
+ ``level_tap`` is process-local. The Windows/Linux in-process overlays
+ subscribe directly, but the macOS companion surface cannot, so relying
+ on the surface's own subscription leaves its speaking bars flat. The
+ bridge already spans that process boundary through ``set_level``; send
+ the same normalized value through it and retain the recency guard that
+ suppresses simultaneous silent-mic updates.
+ """
self._last_tts_level_t = time.monotonic()
+ try:
+ self._orb.set_level(level)
+ except Exception: # noqa: BLE001
+ log.debug("TTS level forward to surface failed", exc_info=True)
def _on_mic_level(self, level: float) -> None:
"""Forward the live mic loudness to the active surface's bars.
@@ -997,10 +1000,11 @@ class OrbBusBridge:
state is LISTENING. Works for whichever surface is current."""
if time.monotonic() - self._last_tts_level_t < self._TTS_OWNS_BARS_S:
return # TTS is making sound → it drives the bars, not the silent mic
- candidate_listening = (
- self._wake_candidate_active
- and self._last_state in {"IDLE", "ERROR", "PAUSED"}
- )
+ candidate_listening = self._wake_candidate_active and self._last_state in {
+ "IDLE",
+ "ERROR",
+ "PAUSED",
+ }
if self._last_state != "LISTENING" and not candidate_listening:
return
try:
diff --git a/ui/orb/overlay.py b/ui/orb/overlay.py
index 794ca43fb3..9e0b7d8dea 100644
--- a/ui/orb/overlay.py
+++ b/ui/orb/overlay.py
@@ -98,6 +98,7 @@ class _DragState:
offset_y: int
moved: bool = False
+
# 108x108 — roughly 1/3 smaller than the old 160-px size
WIN_W = 108
WIN_H = 108
@@ -164,9 +165,7 @@ def key_to_alpha(img: Image.Image) -> Image.Image:
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)
+ alpha = np.where((arr == COLOR_KEY_RGB).all(axis=-1), 0, 255).astype(np.uint8)
return Image.fromarray(np.dstack((arr, alpha)), "RGBA")
@@ -454,10 +453,14 @@ class MascotRenderer:
}
left = _extract_from_bbox(
- cls.ARM_LEFT_BBOX, cls.ARM_LEFT_PIVOT, cls.ARM_LEFT_ERASE_BBOX,
+ cls.ARM_LEFT_BBOX,
+ cls.ARM_LEFT_PIVOT,
+ cls.ARM_LEFT_ERASE_BBOX,
)
right = _extract_from_bbox(
- cls.ARM_RIGHT_BBOX, cls.ARM_RIGHT_PIVOT, cls.ARM_RIGHT_ERASE_BBOX,
+ cls.ARM_RIGHT_BBOX,
+ cls.ARM_RIGHT_PIVOT,
+ cls.ARM_RIGHT_ERASE_BBOX,
)
# Body without arms: set all pixels inside the dilated arm region
@@ -567,8 +570,7 @@ class MascotRenderer:
inner_rx = max(0.6, rx - 1.4) * ss
inner_ry = max(0.4, ry - 1.4) * ss
draw.ellipse(
- [big_cx - inner_rx, big_cy - inner_ry,
- big_cx + inner_rx, big_cy + inner_ry],
+ [big_cx - inner_rx, big_cy - inner_ry, big_cx + inner_rx, big_cy + inner_ry],
fill=self.MOUTH_INNER_COLOR,
)
@@ -636,9 +638,10 @@ class MascotRenderer:
# (close to the mascot = brighter, outer edge = darker gold).
intensity = np.clip(
(self._glow_mask[halo_mask] - halo_threshold) / (1.0 - halo_threshold),
- 0.0, 1.0,
+ 0.0,
+ 1.0,
)
- # Gold-Gradient: dunkel-warm (80,50,0) → hell-gold (255,210,80)
+ # Gold gradient: dark warm (80, 50, 0) → bright gold (255, 210, 80)
frame[halo_mask, 0] = (80 + 175 * intensity).astype(np.uint8)
frame[halo_mask, 1] = (50 + 160 * intensity).astype(np.uint8)
frame[halo_mask, 2] = (0 + 80 * intensity).astype(np.uint8)
@@ -828,9 +831,7 @@ class MascotRenderer:
# The new canvas must be large enough that the maximum distance
# from the pivot to any sprite corner has room in every direction
# (otherwise the rotation clips sprite pixels).
- max_dist = int(math.ceil(math.hypot(
- max(px, sw - px), max(py, sh - py)
- )))
+ max_dist = int(math.ceil(math.hypot(max(px, sw - px), max(py, sh - py))))
canvas_size = 2 * max_dist + 4
canvas = Image.new("RGBA", (canvas_size, canvas_size), (0, 0, 0, 0))
# The sprite's pivot should land at the canvas center
@@ -999,8 +1000,7 @@ class OrbCommentBubble:
import logging
logging.getLogger("jarvis.orb").warning(
- "macOS -transparent unsupported — the comment bubble "
- "renders opaque"
+ "macOS -transparent unsupported — the comment bubble renders opaque"
)
top.configure(bg=COLOR_KEY_HEX)
else:
@@ -1024,11 +1024,22 @@ class OrbCommentBubble:
self._top = top
self._canvas = canvas
+ # Bind named fonts to this Toplevel's interpreter explicitly. The
+ # macOS host keeps a separate bootstrap Tk root alive before creating
+ # the mascot root; relying on tkinter's process-global default root
+ # would create the fonts in the wrong interpreter and make the bubble
+ # fail as soon as it tries to draw text.
self._font = tkfont.Font(
- family=BUBBLE_FONT_FAMILY, size=BUBBLE_FONT_SIZE, weight="bold"
+ root=top,
+ family=BUBBLE_FONT_FAMILY,
+ size=BUBBLE_FONT_SIZE,
+ weight="bold",
)
self._transcript_font = tkfont.Font(
- family=BUBBLE_FONT_FAMILY, size=TRANSCRIPT_BUBBLE_FONT_SIZE, weight="bold"
+ root=top,
+ family=BUBBLE_FONT_FAMILY,
+ size=TRANSCRIPT_BUBBLE_FONT_SIZE,
+ weight="bold",
)
def show(
@@ -1066,8 +1077,13 @@ class OrbCommentBubble:
# Probe text size by creating a throwaway text item and reading bbox.
probe_id = self._canvas.create_text(
- 0, 0, text=text, font=self._font, anchor="nw",
- width=BUBBLE_MAX_WIDTH, fill=BUBBLE_TEXT_HEX,
+ 0,
+ 0,
+ text=text,
+ font=self._font,
+ anchor="nw",
+ width=BUBBLE_MAX_WIDTH,
+ fill=BUBBLE_TEXT_HEX,
)
bbox = self._canvas.bbox(probe_id)
self._canvas.delete(probe_id)
@@ -1099,31 +1115,49 @@ class OrbCommentBubble:
self._canvas.delete("all")
self._draw_rounded_rect(
- 1, 1, bubble_w - 1, body_h - 1, BUBBLE_CORNER_RADIUS,
- fill=BUBBLE_BG_HEX, outline=BUBBLE_BORDER_HEX, width=BUBBLE_BORDER_WIDTH,
+ 1,
+ 1,
+ bubble_w - 1,
+ body_h - 1,
+ BUBBLE_CORNER_RADIUS,
+ fill=BUBBLE_BG_HEX,
+ outline=BUBBLE_BORDER_HEX,
+ width=BUBBLE_BORDER_WIDTH,
)
tail_base_y = body_h - 1
tail_points = [
- tail_tip_x - tail_half, tail_base_y,
- tail_tip_x + tail_half, tail_base_y,
- tail_tip_x, tail_base_y + BUBBLE_TAIL_H,
+ tail_tip_x - tail_half,
+ tail_base_y,
+ tail_tip_x + tail_half,
+ tail_base_y,
+ tail_tip_x,
+ tail_base_y + BUBBLE_TAIL_H,
]
self._canvas.create_polygon(
tail_points,
- fill=BUBBLE_BG_HEX, outline=BUBBLE_BORDER_HEX, width=BUBBLE_BORDER_WIDTH,
+ fill=BUBBLE_BG_HEX,
+ outline=BUBBLE_BORDER_HEX,
+ width=BUBBLE_BORDER_WIDTH,
)
# Hide the seam between body bottom and tail base.
self._canvas.create_line(
- tail_tip_x - tail_half + 1, tail_base_y,
- tail_tip_x + tail_half - 1, tail_base_y,
- fill=BUBBLE_BG_HEX, width=BUBBLE_BORDER_WIDTH + 1,
+ tail_tip_x - tail_half + 1,
+ tail_base_y,
+ tail_tip_x + tail_half - 1,
+ tail_base_y,
+ fill=BUBBLE_BG_HEX,
+ width=BUBBLE_BORDER_WIDTH + 1,
)
self._canvas.create_text(
- BUBBLE_PADDING_X, BUBBLE_PADDING_Y,
- text=text, font=self._font, anchor="nw",
- width=BUBBLE_MAX_WIDTH, fill=BUBBLE_TEXT_HEX,
+ BUBBLE_PADDING_X,
+ BUBBLE_PADDING_Y,
+ text=text,
+ font=self._font,
+ anchor="nw",
+ width=BUBBLE_MAX_WIDTH,
+ fill=BUBBLE_TEXT_HEX,
)
self._top.deiconify()
@@ -1132,17 +1166,11 @@ class OrbCommentBubble:
except tk.TclError:
pass
- self._show_until_t = time.perf_counter() + min(
- BUBBLE_MIN_SHOW_S, duration_ms / 1000.0
- )
+ self._show_until_t = time.perf_counter() + min(BUBBLE_MIN_SHOW_S, duration_ms / 1000.0)
self._dismiss_after_id = self._top.after(duration_ms, self.hide)
def _show_transcript(self, text: str, duration_ms: int) -> None:
- if (
- self._top is None
- or self._canvas is None
- or self._transcript_font is None
- ):
+ if self._top is None or self._canvas is None or self._transcript_font is None:
return
if self._dismiss_after_id is not None:
@@ -1201,24 +1229,38 @@ class OrbCommentBubble:
self._canvas.delete("all")
self._draw_rounded_rect(
- 1, 1, bubble_w - 1, body_h - 1, BUBBLE_CORNER_RADIUS,
- fill=BUBBLE_BG_HEX, outline=BUBBLE_BORDER_HEX, width=BUBBLE_BORDER_WIDTH,
+ 1,
+ 1,
+ bubble_w - 1,
+ body_h - 1,
+ BUBBLE_CORNER_RADIUS,
+ fill=BUBBLE_BG_HEX,
+ outline=BUBBLE_BORDER_HEX,
+ width=BUBBLE_BORDER_WIDTH,
)
tail_base_y = body_h - 1
tail_points = [
- tail_tip_x - tail_half, tail_base_y,
- tail_tip_x + tail_half, tail_base_y,
- tail_tip_x, tail_base_y + BUBBLE_TAIL_H,
+ tail_tip_x - tail_half,
+ tail_base_y,
+ tail_tip_x + tail_half,
+ tail_base_y,
+ tail_tip_x,
+ tail_base_y + BUBBLE_TAIL_H,
]
self._canvas.create_polygon(
tail_points,
- fill=BUBBLE_BG_HEX, outline=BUBBLE_BORDER_HEX, width=BUBBLE_BORDER_WIDTH,
+ fill=BUBBLE_BG_HEX,
+ outline=BUBBLE_BORDER_HEX,
+ width=BUBBLE_BORDER_WIDTH,
)
self._canvas.create_line(
- tail_tip_x - tail_half + 1, tail_base_y,
- tail_tip_x + tail_half - 1, tail_base_y,
- fill=BUBBLE_BG_HEX, width=BUBBLE_BORDER_WIDTH + 1,
+ tail_tip_x - tail_half + 1,
+ tail_base_y,
+ tail_tip_x + tail_half - 1,
+ tail_base_y,
+ fill=BUBBLE_BG_HEX,
+ width=BUBBLE_BORDER_WIDTH + 1,
)
self._canvas.create_text(
@@ -1274,12 +1316,46 @@ class OrbCommentBubble:
if self._canvas is None:
return 0
points = [
- x1 + r, y1, x1 + r, y1, x2 - r, y1, x2 - r, y1,
- x2, y1, x2, y1 + r, x2, y1 + r,
- x2, y2 - r, x2, y2 - r, x2, y2,
- x2 - r, y2, x2 - r, y2, x1 + r, y2, x1 + r, y2,
- x1, y2, x1, y2 - r, x1, y2 - r,
- x1, y1 + r, x1, y1 + r, x1, y1,
+ x1 + r,
+ y1,
+ x1 + r,
+ y1,
+ x2 - r,
+ y1,
+ x2 - r,
+ y1,
+ x2,
+ y1,
+ x2,
+ y1 + r,
+ x2,
+ y1 + r,
+ x2,
+ y2 - r,
+ x2,
+ y2 - r,
+ x2,
+ y2,
+ x2 - r,
+ y2,
+ x2 - r,
+ y2,
+ x1 + r,
+ y2,
+ x1 + r,
+ y2,
+ x1,
+ y2,
+ x1,
+ y2 - r,
+ x1,
+ y2 - r,
+ x1,
+ y1 + r,
+ x1,
+ y1 + r,
+ x1,
+ y1,
]
return self._canvas.create_polygon(points, smooth=True, **kwargs)
@@ -1410,8 +1486,7 @@ class OrbOverlay:
import logging
logging.getLogger("jarvis.orb").warning(
- "macOS -transparent unsupported — the mascot will show "
- "its key colour"
+ "macOS -transparent unsupported — the mascot will show its key colour"
)
self._root.configure(bg=COLOR_KEY_HEX)
else:
@@ -1468,9 +1543,7 @@ class OrbOverlay:
# the orb at the primary anchor and migrate after a brief
# visible flash. Single-monitor and primary-pin boots
# skip the flash entirely (no visual noise in 99% case).
- resolved_screen = next(
- (s for s in screens if s.name == placement.monitor), None
- )
+ resolved_screen = next((s for s in screens if s.name == placement.monitor), None)
if (
len(screens) > 1
and resolved_screen is not None
@@ -1481,13 +1554,9 @@ class OrbOverlay:
placement.abs_x,
placement.abs_y,
)
- self._root.geometry(
- f"{WIN_W}x{WIN_H}+{primary_anchor.x}+{primary_anchor.y}"
- )
+ self._root.geometry(f"{WIN_W}x{WIN_H}+{primary_anchor.x}+{primary_anchor.y}")
else:
- self._root.geometry(
- f"{WIN_W}x{WIN_H}+{placement.abs_x}+{placement.abs_y}"
- )
+ self._root.geometry(f"{WIN_W}x{WIN_H}+{placement.abs_x}+{placement.abs_y}")
else:
# Monitor gone, no screens, or pin on non-primary monitor
# while require_primary is set — fall back to default and
@@ -1587,6 +1656,7 @@ class OrbOverlay:
if self._mic_reactive:
try:
from ui.orb.mic_listener import MicListener
+
self._mic = MicListener(on_level=self.set_level)
self._mic.start()
except Exception as exc:
@@ -1605,9 +1675,11 @@ class OrbOverlay:
taskbar = get_taskbar_info()
tray_rect = get_tray_notify_rect()
return compute_mascot_position(
- screen_w, screen_h,
+ screen_w,
+ screen_h,
mascot_size=WIN_W,
- taskbar=taskbar, tray_rect=tray_rect,
+ taskbar=taskbar,
+ tray_rect=tray_rect,
tray_safe_margin_px=TRAY_SAFE_MARGIN_PX,
right_edge_margin_px=RIGHT_EDGE_MARGIN_PX,
overlap_px=TASKBAR_OVERLAP_PX,
@@ -1779,9 +1851,7 @@ class OrbOverlay:
# The Tk thread must not crash on a downstream bus hiccup.
import logging
- logging.getLogger("jarvis.orb").warning(
- "orb show-window callback raised: %r", exc
- )
+ logging.getLogger("jarvis.orb").warning("orb show-window callback raised: %r", exc)
def _on_mute_double_click(self, _event: tk.Event) -> None:
"""First half of the mute gesture: increment a counter and arm a
@@ -1895,9 +1965,7 @@ class OrbOverlay:
if self._comment_bubble is not None:
self._comment_bubble.update_anchor(anchor.x, anchor.y, screen_w)
- def _monitor_at_orb_center(
- self, screens: list
- ) -> tuple[tuple[int, int, int, int], str]:
+ def _monitor_at_orb_center(self, screens: list) -> tuple[tuple[int, int, int, int], str]:
"""Return (geometry, device_name) of the monitor containing the orb center."""
cx = self._mascot_x + WIN_W // 2
cy = self._mascot_y + WIN_H // 2
@@ -2020,6 +2088,7 @@ class OrbOverlay:
publisher(mode, observed)
except Exception: # noqa: BLE001
import logging
+
logging.getLogger("jarvis.orb").debug(
"feedback publisher raised; suppressed", exc_info=True
)
@@ -2033,9 +2102,7 @@ class OrbOverlay:
remaining_s = self._show_until_t - now
if remaining_s > 0.001:
wait_ms = max(1, int(round(remaining_s * 1000)))
- self._pending_hide_after_id = self._root.after(
- wait_ms, self._actually_hide
- )
+ self._pending_hide_after_id = self._root.after(wait_ms, self._actually_hide)
else:
self._actually_hide()
@@ -2100,16 +2167,12 @@ class OrbOverlay:
return
self._enqueue_ui(lambda: bubble.show(text, duration_ms))
- def show_listening_transcript(
- self, text: str = "", duration_ms: int = 30000
- ) -> None:
+ def show_listening_transcript(self, text: str = "", duration_ms: int = 30000) -> None:
"""Show the larger live transcript bubble used while the user speaks."""
bubble = self._comment_bubble
if bubble is None:
return
- self._enqueue_ui(
- lambda: bubble.show(text, duration_ms, variant="transcript")
- )
+ self._enqueue_ui(lambda: bubble.show(text, duration_ms, variant="transcript"))
def hide_comment(self) -> None:
"""Hide the speech bubble immediately. Thread-safe."""
@@ -2120,6 +2183,7 @@ class OrbOverlay:
def start_mouth_animation(self, duration_ms: int = 60000) -> None:
"""Run the mascot's open/close mouth animation for `duration_ms`."""
+
def _start() -> None:
renderer = self._renderer
if renderer is not None and hasattr(renderer, "start_mouth_anim"):
@@ -2130,6 +2194,7 @@ class OrbOverlay:
def stop_mouth_animation(self) -> None:
"""Immediately stop the mouth animation. Thread-safe."""
+
def _stop() -> None:
renderer = self._renderer
if renderer is not None and hasattr(renderer, "stop_mouth_anim"):
@@ -2160,9 +2225,11 @@ class OrbOverlay:
return
if name not in ANIMATION_REGISTRY:
import logging
+
logging.getLogger("jarvis.orb").warning(
"play_animation(%r) unknown — available: %s",
- name, sorted(ANIMATION_REGISTRY),
+ name,
+ sorted(ANIMATION_REGISTRY),
)
return
renderer = self._renderer
@@ -2174,8 +2241,10 @@ class OrbOverlay:
renderer.add_animation(anim)
except Exception:
import logging
+
logging.getLogger("jarvis.orb").exception(
- "play_animation(%r) failed", name,
+ "play_animation(%r) failed",
+ name,
)
self._enqueue_ui(_start)
@@ -2243,17 +2312,20 @@ class OrbOverlay:
mascot_path = _resolve_mascot_path(self._mascot_path_hint)
if mascot_path is None:
import logging
+
logging.getLogger("jarvis.orb").warning(
"Mascot style requested but PNG not found "
"(looked in: %s, ENV JARVIS_ORB_MASCOT_PATH, %s) — "
"overlay will stay hidden.",
- self._mascot_path_hint, DEFAULT_MASCOT_REL,
+ self._mascot_path_hint,
+ DEFAULT_MASCOT_REL,
)
return None
try:
return MascotRenderer(mascot_path)
except Exception as exc: # noqa: BLE001
import logging
+
logging.getLogger("jarvis.orb").warning(
"MascotRenderer init failed (%s); overlay will stay hidden.",
exc,
@@ -2316,6 +2388,7 @@ class OrbOverlay:
running into a None root.
"""
import logging
+
_log = logging.getLogger("jarvis.orb")
if sys.platform == "darwin":
@@ -2332,6 +2405,7 @@ class OrbOverlay:
# pythonw.exe has no stdout → print goes nowhere. The logger
# writes to the watchdog log and makes silent deaths visible.
_log.exception("Orb thread start failed: %s", exc)
+
t = threading.Thread(target=_run, name="orb-tk-mainloop", daemon=True)
t.start()
ok = self._started.wait(timeout=timeout)
@@ -2354,12 +2428,14 @@ class OrbOverlay:
img = key_to_alpha(img)
# The PhotoImage must be kept as self._photo — otherwise Tkinter
- # garbage-collects the image before it gets rendered.
- self._photo = ImageTk.PhotoImage(img)
+ # garbage-collects the image before it gets rendered. It must also be
+ # created in this root's Tcl interpreter: the macOS companion process
+ # keeps a separate bootstrap Tk root alive to initialize NSApp, so an
+ # unqualified PhotoImage lands in that other interpreter and the mascot
+ # canvas reports ``image \"pyimageN\" does not exist``.
+ self._photo = ImageTk.PhotoImage(img, master=self._root)
if self._image_id is None:
- self._image_id = self._canvas.create_image(
- 0, 0, anchor="nw", image=self._photo
- )
+ self._image_id = self._canvas.create_image(0, 0, anchor="nw", image=self._photo)
else:
self._canvas.itemconfig(self._image_id, image=self._photo)
@@ -2405,8 +2481,7 @@ def main() -> int:
type=str,
default=None,
help=(
- "Optional: explicit path to a mascot PNG "
- "(otherwise assets/icons/jarvis-gigi-256.png)."
+ "Optional: explicit path to a mascot PNG (otherwise assets/icons/jarvis-gigi-256.png)."
),
)
parser.add_argument(
@@ -2415,8 +2490,7 @@ def main() -> int:
default=None,
help=(
"Visual QA: plays a specific animation in an endless loop "
- "(implies --mascot --sticky). Available: "
- + ", ".join(sorted(ANIMATION_REGISTRY))
+ "(implies --mascot --sticky). Available: " + ", ".join(sorted(ANIMATION_REGISTRY))
),
)
parser.add_argument(
@@ -2460,8 +2534,10 @@ def main() -> int:
time.sleep(wait + 0.6)
if cls.duration <= 0:
overlay.stop_animation(args.animation)
+
threading.Thread(target=_loop_anim, daemon=True).start()
elif args.all_animations:
+
def _all_demo() -> None:
overlay._started.wait(timeout=5.0)
overlay.show(mode="listen")
@@ -2474,6 +2550,7 @@ def main() -> int:
if cls.duration <= 0:
overlay.stop_animation(name)
time.sleep(0.3)
+
threading.Thread(target=_all_demo, daemon=True).start()
else:
# Classic demo (shows the listen/speak switch) when nothing is specified.