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.

feat(pets): pet style in the floating orb window

rubenluetke10-beepad482113483f
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 344181361c..9e13869b5a 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -140,6 +140,25 @@ _REALTIME_WARM_MIN_INTERVAL_S = 20.0
_BACKEND_MIN_UPTIME_FOR_RECOVERY_S = 120.0
+def _clamp_pet_scale(value: object) -> float:
+ """``[ui] pet_scale`` as a usable multiplier: 0.5–2.0, 1.0 when unusable."""
+ import math
+
+ try:
+ scale = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return 1.0
+ if not math.isfinite(scale):
+ return 1.0
+ return max(0.5, min(2.0, scale))
+
+
+def _pet_toggle_hotkey(cfg: Any) -> str:
+ """``[trigger] hotkey_pet_toggle``, stripped; empty when unset or disabled."""
+ value = getattr(getattr(cfg, "trigger", None), "hotkey_pet_toggle", "")
+ return str(value or "").strip()
+
+
def boot_overlay_style(configured: str | None, *, instance: Any | None = None) -> str:
"""The on-screen overlay style this process boots with.
@@ -1972,6 +1991,7 @@ class DesktopApp:
# the window is still rendering. See the note at the top of _run_backend.
from jarvis.brain.factory import build_default_brain
from jarvis.core.events import (
+ ComposeRequested,
ErrorOccurred,
MessageSent,
ResponseGenerated,
@@ -2595,6 +2615,9 @@ class DesktopApp:
# handler runs on the asyncio loop and immediately thread-hops, because
# pywebview calls block their calling thread (see _on_show_window_requested).
server.bus.subscribe(ShowWindowRequested, self._on_show_window_requested)
+ # The pet's pen asks for a fresh chat: the window comes up through the
+ # very same off-loop path; the frontend opens the new chat itself.
+ server.bus.subscribe(ComposeRequested, self._on_show_window_requested)
self._install_focus_route(server)
# Workflow system (Phase 6) — store + runner + scheduler. Its own
@@ -3364,6 +3387,7 @@ class DesktopApp:
surface = SubprocessMascotOverlay(
mascot_path=self.cfg.ui.orb_mascot_path or None,
style=style,
+ **self._pet_surface_kwargs(),
)
surface.start_in_thread()
logger.info(
@@ -3403,10 +3427,105 @@ class DesktopApp:
mic_reactive=False,
style=style,
mascot_path=self.cfg.ui.orb_mascot_path or None,
+ **self._pet_surface_kwargs(),
)
surface.start_in_thread()
return surface
+ def _pet_surface_kwargs(self) -> dict[str, object]:
+ """The pet's ``[ui]`` settings for the orb window (``docs/pets.md``).
+
+ Passed to every orb-window surface, not only a pet one: a live swap to
+ the pet style reuses the same window, which must already know them.
+ """
+ from jarvis.ui.pets.states import DEFAULT_PET_ID
+
+ ui = self.cfg.ui
+ return {
+ "pet_id": str(getattr(ui, "pet_id", DEFAULT_PET_ID) or DEFAULT_PET_ID),
+ "pet_scale": _clamp_pet_scale(getattr(ui, "pet_scale", 1.0)),
+ "pet_bubble": bool(getattr(ui, "pet_bubble", True)),
+ }
+
+ def _hide_on_idle_for(self, style: str) -> bool:
+ """The bridge's idle regime for one overlay style.
+
+ The bar follows "show at all times"; a persistent orb style (the pet)
+ stays up while idle; the mascot and the voice orb pop up per session.
+ """
+ from jarvis.ui.overlay_styles import PERSISTENT_ORB_STYLES
+
+ if style == "jarvis_bar":
+ return not bool(getattr(self.cfg.ui, "bar_persistent", True))
+ return style not in PERSISTENT_ORB_STYLES
+
+ def _pet_call(self, method: str, *args: object) -> bool:
+ """Call a pet surface method on the live overlay. True when it ran."""
+ from loguru import logger
+
+ fn = getattr(getattr(self, "_orb", None), method, None)
+ if not callable(fn):
+ return False
+ try:
+ fn(*args)
+ except Exception as exc: # noqa: BLE001 — cosmetic; the setting is stored
+ logger.opt(exception=exc).warning("pet surface call {} failed", method)
+ return False
+ return True
+
+ def set_pet(self, pet_id: str) -> dict[str, object]:
+ """Switch the desktop pet live (``PUT /api/pets/active``).
+
+ Updates ``[ui] pet_id`` in memory (the route persists it) and swaps the
+ figure on the running orb window. ``applied_live`` is False when there
+ is no orb window to swap it on — the choice then applies at the next
+ start or the next switch to the pet style.
+ """
+ from loguru import logger
+
+ from jarvis.ui.pets.states import NO_PET_ID
+
+ pet = str(pet_id or "").strip() or NO_PET_ID
+ try:
+ self.cfg.ui.pet_id = pet
+ except Exception as exc: # noqa: BLE001
+ logger.warning("pet_id not stored in config: {}", exc)
+ return {"ok": True, "applied_live": self._pet_call("set_pet", pet)}
+
+ def set_pet_look(
+ self, scale: float | None = None, bubble: bool | None = None
+ ) -> dict[str, object]:
+ """Apply the pet's size and status-bubble switch live (``PUT /api/pets/settings``)."""
+ from loguru import logger
+
+ clamped = None if scale is None else _clamp_pet_scale(scale)
+ flag = None if bubble is None else bool(bubble)
+ try:
+ if clamped is not None:
+ self.cfg.ui.pet_scale = clamped
+ if flag is not None:
+ self.cfg.ui.pet_bubble = flag
+ except Exception as exc: # noqa: BLE001
+ logger.warning("pet look not stored in config: {}", exc)
+ return {"ok": True, "applied_live": self._pet_call("set_pet_look", clamped, flag)}
+
+ def set_pet_visible(self, visible: bool) -> dict[str, object]:
+ """Hide or show the pet for this run (``POST /api/pets/visibility``).
+
+ Runtime only by design, like the shortcut: nothing is written, and the
+ pet is back at the next start.
+ """
+ return {"ok": True, "applied_live": self._pet_call("set_visible", bool(visible))}
+
+ def pet_visible(self) -> bool:
+ """Is the pet shown for this run? False only after the user hid it.
+
+ Read by ``GET /api/pets``. A surface without the flag (the bar,
+ ``NullOverlay``, no overlay at all) reports True: nothing hid a pet.
+ """
+ hidden = getattr(getattr(self, "_orb", None), "pet_user_hidden", None)
+ return not hidden if isinstance(hidden, bool) else True
+
def set_bar_persistent(self, enabled: bool) -> dict[str, object]:
"""Live-toggle 'show bar at all times' (bar_persistent) without a restart.
@@ -3529,7 +3648,11 @@ class DesktopApp:
"""
from loguru import logger
- from jarvis.ui.overlay_styles import ORB_STYLES, OVERLAY_STYLES
+ from jarvis.ui.overlay_styles import (
+ ORB_STYLES,
+ OVERLAY_STYLES,
+ PERSISTENT_ORB_STYLES,
+ )
style = (style or "jarvis_bar").strip()
if style not in OVERLAY_STYLES:
@@ -3550,10 +3673,19 @@ class DesktopApp:
# transition needs a restart (a second tk.Tk() root would abort the
# process — BUG-031).
if style in ORB_STYLES and old is not None and hasattr(old, "set_style"):
+ previous = str(getattr(self.cfg.ui, "orb_style", "") or "")
old.set_style(style)
for key in [k for k, v in cache.items() if v is old]:
cache.pop(key, None)
cache[style] = old
+ # The idle regime travels with the look: the pet stays up
+ # while idle, the mascot and the voice orb pop up per session.
+ bridge._hide_on_idle = self._hide_on_idle_for(style)
+ mode = str(getattr(old, "_mode", "idle") or "idle")
+ if style in PERSISTENT_ORB_STYLES:
+ old.show(mode)
+ elif previous in PERSISTENT_ORB_STYLES and mode == "idle":
+ old.hide()
try:
self.cfg.ui.orb_style = style # best-effort in-memory
except Exception: # noqa: BLE001
@@ -3582,13 +3714,16 @@ class DesktopApp:
bridge.set_surface(new)
self._orb = new
+ bridge._hide_on_idle = self._hide_on_idle_for(style)
if old is not None and old is not new:
try:
old.hide()
except Exception: # noqa: BLE001
logger.debug("old overlay hide failed", exc_info=True)
try:
- if style == "jarvis_bar" and self.cfg.ui.bar_persistent:
+ if (
+ style == "jarvis_bar" and self.cfg.ui.bar_persistent
+ ) or style in PERSISTENT_ORB_STYLES:
new.show("idle")
except Exception: # noqa: BLE001
logger.debug("post-swap show failed", exc_info=True)
@@ -3978,11 +4113,23 @@ class DesktopApp:
orb_style,
gate_until_voice_ready=(orb_style == "jarvis_bar"),
)
- hide_on_idle = (
- (not self.cfg.ui.bar_persistent) if orb_style == "jarvis_bar" else True
+ hide_on_idle = self._hide_on_idle_for(orb_style)
+ bridge = OrbBusBridge(
+ bus=bus,
+ orb=surface,
+ hide_on_idle=hide_on_idle,
+ # The pet's bubble headers follow the interface language
+ # (and UiLanguageChanged live, inside the bridge).
+ language=str(getattr(self.cfg.ui, "language", "") or "") or None,
)
- bridge = OrbBusBridge(bus=bus, orb=surface, hide_on_idle=hide_on_idle)
bridge.attach()
+ if not hide_on_idle and orb_style != "jarvis_bar":
+ # A persistent orb style (the pet) is on screen from the
+ # start; the bar keeps its voice-ready gate instead.
+ try:
+ surface.show("idle")
+ except Exception: # noqa: BLE001 — cosmetic; never block boot
+ logger.debug("persistent overlay boot reveal failed", exc_info=True)
self._orb = surface
self._bridge = bridge
# Cache the boot surface so a later swap back to it reuses the
@@ -4280,6 +4427,10 @@ class DesktopApp:
if self.cfg.trigger.hotkey_paste_last.strip()
else ()
),
+ # "Hide / show the desktop pet" (docs/pets.md). Armed here like
+ # every other editable shortcut; its dispatch publishes
+ # PetVisibilityToggleRequested, which the bridge forwards.
+ pet_toggle_hotkeys=tuple(filter(None, (_pet_toggle_hotkey(self.cfg),))),
dictate_mode=self.cfg.dictation.mode,
dictation_config=self.cfg.dictation,
hangup_hotkeys=(
@@ -6143,6 +6294,10 @@ class DesktopApp:
# Always-on bar: the tray-minimise must not disturb it.
if bool(getattr(self.cfg.ui, "bar_persistent", True)):
return
+ # The pet is always-on by nature: a companion that vanished whenever
+ # the app went to the tray would be exactly the pop-up it is not.
+ if not self._hide_on_idle_for(str(getattr(self.cfg.ui, "orb_style", "") or "")):
+ return
bar = getattr(self, "_orb", None)
bridge = getattr(self, "_bridge", None)
if bar is None or bridge is None:
@@ -6177,13 +6332,16 @@ class DesktopApp:
orb_style = getattr(self.cfg.ui, "orb_style", "jarvis_bar") or "jarvis_bar"
persistent = bool(getattr(self.cfg.ui, "bar_persistent", True))
is_bar = orb_style == "jarvis_bar"
- bridge._hide_on_idle = (not persistent) if is_bar else True
+ bridge._hide_on_idle = self._hide_on_idle_for(orb_style)
if hasattr(bar, "_persistent"):
bar._persistent = persistent
+ show = getattr(bar, "show", None)
if is_bar and persistent:
- show = getattr(bar, "show", None)
if callable(show):
show("idle")
+ elif not is_bar and not bridge._hide_on_idle and callable(show):
+ # The pet comes back with the window, in whatever it is doing.
+ show(str(getattr(bar, "_mode", "idle") or "idle"))
except Exception: # noqa: BLE001
from loguru import logger
diff --git a/jarvis/ui/jarvisbar/host.py b/jarvis/ui/jarvisbar/host.py
index 5ac0fd5da7..028e741abd 100644
--- a/jarvis/ui/jarvisbar/host.py
+++ b/jarvis/ui/jarvisbar/host.py
@@ -16,14 +16,15 @@ Protocol (UTF-8, one JSON object per line):
the ``OrbBusBridge`` surface API (``show``, ``hide``, ``set_level``, ...).
An optional ``"surface"`` key selects what the host renders:
``"jarvis_bar"`` (default) or ``"mascot"`` (the OrbOverlay window, whose look
- comes from the optional ``"style"`` key — ``"mascot"`` or ``"voice_orb"`` —
- plus an optional ``"mascot_path"`` passthrough).
+ comes from the optional ``"style"`` key — ``"mascot"``, ``"voice_orb"`` or
+ ``"pet"`` — plus optional ``"mascot_path"``, ``"pet_id"``, ``"pet_scale"`` and
+ ``"pet_bubble"`` passthroughs).
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 surface
is initialized, plus user interactions (``talk``, ``hangup``,
- ``mute_toggle``, ``feedback``, ``show_window``, ``drop``). Logging goes to
- stderr so stdout stays pure protocol.
+ ``mute_toggle``, ``feedback``, ``show_window``, ``drop``, and the pet's
+ ``compose``). Logging goes to stderr so stdout stays pure protocol.
``drop`` is the one round trip: the child forwards a file/text dropped on the
hosted surface, the parent runs the intake (the brain lives there), and the
@@ -157,6 +158,29 @@ def dispatch(surface: Any, msg: dict[str, Any]) -> bool:
elif op == "reset_position":
# The double-click reset seam.
_call(surface, "_on_reset_double_click")
+ # The desktop pet's surface methods (docs/pets.md); the bar has none of
+ # them, so there each degrades to the no-op _call() logs.
+ elif op == "set_pet":
+ _call(surface, "set_pet", str(msg.get("pet_id") or ""))
+ elif op == "set_pet_look":
+ scale = msg.get("scale")
+ bubble = msg.get("bubble")
+ _call(
+ surface,
+ "set_pet_look",
+ None if scale is None else float(scale),
+ None if bubble is None else bool(bubble),
+ )
+ elif op == "set_pet_outcome":
+ _call(surface, "set_pet_outcome", str(msg.get("kind", "")))
+ elif op == "show_status":
+ _call(surface, "show_status", str(msg.get("header", "")), str(msg.get("line", "")))
+ elif op == "set_speaker_muted":
+ _call(surface, "set_speaker_muted", bool(msg.get("muted", False)))
+ elif op == "set_visible":
+ _call(surface, "set_visible", bool(msg.get("visible", True)))
+ elif op == "toggle_visible":
+ _call(surface, "toggle_visible")
else:
log.warning("bar-host: unknown op %r", op)
return True
@@ -234,6 +258,7 @@ class _EchoBar:
def set_feedback_publisher(self, cb: Any) -> None: ...
def set_on_show_window(self, cb: Any) -> None: ...
def set_on_speaker_toggle(self, cb: Any) -> None: ...
+ def set_on_compose(self, cb: Any) -> None: ...
def __getattr__(self, name: str) -> Any:
if name.startswith("__"):
@@ -330,14 +355,18 @@ def _build_surface(cfg: dict[str, Any]) -> Any:
# skips this: QApplication must own its own Cocoa lifecycle.
_hide_dock_icon()
orb_overlay_cls = _import_orb_overlay()
+ pet_scale = cfg.get("pet_scale")
return orb_overlay_cls(
sticky=False,
mic_reactive=False,
- # The look inside the orb window (mascot / voice_orb). Forwarded
- # verbatim; OrbOverlay owns the one list of known styles and falls
- # back to the mascot for anything it does not recognise.
+ # The look inside the orb window (mascot / voice_orb / pet).
+ # Forwarded verbatim; OrbOverlay owns the one list of known styles
+ # and falls back to the mascot for anything it does not recognise.
style=str(cfg.get("style") or "mascot"),
mascot_path=cfg.get("mascot_path") or None,
+ pet_id=cfg.get("pet_id") or None,
+ pet_scale=1.0 if pet_scale is None else float(pet_scale),
+ pet_bubble=bool(cfg.get("pet_bubble", True)),
)
kwargs = {
key: cfg[key]
@@ -405,6 +434,9 @@ def _wire_surface_events(surface: Any) -> None:
lambda kind, payload: emit("feedback", kind=kind, payload=payload),
)
_call(surface, "set_on_show_window", lambda: emit("show_window"))
+ # The pet's pen: raising the window (and the new chat) happens in the
+ # parent, where the bus and the window live.
+ _call(surface, "set_on_compose", lambda: emit("compose"))
_wire_drop_forwarding()
diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.py
index b2a9ae3cf0..fe83e23ff1 100644
--- a/jarvis/ui/jarvisbar/subprocess_overlay.py
+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py
@@ -694,23 +694,39 @@ class SubprocessMascotOverlay(SubprocessBarOverlay):
Same spawn / ready / EOF-degrade plumbing as the bar proxy — the host
process picks the surface from the init line's ``"surface"`` key and the
- look from ``"style"`` (``mascot`` or ``voice_orb``). Unlike the bar (which
- draws no text bubble and no mouth), the orb window renders all of them, so
- the text/mouth/animation ops are FORWARDED over stdio instead of no-opped
- locally.
+ look from ``"style"`` (``mascot``, ``voice_orb`` or ``pet``). Unlike the bar
+ (which draws no text bubble and no mouth), the orb window renders all of
+ them, so the text/mouth/animation ops are FORWARDED over stdio instead of
+ no-opped locally. The pet's surface methods (``docs/pets.md``) travel the
+ same way, and its pen comes back up as the ``compose`` event.
"""
_EVENTS_THREAD_NAME = "orb-host-events"
_STDERR_THREAD_NAME = "orb-host-stderr"
_RESPAWN_THREAD_NAME = "orb-host-respawn"
- def __init__(self, mascot_path: str | None = None, style: str = "mascot") -> None:
+ def __init__(
+ self,
+ mascot_path: str | None = None,
+ style: str = "mascot",
+ pet_id: str | None = None,
+ pet_scale: float = 1.0,
+ pet_bubble: bool = True,
+ ) -> None:
super().__init__()
self._mascot_path = mascot_path
self._style = str(style or "mascot")
# OrbOverlay(sticky=False) always starts withdrawn. The base proxy's
# persistent-bar visibility default does not apply to this surface.
self._visible = False
+ # The pet's settings ride the init line (a respawn restores them) and
+ # its runtime mirrors are replayed by _reapply_desired_state.
+ self._pet_id = pet_id
+ self._pet_scale = float(pet_scale)
+ self._pet_bubble = bool(pet_bubble)
+ self._speaker_muted = False
+ self._user_visible = True
+ self._on_compose: Callable[[], None] | None = None
def _init_payload(self) -> dict[str, Any]:
return {
@@ -718,8 +734,86 @@ class SubprocessMascotOverlay(SubprocessBarOverlay):
"surface": "mascot",
"style": self._style,
"mascot_path": self._mascot_path,
+ "pet_id": self._pet_id,
+ "pet_scale": self._pet_scale,
+ "pet_bubble": self._pet_bubble,
}
+ @property
+ def wants_status_lines(self) -> bool:
+ """True when the hosted window is the pet, which shows status lines."""
+ return self._style == "pet"
+
+ @property
+ def keeps_visible_when_idle(self) -> bool:
+ """True when the hosted window is the pet, which stays up while idle."""
+ return self._style == "pet"
+
+ @property
+ def pet_user_hidden(self) -> bool:
+ """True while the user hid the pet (this proxy's best knowledge)."""
+ return not self._user_visible
+
+ def set_pet(self, pet_id: str) -> None:
+ self._pet_id = str(pet_id or "")
+ self._send({"op": "set_pet", "pet_id": self._pet_id})
+
+ def set_pet_look(self, scale: float | None = None, bubble: bool | None = None) -> None:
+ if scale is not None:
+ self._pet_scale = float(scale)
+ if bubble is not None:
+ self._pet_bubble = bool(bubble)
+ self._send(
+ {
+ "op": "set_pet_look",
+ "scale": None if scale is None else float(scale),
+ "bubble": None if bubble is None else bool(bubble),
+ }
+ )
+
+ def set_pet_outcome(self, kind: str) -> None:
+ self._send({"op": "set_pet_outcome", "kind": str(kind)})
+
+ def show_status(self, header: str = "", line: str = "") -> None:
+ self._send({"op": "show_status", "header": str(header), "line": str(line)})
+
+ def set_speaker_muted(self, muted: bool) -> None:
+ self._speaker_muted = bool(muted)
+ self._send({"op": "set_speaker_muted", "muted": self._speaker_muted})
+
+ def set_visible(self, visible: bool) -> None:
+ self._user_visible = bool(visible)
+ self._send({"op": "set_visible", "visible": self._user_visible})
+
+ def toggle_visible(self) -> None:
+ # The host knows whether the pet is on screen; this proxy only guesses.
+ # The guess matters for one thing: a respawn replaying a hidden pet.
+ self._user_visible = not self._user_visible
+ self._send({"op": "toggle_visible"})
+
+ def set_on_compose(self, callback: Callable[[], None] | None) -> None:
+ self._on_compose = callback
+
+ def _dispatch_event(self, msg: dict[str, Any]) -> None:
+ if msg.get("event") != "compose":
+ super()._dispatch_event(msg)
+ return
+ # The pen: without a compose callback, raising the window is the
+ # honest fallback (the same one the in-process pet uses).
+ callback = self._on_compose or self._on_show_window
+ try:
+ if callback is not None:
+ callback()
+ except Exception: # noqa: BLE001 — a bad callback must not kill the pump
+ log.exception("orb host compose callback failed")
+
+ def _reapply_desired_state(self) -> None:
+ super()._reapply_desired_state()
+ if self._speaker_muted:
+ self._send({"op": "set_speaker_muted", "muted": True})
+ if not self._user_visible:
+ self._send({"op": "set_visible", "visible": False})
+
def set_style(self, style: str) -> None:
"""Re-style the hosted orb window live (mascot <-> voice orb).
diff --git a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
index 0e3716ae8a..0fbeece912 100644
--- a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
+++ b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
@@ -552,11 +552,16 @@ def _started_mascot(monkeypatch, **kwargs) -> tuple[SubprocessMascotOverlay, _Fa
def test_mascot_init_line_declares_surface_and_mascot_path(monkeypatch) -> None:
surface, proc = _started_mascot(monkeypatch, mascot_path="assets/m.png")
init = proc.sent()[0]
+ # The pet settings ride along for every orb-window style: a live swap to
+ # the pet reuses this window, and a respawn re-initializes it from here.
assert init == {
"op": "init",
"surface": "mascot",
"style": "mascot",
"mascot_path": "assets/m.png",
+ "pet_id": None,
+ "pet_scale": 1.0,
+ "pet_bubble": True,
}
assert surface._ready.is_set() # scripted ready event consumed
assert surface._visible is False # sticky=False mascot starts withdrawn
diff --git a/tests/unit/ui/test_orb_controls_pet.py b/tests/unit/ui/test_orb_controls_pet.py
new file mode 100644
index 0000000000..65efce15b5
--- /dev/null
+++ b/tests/unit/ui/test_orb_controls_pet.py
@@ -0,0 +1,201 @@
+"""The desktop pet's control strip (``ui.orb.controls``, ``PET_ACTIONS``).
+
+Pure geometry and pixels, no Tk: a click lands on the control the user aimed
+at, the strip's empty area stays free for dragging, every silhouette meets the
+colour key with a hard edge (a blended pixel survives as a pink fleck), the
+controls say what the system is doing, and a strip at rest costs nothing to
+repaint. Plus the speaker toggle's volume read, which the pet's speaker relies
+on to unmute again.
+"""
+
+from __future__ import annotations
+
+import pytest
+from PIL import Image
+
+from jarvis.core import runtime_refs
+from ui.orb import controls
+
+KEY = (255, 0, 255)
+
+
+def _centre(action: str, scale: float = 1.0) -> tuple[float, float]:
+ layout = controls.pet_strip_layout(scale)
+ if action == "compose":
+ return layout.pen[0], layout.pen[1]
+ for name, x0, x1 in layout.slots:
+ if name == action:
+ return (x0 + x1) / 2.0, (layout.pill[1] + layout.pill[3]) / 2.0
+ raise AssertionError(action)
+
+
+# --- geometry ---------------------------------------------------------------
+
+
[email protected]("scale", [1.0, 1.25, 1.5, 2.0])
+def test_every_pet_action_is_reachable_at_its_centre(scale: float) -> None:
+ hits = [
+ controls.pet_hit_test(*_centre(action, scale), scale) for action in controls.PET_ACTIONS
+ ]
+ assert hits == list(controls.PET_ACTIONS)
+
+
+def test_the_voice_orb_row_keeps_its_own_actions() -> None:
+ assert controls.ACTIONS == ("attach", "mic", "close", "speaker")
+ assert controls.PET_ACTIONS == ("compose", "mic_mute", "orb", "speaker")
+
+
+def test_the_gap_between_pen_and_pill_is_a_drag_handle_not_a_button() -> None:
+ layout = controls.pet_strip_layout(1.0)
+ gap_x = (layout.pen[0] + layout.pen[2] + layout.pill[0]) / 2.0
+ assert controls.pet_hit_test(gap_x, layout.height / 2.0) is None
+ # The padding band above the controls is empty too.
+ assert controls.pet_hit_test(_centre("orb")[0], 0.5) is None
+
+
+def test_a_divider_click_goes_to_a_neighbour_instead_of_nowhere() -> None:
+ layout = controls.pet_strip_layout(1.0)
+ divider = layout.dividers[0]
+ hit = controls.pet_hit_test(divider + 0.5, layout.height / 2.0)
+ assert hit in ("mic_mute", "orb")
+
+
+def test_the_pill_ends_are_round_so_its_corners_are_not_clickable() -> None:
+ layout = controls.pet_strip_layout(1.0)
+ x0, y0, x1, _y1 = layout.pill
+ assert controls.pet_hit_test(x1 - 1, y0 + 1) is None
+ assert controls.pet_hit_test(x0 + 1, y0 + 1) is None
+
+
+def test_the_strip_scales_with_the_display() -> None:
+ small = controls.pet_strip_size(1.0)
+ large = controls.pet_strip_size(2.0)
+ assert large[0] == pytest.approx(small[0] * 2, abs=4)
+ assert large[1] == pytest.approx(small[1] * 2, abs=2)
+
+
+# --- rendering --------------------------------------------------------------
+
+
+def _frame(state: controls.PetStripState, scale: float = 1.0) -> Image.Image:
+ return controls.render_pet_strip(state, scale, KEY)
+
+
[email protected]("scale", [1.0, 1.5])
+def test_every_pixel_is_either_pure_key_or_fully_opaque_art(scale: float) -> None:
+ """No pixel may blend into the key: along every silhouette edge the
+ neighbour of a key pixel is never a magenta-tinted mix."""
+ frame = _frame(controls.PetStripState(hovered="orb"), scale)
+ width, height = frame.size
+ px = frame.load()
+ for x, y in [(0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)]:
+ assert px[x, y] == KEY
+ for y in range(height):
+ for x in range(width):
+ r, g, b = px[x, y]
+ if (r, g, b) == KEY:
+ continue
+ # A key blend is strongly red+blue with little green; the palette
+ # is grey/blue, so such a pixel can only be a fringe.
+ assert not (r > 120 and b > 120 and g < 60), (x, y, px[x, y])
+
+
+def test_control_centres_are_painted_not_keyed_out() -> None:
+ frame = _frame(controls.PetStripState())
+ for action in controls.PET_ACTIONS:
+ x, y = _centre(action)
+ assert frame.getpixel((int(x), int(y))) != KEY, action
+
+
+def _red_pixels(frame: Image.Image, box: tuple[int, int, int, int]) -> int:
+ return sum(
+ 1
+ for (r, g, b) in frame.crop(box).getdata()
+ if r > 150 and g < 110 and b < 110 and (r, g, b) != KEY
+ )
+
+
+def _slot_box(action: str) -> tuple[int, int, int, int]:
+ layout = controls.pet_strip_layout(1.0)
+ for name, x0, x1 in layout.slots:
+ if name == action:
+ return (x0, layout.pill[1], x1, layout.pill[3])
+ raise AssertionError(action)
+
+
+def test_a_muted_microphone_carries_a_red_slash() -> None:
+ box = _slot_box("mic_mute")
+ assert _red_pixels(_frame(controls.PetStripState()), box) == 0
+ assert _red_pixels(_frame(controls.PetStripState(mic_muted=True)), box) > 5
+
+
+def test_a_muted_speaker_carries_a_red_slash() -> None:
+ box = _slot_box("speaker")
+ assert _red_pixels(_frame(controls.PetStripState()), box) == 0
+ assert _red_pixels(_frame(controls.PetStripState(speaker_muted=True)), box) > 5
+
+
+def test_the_orb_is_bluish_and_swells_only_while_engaged() -> None:
+ box = _slot_box("orb")
+
+ def _blue(frame: Image.Image) -> int:
+ return sum(1 for (r, g, b) in frame.crop(box).getdata() if b > 180 and r < 150)
+
+ rest = _blue(_frame(controls.PetStripState(level=6))) # level ignored at rest
+ assert rest > 20
+ assert rest == _blue(_frame(controls.PetStripState(level=0)))
+ loud = _blue(_frame(controls.PetStripState(active=True, level=6)))
+ assert loud > rest
+
+
+def test_a_resting_strip_is_one_cached_frame() -> None:
+ state = controls.PetStripState(mic_muted=True)
+ assert _frame(state) is _frame(controls.PetStripState(mic_muted=True))
+
+
+def test_levels_quantise_into_a_handful_of_steps() -> None:
+ assert controls.quantize_level(None) == 0
+ assert controls.quantize_level(0.0) == 0
+ assert controls.quantize_level(1.0) == controls.PET_LEVEL_STEPS
+ assert controls.quantize_level(7.0) == controls.PET_LEVEL_STEPS
+ assert controls.quantize_level(float("nan")) == 0
+ steps = {controls.quantize_level(i / 100) for i in range(101)}
+ assert len(steps) == controls.PET_LEVEL_STEPS + 1
+
+
+# --- the speaker volume the pet reads --------------------------------------------
+
+
+class _Pipeline:
+ def __init__(self, volume: float) -> None:
+ self._volume = volume
+ # A stale attribute that must NOT win over the getter.
+ self._tts_volume = 1.0
+
+ def get_tts_volume(self) -> float:
+ return self._volume
+
+ def set_tts_volume(self, volume: float) -> None:
+ self._volume = float(volume)
+
+
+def pipeline() -> _Pipeline:
+ live = _Pipeline(0.7)
+ runtime_refs.set_speech_pipeline(live)
+ try:
+ yield live
+ finally:
+ runtime_refs.set_speech_pipeline(None)
+
+
+def test_the_volume_getter_wins_over_any_attribute(pipeline: _Pipeline) -> None:
+ pipeline._volume = 0.0
+ assert controls.speaker_is_muted() is True
+
+
+def test_the_speaker_toggle_mutes_and_then_unmutes_again(pipeline: _Pipeline) -> None:
+ assert controls.toggle_speaker_mute() is True
+ assert pipeline._volume == 0.0
+ assert controls.toggle_speaker_mute() is False
+ assert pipeline._volume == pytest.approx(0.7)
diff --git a/tests/unit/ui/test_pet_overlay_renderer.py b/tests/unit/ui/test_pet_overlay_renderer.py
new file mode 100644
index 0000000000..7912109c08
--- /dev/null
+++ b/tests/unit/ui/test_pet_overlay_renderer.py
@@ -0,0 +1,306 @@
+"""The desktop pet's renderer (``ui.orb.pet_renderer``) — pacing and scaling.
+
+The pet's performance budget (``docs/pets.md``) rests on three promises this
+module makes to the overlay: every frame is scaled once, ``frame_key`` changes
+exactly when the picture does, and ``next_frame_delay_ms`` lets the overlay
+sleep until then. These tests pin all three without Tk, with a hand-written
+pack, a real :class:`PetStateMachine` and a clock the test moves by hand.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+from PIL import Image
+
+from jarvis.ui.pets.state_machine import PetStateMachine
+from jarvis.ui.pets.states import PET_STATES, SLEEP_AFTER_SECONDS
+from ui.orb import controls as orb_controls
+from ui.orb import pet_renderer as pr
+
+
+class _Clock:
+ def __init__(self) -> None:
+ self.now = 1000.0
+
+ def __call__(self) -> float:
+ return self.now
+
+
+@dataclass(frozen=True)
+class _Spec:
+ row: int
+ frames: int
+ fps: int
+ loop: bool
+
+
+class _Manifest:
+ def __init__(self, frame_size: int, specs: dict[str, _Spec], pet_id: str = "fake") -> None:
+ self.frame_size = frame_size
+ self.id = pet_id
+ self._specs = specs
+
+ def spec_for(self, state: str) -> tuple[str, _Spec]:
+ if state in self._specs:
+ return state, self._specs[state]
+ return "idle", self._specs["idle"]
+
+
+class _Pack:
+ def __init__(self, frame_size: int = 48, pet_id: str = "fake") -> None:
+ specs = {
+ "idle": _Spec(0, 4, 4, True),
+ "listening": _Spec(1, 4, 8, True),
+ "talking": _Spec(3, 4, 10, True),
+ "success": _Spec(4, 3, 10, False),
+ "sleeping": _Spec(6, 2, 2, True),
+ }
+ self.manifest = _Manifest(frame_size, specs, pet_id)
+ self.frames: dict[str, tuple[Image.Image, ...]] = {}
+ for state in PET_STATES:
+ resolved, spec = self.manifest.spec_for(state)
+ self.frames[state] = tuple(
+ Image.new("RGBA", (frame_size, frame_size), (index * 40, row, 0, 255))
+ for index, row in [(i, spec.row) for i in range(spec.frames)]
+ )
+
+
+class _Loader:
+ def __init__(self, packs: dict[str, _Pack | None]) -> None:
+ self.packs = packs
+ self.calls: list[str] = []
+
+ def __call__(self, pet_id: str) -> _Pack | None:
+ self.calls.append(pet_id)
+ return self.packs.get(pet_id, self.packs.get("fake"))
+
+
+def _scale_calls() -> tuple[list[int], object]:
+ calls: list[int] = []
+
+ def _to_key(frame: Image.Image, scale: int, key: tuple[int, int, int]) -> Image.Image:
+ calls.append(scale)
+ return frame.convert("RGB").resize((frame.width * scale, frame.height * scale))
+
+ return calls, _to_key
+
+
+def _renderer(clock: _Clock, **kwargs) -> tuple[pr.PetRenderer, list[int]]:
+ calls, to_key = _scale_calls()
+ loader = kwargs.pop("loader", _Loader({"fake": _Pack()}))
+ renderer = pr.PetRenderer(
+ kwargs.pop("pet_id", "fake"),
+ clock=clock,
+ loader=loader,
+ to_color_key=to_key,
+ machine=PetStateMachine(clock),
+ **kwargs,
+ )
+ return renderer, calls
+
+
+# --- pure helpers -------------------------------------------------------------
+
+
+def test_a_48_pixel_sheet_is_drawn_at_exactly_3x_at_100_percent() -> None:
+ assert pr.pixel_factor(48, 1.0, 1.0) == 3
+
+
+def test_other_sheet_sizes_land_near_the_same_on_screen_size() -> None:
+ assert pr.pixel_factor(32, 1.0, 1.0) * 32 == pytest.approx(pr.PET_TARGET_EDGE_PX, abs=16)
+ assert pr.pixel_factor(64, 1.0, 1.0) * 64 == pytest.approx(pr.PET_TARGET_EDGE_PX, abs=16)
+
+
+def test_the_factor_follows_dpi_and_user_size_and_rounds_half_up() -> None:
+ assert pr.pixel_factor(48, 1.5, 1.0) == 5 # 4.5 -> 5, never banker's 4
+ assert pr.pixel_factor(48, 2.0, 1.0) == 6
+ assert pr.pixel_factor(48, 1.0, 2.0) == 6
+ assert pr.pixel_factor(48, 1.0, 0.5) == 2
+
+
+def test_the_factor_never_drops_below_one_and_survives_garbage() -> None:
+ assert pr.pixel_factor(64, 0.1, 0.1) == 1
+ assert pr.pixel_factor(48, float("nan"), 1.0) == 3
+ assert pr.pixel_factor("x", 1.0, 1.0) == 1 # type: ignore[arg-type]
+
+
+def test_dpi_ratio_reads_logical_dpi_except_on_macos() -> None:
+ assert pr.dpi_ratio_for(96.0, "win32") == 1.0
+ assert pr.dpi_ratio_for(144.0, "linux") == 1.5
+ assert pr.dpi_ratio_for(144.0, "darwin") == 1.0 # Aqua already measures in points
+ assert pr.dpi_ratio_for(None, "win32") == 1.0
+ assert pr.dpi_ratio_for(float("inf"), "win32") == 1.0
+ assert pr.dpi_ratio_for(-3.0, "win32") == 1.0
+
+
+def test_frame_index_loops_or_rests_on_the_last_frame() -> None:
+ assert pr.frame_index(0.0, 4, 4, True) == 0
+ assert pr.frame_index(0.26, 4, 4, True) == 1
+ assert pr.frame_index(1.01, 4, 4, True) == 0 # wrapped
+ assert pr.frame_index(5.0, 3, 10, False) == 2 # a one-shot rests at its end
+ assert pr.frame_index(9.0, 1, 4, True) == 0
+
+
+def test_seconds_to_next_frame_is_the_boundary_or_never() -> None:
+ assert pr.seconds_to_next_frame(0.1, 4, 4, True) == pytest.approx(0.15)
+ assert pr.seconds_to_next_frame(0.0, 1, 8, True) is None # one frame never changes
+ assert pr.seconds_to_next_frame(0.5, 3, 10, False) is None # one-shot finished
+ assert pr.seconds_to_next_frame(0.05, 3, 10, False) == pytest.approx(0.05)
+
+
+# --- scaling happens once ------------------------------------------------------
+
+
+def test_every_frame_is_scaled_once_at_load_and_never_while_painting() -> None:
+ clock = _Clock()
+ renderer, calls = _renderer(clock)
+ scaled_at_load = len(calls)
+ assert scaled_at_load == sum(len(v) for v in _Pack().frames.values())
+ assert set(calls) == {3}
+ for _ in range(50):
+ clock.now += 0.07
+ renderer.render()
+ renderer.frame_key()
+ renderer.next_frame_delay_ms()
+ assert len(calls) == scaled_at_load
+ assert renderer.size == (144, 144)
+ assert renderer.render().size == (144, 144)
+
+
+def test_a_new_size_rescales_and_reports_the_change() -> None:
+ clock = _Clock()
+ renderer, calls = _renderer(clock)
+ calls.clear()
+ assert renderer.set_look(pet_scale=2.0) is True
+ assert renderer.size == (288, 288)
+ assert set(calls) == {6}
+ assert renderer.set_look(pet_scale=2.0) is False # same size, no window change
+
+
+# --- frame keys and pacing ------------------------------------------------------
+
+
+def test_the_key_changes_only_at_frame_boundaries_while_idle() -> None:
+ clock = _Clock()
+ renderer, _ = _renderer(clock)
+ first = renderer.frame_key()
+ clock.now += 0.2 # idle is 4 fps: still frame 0
+ assert renderer.frame_key() == first
+ clock.now += 0.06
+ assert renderer.frame_key() != first
+
+
+def test_idle_sleeps_until_the_next_quarter_second() -> None:
+ clock = _Clock()
+ renderer, _ = _renderer(clock)
+ delay = renderer.next_frame_delay_ms()
+ assert 250 <= delay <= 255
+ clock.now += 0.1
+ assert 150 <= renderer.next_frame_delay_ms() <= 155
+
+
+def test_active_states_tick_at_the_manifest_rate() -> None:
+ clock = _Clock()
+ renderer, _ = _renderer(clock)
+ renderer.on_mode("listen")
+ assert renderer.state() == "listening"
+ assert 125 <= renderer.next_frame_delay_ms() <= 130 # 8 fps
+ renderer.on_mode("speak")
+ assert 100 <= renderer.next_frame_delay_ms() <= 105 # 10 fps
+
+
+def test_asleep_the_pet_ticks_at_two_frames_a_second() -> None:
+ clock = _Clock()
+ renderer, _ = _renderer(clock)
+ clock.now += SLEEP_AFTER_SECONDS + 0.01
+ assert renderer.state() == "sleeping"
+ delay = renderer.next_frame_delay_ms()
+ assert 490 <= delay <= 505
+
+
+def test_a_one_shot_wakes_the_loop_when_it_ends() -> None:
+ clock = _Clock()
+ renderer, _ = _renderer(clock)
+ renderer.on_outcome("success")
+ clock.now += 0.25 # the 3-frame one-shot rests on its last frame at 10 fps
+ # No frame boundary is left; the next change is the one-shot ending in
+ # 1.25 s, beyond the ceiling — so the loop sleeps the full second.
+ assert renderer.next_frame_delay_ms() == pr.MAX_FRAME_DELAY_MS
+ clock.now += 1.0
+ assert 250 <= renderer.next_frame_delay_ms() <= 255 # wakes exactly at the end
+ clock.now += 0.26
+ assert renderer.state() == "idle"
+
+
+def test_the_delay_is_clamped_to_a_sane_band() -> None:
+ clock = _Clock()
+ renderer, _ = _renderer(clock)
+ for _ in range(200):
+ clock.now += 0.013
+ delay = renderer.next_frame_delay_ms()
+ assert pr.MIN_FRAME_DELAY_MS <= delay <= pr.MAX_FRAME_DELAY_MS
+
+
+# --- the pet "none" and unknown ids ------------------------------------------------
+
+
+def test_no_pet_paints_an_invisible_strip_wide_line() -> None:
+ clock = _Clock()
+ loader = _Loader({"fake": _Pack()})
+ renderer, calls = _renderer(clock, pet_id="none", loader=loader)
+ assert loader.calls == [] # "none" never touches the disk
+ assert calls == []
+ assert renderer.has_figure is False
+ width, height = renderer.size
+ assert (width, height) == (orb_controls.pet_strip_size(1.0)[0], 1)
+ frame = renderer.render()
+ assert frame.getcolors() == [(width * height, (255, 0, 255))]
+ # A figure-less pet has nothing to animate: it idles on the slow ceiling.
+ assert renderer.next_frame_delay_ms() <= pr.MAX_FRAME_DELAY_MS
+
+
+def test_the_reported_id_is_the_pack_that_actually_loaded() -> None:
+ clock = _Clock()
+ loader = _Loader({"fake": _Pack(pet_id="gigi")})
+ renderer, _ = _renderer(clock, pet_id="u0123456789abcdef", loader=loader)
+ assert renderer.pet_id == "gigi"
+
+
+def test_a_crashing_loader_degrades_to_the_strip_only() -> None:
+ def _broken(_pet_id: str) -> None:
+ raise OSError("disk gone")
+
+ renderer, _ = _renderer(_Clock(), loader=_broken)
+ assert renderer.has_figure is False
+ assert renderer.pet_id == "none"
+
+
+def test_switching_pets_keeps_the_state_machine() -> None:
+ clock = _Clock()
+ loader = _Loader({"fake": _Pack(), "miso": _Pack(frame_size=32, pet_id="miso")})
+ renderer, _ = _renderer(clock, loader=loader)
+ renderer.on_mode("listen")
+ renderer.load("miso")
+ assert renderer.state() == "listening"
+ assert renderer.size == (160, 160) # 32 px at the nearest factor (5x)
+ assert renderer.frame_key()[0] == "miso"
+
+
+# --- the real engine, end to end ---------------------------------------------------
+
+
+def test_the_built_in_default_pet_loads_through_the_real_engine() -> None:
+ """Drift guard: the renderer's assumptions about the engine's API hold."""
+ clock = _Clock()
+ renderer = pr.PetRenderer("gigi", clock=clock, dpi_ratio=1.0)
+ assert renderer.has_figure
+ edge = renderer.size[0]
+ assert renderer.size == (edge, edge)
+ assert renderer.render().mode == "RGB"
+ for mode in ("idle", "listen", "think", "speak", "notice"):
+ renderer.on_mode(mode)
+ assert renderer.state() in PET_STATES
+ assert renderer.render().size == renderer.size
+ assert pr.MIN_FRAME_DELAY_MS <= renderer.next_frame_delay_ms() <= pr.MAX_FRAME_DELAY_MS
diff --git a/tests/unit/ui/test_pet_overlay_surface.py b/tests/unit/ui/test_pet_overlay_surface.py
new file mode 100644
index 0000000000..b87af9b173
--- /dev/null
+++ b/tests/unit/ui/test_pet_overlay_surface.py
@@ -0,0 +1,280 @@
+"""The desktop pet's surface contract, without a real window (docs/pets.md).
+
+Covers what the bridge and the REST routes rely on: the pet stays up while
+idle (``keeps_visible_when_idle``) and only the pet asks for status lines, the
+user-hidden flag is reported the same way in-process and through the macOS
+proxy, DesktopApp's pet methods update the config and degrade without a
+surface, a live swap between orb looks changes the bridge's idle regime, and
+the speaker control names itself to the pipeline when the pipeline asks.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.core import runtime_refs
+from jarvis.ui.desktop_app import DesktopApp
+from jarvis.ui.jarvisbar.null_overlay import NullOverlay
+from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessMascotOverlay
+from ui.orb import controls
+from ui.orb.overlay import OrbOverlay
+
+# --- OrbOverlay (never started: no Tk root under pytest) --------------------------
+
+
+def test_only_the_pet_stays_visible_while_idle_and_wants_status_lines() -> None:
+ pet = OrbOverlay(style="pet")
+ assert pet.keeps_visible_when_idle is True
+ assert pet.wants_status_lines is True
+ for style in ("mascot", "voice_orb"):
+ other = OrbOverlay(style=style)
+ assert other.keeps_visible_when_idle is False
+ assert other.wants_status_lines is False
+
+
+def test_the_idle_regime_follows_a_style_change() -> None:
+ surface = OrbOverlay(style="mascot")
+ surface.set_style("pet") # before start(): remembered for the boot
+ assert surface.keeps_visible_when_idle is True
+ surface.set_style("voice_orb")
+ assert surface.keeps_visible_when_idle is False
+
+
+def test_the_user_hidden_flag_is_set_synchronously() -> None:
+ pet = OrbOverlay(style="pet")
+ assert pet.pet_user_hidden is False
+ pet.set_visible(False)
+ assert pet.pet_user_hidden is True
+ pet.set_visible(True)
+ assert pet.pet_user_hidden is False
+
+
+def test_pet_calls_are_safe_before_the_window_exists() -> None:
+ pet = OrbOverlay(style="pet", pet_id="none", pet_scale=9.0, pet_bubble=False)
+ pet.set_pet("gigi")
+ pet.set_pet_look(scale=0.1, bubble=True)
+ pet.set_pet_outcome("success")
+ pet.set_pet_outcome("confetti") # unknown kind: ignored
+ pet.show_status("Thinking …", "Reading the calendar")
+ pet.set_muted(True)
+ pet.set_speaker_muted(True)
+ pet.toggle_visible()
+ assert pet._pet_id == "gigi"
+ assert pet._pet_scale == 0.5 # clamped into 0.5–2.0
+ assert pet._pet_bubble is True
+ assert pet._mic_muted is True and pet._speaker_muted is True
+
+
+# --- the macOS proxy mirrors the same attributes -------------------------------------
+
+
+def test_the_macos_proxy_reports_the_same_pet_attributes() -> None:
+ proxy = SubprocessMascotOverlay(style="pet", pet_id="miso")
+ assert proxy.keeps_visible_when_idle is True
+ assert proxy.wants_status_lines is True
+ assert proxy.pet_user_hidden is False
+ mascot = SubprocessMascotOverlay(style="mascot")
+ assert mascot.keeps_visible_when_idle is False
+ assert mascot.wants_status_lines is False
+
+
+def test_the_macos_proxy_forwards_the_hidden_flag() -> None:
+ proxy = SubprocessMascotOverlay(style="pet")
+ sent: list[dict] = []
+ proxy._send = sent.append # type: ignore[method-assign]
+ proxy.set_visible(False)
+ assert proxy.pet_user_hidden is True
+ assert sent[-1] == {"op": "set_visible", "visible": False}
+ proxy.toggle_visible()
+ assert proxy.pet_user_hidden is False
+ assert sent[-1] == {"op": "toggle_visible"}
+
+
+# --- DesktopApp's pet methods ------------------------------------------------------------
+
+
+class _PetSurface:
+ """The part of the orb window DesktopApp talks to."""
+
+ def __init__(self) -> None:
+ self.calls: list[tuple] = []
+ self.pet_user_hidden = False
+ self._mode = "idle"
+
+ def set_pet(self, pet_id: str) -> None:
+ self.calls.append(("set_pet", pet_id))
+
+ def set_pet_look(self, scale, bubble) -> None:
+ self.calls.append(("set_pet_look", scale, bubble))
+
+ def set_visible(self, visible: bool) -> None:
+ self.pet_user_hidden = not visible
+ self.calls.append(("set_visible", visible))
+
+ def set_style(self, style: str) -> None:
+ self.calls.append(("set_style", style))
+
+ def show(self, mode: str) -> None:
+ self.calls.append(("show", mode))
+
+ def hide(self) -> None:
+ self.calls.append(("hide",))
+
+
+class _Bridge:
+ def __init__(self) -> None:
+ self._hide_on_idle = True
+ self.surface = None
+
+ def set_surface(self, surface) -> None:
+ self.surface = surface
+
+
+def _app(*, orb=None, bridge=None, orb_style: str = "pet") -> DesktopApp:
+ app = DesktopApp.__new__(DesktopApp) # bypass the heavy __init__
+ app.cfg = SimpleNamespace(
+ ui=SimpleNamespace(
+ orb_style=orb_style,
+ bar_persistent=True,
+ bar_accent="#e7c46e",
+ orb_mascot_path="",
+ pet_id="gigi",
+ pet_scale=1.0,
+ pet_bubble=True,
+ ),
+ trigger=SimpleNamespace(hotkey_pet_toggle=" alt+win+p "),
+ )
+ app._orb = orb
+ app._bridge = bridge
+ return app
+
+
+def test_set_pet_updates_the_config_and_the_live_window() -> None:
+ surface = _PetSurface()
+ app = _app(orb=surface)
+ assert app.set_pet("miso") == {"ok": True, "applied_live": True}
+ assert app.cfg.ui.pet_id == "miso"
+ assert surface.calls[-1] == ("set_pet", "miso")
+ assert app.set_pet("") == {"ok": True, "applied_live": True}
+ assert app.cfg.ui.pet_id == "none"
+
+
+def test_set_pet_look_clamps_and_applies() -> None:
+ surface = _PetSurface()
+ app = _app(orb=surface)
+ result = app.set_pet_look(scale=7.0, bubble=False)
+ assert result == {"ok": True, "applied_live": True}
+ assert app.cfg.ui.pet_scale == 2.0
+ assert app.cfg.ui.pet_bubble is False
+ assert surface.calls[-1] == ("set_pet_look", 2.0, False)
+
+
+def test_pet_methods_degrade_without_a_pet_surface() -> None:
+ for orb in (None, NullOverlay()):
+ app = _app(orb=orb)
+ assert app.set_pet("brew") == {"ok": True, "applied_live": False}
+ assert app.set_pet_look(scale=1.5) == {"ok": True, "applied_live": False}
+ assert app.set_pet_visible(False) == {"ok": True, "applied_live": False}
+ assert app.pet_visible() is True # nothing hid a pet
+ assert app.cfg.ui.pet_id == "brew"
+
+
+def test_pet_visible_reports_the_runtime_hide() -> None:
+ surface = _PetSurface()
+ app = _app(orb=surface)
+ assert app.pet_visible() is True
+ assert app.set_pet_visible(False)["applied_live"] is True
+ assert app.pet_visible() is False
+ app.set_pet_visible(True)
+ assert app.pet_visible() is True
+
+
+def test_the_idle_regime_per_style() -> None:
+ app = _app()
+ assert app._hide_on_idle_for("pet") is False
+ assert app._hide_on_idle_for("mascot") is True
+ assert app._hide_on_idle_for("voice_orb") is True
+ assert app._hide_on_idle_for("jarvis_bar") is False # bar_persistent=True
+ app.cfg.ui.bar_persistent = False
+ assert app._hide_on_idle_for("jarvis_bar") is True
+
+
+def test_a_live_swap_to_the_pet_keeps_it_up_and_back_lets_the_mascot_hide() -> None:
+ surface, bridge = _PetSurface(), _Bridge()
+ app = _app(orb=surface, bridge=bridge, orb_style="mascot")
+ app._surfaces = {"mascot": surface}
+ result = app.swap_overlay("pet")
+ assert result == {"ok": True, "applied_live": True, "style": "pet"}
+ assert bridge._hide_on_idle is False
+ assert ("show", "idle") in surface.calls
+ surface.calls.clear()
+ app.swap_overlay("mascot")
+ assert bridge._hide_on_idle is True
+ assert ("hide",) in surface.calls # an idle pet does not linger as a mascot
+
+
+def test_the_pet_shortcut_is_read_stripped_and_empty_when_unset() -> None:
+ from jarvis.ui.desktop_app import _pet_toggle_hotkey
+
+ assert _pet_toggle_hotkey(_app().cfg) == "alt+win+p"
+ assert _pet_toggle_hotkey(SimpleNamespace(trigger=SimpleNamespace())) == ""
+ assert _pet_toggle_hotkey(SimpleNamespace()) == ""
+
+
+# --- the speaker control names itself to the pipeline -------------------------------------
+
+
+class _SourcePipeline:
+ def __init__(self) -> None:
+ self.volume = 0.8
+ self.sources: list[str] = []
+
+ def get_tts_volume(self) -> float:
+ return self.volume
+
+ def set_tts_volume(self, volume: float, *, source: str = "") -> None:
+ self.volume = float(volume)
+ self.sources.append(source)
+
+
+class _PlainPipeline:
+ def __init__(self) -> None:
+ self.volume = 0.8
+
+ def get_tts_volume(self) -> float:
+ return self.volume
+
+ def set_tts_volume(self, volume: float) -> None:
+ self.volume = float(volume)
+
+
+def live_pipeline():
+ holder: dict[str, object] = {}
+
+ def install(pipeline: object) -> object:
+ runtime_refs.set_speech_pipeline(pipeline)
+ holder["p"] = pipeline
+ return pipeline
+
+ try:
+ yield install
+ finally:
+ runtime_refs.set_speech_pipeline(None)
+
+
+def test_the_speaker_toggle_passes_its_source_when_the_pipeline_takes_one(live_pipeline) -> None:
+ pipeline = live_pipeline(_SourcePipeline())
+ assert controls.toggle_speaker_mute(source="pet") is True
+ assert controls.toggle_speaker_mute(source="pet") is False
+ assert pipeline.sources == ["pet", "pet"]
+ assert pipeline.volume == pytest.approx(0.8)
+
+
+def test_the_speaker_toggle_still_works_with_an_older_setter(live_pipeline) -> None:
+ pipeline = live_pipeline(_PlainPipeline())
+ assert controls.toggle_speaker_mute(source="pet") is True
+ assert pipeline.volume == 0.0
+ assert controls.toggle_speaker_mute() is False
+ assert pipeline.volume == pytest.approx(0.8)
diff --git a/ui/orb/controls.py b/ui/orb/controls.py
index 9e85a2e52a..00fd2a9603 100644
--- a/ui/orb/controls.py
+++ b/ui/orb/controls.py
@@ -26,6 +26,8 @@ colour on the desktop.
from __future__ import annotations
+import functools
+import inspect
import logging
import math
import os
@@ -362,13 +364,312 @@ def render_row(
return frame
-def toggle_speaker_mute() -> bool | None:
+# --- The pet's control strip ------------------------------------------------
+# The desktop pet (``docs/pets.md``) carries its controls in a different shape:
+# a pen disc on its own, then ONE pill holding microphone mute, the talk orb and
+# the speaker, separated by thin dividers. Same hard-edge rules as the row
+# above: every silhouette that meets the colour key goes through a binary mask,
+# every glyph is drawn at 4x and downscaled INSIDE its opaque surface.
+
+#: The strip's actions, left to right. The voice orb's ``ACTIONS`` stay as they
+#: are; the two layouts never share a hit-test.
+PET_ACTIONS: tuple[str, ...] = ("compose", "mic_mute", "orb", "speaker")
+
+#: Unscaled geometry, in pixels at 100 % display scaling.
+PET_SLOT = 28
+PET_PEN_GAP = 6
+PET_DIVIDER_W = 1
+PET_PILL_INSET = 4
+PET_STRIP_PADDING = 4
+#: Vertical distance from the figure's bottom edge to the strip.
+PET_STRIP_GAP_FROM_FIGURE = 4
+#: How many steps the orb's pulse is quantised into. A handful is enough to
+#: read as "breathing with the voice" and bounds how often the strip repaints.
+PET_LEVEL_STEPS = 6
+
+#: The talk orb's colours: a small bluish sphere, brighter while engaged.
+PET_ORB_REST = (74, 124, 230)
+PET_ORB_ACTIVE = (98, 152, 255)
+PET_ORB_HIGHLIGHT = (170, 200, 255)
+#: The divider between pill slots — a shade above the border so it reads.
+PET_DIVIDER = (44, 44, 44)
+
+
+def _spx(value: float, scale: float) -> int:
+ """One unscaled length at ``scale``, never below one pixel."""
+ return max(1, int(round(value * max(0.1, float(scale)))))
+
+
+@dataclass(frozen=True)
+class PetStripLayout:
+ """Where everything sits inside the strip window, at one display scale."""
+
+ width: int
+ height: int
+ #: The pen disc: centre and radius.
+ pen: tuple[float, float, float]
+ #: The pill's bounding box ``(x0, y0, x1, y1)``, x1/y1 exclusive.
+ pill: tuple[int, int, int, int]
+ #: Each pill action's horizontal span ``(x0, x1)`` inside the window.
+ slots: tuple[tuple[str, int, int], ...]
+ #: Divider x positions (their left edge) inside the window.
+ dividers: tuple[int, ...]
+
+
[email protected]_cache(maxsize=16)
+def pet_strip_layout(scale: float = 1.0) -> PetStripLayout:
+ """The strip's geometry at ``scale`` (the monitor's DPI ratio)."""
+ pad = _spx(PET_STRIP_PADDING, scale)
+ slot = _spx(PET_SLOT, scale)
+ gap = _spx(PET_PEN_GAP, scale)
+ divider = _spx(PET_DIVIDER_W, scale)
+ inset = _spx(PET_PILL_INSET, scale)
+ pen_r = slot / 2.0
+ pen = (pad + pen_r, pad + pen_r, pen_r)
+ pill_x0 = pad + slot + gap
+ pill_w = 2 * inset + 3 * slot + 2 * divider
+ pill = (pill_x0, pad, pill_x0 + pill_w, pad + slot)
+ slots: list[tuple[str, int, int]] = []
+ dividers: list[int] = []
+ x = pill_x0 + inset
+ for index, action in enumerate(PET_ACTIONS[1:]):
+ slots.append((action, x, x + slot))
+ x += slot
+ if index < 2:
+ dividers.append(x)
+ x += divider
+ width = pill[2] + pad
+ height = slot + 2 * pad
+ return PetStripLayout(
+ width=width,
+ height=height,
+ pen=pen,
+ pill=pill,
+ slots=tuple(slots),
+ dividers=tuple(dividers),
+ )
+
+
+def pet_strip_size(scale: float = 1.0) -> tuple[int, int]:
+ """Pixel size of the pet strip window at ``scale``."""
+ layout = pet_strip_layout(scale)
+ return layout.width, layout.height
+
+
+def _inside_stadium(x: float, y: float, box: tuple[int, int, int, int]) -> bool:
+ """Is ``(x, y)`` inside the pill (a rectangle with fully rounded ends)?"""
+ x0, y0, x1, y1 = box
+ r = (y1 - y0) / 2.0
+ cy = y0 + r
+ if y < y0 or y >= y1:
+ return False
+ if x0 + r <= x <= x1 - r:
+ return True
+ cx = x0 + r if x < x0 + r else x1 - r
+ return math.hypot(x - cx, y - cy) <= r
+
+
+def pet_hit_test(x: float, y: float, scale: float = 1.0) -> str | None:
+ """Which pet action a click at ``(x, y)`` lands on, or ``None``.
+
+ Outside the pen disc and the pill is nothing — that empty area is where the
+ user grabs the strip to drag the pet (the only handle when the pet is
+ "None"). Inside the pill every pixel belongs to a slot: a divider resolves
+ to the nearer neighbour instead of eating the click.
+ """
+ layout = pet_strip_layout(scale)
+ pcx, pcy, pr = layout.pen
+ if math.hypot(x - pcx, y - pcy) <= pr:
+ return "compose"
+ if not _inside_stadium(x, y, layout.pill):
+ return None
+ best: str | None = None
+ best_distance = math.inf
+ for action, x0, x1 in layout.slots:
+ if x0 <= x < x1:
+ return action
+ distance = min(abs(x - x0), abs(x - x1))
+ if distance < best_distance:
+ best, best_distance = action, distance
+ return best
+
+
+def quantize_level(level: float | None) -> int:
+ """A 0..1 audio level as one of ``PET_LEVEL_STEPS + 1`` pulse steps."""
+ if level is None:
+ return 0
+ try:
+ value = float(level)
+ except (TypeError, ValueError):
+ return 0
+ if not math.isfinite(value):
+ return 0
+ value = max(0.0, min(1.0, value))
+ return int(round(value * PET_LEVEL_STEPS))
+
+
+@dataclass(frozen=True)
+class PetStripState:
+ """Everything the pet strip needs to paint itself truthfully."""
+
+ #: Jarvis's microphone is muted (``VoiceMuteChanged``).
+ mic_muted: bool = False
+ #: The assistant's voice is muted for this session.
+ speaker_muted: bool = False
+ #: A conversation is running — the orb hangs up instead of starting one.
+ active: bool = False
+ #: The orb's pulse step (``quantize_level``); only drawn while ``active``.
+ level: int = 0
+ #: Which control the pointer is over, if any.
+ hovered: str | None = None
+
+
+def _draw_pen(d: ImageDraw.ImageDraw, cx: float, cy: float, r: float, color, w: int) -> None:
+ """A pencil on the diagonal, tip at the bottom left — "write something"."""
+ dx, dy = math.cos(-math.pi / 4), math.sin(-math.pi / 4)
+ nx, ny = -dy, dx
+ half = r * 0.17
+
+ def p(u: float, v: float) -> tuple[float, float]:
+ return (cx + u * r * dx + v * nx, cy + u * r * dy + v * ny)
+
+ d.polygon(
+ [p(0.70, -half), p(0.70, half), p(-0.45, half), p(-0.78, 0.0), p(-0.45, -half)],
+ outline=color,
+ width=w,
+ )
+ # The ferrule: where the eraser meets the body.
+ d.line([p(0.42, -half), p(0.42, half)], fill=color, width=w)
+
+
+def _draw_orb(
+ d: ImageDraw.ImageDraw,
+ cx: float,
+ cy: float,
+ r: float,
+ *,
+ active: bool,
+ level: int,
+) -> None:
+ """The talk orb: a small sphere that swells with the voice while engaged."""
+ pulse = (level / PET_LEVEL_STEPS) if active else 0.0
+ radius = r * (0.46 + 0.30 * pulse)
+ body = PET_ORB_ACTIVE if active else PET_ORB_REST
+ d.ellipse([cx - radius, cy - radius, cx + radius, cy + radius], fill=body)
+ shine = radius * 0.38
+ sx, sy = cx - radius * 0.32, cy - radius * 0.32
+ d.ellipse([sx - shine, sy - shine, sx + shine, sy + shine], fill=PET_ORB_HIGHLIGHT)
+
+
+def _slash(d: ImageDraw.ImageDraw, cx: float, cy: float, r: float, color, w: int) -> None:
+ s = r * 0.74
+ d.line([(cx - s, cy + s), (cx + s, cy - s)], fill=color, width=w)
+
+
+def _pet_icon_color(action: str, state: PetStripState) -> _Rgb:
+ if state.hovered == action:
+ return BTN_ICON_HOVER
+ return BTN_ICON
+
+
+def _render_pen_disc(state: PetStripState, diameter: int) -> Image.Image:
+ size = diameter * _SS
+ hovered = state.hovered == "compose"
+ layer = Image.new("RGB", (size, size), BTN_BG_HOVER if hovered else BTN_BG)
+ d = ImageDraw.Draw(layer)
+ stroke = max(1, round(1.0 * _SS))
+ d.ellipse(
+ [stroke, stroke, size - 1 - stroke, size - 1 - stroke], outline=BTN_BORDER, width=stroke
+ )
+ glyph_w = max(1, round(1.35 * _SS))
+ _draw_pen(d, size / 2.0, size / 2.0, size * 0.30, _pet_icon_color("compose", state), glyph_w)
+ return layer.resize((diameter, diameter), Image.Resampling.LANCZOS)
+
+
+def _render_pill(state: PetStripState, layout: PetStripLayout) -> Image.Image:
+ x0, y0, x1, y1 = layout.pill
+ width, height = x1 - x0, y1 - y0
+ w_ss, h_ss = width * _SS, height * _SS
+ layer = Image.new("RGB", (w_ss, h_ss), BTN_BG)
+ d = ImageDraw.Draw(layer)
+ stroke = max(1, round(1.0 * _SS))
+ glyph_w = max(1, round(1.35 * _SS))
+ for action, sx0, sx1 in layout.slots:
+ if state.hovered == action:
+ d.rectangle([(sx0 - x0) * _SS, 0, (sx1 - x0) * _SS - 1, h_ss - 1], fill=BTN_BG_HOVER)
+ for dx, (_action, next_x0, _next_x1) in zip(layout.dividers, layout.slots[1:], strict=False):
+ d.rectangle(
+ [(dx - x0) * _SS, h_ss * 0.22, (next_x0 - x0) * _SS - 1, h_ss * 0.78],
+ fill=PET_DIVIDER,
+ )
+ d.rounded_rectangle(
+ [stroke, stroke, w_ss - 1 - stroke, h_ss - 1 - stroke],
+ radius=(h_ss - 2 * stroke) / 2.0,
+ outline=BTN_BORDER,
+ width=stroke,
+ )
+ cy = h_ss / 2.0
+ for action, sx0, sx1 in layout.slots:
+ cx = ((sx0 + sx1) / 2.0 - x0) * _SS
+ radius = (sx1 - sx0) * _SS * 0.30
+ colour = _pet_icon_color(action, state)
+ if action == "mic_mute":
+ _draw_mic(d, cx, cy, radius, colour, glyph_w, slashed=False)
+ if state.mic_muted:
+ _slash(d, cx, cy, radius, BTN_ICON_OFF, glyph_w)
+ elif action == "orb":
+ _draw_orb(d, cx, cy, radius * 1.4, active=state.active, level=state.level)
+ else:
+ _draw_speaker(d, cx, cy, radius, colour, glyph_w, muted=False)
+ if state.speaker_muted:
+ _slash(d, cx, cy, radius, BTN_ICON_OFF, glyph_w)
+ return layer.resize((width, height), Image.Resampling.LANCZOS)
+
+
+def _binary_stadium_mask(width: int, height: int) -> Image.Image:
+ """Aliased pill mask. Binary on purpose — see the module docstring."""
+ mask = Image.new("L", (width, height), 0)
+ ImageDraw.Draw(mask).rounded_rectangle(
+ [0, 0, width - 1, height - 1], radius=(height - 1) / 2.0, fill=255
+ )
+ return mask
+
+
[email protected]_cache(maxsize=96)
+def render_pet_strip(
+ state: PetStripState,
+ scale: float = 1.0,
+ color_key: tuple[int, int, int] = (255, 0, 255),
+) -> Image.Image:
+ """The pet strip as a colour-keyed RGB frame, ready for a layered window.
+
+ Cached: the state space is small (a few flags, a hovered action and a
+ quantised pulse step), so a strip at rest costs one render per look and a
+ pulsing orb cycles through a handful of cached frames. Callers must not
+ mutate the returned image.
+ """
+ layout = pet_strip_layout(scale)
+ frame = Image.new("RGB", (layout.width, layout.height), color_key)
+ pcx, pcy, pr = layout.pen
+ diameter = int(round(pr * 2))
+ pen = _render_pen_disc(state, diameter)
+ frame.paste(pen, (int(round(pcx - pr)), int(round(pcy - pr))), _disc_mask(diameter))
+ x0, y0, x1, y1 = layout.pill
+ pill = _render_pill(state, layout)
+ frame.paste(pill, (x0, y0), _binary_stadium_mask(x1 - x0, y1 - y0))
+ return frame
+
+
+def toggle_speaker_mute(source: str = "orb") -> bool | None:
"""Mute / unmute the assistant's voice for this session. Returns the new state.
Session-only by design, exactly like the in-app speaker button: a mute the
user forgot about must not survive a restart and leave Jarvis mysteriously
silent tomorrow. Nothing is written to ``jarvis.toml``.
+ ``source`` names the control for the pipeline's ``VoiceSpeakerMuteChanged``
+ broadcast (``"orb"``, ``"pet"``).
+
Returns ``None`` when there is no live pipeline to talk to (a headless or
still-booting host), so the caller can leave the icon alone instead of
lying about a mute that never happened.
@@ -386,12 +687,27 @@ def toggle_speaker_mute() -> bool | None:
current = _current_tts_volume(pipeline)
if current > 0.0:
_remember_volume(pipeline, current)
- setter(0.0)
+ _apply_volume(setter, 0.0, source)
return True
- setter(_remembered_volume(pipeline))
+ _apply_volume(setter, _remembered_volume(pipeline), source)
return False
+def _apply_volume(setter: Callable[..., object], volume: float, source: str) -> None:
+ """Call ``set_tts_volume`` with ``source`` when the pipeline takes one."""
+ try:
+ params = inspect.signature(setter).parameters
+ except (TypeError, ValueError): # a builtin or C callable: no signature
+ params = {}
+ takes_source = "source" in params or any(
+ p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()
+ )
+ if takes_source:
+ setter(volume, source=source)
+ else:
+ setter(volume)
+
+
#: Where the pre-mute volume is parked, keyed per pipeline instance so a
#: restarted pipeline cannot inherit a stale value.
_PRE_MUTE_VOLUME: dict[int, float] = {}
diff --git a/ui/orb/overlay.py b/ui/orb/overlay.py
index 5229ae612a..032a0955ba 100644
--- a/ui/orb/overlay.py
+++ b/ui/orb/overlay.py
@@ -56,8 +56,9 @@ import threading
import time
import tkinter as tk
import tkinter.font as tkfont
-from collections.abc import Callable
-from dataclasses import dataclass
+from collections import OrderedDict
+from collections.abc import Callable, Hashable
+from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
@@ -67,7 +68,8 @@ from PIL import Image, ImageDraw, ImageFilter, ImageTk
from jarvis.core.config import DEFAULT_CONFIG_FILE as JARVIS_TOML_PATH
from jarvis.core.win32_dpi import ensure_dpi_awareness as _ensure_dpi_awareness
from jarvis.ui.jarvisbar.modes import MODES
-from jarvis.ui.overlay_styles import LEGACY_STYLE_ALIASES, ORB_STYLES
+from jarvis.ui.overlay_styles import LEGACY_STYLE_ALIASES, ORB_STYLES, PERSISTENT_ORB_STYLES
+from jarvis.ui.pets.states import DEFAULT_PET_ID, NO_PET_ID, ONE_SHOT_STATES
from ui.orb import controls as orb_controls
from ui.orb.animations import (
ANIMATION_REGISTRY,
@@ -88,6 +90,7 @@ from ui.orb.drag_persistence import (
save_position_to_toml,
screens_from_tk,
)
+from ui.orb.pet_renderer import PET_TARGET_EDGE_PX, PetRenderer, dpi_ratio_for
from ui.orb.taskbar import (
MascotAnchor,
compute_mascot_position,
@@ -130,10 +133,21 @@ VOICE_ORB_WIN_W = 216
VOICE_ORB_WIN_H = 216
-def window_size_for_style(style: str) -> tuple[int, int]:
- """Window edge length for one orb style."""
+def window_size_for_style(style: str, renderer: object | None = None) -> tuple[int, int]:
+ """Window size for one orb style.
+
+ The pet's size is not a constant: it comes from its sprite sheet, the
+ monitor's DPI and the user's ``pet_scale``, all of which the loaded
+ :class:`PetRenderer` knows. Before one exists the pet gets its nominal
+ edge, which the real size replaces the moment the pack is loaded.
+ """
if style == "voice_orb":
return VOICE_ORB_WIN_W, VOICE_ORB_WIN_H
+ if style == "pet":
+ size = getattr(renderer, "size", None)
+ if isinstance(size, tuple) and len(size) == 2:
+ return max(1, int(size[0])), max(1, int(size[1]))
+ return PET_TARGET_EDGE_PX, PET_TARGET_EDGE_PX
return WIN_W, WIN_H
@@ -212,6 +226,10 @@ class BubbleTheme:
#: and the in-app bubble it copies has no tail either.
tail: bool
corner_radius: int
+ #: The pet's status lines are read as narration, not speech.
+ italic: bool = False
+ #: The muted header line above a pet status ("Thinking …").
+ header: str = "#8A8A8A"
#: The Gigi bubble, unchanged — the ghost's own voice.
@@ -240,9 +258,91 @@ ORB_BUBBLE_THEME = BubbleTheme(
)
+#: The pet's status bubble: the app's own card look (a dark rounded surface, a
+#: hairline border, light italic narration under a muted header) and no tail —
+#: it reports what Jarvis is doing, it is not the pet talking.
+PET_BUBBLE_THEME = BubbleTheme(
+ bg="#141414",
+ border="#2E2E2E",
+ text="#E6E6E6",
+ border_width=1,
+ bold=False,
+ tail=False,
+ corner_radius=16,
+ italic=True,
+ header="#8A8A8A",
+)
+
+
def bubble_theme_for_style(style: str) -> BubbleTheme:
"""The bubble look one orb style wears."""
- return ORB_BUBBLE_THEME if style == "voice_orb" else MASCOT_BUBBLE_THEME
+ if style == "voice_orb":
+ return ORB_BUBBLE_THEME
+ if style == "pet":
+ return PET_BUBBLE_THEME
+ return MASCOT_BUBBLE_THEME
+
+
+# The pet's status bubble (docs/pets.md): below the control strip, two lines
+# collapsed, six after a click, gone six seconds after the last update once
+# Jarvis is idle again. Pixel sizes are at 100 % and scale with the DPI ratio.
+PET_BUBBLE_WIDTH = 260
+PET_BUBBLE_COLLAPSED_LINES = 2
+PET_BUBBLE_EXPANDED_LINES = 6
+PET_BUBBLE_GAP = 6
+PET_BUBBLE_IDLE_HIDE_MS = 6000
+PET_BUBBLE_BODY_FONT_SIZE = 11
+PET_BUBBLE_HEADER_FONT_SIZE = 9
+PET_BUBBLE_HEADER_GAP = 2
+PET_BUBBLE_ELLIPSIS = "…"
+
+
+def wrap_text_lines(
+ text: str,
+ measure: Callable[[str], int],
+ max_width: int,
+ max_lines: int,
+ ellipsis: str = PET_BUBBLE_ELLIPSIS,
+) -> list[str]:
+ """Word-wrap ``text`` into at most ``max_lines`` lines of ``max_width`` pixels.
+
+ ``measure`` returns a string's width in pixels (``tkfont.Font.measure`` in
+ the overlay, a plain character count in tests). A word wider than a whole
+ line is broken by characters. When the text does not fit, the last kept
+ line ends in ``ellipsis`` so a truncated status never reads as complete.
+ """
+ limit = max(1, int(max_lines))
+ width = max(1, int(max_width))
+ lines: list[str] = []
+ current = ""
+ for word in " ".join(str(text or "").split()).split(" "):
+ if not word:
+ continue
+ candidate = f"{current} {word}" if current else word
+ if measure(candidate) <= width:
+ current = candidate
+ continue
+ if current:
+ lines.append(current)
+ while len(word) > 1 and measure(word) > width:
+ cut = len(word) - 1
+ while cut > 1 and measure(word[:cut]) > width:
+ cut -= 1
+ lines.append(word[:cut])
+ word = word[cut:]
+ current = word
+ if len(lines) > limit:
+ break
+ if current and len(lines) <= limit:
+ lines.append(current)
+ if len(lines) <= limit:
+ return lines
+ kept = lines[:limit]
+ last = kept[-1]
+ while last and measure(last + ellipsis) > width:
+ last = last[:-1].rstrip()
+ kept[-1] = last + ellipsis
+ return kept
# Magenta color key — Tkinter renders this color pixel-perfect transparent
@@ -1185,6 +1285,17 @@ class OrbCommentBubble:
self._queued_text: str | None = None
self._queued_duration_ms: int = 0
self._queue_after_id: str | None = None
+ # The pet's status variant (show_status): its own fonts, content,
+ # placement and expand state, so the comment/transcript variants the
+ # mascot uses stay exactly as they were.
+ self._status_font: tkfont.Font | None = None
+ self._header_font: tkfont.Font | None = None
+ self._status: tuple[str, str] | None = None
+ self._status_showing = False
+ self._status_expanded = False
+ self._status_anchor: tuple[int, int, int, int] | None = None
+ self._status_auto_hide_ms: int | None = None
+ self._ui_scale = 1.0
self._build()
def update_anchor(self, orb_x: int, orb_y: int, screen_w: int) -> None:
@@ -1277,6 +1388,11 @@ class OrbCommentBubble:
font.configure(weight=weight)
except tk.TclError:
pass
+ if self._status_font is not None:
+ try:
+ self._status_font.configure(slant="italic" if theme.italic else "roman")
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("status font restyle failed", exc_info=True)
self.hide()
def show(
@@ -1539,7 +1655,199 @@ class OrbCommentBubble:
if text:
self.show(text, duration_ms)
+ # -- the pet's status variant ------------------------------------------
+
+ def set_ui_scale(self, scale: float) -> None:
+ """Pixel sizes of the status variant follow the monitor's DPI ratio."""
+ try:
+ self._ui_scale = max(0.5, min(4.0, float(scale)))
+ except (TypeError, ValueError):
+ self._ui_scale = 1.0
+
+ @property
+ def status_showing(self) -> bool:
+ return self._status_showing
+
+ @property
+ def window(self) -> tk.Toplevel | None:
+ return self._top
+
+ def _ensure_status_fonts(self) -> bool:
+ if self._top is None or self._canvas is None:
+ return False
+ if self._status_font is None:
+ # A click expands a pet status to six lines (and collapses it
+ # again). Bound with the first status, so the mascot's comment and
+ # transcript variants keep ignoring clicks as they always have.
+ self._canvas.bind("<ButtonRelease-1>", self._on_click)
+ self._status_font = tkfont.Font(
+ root=self._top,
+ family=BUBBLE_FONT_FAMILY,
+ size=PET_BUBBLE_BODY_FONT_SIZE,
+ slant="italic" if self._theme.italic else "roman",
+ )
+ if self._header_font is None:
+ self._header_font = tkfont.Font(
+ root=self._top,
+ family=BUBBLE_FONT_FAMILY,
+ size=PET_BUBBLE_HEADER_FONT_SIZE,
+ )
+ return True
+
+ def show_status(
+ self,
+ header: str,
+ body: str,
+ *,
+ anchor: tuple[int, int, int, int],
+ auto_hide_ms: int | None,
+ ) -> None:
+ """Show (or update) the pet's condensed status lines.
+
+ ``anchor`` is ``(center_x, below_y, above_y, limit_bottom)``: the bubble
+ hangs from ``below_y`` (just under the control strip) when it fits above
+ ``limit_bottom``, else it sits on ``above_y`` (just over the figure) —
+ a pet parked on the taskbar would otherwise push its bubble off screen.
+ ``auto_hide_ms`` arms the fade timer; ``None`` keeps the bubble up.
+ """
+ if self._top is None or self._canvas is None:
+ return
+ header = " ".join(str(header or "").split())
+ body = " ".join(str(body or "").split())
+ if not header and not body:
+ self.hide()
+ return
+ self._cancel_timers()
+ self._status = (header, body)
+ self._status_anchor = anchor
+ self._status_auto_hide_ms = auto_hide_ms
+ if self._render_status():
+ self._arm_status_hide()
+
+ def move_status(self, anchor: tuple[int, int, int, int]) -> None:
+ """Follow the pet (drag, resize) without restarting the fade timer."""
+ self._status_anchor = anchor
+ if self._status_showing:
+ self._render_status()
+
+ def arm_auto_hide(self, delay_ms: int | None) -> None:
+ """(Re)arm or cancel the status fade timer."""
+ self._status_auto_hide_ms = delay_ms
+ if self._status_showing:
+ self._arm_status_hide()
+
+ def _arm_status_hide(self) -> None:
+ if self._top is None:
+ return
+ if self._dismiss_after_id is not None:
+ try:
+ self._top.after_cancel(self._dismiss_after_id)
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("bubble timer cancel failed", exc_info=True)
+ self._dismiss_after_id = None
+ delay = self._status_auto_hide_ms
+ if delay is not None:
+ self._dismiss_after_id = self._top.after(max(1, int(delay)), self.hide)
+
+ def _on_click(self, _event: tk.Event | None = None) -> None:
+ if not self._status_showing:
+ return
+ self._status_expanded = not self._status_expanded
+ self._render_status()
+ # Reading takes time: a click restarts the fade instead of racing it.
+ self._arm_status_hide()
+
+ def _render_status(self) -> bool:
+ """Paint the status variant. Returns False when nothing could be drawn."""
+ if (
+ self._top is None
+ or self._canvas is None
+ or self._status is None
+ or self._status_anchor is None
+ or not self._ensure_status_fonts()
+ ):
+ return False
+ body_font = self._status_font
+ header_font = self._header_font
+ assert body_font is not None and header_font is not None # noqa: S101 — set above
+ header, body = self._status
+ theme = self._theme
+ scale = self._ui_scale
+ pad_x = int(round(BUBBLE_PADDING_X * scale))
+ pad_y = int(round(BUBBLE_PADDING_Y * scale))
+ bubble_w = min(int(round(PET_BUBBLE_WIDTH * scale)), max(160, self._screen_w - 16))
+ text_w = max(40, bubble_w - 2 * pad_x)
+ max_lines = (
+ PET_BUBBLE_EXPANDED_LINES if self._status_expanded else PET_BUBBLE_COLLAPSED_LINES
+ )
+ lines = wrap_text_lines(body, body_font.measure, text_w, max_lines) if body else []
+ header_line = ""
+ if header:
+ header_line = wrap_text_lines(header, header_font.measure, text_w, 1)[0]
+ body_lh = max(1, int(body_font.metrics("linespace")))
+ header_lh = max(1, int(header_font.metrics("linespace")))
+ height = 2 * pad_y + body_lh * len(lines)
+ if header_line:
+ height += header_lh + (PET_BUBBLE_HEADER_GAP if lines else 0)
+
+ center_x, below_y, above_y, limit_bottom = self._status_anchor
+ x = max(8, min(center_x - bubble_w // 2, self._screen_w - bubble_w - 8))
+ y = below_y if below_y + height <= limit_bottom else max(8, above_y - height)
+ try:
+ self._top.geometry(f"{bubble_w}x{height}+{x}+{y}")
+ self._canvas.configure(width=bubble_w, height=height)
+ self._canvas.delete("all")
+ self._draw_rounded_rect(
+ 1,
+ 1,
+ bubble_w - 1,
+ height - 1,
+ theme.corner_radius,
+ fill=theme.bg,
+ outline=theme.border,
+ width=theme.border_width,
+ )
+ cursor_y = pad_y
+ if header_line:
+ self._canvas.create_text(
+ pad_x,
+ cursor_y,
+ text=header_line,
+ font=header_font,
+ anchor="nw",
+ fill=theme.header,
+ )
+ cursor_y += header_lh + PET_BUBBLE_HEADER_GAP
+ for line in lines:
+ self._canvas.create_text(
+ pad_x, cursor_y, text=line, font=body_font, anchor="nw", fill=theme.text
+ )
+ cursor_y += body_lh
+ self._top.deiconify()
+ self._top.lift()
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("pet status bubble paint failed", exc_info=True)
+ return False
+ self._status_showing = True
+ return True
+
+ def _cancel_timers(self) -> None:
+ if self._top is None:
+ return
+ for attr in ("_dismiss_after_id", "_queue_after_id"):
+ after_id = getattr(self, attr)
+ if after_id is None:
+ continue
+ try:
+ self._top.after_cancel(after_id)
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("bubble timer cancel failed", exc_info=True)
+ setattr(self, attr, None)
+ self._queued_text = None
+
def hide(self) -> None:
+ self._status_showing = False
+ self._status_expanded = False
if self._top is None:
return
if self._dismiss_after_id is not None:
@@ -1636,6 +1944,9 @@ class OrbControlRow:
#: land as "start a new session" (the request_hangup storm, 2026-06-19).
CLICK_GUARD_S = 0.6
+ #: Actions whose click arms :attr:`CLICK_GUARD_S` while a session runs.
+ GUARDED_ACTIONS: tuple[str, ...] = ("mic", "close")
+
def __init__(self, parent: tk.Tk, orb_x: int, orb_y: int, orb_w: int, orb_h: int) -> None:
self._parent = parent
self._orb_x = orb_x
@@ -1646,16 +1957,41 @@ class OrbControlRow:
self._canvas: tk.Canvas | None = None
self._photo: ImageTk.PhotoImage | None = None
self._image_id: int | None = None
- self._state = orb_controls.ControlState()
+ self._state = self._initial_state()
self._visible = False
self._pointer_inside = False
self._hide_after_id: str | None = None
self._pressed_action: str | None = None
self._click_block_until = 0.0
self._on_action: Callable[[str], None] | None = None
- self._width, self._height = orb_controls.row_size()
+ self._width, self._height = self._row_size()
self._build()
+ # -- layout hooks (the pet strip overrides these) ------------------------
+
+ def _initial_state(self) -> Any:
+ return orb_controls.ControlState()
+
+ def _row_size(self) -> tuple[int, int]:
+ return orb_controls.row_size()
+
+ def _render_frame(self) -> Image.Image:
+ return orb_controls.render_row(self._state, color_key=tuple(COLOR_KEY_RGB.tolist()))
+
+ def _hit(self, x: float, y: float) -> str | None:
+ return orb_controls.hit_test(x, y)
+
+ def _with_hovered(self, action: str | None) -> Any:
+ return orb_controls.ControlState(
+ active=self._state.active,
+ speaker_muted=self._state.speaker_muted,
+ hovered=action,
+ can_attach=self._state.can_attach,
+ )
+
+ def _row_y(self) -> int:
+ return self._orb_y + self._orb_h + orb_controls.ROW_GAP_FROM_ORB
+
# -- wiring ---------------------------------------------------------
def set_on_action(self, callback: Callable[[str], None] | None) -> None:
@@ -1727,7 +2063,7 @@ class OrbControlRow:
if self._top is None:
return
x = self._orb_x + self._orb_w // 2 - self._width // 2
- y = self._orb_y + self._orb_h + orb_controls.ROW_GAP_FROM_ORB
+ y = self._row_y()
try:
self._top.geometry(f"{self._width}x{self._height}+{x}+{y}")
except tk.TclError:
@@ -1760,7 +2096,7 @@ class OrbControlRow:
if self._canvas is None:
return
try:
- frame = orb_controls.render_row(self._state, color_key=tuple(COLOR_KEY_RGB.tolist()))
+ frame = self._render_frame()
image = key_to_alpha(frame) if self._mac_transparent else frame
self._photo = ImageTk.PhotoImage(image, master=self._canvas)
if self._image_id is None:
@@ -1790,12 +2126,7 @@ class OrbControlRow:
self._cancel_pending_hide()
self._pointer_inside = False
if self._state.hovered is not None:
- self._state = orb_controls.ControlState(
- active=self._state.active,
- speaker_muted=self._state.speaker_muted,
- hovered=None,
- can_attach=self._state.can_attach,
- )
+ self._state = self._with_hovered(None)
self._repaint()
if self._top is None or not self._visible:
return
@@ -1835,6 +2166,10 @@ class OrbControlRow:
def pointer_inside(self) -> bool:
return self._pointer_inside
+ @property
+ def window(self) -> tk.Toplevel | None:
+ return self._top
+
@property
def visible(self) -> bool:
return self._visible
@@ -1865,17 +2200,12 @@ class OrbControlRow:
self.hide_after_grace()
def _on_motion(self, event: tk.Event) -> None:
- self._set_hovered(orb_controls.hit_test(event.x, event.y))
+ self._set_hovered(self._hit(event.x, event.y))
def _set_hovered(self, action: str | None) -> None:
if action == self._state.hovered:
return
- self._state = orb_controls.ControlState(
- active=self._state.active,
- speaker_muted=self._state.speaker_muted,
- hovered=action,
- can_attach=self._state.can_attach,
- )
+ self._state = self._with_hovered(action)
self._repaint()
if self._canvas is not None:
try:
@@ -1884,7 +2214,7 @@ class OrbControlRow:
pass
def _on_press(self, event: tk.Event) -> None:
- self._pressed_action = orb_controls.hit_test(event.x, event.y)
+ self._pressed_action = self._hit(event.x, event.y)
def _on_release(self, event: tk.Event) -> None:
pressed = self._pressed_action
@@ -1894,11 +2224,11 @@ class OrbControlRow:
# Press and release must agree: a pointer that slid off the disc did
# not click it, and every action here is one the user would rather not
# trigger by accident.
- if orb_controls.hit_test(event.x, event.y) != pressed:
+ if self._hit(event.x, event.y) != pressed:
return
if time.monotonic() < self._click_block_until:
return
- if pressed in ("mic", "close") and self._state.active:
+ if pressed in self.GUARDED_ACTIONS and self._state.active:
self._click_block_until = time.monotonic() + self.CLICK_GUARD_S
callback = self._on_action
if callback is None:
@@ -1911,6 +2241,155 @@ class OrbControlRow:
)
+class PetControlStrip(OrbControlRow):
+ """The pet's control strip — see ``ui.orb.controls`` (``PET_ACTIONS``).
+
+ The voice orb's row with three differences that make it the pet's own: it
+ stays up whenever the pet is on screen (a companion, not a pop-up), its
+ empty area is a drag handle for the whole group (the only one when the pet
+ is "None"), and its orb pulses with the live audio level through cached
+ frames, so a strip at rest never repaints.
+ """
+
+ GUARDED_ACTIONS: tuple[str, ...] = ("orb",)
+
+ def __init__(
+ self,
+ parent: tk.Tk,
+ orb_x: int,
+ orb_y: int,
+ orb_w: int,
+ orb_h: int,
+ *,
+ scale: float = 1.0,
+ on_drag_press: Callable[[Any], None] | None = None,
+ on_drag_motion: Callable[[Any], None] | None = None,
+ on_drag_release: Callable[[Any], None] | None = None,
+ on_context: Callable[[Any], None] | None = None,
+ ) -> None:
+ self._scale = float(scale)
+ self._on_drag_press = on_drag_press
+ self._on_drag_motion = on_drag_motion
+ self._on_drag_release = on_drag_release
+ self._on_context = on_context
+ self._dragging = False
+ super().__init__(parent, orb_x, orb_y, orb_w, orb_h)
+
+ # -- layout hooks -----------------------------------------------------
+
+ def _initial_state(self) -> orb_controls.PetStripState:
+ return orb_controls.PetStripState()
+
+ def _row_size(self) -> tuple[int, int]:
+ return orb_controls.pet_strip_size(self._scale)
+
+ def _render_frame(self) -> Image.Image:
+ return orb_controls.render_pet_strip(
+ self._state, self._scale, tuple(int(c) for c in COLOR_KEY_RGB)
+ )
+
+ def _hit(self, x: float, y: float) -> str | None:
+ return orb_controls.pet_hit_test(x, y, self._scale)
+
+ def _with_hovered(self, action: str | None) -> orb_controls.PetStripState:
+ return replace(self._state, hovered=action)
+
+ def _row_y(self) -> int:
+ gap = max(1, int(round(orb_controls.PET_STRIP_GAP_FROM_FIGURE * self._scale)))
+ return self._orb_y + self._orb_h + gap
+
+ def _build(self) -> None:
+ super()._build()
+ if self._canvas is not None:
+ self._canvas.bind("<B1-Motion>", self._on_drag_motion_event)
+ self._canvas.bind("<Button-3>", self._on_context_event)
+
+ # -- state ------------------------------------------------------------
+
+ @property
+ def state(self) -> orb_controls.PetStripState:
+ return self._state
+
+ def set_state(
+ self,
+ *,
+ active: bool | None = None,
+ speaker_muted: bool | None = None,
+ can_attach: bool | None = None,
+ mic_muted: bool | None = None,
+ level: int | None = None,
+ ) -> None:
+ """Update what the strip says, repainting only on a real change."""
+ _ = can_attach # the pet strip has no attach control
+ current = self._state
+ state = orb_controls.PetStripState(
+ mic_muted=current.mic_muted if mic_muted is None else bool(mic_muted),
+ speaker_muted=current.speaker_muted if speaker_muted is None else bool(speaker_muted),
+ active=current.active if active is None else bool(active),
+ level=current.level if level is None else int(level),
+ hovered=current.hovered,
+ )
+ if state == current:
+ return
+ self._state = state
+ self._repaint()
+
+ # -- pointer ----------------------------------------------------------
+
+ def hide_after_grace(self) -> None:
+ """The strip stays while the pet is on screen; the pointer leaving is not a reason."""
+
+ def _on_leave(self, _event: tk.Event) -> None:
+ self._pointer_inside = False
+ self._set_hovered(None)
+
+ def _on_press(self, event: tk.Event) -> None:
+ super()._on_press(event)
+ self._dragging = self._pressed_action is None
+ if self._dragging and self._on_drag_press is not None:
+ self._on_drag_press(event)
+
+ def _on_drag_motion_event(self, event: tk.Event) -> None:
+ if self._dragging and self._on_drag_motion is not None:
+ self._on_drag_motion(event)
+
+ def _on_release(self, event: tk.Event) -> None:
+ if self._dragging:
+ self._dragging = False
+ self._pressed_action = None
+ if self._on_drag_release is not None:
+ self._on_drag_release(event)
+ return
+ super()._on_release(event)
+
+ def _on_context_event(self, event: tk.Event) -> None:
+ if self._on_context is not None:
+ self._on_context(event)
+
+
+def _clamp_pet_scale(value: object) -> float:
+ """``[ui] pet_scale`` as a usable multiplier (0.5–2.0, 1.0 when unusable)."""
+ try:
+ scale = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return 1.0
+ if not math.isfinite(scale):
+ return 1.0
+ return max(0.5, min(2.0, scale))
+
+
+#: Pet Tk images kept per frame key. A pet has at most 7 states x 8 frames;
+#: the bound only matters when a user flips between pets or sizes.
+PET_PHOTO_CACHE_MAX = 64
+
+#: The mascot and voice orb repaint on a fixed ~60 fps timer.
+FRAME_INTERVAL_MS = 16
+
+#: While the strip's orb pulses (listening / talking) the pet ticks at least
+#: this often, so the pulse follows the voice even when the figure is slow.
+PET_PULSE_INTERVAL_MS = 100
+
+
class OrbOverlay:
"""Public facade — Tkinter-based, thread-safe via root.after(0, ...).
@@ -1925,12 +2404,18 @@ class OrbOverlay:
mic_reactive: bool = False,
style: str | None = None,
mascot_path: str | Path | None = None,
+ pet_id: str | None = None,
+ pet_scale: float | None = 1.0,
+ pet_bubble: bool = True,
) -> None:
"""
- style: one of :data:`ORB_STYLES` — ``"mascot"`` (the Gigi ghost) or
- ``"voice_orb"`` (the procedural weather sphere). Anything else,
+ style: one of :data:`ORB_STYLES` — ``"mascot"`` (the Gigi ghost),
+ ``"voice_orb"`` (the procedural weather sphere) or ``"pet"`` (an
+ animated pixel-art companion, ``docs/pets.md``). Anything else,
including the legacy ``"orb"``, is coerced to ``"mascot"``.
mascot_path: optional explicit path, otherwise via ENV or the default asset.
+ pet_id / pet_scale / pet_bubble: the pet style's ``[ui]`` settings — which
+ pet, its size multiplier (0.5–2.0) and whether the status bubble shows.
ENV-Override: ``JARVIS_ORB_STYLE=mascot|voice_orb`` selects the look;
unknown values are ignored.
"""
@@ -1972,6 +2457,25 @@ class OrbOverlay:
self._controls: OrbControlRow | None = None
self._pointer_over_orb = False
self._speaker_muted = False
+ # --- the desktop pet (style "pet", docs/pets.md) ---
+ self._pet_id = str(pet_id or DEFAULT_PET_ID).strip() or DEFAULT_PET_ID
+ self._pet_scale = _clamp_pet_scale(1.0 if pet_scale is None else pet_scale)
+ self._pet_bubble = bool(pet_bubble)
+ #: Mirrors ``VoiceMuteChanged`` for the strip's microphone control.
+ self._mic_muted = False
+ #: Hidden by the shortcut or the settings page — lasts until restart.
+ self._user_hidden = False
+ self._on_compose: Callable[[], None] | None = None
+ #: The monitor's display scale (1.0 at 100 %), read once the root exists.
+ self._dpi_ratio = 1.0
+ # Frame-loop bookkeeping: ONE pending tick at most, and for renderers
+ # that name their frames (the pet) one cached Tk image per frame.
+ self._frame_after_id: str | None = None
+ self._frame_key: Hashable | None = None
+ self._photo_cache: OrderedDict[Hashable, Any] = OrderedDict()
+ self._frame_error_logged = False
+ self._topmost_fns: tuple[Callable[..., Any], Callable[..., Any]] | None = None
+ self._work_area_cache: tuple[tuple[int, int], int] | None = None
# Counter + Tk timer-id for the two-double-click gesture. The
# earlier single-double-click implementation muted Jarvis as soon
# as the user clicked twice on the popup logo, which fired
@@ -2093,6 +2597,12 @@ class OrbOverlay:
_apply_jarvis_icon_to_tk_root(self._root)
_hide_tk_window_from_task_switcher(self._root)
_exclude_tk_window_from_capture(self._root)
+ self._dpi_ratio = self._read_dpi_ratio()
+ if self._style == "pet":
+ # The pet's window size comes from its sprite sheet, so the pack is
+ # loaded before the anchor below is computed from that size.
+ self._renderer = self._build_renderer("pet")
+ self._win_w, self._win_h = window_size_for_style("pet", self._renderer)
# Resolve mascot anchor. If the user has manually pinned the orb
# in a prior session, restore that position; otherwise compute
@@ -2234,9 +2744,11 @@ class OrbOverlay:
screen_w=screen_w,
theme=bubble_theme_for_style(self._style),
)
+ self._comment_bubble.set_ui_scale(self._dpi_ratio)
self._ensure_controls()
- self._renderer = self._build_renderer(self._style)
+ if self._renderer is None:
+ self._renderer = self._build_renderer(self._style)
self._t0 = time.perf_counter()
self._running = True
@@ -2269,26 +2781,83 @@ class OrbOverlay:
threading.Thread(target=self._run_demo, daemon=True).start()
self._schedule_ui_queue()
- self._schedule_frame()
+ # Through the guard, not a direct call: a show() drained just above may
+ # already have armed the loop, and a second chain would double every tick.
+ self._ensure_frame_loop()
self._schedule_position_recheck()
self._root.mainloop()
def _resolve_anchor(self, screen_w: int, screen_h: int) -> MascotAnchor:
- """Read live taskbar+tray rects from Win32 and compute mascot anchor."""
+ """Read live taskbar+tray rects from Win32 and compute mascot anchor.
+
+ The pet is not square and carries its control strip below it, so its
+ anchor takes x from its width, y from its height, and then lifts the
+ whole group until the STRIP stands on the taskbar line.
+ """
taskbar = get_taskbar_info()
tray_rect = get_tray_notify_rect()
- return compute_mascot_position(
- screen_w,
- screen_h,
- mascot_size=self._win_w,
- 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,
- autohide_bottom_margin_px=AUTOHIDE_BOTTOM_MARGIN_PX,
+
+ def _anchor(size: int) -> MascotAnchor:
+ return compute_mascot_position(
+ screen_w,
+ screen_h,
+ mascot_size=size,
+ 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,
+ autohide_bottom_margin_px=AUTOHIDE_BOTTOM_MARGIN_PX,
+ )
+
+ if self._style != "pet":
+ return _anchor(self._win_w)
+ by_width = _anchor(self._win_w)
+ by_height = _anchor(self._win_h)
+ return MascotAnchor(
+ x=by_width.x,
+ y=max(8, by_height.y - self._pet_below_height()),
+ taskbar_aligned=by_height.taskbar_aligned,
)
+ def _pet_below_height(self) -> int:
+ """Height of what hangs under the pet's figure: the gap plus the strip."""
+ _strip_w, strip_h = orb_controls.pet_strip_size(self._dpi_ratio)
+ gap = max(1, int(round(orb_controls.PET_STRIP_GAP_FROM_FIGURE * self._dpi_ratio)))
+ return strip_h + gap
+
+ def _clamp_position(
+ self, x: int, y: int, monitor_geo: tuple[int, int, int, int]
+ ) -> tuple[int, int]:
+ """Keep the window (for the pet: the figure plus its strip) on screen."""
+ if self._style != "pet":
+ return clamp_to_work_area(x, y, monitor_geo, mascot_size_px=self._win_w)
+ clamped_x, _ = clamp_to_work_area(x, y, monitor_geo, mascot_size_px=self._win_w)
+ _, clamped_y = clamp_to_work_area(
+ x, y, monitor_geo, mascot_size_px=self._win_h + self._pet_below_height()
+ )
+ return clamped_x, clamped_y
+
+ def _move_attached(self, x: int, y: int, screen_w: int) -> None:
+ """Bring the bubble and the control row along after the window moved."""
+ bubble = self._comment_bubble
+ if bubble is not None:
+ if self._style == "pet":
+ bubble.move_status(self._status_anchor(refresh_limit=False))
+ else:
+ bubble.update_anchor(x, y, screen_w)
+ if self._controls is not None:
+ self._controls.update_anchor(x, y)
+
+ def _read_dpi_ratio(self) -> float:
+ """The monitor's display scale as Tk sees it (1.0 at 100 %)."""
+ if self._root is None:
+ return 1.0
+ try:
+ return dpi_ratio_for(float(self._root.winfo_fpixels("1i")))
+ except (tk.TclError, TypeError, ValueError):
+ return 1.0
+
def _schedule_position_recheck(self) -> None:
"""Re-resolve the mascot anchor periodically.
@@ -2306,17 +2875,14 @@ class OrbOverlay:
if self._manual_pinned:
screens = screens_from_tk(self._root)
monitor_geo, monitor_name = self._monitor_at_orb_center(screens)
- clamped_x, clamped_y = clamp_to_work_area(
- self._mascot_x, self._mascot_y, monitor_geo, mascot_size_px=self._win_w
+ clamped_x, clamped_y = self._clamp_position(
+ self._mascot_x, self._mascot_y, monitor_geo
)
if (clamped_x, clamped_y) != (self._mascot_x, self._mascot_y):
self._mascot_x = clamped_x
self._mascot_y = clamped_y
self._root.geometry(f"{self._win_w}x{self._win_h}+{clamped_x}+{clamped_y}")
- if self._comment_bubble is not None:
- self._comment_bubble.update_anchor(clamped_x, clamped_y, screen_w)
- if self._controls is not None:
- self._controls.update_anchor(clamped_x, clamped_y)
+ self._move_attached(clamped_x, clamped_y, screen_w)
try:
save_position_to_toml(
JARVIS_TOML_PATH,
@@ -2334,15 +2900,60 @@ class OrbOverlay:
self._mascot_x = anchor.x
self._mascot_y = anchor.y
self._root.geometry(f"{self._win_w}x{self._win_h}+{anchor.x}+{anchor.y}")
- if self._comment_bubble is not None:
- self._comment_bubble.update_anchor(anchor.x, anchor.y, screen_w)
- if self._controls is not None:
- self._controls.update_anchor(anchor.x, anchor.y)
+ self._move_attached(anchor.x, anchor.y, screen_w)
+ if self._style == "pet":
+ # Same cadence, one more job: a persistent pet must not sink
+ # under a freshly opened window (see _reassert_topmost).
+ self._reassert_topmost()
except (tk.TclError, OSError):
- pass
+ logging.getLogger("jarvis.orb").debug("orb position recheck skipped", exc_info=True)
if self._root is not None:
self._root.after(POSITION_RECHECK_MS, self._schedule_position_recheck)
+ def _topmost_helpers(
+ self,
+ ) -> tuple[Callable[..., Any], Callable[..., Any]] | None:
+ """The Jarvis Bar's Win32 Z-order probe and repair, imported once."""
+ if self._topmost_fns is None:
+ try:
+ from jarvis.ui.jarvisbar.overlay import ( # noqa: PLC0415
+ _win32_force_topmost,
+ _win32_topmost_band_is_healthy,
+ )
+ except Exception: # noqa: BLE001 — cosmetic; the -topmost flag remains
+ logging.getLogger("jarvis.orb").debug("topmost helpers unavailable", exc_info=True)
+ return None
+ self._topmost_fns = (_win32_topmost_band_is_healthy, _win32_force_topmost)
+ return self._topmost_fns
+
+ def _reassert_topmost(self, *, force: bool = False) -> None:
+ """Put the pet's windows back in Windows' real topmost band.
+
+ A mapped Tk window can keep its topmost flag and still sit under an
+ ordinary window (the Jarvis Bar's bug, same cure). ``SWP_NOACTIVATE``
+ inside the helper keeps this from ever stealing focus. Windows only;
+ elsewhere Tk's ``-topmost`` request is all there is.
+ """
+ if sys.platform != "win32" or self._root is None or not self._window_mapped():
+ return
+ helpers = self._topmost_helpers()
+ if helpers is None:
+ return
+ is_healthy, force_topmost = helpers
+ windows: list[Any] = [self._root]
+ row = self._controls
+ if row is not None and row.visible and row.window is not None:
+ windows.append(row.window)
+ bubble = self._comment_bubble
+ if bubble is not None and bubble.status_showing and bubble.window is not None:
+ windows.append(bubble.window)
+ for window in windows:
+ try:
+ if force or is_healthy(window) is not True:
+ force_topmost(window)
+ except Exception: # noqa: BLE001 — Z-order repair is best-effort
+ logging.getLogger("jarvis.orb").debug("topmost re-assert failed", exc_info=True)
+
# ------------------------------------------------------------------
# Drag-and-pin handlers (Spec: docs/superpowers/specs/2026-05-17-orb-drag-design.md)
# ------------------------------------------------------------------
@@ -2378,11 +2989,7 @@ class OrbOverlay:
self._root.geometry(f"{self._win_w}x{self._win_h}+{new_x}+{new_y}")
except tk.TclError:
return
- if self._comment_bubble is not None:
- screen_w = self._root.winfo_screenwidth()
- self._comment_bubble.update_anchor(new_x, new_y, screen_w)
- if self._controls is not None:
- self._controls.update_anchor(new_x, new_y)
+ self._move_attached(new_x, new_y, self._root.winfo_screenwidth())
def _on_drag_release(self, _event: tk.Event) -> None:
if self._root is not None:
@@ -2397,18 +3004,21 @@ class OrbOverlay:
screens = screens_from_tk(self._root)
monitor_geo, monitor_name = self._monitor_at_orb_center(screens)
- clamped_x, clamped_y = clamp_to_work_area(
- self._mascot_x, self._mascot_y, monitor_geo, mascot_size_px=self._win_w
- )
+ clamped_x, clamped_y = self._clamp_position(self._mascot_x, self._mascot_y, monitor_geo)
if (clamped_x, clamped_y) != (self._mascot_x, self._mascot_y):
self._mascot_x = clamped_x
self._mascot_y = clamped_y
try:
self._root.geometry(f"{self._win_w}x{self._win_h}+{clamped_x}+{clamped_y}")
except tk.TclError:
- pass
+ logging.getLogger("jarvis.orb").debug("orb clamp move failed", exc_info=True)
+ if self._style == "pet":
+ # The monitor may have changed with the drop: re-read its work area.
+ self._work_area_cache = None
if self._controls is not None:
self._controls.update_anchor(self._mascot_x, self._mascot_y)
+ if self._style == "pet" and self._comment_bubble is not None:
+ self._comment_bubble.move_status(self._status_anchor())
self._manual_pinned = True
try:
@@ -2444,11 +3054,16 @@ class OrbOverlay:
# ------------------------------------------------------------------
def _controls_wanted(self) -> bool:
- """Does this style show the control row at all?"""
- return self._style == "voice_orb"
+ """Does this style show a control row at all?
+
+ The voice orb wears its four discs, the pet its strip. The mascot has
+ its own arms and expressions, and a row of discs under the ghost would
+ read as a toolbar bolted to a cartoon.
+ """
+ return self._style in ("voice_orb", "pet")
def _ensure_controls(self) -> None:
- """Create or tear down the row so it matches the current style."""
+ """Create, swap or tear down the row so it matches the current style."""
if self._root is None:
return
if not self._controls_wanted():
@@ -2456,16 +3071,34 @@ class OrbOverlay:
self._controls.destroy()
self._controls = None
return
+ wanted = PetControlStrip if self._style == "pet" else OrbControlRow
if self._controls is not None:
- return
+ if type(self._controls) is wanted:
+ return
+ self._controls.destroy()
+ self._controls = None
try:
- row = OrbControlRow(
- parent=self._root,
- orb_x=self._mascot_x,
- orb_y=self._mascot_y,
- orb_w=self._win_w,
- orb_h=self._win_h,
- )
+ if wanted is PetControlStrip:
+ row: OrbControlRow = PetControlStrip(
+ parent=self._root,
+ orb_x=self._mascot_x,
+ orb_y=self._mascot_y,
+ orb_w=self._win_w,
+ orb_h=self._win_h,
+ scale=self._dpi_ratio,
+ on_drag_press=self._on_drag_press,
+ on_drag_motion=self._on_drag_motion,
+ on_drag_release=self._on_drag_release,
+ on_context=self._on_right_click,
+ )
+ else:
+ row = OrbControlRow(
+ parent=self._root,
+ orb_x=self._mascot_x,
+ orb_y=self._mascot_y,
+ orb_w=self._win_w,
+ orb_h=self._win_h,
+ )
except tk.TclError:
logging.getLogger("jarvis.orb").debug("orb control row unavailable", exc_info=True)
return
@@ -2474,6 +3107,8 @@ class OrbOverlay:
active=self._mode in ("listen", "think", "speak"),
speaker_muted=self._speaker_muted,
)
+ if isinstance(row, PetControlStrip):
+ row.set_state(mic_muted=self._mic_muted)
self._controls = row
def _on_orb_pointer_enter(self, _event: tk.Event | None = None) -> None:
@@ -2485,7 +3120,8 @@ class OrbOverlay:
def _on_orb_pointer_leave(self, _event: tk.Event | None = None) -> None:
self._pointer_over_orb = False
row = self._controls
- if row is None:
+ if row is None or self._style == "pet":
+ # The pet's strip stays while the pet does.
return
# A live conversation keeps the controls out: hanging up is the one
# thing the user reaches for mid-call, and hunting for a row that hides
@@ -2501,6 +3137,13 @@ class OrbOverlay:
return
active = self._mode in ("listen", "think", "speak")
row.set_state(active=active)
+ if self._style == "pet":
+ # The pet's strip lives exactly as long as the pet is on screen.
+ if self._window_mapped():
+ row.show()
+ else:
+ row.hide()
+ return
# Never on its own: the row is the orb's controls, so a mode change
# arriving while the sphere is withdrawn must not float four buttons
# over an empty desktop.
@@ -2531,12 +3174,44 @@ class OrbOverlay:
"""Run one control-row button. Always on the Tk thread."""
if action == "attach":
self._do_attach()
- elif action == "mic":
+ elif action in ("mic", "orb"):
self._do_talk_or_hangup()
elif action == "close":
self._do_close()
elif action == "speaker":
self._do_speaker_toggle()
+ elif action == "compose":
+ self._do_compose()
+ elif action == "mic_mute":
+ self._do_mic_mute()
+
+ def _do_compose(self) -> None:
+ """The pen: raise the main window on a fresh chat (``ComposeRequested``).
+
+ Without a compose callback (an older bridge) the right-click action is
+ the honest fallback — it at least brings the window up.
+ """
+ callback = self._on_compose or self._on_show_window
+ if callback is None:
+ logging.getLogger("jarvis.orb").info("pet compose ignored — nothing wired")
+ return
+ callback()
+
+ def _do_mic_mute(self) -> None:
+ """The strip's microphone: flip Jarvis's mute.
+
+ The flip on the strip is optimistic; ``set_muted`` (fed by
+ ``VoiceMuteChanged``) reconciles it with what the pipeline really did.
+ Unwired, nothing is flipped — a mute icon that mutes nothing lies.
+ """
+ if self._mute_toggle_callback is None:
+ logging.getLogger("jarvis.orb").info("pet mic mute ignored — nothing wired")
+ return
+ self._mic_muted = not self._mic_muted
+ row = self._controls
+ if isinstance(row, PetControlStrip):
+ row.set_state(mic_muted=self._mic_muted)
+ self._fire_mute_toggle()
def _do_attach(self) -> None:
"""Pick files and hand them to the conversation (same path as a drop)."""
@@ -2596,7 +3271,9 @@ class OrbOverlay:
# re-reads the truth via _refresh_speaker_state.
self._speaker_muted = not self._speaker_muted
else:
- result = orb_controls.toggle_speaker_mute()
+ result = orb_controls.toggle_speaker_mute(
+ source="pet" if self._style == "pet" else "orb"
+ )
if result is None:
logging.getLogger("jarvis.orb").info(
"orb speaker toggle ignored — no live speech pipeline"
@@ -2829,7 +3506,7 @@ class OrbOverlay:
def _show() -> None:
self._cancel_pending_hide()
self._set_mode(mode)
- if self._root:
+ if self._root and not self._pet_hidden_by_user():
self._root.deiconify()
if self._mac_transparent:
# Tk 9 can (re)materialize the NSWindow on mapping after a
@@ -2849,6 +3526,9 @@ class OrbOverlay:
# set elsewhere (settings slider, voice command) is reflected
# rather than remembered wrong.
self._root.after(50, self._reveal_controls)
+ if self._style == "pet":
+ self._sync_controls_visibility()
+ self._ensure_frame_loop()
now = time.perf_counter() - self._t0
self._show_until_t = max(self._show_until_t, now + self.SHOW_MIN_DURATION_S)
@@ -2876,13 +3556,17 @@ class OrbOverlay:
# Only withdraw if no active LISTENING/THINKING/SPEAKING state has
# claimed the orb during the flash window. ``_show_until_t`` is
# set by ``show()`` and stays in the future while the orb is
- # actively requested visible.
+ # actively requested visible. The pet is on screen while idle, so
+ # only a pet the user hid goes away here.
now = time.perf_counter() - self._t0
- if now >= self._show_until_t:
+ withdraw = self._user_hidden if self._style == "pet" else now >= self._show_until_t
+ if withdraw:
try:
self._root.withdraw()
except tk.TclError:
- pass
+ logging.getLogger("jarvis.orb").debug("boot-flash withdraw failed", exc_info=True)
+ elif self._style == "pet":
+ self._move_attached(target_x, target_y, self._root.winfo_screenwidth())
self._boot_flash_target_xy = None
def set_feedback_publisher(
@@ -2958,11 +3642,14 @@ class OrbOverlay:
if row is not None:
row.hide()
self._pointer_over_orb = False
+ if self._style == "pet" and self._comment_bubble is not None:
+ # The pet's status bubble hangs off the pet; it goes with it.
+ self._comment_bubble.hide()
if self._root is not None:
try:
self._root.withdraw()
except tk.TclError:
- pass
+ logging.getLogger("jarvis.orb").debug("orb withdraw failed", exc_info=True)
def stop(self) -> None:
"""Tear the mascot overlay down at runtime (live display-style swap).
@@ -2984,8 +3671,8 @@ class OrbOverlay:
bubble = self._comment_bubble
if bubble is not None and hasattr(bubble, "hide"):
bubble.hide()
- except Exception: # noqa: BLE001
- pass
+ except Exception: # noqa: BLE001 — teardown must reach root.destroy
+ logging.getLogger("jarvis.orb").debug("orb bubble teardown failed", exc_info=True)
try:
row = self._controls
self._controls = None
@@ -2997,13 +3684,13 @@ class OrbOverlay:
)
try:
root.destroy()
- except Exception: # noqa: BLE001
- pass
+ except Exception: # noqa: BLE001 — the process may be exiting anyway
+ logging.getLogger("jarvis.orb").debug("orb root destroy failed", exc_info=True)
try:
root.after(0, _teardown)
- except Exception: # noqa: BLE001
- pass
+ except Exception: # noqa: BLE001 — a dead interpreter has nothing to tear down
+ logging.getLogger("jarvis.orb").debug("orb teardown scheduling failed", exc_info=True)
def _cancel_pending_hide(self) -> None:
if self._pending_hide_after_id is not None and self._root is not None:
@@ -3023,6 +3710,8 @@ class OrbOverlay:
in how the orb moves — it swells on the voice, and its colours churn
while it thinks.
"""
+ if self._style == "pet":
+ return self._pet_bubble
return self._style != "voice_orb"
def show_comment(self, text: str, duration_ms: int = 3500) -> None:
@@ -3030,26 +3719,292 @@ class OrbOverlay:
Does NOT trigger the mouth animation — call start_mouth_animation()
separately so the mouth only moves while audio is actually playing.
+ On the pet the text lands in its status bubble instead.
"""
+ if self._style == "pet":
+ if text:
+ self.show_status("", text)
+ return
bubble = self._comment_bubble
if bubble is None or not text or not self._bubble_wanted():
return
self._enqueue_ui(lambda: bubble.show(text, duration_ms))
def show_listening_transcript(self, text: str = "", duration_ms: int = 30000) -> None:
- """Show the larger live transcript bubble used while the user speaks."""
+ """Show the larger live transcript bubble used while the user speaks.
+
+ On the pet the transcript is a status line; an empty one (a fresh turn
+ resetting the bubble) clears it instead of showing a placeholder.
+ """
+ if self._style == "pet":
+ if (text or "").strip():
+ self.show_status("", text)
+ else:
+ self._note_activity()
+ bubble = self._comment_bubble
+ if bubble is not None:
+ self._enqueue_ui(bubble.hide)
+ return
bubble = self._comment_bubble
if bubble is None or not self._bubble_wanted():
return
self._enqueue_ui(lambda: bubble.show(text, duration_ms, variant="transcript"))
def hide_comment(self) -> None:
- """Hide the speech bubble immediately. Thread-safe."""
+ """Hide the speech bubble immediately. Thread-safe.
+
+ The pet's status bubble is not snatched away the moment a turn ends:
+ it fades six seconds later, so the last line can still be read.
+ """
bubble = self._comment_bubble
if bubble is None:
return
+ if self._style == "pet":
+ self._enqueue_ui(lambda: bubble.arm_auto_hide(PET_BUBBLE_IDLE_HIDE_MS))
+ return
self._enqueue_ui(bubble.hide)
+ # --- the desktop pet (docs/pets.md "Surface methods") ------------------
+
+ @property
+ def wants_status_lines(self) -> bool:
+ """True when this surface shows condensed status lines (the pet only)."""
+ return self._style == "pet"
+
+ @property
+ def keeps_visible_when_idle(self) -> bool:
+ """True while the look is the pet: the bridge shows ``idle`` instead of hiding.
+
+ Read on every idle edge, so a live swap between the pet and the
+ mascot / voice orb changes the idle regime at once. ``hide()`` itself
+ stays a real withdraw for every look.
+ """
+ return self._style in PERSISTENT_ORB_STYLES
+
+ @property
+ def pet_user_hidden(self) -> bool:
+ """True while the user hid the pet (shortcut / settings) for this run."""
+ return self._user_hidden
+
+ def set_on_compose(self, callback: Callable[[], None] | None) -> None:
+ """Inject the pen control's action (the bridge publishes ``ComposeRequested``)."""
+ self._on_compose = callback
+
+ def set_pet(self, pet_id: str) -> None:
+ """Swap the figure live; ``"none"`` keeps the strip without a figure. Thread-safe."""
+ pet = str(pet_id or "").strip() or NO_PET_ID
+ self._pet_id = pet
+ self._note_activity()
+ self._enqueue_ui(lambda: self._apply_pet(pet))
+
+ def set_pet_look(self, scale: float | None = None, bubble: bool | None = None) -> None:
+ """Apply the pet's size multiplier and bubble on/off live. Thread-safe."""
+ if scale is not None:
+ self._pet_scale = _clamp_pet_scale(scale)
+ if bubble is not None:
+ self._pet_bubble = bool(bubble)
+ self._note_activity()
+ self._enqueue_ui(self._apply_pet_look)
+
+ def set_pet_outcome(self, kind: str) -> None:
+ """Play the one-shot ``success`` or ``error`` animation. Thread-safe."""
+ outcome = str(kind or "").strip().lower()
+ if outcome not in ONE_SHOT_STATES:
+ return
+ self._enqueue_ui(lambda: self._apply_outcome(outcome))
+
+ def show_status(self, header: str = "", line: str = "") -> None:
+ """Update the pet's status bubble with one condensed line. Thread-safe."""
+ if self._style != "pet":
+ return
+ self._note_activity()
+ if not self._pet_bubble or self._comment_bubble is None:
+ return
+ header_text = str(header or "")
+ line_text = str(line or "")
+ self._enqueue_ui(lambda: self._apply_status(header_text, line_text))
+
+ def set_muted(self, muted: bool) -> None:
+ """Mirror Jarvis's microphone mute on the strip. Thread-safe."""
+ self._mic_muted = bool(muted)
+ self._note_activity()
+ self._enqueue_ui(self._sync_strip_flags)
+
+ def set_speaker_muted(self, muted: bool) -> None:
+ """Mirror the assistant-voice mute on the speaker control. Thread-safe."""
+ self._speaker_muted = bool(muted)
+ self._note_activity()
+ self._enqueue_ui(self._sync_strip_flags)
+
+ def set_visible(self, visible: bool) -> None:
+ """Hide or show the whole pet (shortcut, settings). Runtime only. Thread-safe."""
+ self._user_hidden = not bool(visible)
+ self._note_activity()
+ self._enqueue_ui(self._apply_user_visibility)
+
+ def toggle_visible(self) -> None:
+ """The pet shortcut: hide the pet, or show it and bring it to the front."""
+ self._note_activity()
+ self._enqueue_ui(self._toggle_visible_now)
+
+ def _pet_hidden_by_user(self) -> bool:
+ return self._style == "pet" and self._user_hidden
+
+ def _note_activity(self) -> None:
+ """Every call from Jarvis keeps the pet awake (docs/pets.md "States")."""
+ if self._style != "pet":
+ return
+ self._enqueue_ui(self._apply_activity)
+
+ def _apply_activity(self) -> None:
+ renderer = self._renderer
+ if not isinstance(renderer, PetRenderer):
+ return
+ before = renderer.state()
+ renderer.on_activity()
+ if renderer.state() != before:
+ self._kick_frame()
+
+ def _apply_pet(self, pet_id: str) -> None:
+ renderer = self._renderer
+ if self._style != "pet" or not isinstance(renderer, PetRenderer):
+ return
+ renderer.load(pet_id)
+ self._refit_pet_window()
+
+ def _apply_pet_look(self) -> None:
+ if self._style != "pet":
+ return
+ if not self._pet_bubble and self._comment_bubble is not None:
+ self._comment_bubble.hide()
+ renderer = self._renderer
+ if isinstance(renderer, PetRenderer):
+ renderer.set_look(pet_scale=self._pet_scale)
+ self._refit_pet_window()
+
+ def _apply_outcome(self, kind: str) -> None:
+ renderer = self._renderer
+ if not isinstance(renderer, PetRenderer):
+ return
+ renderer.on_outcome(kind)
+ self._kick_frame()
+
+ def _refit_pet_window(self) -> None:
+ """Resize to the pet's new size, keeping its feet where they stood.
+
+ The bottom centre stays fixed, so the strip under the figure does not
+ jump when the user picks another pet or another size.
+ """
+ old_w, old_h = self._win_w, self._win_h
+ new_w, new_h = window_size_for_style("pet", self._renderer)
+ self._reset_frame_cache()
+ if (new_w, new_h) != (old_w, old_h):
+ self._mascot_x = self._mascot_x + old_w // 2 - new_w // 2
+ self._mascot_y = self._mascot_y + old_h - new_h
+ self._win_w, self._win_h = new_w, new_h
+ self._resize_window()
+ self._kick_frame()
+
+ def _sync_strip_flags(self) -> None:
+ row = self._controls
+ if isinstance(row, PetControlStrip):
+ row.set_state(mic_muted=self._mic_muted, speaker_muted=self._speaker_muted)
+ elif row is not None:
+ row.set_state(speaker_muted=self._speaker_muted)
+
+ def _apply_status(self, header: str, line: str) -> None:
+ bubble = self._comment_bubble
+ if bubble is None or self._style != "pet" or not self._pet_bubble:
+ return
+ # No bubble floating over an empty desktop: it belongs to the pet.
+ if self._user_hidden or not self._window_mapped():
+ return
+ bubble.show_status(
+ header,
+ line,
+ anchor=self._status_anchor(),
+ auto_hide_ms=PET_BUBBLE_IDLE_HIDE_MS if self._mode == "idle" else None,
+ )
+
+ def _sync_status_fade(self) -> None:
+ """Idle starts the six-second fade; an active mode keeps the bubble up."""
+ bubble = self._comment_bubble
+ if bubble is None or self._style != "pet" or not bubble.status_showing:
+ return
+ bubble.arm_auto_hide(PET_BUBBLE_IDLE_HIDE_MS if self._mode == "idle" else None)
+
+ def _status_anchor(self, *, refresh_limit: bool = True) -> tuple[int, int, int, int]:
+ """``(center_x, below_y, above_y, limit_bottom)`` for the status bubble."""
+ ratio = self._dpi_ratio
+ bubble_gap = max(1, int(round(PET_BUBBLE_GAP * ratio)))
+ center_x = self._mascot_x + self._win_w // 2
+ below_y = self._mascot_y + self._win_h + self._pet_below_height() + bubble_gap
+ above_y = self._mascot_y - bubble_gap
+ return (center_x, below_y, above_y, self._work_area_bottom(refresh=refresh_limit))
+
+ def _work_area_bottom(self, *, refresh: bool = True) -> int:
+ """Bottom edge of the work area under the pet (cached between moves)."""
+ center = (self._mascot_x + self._win_w // 2, self._mascot_y + self._win_h // 2)
+ cached = self._work_area_cache
+ if cached is not None and (not refresh or cached[0] == center):
+ return cached[1]
+ bottom: int | None = None
+ try:
+ from jarvis.platform.monitors import work_area_at # noqa: PLC0415
+
+ area = work_area_at(*center)
+ if area:
+ bottom = int(area[1]) + int(area[3])
+ except Exception: # noqa: BLE001 — placement falls back to the screen edge
+ logging.getLogger("jarvis.orb").debug("work area lookup failed", exc_info=True)
+ if bottom is None:
+ try:
+ bottom = int(self._root.winfo_screenheight()) if self._root else 1080
+ except tk.TclError:
+ bottom = 1080
+ self._work_area_cache = (center, bottom)
+ return bottom
+
+ def _apply_user_visibility(self) -> None:
+ if self._style != "pet":
+ return
+ if self._user_hidden:
+ self._show_until_t = 0.0
+ self._cancel_pending_hide()
+ self._actually_hide()
+ return
+ self._reveal_pet(raise_to_front=False)
+
+ def _toggle_visible_now(self) -> None:
+ if self._style != "pet":
+ return
+ if not self._user_hidden and self._window_mapped():
+ self._user_hidden = True
+ self._apply_user_visibility()
+ return
+ self._user_hidden = False
+ self._reveal_pet(raise_to_front=True)
+
+ def _reveal_pet(self, *, raise_to_front: bool) -> None:
+ """Map the pet window, its strip, and restart the frame loop."""
+ root = self._root
+ if root is None:
+ return
+ self._cancel_pending_hide()
+ try:
+ root.deiconify()
+ if self._mac_transparent:
+ apply_macos_clear_backing()
+ root.lift()
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("pet reveal failed", exc_info=True)
+ return
+ self._sync_controls_visibility()
+ if raise_to_front:
+ # Focus-safe: SetWindowPos with SWP_NOACTIVATE, never a focus grab.
+ self._reassert_topmost(force=True)
+ self._ensure_frame_loop()
+
def start_mouth_animation(self, duration_ms: int = 60000) -> None:
"""Run the mascot's open/close mouth animation for `duration_ms`."""
@@ -3166,16 +4121,27 @@ class OrbOverlay:
self._enqueue_ui(lambda: self._apply_style(style))
def _apply_style(self, style: str) -> None:
- # Size first: _build_renderer paints at the window's edge length, so a
- # renderer built before the resize would be drawn at the old scale.
- self._win_w, self._win_h = window_size_for_style(style)
- new_renderer = self._build_renderer(style)
- if new_renderer is None:
- # Undo the resize — the old renderer is still the one painting.
- self._win_w, self._win_h = window_size_for_style(self._style)
- return # The fallback case was already logged in _build_renderer
+ if style == "pet":
+ # The pet is the other way round: its size comes FROM its renderer.
+ new_renderer = self._build_renderer(style)
+ if new_renderer is None:
+ return # already logged in _build_renderer
+ new_size = window_size_for_style(style, new_renderer)
+ else:
+ # Size first: _build_renderer paints at the window's edge length, so
+ # a renderer built before the resize would be drawn at the old scale.
+ new_size = window_size_for_style(style)
+ old_size = (self._win_w, self._win_h)
+ self._win_w, self._win_h = new_size
+ new_renderer = self._build_renderer(style)
+ if new_renderer is None:
+ # Undo the resize — the old renderer is still the one painting.
+ self._win_w, self._win_h = old_size
+ return # The fallback case was already logged in _build_renderer
self._renderer = new_renderer
self._style = style
+ self._win_w, self._win_h = new_size
+ self._reset_frame_cache()
self._resize_window()
# The bubble's look and the control row both belong to the style, so a
# live swap has to carry them across or the new sphere inherits the
@@ -3184,9 +4150,10 @@ class OrbOverlay:
self._comment_bubble.set_theme(bubble_theme_for_style(style))
self._ensure_controls()
self._sync_controls_visibility()
+ self._kick_frame()
def _resize_window(self) -> None:
- """Re-fit root, canvas and the attached surfaces after a style swap."""
+ """Re-fit root, canvas and the attached surfaces after a style or size swap."""
if self._root is None:
return
try:
@@ -3196,18 +4163,33 @@ class OrbOverlay:
except tk.TclError:
logging.getLogger("jarvis.orb").debug("orb resize failed", exc_info=True)
return
+ try:
+ screen_w = self._root.winfo_screenwidth()
+ except tk.TclError:
+ screen_w = self._win_w
if self._comment_bubble is not None:
- try:
- screen_w = self._root.winfo_screenwidth()
- except tk.TclError:
- screen_w = self._win_w
- self._comment_bubble.update_anchor(self._mascot_x, self._mascot_y, screen_w)
self._comment_bubble.set_orb_width(self._win_w)
if self._controls is not None:
self._controls.set_orb_size(self._win_w, self._win_h)
- self._controls.update_anchor(self._mascot_x, self._mascot_y)
+ self._move_attached(self._mascot_x, self._mascot_y, screen_w)
- def _build_renderer(self, style: str) -> MascotRenderer | VoiceOrbRenderer | None:
+ def _build_renderer(self, style: str) -> MascotRenderer | VoiceOrbRenderer | PetRenderer | None:
+ if style == "pet":
+ try:
+ renderer = PetRenderer(
+ self._pet_id,
+ pet_scale=self._pet_scale,
+ dpi_ratio=self._dpi_ratio,
+ color_key=(int(COLOR_KEY_RGB[0]), int(COLOR_KEY_RGB[1]), int(COLOR_KEY_RGB[2])),
+ )
+ # A fresh state machine starts where the conversation is.
+ renderer.on_mode(self._mode)
+ return renderer
+ except Exception as exc: # noqa: BLE001
+ logging.getLogger("jarvis.orb").warning(
+ "PetRenderer init failed (%s); overlay will stay hidden.", exc
+ )
+ return None
if style == "voice_orb":
try:
return VoiceOrbRenderer(
@@ -3256,6 +4238,11 @@ class OrbOverlay:
raise ValueError(f"Unknown mode: {mode!r} (allowed: {', '.join(MODES)})")
changed = mode != self._mode
self._mode = mode
+ renderer = getattr(self, "_renderer", None)
+ if isinstance(renderer, PetRenderer):
+ renderer.on_mode(mode)
+ self._kick_frame()
+ self._sync_status_fade()
if changed:
self._sync_controls_visibility()
@@ -3337,10 +4324,36 @@ class OrbOverlay:
_log.info("Orb overlay Tk mainloop is running (window initialized).")
def _schedule_frame(self) -> None:
+ """One frame tick. Re-arms itself; ONE pending tick exists at most.
+
+ Two rules on top of painting. A withdrawn window gets no ticks at all
+ (nothing is on screen to animate); every path that maps the window
+ restarts the loop through :meth:`_ensure_frame_loop`. And one failing
+ frame never ends the animation: the re-arm sits in a ``finally``.
+ """
+ self._frame_after_id = None
if not self._running or not self._root or not self._canvas or not self._renderer:
return
+ if not self._window_mapped():
+ return
+ delay_ms = FRAME_INTERVAL_MS
+ try:
+ delay_ms = self._paint_frame()
+ except Exception: # noqa: BLE001 — logged once; the loop must survive a bad frame
+ if not getattr(self, "_frame_error_logged", False):
+ self._frame_error_logged = True
+ logging.getLogger("jarvis.orb").exception("orb frame failed; animation continues")
+ finally:
+ self._arm_frame(delay_ms)
+
+ def _paint_frame(self) -> int:
+ """Paint the frame due now. Returns the delay until the next tick, in ms."""
+ renderer = self._renderer
t = time.perf_counter() - self._t0
- img = self._renderer.render(t, self._mode, self._ext_level)
+ frame_key_fn = getattr(renderer, "frame_key", None)
+ if callable(frame_key_fn):
+ return self._paint_keyed_frame(renderer, t, frame_key_fn(t))
+ img = renderer.render(t, self._mode, self._ext_level)
if self._mac_transparent:
# macOS has no color key — the frame carries a real alpha
# channel instead (magenta → fully transparent).
@@ -3353,12 +4366,93 @@ class OrbOverlay:
# 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)
+ self._show_photo(self._photo)
+ return FRAME_INTERVAL_MS # ~60 FPS
+
+ def _paint_keyed_frame(self, renderer: Any, t: float, key: Hashable) -> int:
+ """The pet's path: repaint only when the frame changes, sleep until it does."""
+ if key != self._frame_key or self._image_id is None:
+ cache = self._photo_cache
+ photo = cache.get(key)
+ if photo is None:
+ img = renderer.render(t, self._mode, self._ext_level)
+ if self._mac_transparent:
+ img = key_to_alpha(img)
+ photo = ImageTk.PhotoImage(img, master=self._root)
+ cache[key] = photo
+ while len(cache) > PET_PHOTO_CACHE_MAX:
+ cache.popitem(last=False)
+ else:
+ cache.move_to_end(key)
+ self._photo = photo
+ self._show_photo(photo)
+ self._frame_key = key
+ delay_ms = int(renderer.next_frame_delay_ms(t))
+ if self._pump_strip_level():
+ delay_ms = min(delay_ms, PET_PULSE_INTERVAL_MS)
+ return delay_ms
+
+ def _show_photo(self, photo: Any) -> None:
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=photo)
else:
- self._canvas.itemconfig(self._image_id, image=self._photo)
+ self._canvas.itemconfig(self._image_id, image=photo)
+
+ def _pump_strip_level(self) -> bool:
+ """Feed the strip's orb the audio level. True while it is pulsing.
- self._root.after(16, self._schedule_frame) # ~60 FPS
+ Only while listening or talking; at rest the orb is static and the
+ strip is not repainted at all.
+ """
+ row = self._controls
+ if not isinstance(row, PetControlStrip):
+ return False
+ pulsing = self._mode in ("listen", "speak", "dictate")
+ level = orb_controls.quantize_level(self._ext_level) if pulsing else 0
+ row.set_state(level=level)
+ return pulsing
+
+ def _arm_frame(self, delay_ms: int) -> None:
+ root = self._root
+ if root is None or not self._running:
+ return
+ try:
+ self._frame_after_id = root.after(max(1, int(delay_ms)), self._schedule_frame)
+ except (tk.TclError, RuntimeError):
+ logging.getLogger("jarvis.orb").debug("orb frame re-arm failed", exc_info=True)
+
+ def _kick_frame(self) -> None:
+ """Repaint right away (a state change), replacing the pending tick."""
+ root = self._root
+ if root is None or not self._running:
+ return
+ pending = self._frame_after_id
+ self._frame_after_id = None
+ if pending is not None:
+ try:
+ root.after_cancel(pending)
+ except tk.TclError:
+ logging.getLogger("jarvis.orb").debug("frame tick cancel failed", exc_info=True)
+ self._arm_frame(1)
+
+ def _ensure_frame_loop(self) -> None:
+ """Restart the frame loop after the window was mapped again."""
+ if self._frame_after_id is None:
+ self._kick_frame()
+
+ def _reset_frame_cache(self) -> None:
+ self._photo_cache.clear()
+ self._frame_key = None
+
+ def _window_mapped(self) -> bool:
+ """Is the orb window mapped (not withdrawn)? Test doubles count as mapped."""
+ root = self._root
+ if root is None:
+ return False
+ try:
+ return str(root.state()) != "withdrawn"
+ except (tk.TclError, AttributeError):
+ return True
def _run_demo(self) -> None:
self._started.wait(timeout=5.0)
diff --git a/ui/orb/pet_renderer.py b/ui/orb/pet_renderer.py
new file mode 100644
index 0000000000..c13510732e
--- /dev/null
+++ b/ui/orb/pet_renderer.py
@@ -0,0 +1,313 @@
+"""The desktop pet's renderer for ``OrbOverlay`` (style ``pet``, ``docs/pets.md``).
+
+The mascot and the voice orb are drawn fresh every frame at 60 fps; a pixel-art
+pet does not need that and must not pay for it (the budget in ``docs/pets.md``:
+an idle pet costs next to nothing). So this renderer works the other way round:
+
+* every frame of every state is scaled ONCE, when the pet is loaded — an
+ integer nearest-neighbour factor from the monitor's DPI times the user's
+ ``pet_scale``, keyed to the overlay's magenta colour key;
+* ``frame_key`` names the frame that is due now, so the overlay repaints only
+ when that key changes and reuses its cached Tk image otherwise;
+* ``next_frame_delay_ms`` says how long the overlay may sleep until the next
+ frame boundary or the next state change the state machine will make on its
+ own (a one-shot ending, the pet falling asleep) — 4 fps idle, 2 fps asleep,
+ whatever the manifest asks for while active.
+
+The state itself comes from :class:`jarvis.ui.pets.state_machine.PetStateMachine`,
+fed by the overlay from real Jarvis events. Pet ``"none"`` loads no pack: the
+renderer then paints a fully keyed (invisible, click-through) strip-wide line so
+the overlay window keeps a real position for the control strip to hang from.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import sys
+import time
+from collections.abc import Callable, Hashable, Mapping
+from typing import Any
+
+from PIL import Image
+
+from jarvis.ui.pets.states import NO_PET_ID
+from ui.orb import controls as orb_controls
+
+log = logging.getLogger("jarvis.orb")
+
+#: The figure's on-screen edge at 100 % display scaling and ``pet_scale`` 1.0.
+#: A 48-pixel sheet lands on exactly 3x; 32 and 64 pixel sheets get the integer
+#: factor nearest to the same size, so every pet is about as tall as the next.
+PET_TARGET_EDGE_PX = 144
+
+#: Logical pixels per inch Tk reports at 100 % scaling on Windows and X11.
+_BASE_PPI = 96.0
+
+#: Bounds for the frame timer. The floor keeps a broken manifest from spinning
+#: the Tk loop; the ceiling makes sure a state change the overlay did not kick
+#: (it always does, this is the backstop) is picked up within a second.
+MIN_FRAME_DELAY_MS = 15
+MAX_FRAME_DELAY_MS = 1000
+
+_ColorKey = tuple[int, int, int]
+
+
+def dpi_ratio_for(points_per_inch: float | None, platform: str = sys.platform) -> float:
+ """The display scale factor from what Tk reports as one inch, in pixels.
+
+ Windows and X11 report logical DPI (96 at 100 %, 144 at 150 %). Aqua-Tk on
+ macOS measures in points, which the system already scales for Retina, so
+ the ratio there is 1.0 whatever the number says. Anything implausible
+ degrades to 1.0 — the pet is then simply drawn at its base size.
+ """
+ if platform == "darwin" or points_per_inch is None:
+ return 1.0
+ try:
+ ppi = float(points_per_inch)
+ except (TypeError, ValueError):
+ return 1.0
+ if not math.isfinite(ppi) or ppi <= 0:
+ return 1.0
+ return max(0.75, min(4.0, ppi / _BASE_PPI))
+
+
+def pixel_factor(frame_size: int, dpi_ratio: float = 1.0, pet_scale: float = 1.0) -> int:
+ """The integer nearest-neighbour factor a sprite sheet is scaled by.
+
+ Integer on purpose: a fractional factor duplicates some source pixels and
+ not others, and pixel art then looks smeared. Rounded half up (Python's
+ ``round`` would send 4.5 to 4) and never below 1.
+ """
+ try:
+ edge = max(1, int(frame_size))
+ ratio = float(dpi_ratio) if math.isfinite(float(dpi_ratio)) else 1.0
+ scale = float(pet_scale) if math.isfinite(float(pet_scale)) else 1.0
+ except (TypeError, ValueError):
+ return 1
+ target = PET_TARGET_EDGE_PX * max(0.1, ratio) * max(0.1, scale)
+ return max(1, int(math.floor(target / edge + 0.5)))
+
+
+def frame_index(elapsed_s: float, frames: int, fps: float, loop: bool) -> int:
+ """Which frame of an animation is due ``elapsed_s`` after it started."""
+ count = max(1, int(frames))
+ if count == 1 or fps <= 0:
+ return 0
+ step = int(math.floor(max(0.0, elapsed_s) * float(fps)))
+ if loop:
+ return step % count
+ return min(step, count - 1)
+
+
+def seconds_to_next_frame(elapsed_s: float, frames: int, fps: float, loop: bool) -> float | None:
+ """Seconds until the frame index changes, or ``None`` if it never will.
+
+ ``None`` covers a single-frame animation and a one-shot resting on its
+ last frame — nothing on screen changes until the state does.
+ """
+ count = max(1, int(frames))
+ if count == 1 or fps <= 0:
+ return None
+ elapsed = max(0.0, elapsed_s)
+ step = int(math.floor(elapsed * float(fps)))
+ if not loop and step >= count - 1:
+ return None
+ boundary = (step + 1) / float(fps)
+ return max(0.0, boundary - elapsed)
+
+
+def _default_loader(pet_id: str) -> Any:
+ from jarvis.ui.pets.loader import load_pet_by_id # noqa: PLC0415 — engine is lazy
+
+ return load_pet_by_id(pet_id)
+
+
+def _default_to_color_key(frame: Image.Image, scale: int, key: _ColorKey) -> Image.Image:
+ from jarvis.ui.pets.loader import to_color_key # noqa: PLC0415
+
+ return to_color_key(frame, scale, key=key)
+
+
+def _default_machine(clock: Callable[[], float]) -> Any:
+ from jarvis.ui.pets.state_machine import PetStateMachine # noqa: PLC0415
+
+ return PetStateMachine(clock)
+
+
+class PetRenderer:
+ """Renderer protocol for ``OrbOverlay`` plus frame-pacing hints.
+
+ ``render(t, mode, level)`` matches the mascot / voice-orb renderers; ``t``
+ and ``level`` are accepted for that protocol and ignored — the pet's clock
+ is its state machine's, and its figure does not follow the audio level (the
+ control strip's orb does). All methods run on the Tk thread.
+ """
+
+ def __init__(
+ self,
+ pet_id: str,
+ *,
+ pet_scale: float = 1.0,
+ dpi_ratio: float = 1.0,
+ color_key: _ColorKey = (255, 0, 255),
+ clock: Callable[[], float] = time.monotonic,
+ loader: Callable[[str], Any] | None = None,
+ to_color_key: Callable[[Image.Image, int, _ColorKey], Image.Image] | None = None,
+ machine: Any | None = None,
+ ) -> None:
+ self._clock = clock
+ self._color_key = tuple(int(c) for c in color_key)
+ self._dpi_ratio = float(dpi_ratio)
+ self._pet_scale = float(pet_scale)
+ self._loader = loader or _default_loader
+ self._to_color_key = to_color_key or _default_to_color_key
+ self._machine = machine if machine is not None else _default_machine(clock)
+ self._pack: Any = None
+ self._frames: dict[str, tuple[Image.Image, ...]] = {}
+ self._factor = 1
+ self._size = (1, 1)
+ self._blank: Image.Image | None = None
+ self._pet_id = NO_PET_ID
+ self.load(pet_id)
+
+ # -- pack ------------------------------------------------------------
+
+ def load(self, pet_id: str) -> None:
+ """(Re)load the pet and pre-scale every frame. Keeps the state machine."""
+ requested = str(pet_id or "").strip() or NO_PET_ID
+ pack = None
+ if requested != NO_PET_ID:
+ try:
+ pack = self._loader(requested)
+ except Exception: # noqa: BLE001 — a broken pack must not kill the overlay
+ log.warning("pet %r failed to load; showing the strip only", requested)
+ pack = None
+ self._pack = pack
+ # The id of what actually loaded: an unknown id falls back to the
+ # default pet, and the frame keys must say so.
+ manifest_id = getattr(getattr(pack, "manifest", None), "id", None)
+ self._pet_id = NO_PET_ID if pack is None else str(manifest_id or requested)
+ self._rescale()
+
+ def set_look(self, *, pet_scale: float | None = None, dpi_ratio: float | None = None) -> bool:
+ """Apply a new size. Returns True when the window size changed."""
+ before = self._size
+ if pet_scale is not None:
+ self._pet_scale = float(pet_scale)
+ if dpi_ratio is not None:
+ self._dpi_ratio = float(dpi_ratio)
+ self._rescale()
+ return self._size != before
+
+ def _rescale(self) -> None:
+ self._frames = {}
+ self._blank = None
+ pack = self._pack
+ if pack is None:
+ strip_w, _strip_h = orb_controls.pet_strip_size(self._dpi_ratio)
+ self._factor = 1
+ self._size = (max(1, strip_w), 1)
+ return
+ edge = int(pack.manifest.frame_size)
+ self._factor = pixel_factor(edge, self._dpi_ratio, self._pet_scale)
+ frames: Mapping[str, Any] = pack.frames
+ for state, sequence in frames.items():
+ self._frames[str(state)] = tuple(
+ self._to_color_key(frame, self._factor, self._color_key) for frame in sequence
+ )
+ self._size = (edge * self._factor, edge * self._factor)
+
+ @property
+ def pet_id(self) -> str:
+ """The pet actually shown (``"none"`` when nothing loaded)."""
+ return self._pet_id
+
+ @property
+ def has_figure(self) -> bool:
+ return self._pack is not None
+
+ @property
+ def size(self) -> tuple[int, int]:
+ """The window size this pet needs, in pixels."""
+ return self._size
+
+ @property
+ def factor(self) -> int:
+ return self._factor
+
+ @property
+ def machine(self) -> Any:
+ return self._machine
+
+ # -- state feed ------------------------------------------------------
+
+ def on_mode(self, mode: str) -> None:
+ self._machine.on_mode(mode)
+
+ def on_outcome(self, kind: str) -> None:
+ self._machine.on_outcome(kind)
+
+ def on_activity(self) -> None:
+ self._machine.on_activity()
+
+ def state(self) -> str:
+ return str(self._machine.state())
+
+ # -- frame selection -------------------------------------------------
+
+ def _current(self) -> tuple[str, Any, int, float]:
+ """(resolved state, spec, frame index, elapsed seconds) for now."""
+ state = self.state()
+ resolved, spec = self._pack.manifest.spec_for(state)
+ resolved = str(resolved)
+ sequence = self._frames.get(resolved) or self._frames.get(state) or ()
+ frames = len(sequence) or max(1, int(getattr(spec, "frames", 1)))
+ elapsed = max(0.0, float(self._clock()) - float(self._machine.state_started_at()))
+ index = frame_index(elapsed, frames, float(spec.fps), bool(spec.loop))
+ return resolved, spec, index, elapsed
+
+ def frame_key(self, t: float = 0.0) -> Hashable:
+ """A key that changes exactly when the picture on screen changes."""
+ _ = t
+ if self._pack is None:
+ return ("none", self._size)
+ resolved, _spec, index, _elapsed = self._current()
+ return (self._pet_id, self._factor, resolved, index)
+
+ def next_frame_delay_ms(self, t: float = 0.0) -> int:
+ """How long the overlay may sleep before the next repaint is due."""
+ _ = t
+ waits: list[float] = []
+ change = self._machine.next_change_in()
+ if change is not None:
+ waits.append(max(0.0, float(change)))
+ if self._pack is not None:
+ resolved, spec, _index, elapsed = self._current()
+ frames = len(self._frames.get(resolved) or ()) or int(getattr(spec, "frames", 1))
+ boundary = seconds_to_next_frame(elapsed, frames, float(spec.fps), bool(spec.loop))
+ if boundary is not None:
+ waits.append(boundary)
+ if not waits:
+ return MAX_FRAME_DELAY_MS
+ # A hair past the boundary, so the tick lands on the new frame rather
+ # than a microsecond before it (which would repaint the old one again).
+ delay_ms = int(math.ceil(min(waits) * 1000.0)) + 2
+ return max(MIN_FRAME_DELAY_MS, min(MAX_FRAME_DELAY_MS, delay_ms))
+
+ def render(
+ self, t: float = 0.0, mode: str = "idle", ext_level: float | None = None
+ ) -> Image.Image:
+ """The frame due now, colour-keyed at window size (shared; never mutate)."""
+ _ = t, mode, ext_level
+ if self._pack is None:
+ if self._blank is None:
+ self._blank = Image.new("RGB", self._size, self._color_key)
+ return self._blank
+ resolved, _spec, index, _elapsed = self._current()
+ sequence = self._frames.get(resolved) or self._frames.get("idle") or ()
+ if not sequence:
+ if self._blank is None:
+ self._blank = Image.new("RGB", self._size, self._color_key)
+ return self._blank
+ return sequence[min(index, len(sequence) - 1)]