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): config, shortcut, speaker-mute event, bridge wiring and pets REST

rubenluetke10-beep175adb527ece
diff --git a/jarvis.toml.example b/jarvis.toml.example
index 23552823af..d0ca04adbe 100644
--- a/jarvis.toml.example
+++ b/jarvis.toml.example
@@ -31,6 +31,7 @@ name = ""
[trigger]
wake_word_enabled = true # always-on wake listener (needs a mic)
single_turn_mode = false # false = conversation stays open until "hang up"/idle
+hotkey_pet_toggle = "alt+win+p" # hide / show the desktop pet (macOS: cmd+alt+p); "" = off
[trigger.wake_word]
# Type any phrase you like — no wake word ships with the product (design
@@ -189,11 +190,14 @@ admin_api_port = 47821
startup_chime = true
# On-screen overlay shown by default on a desktop install: the slim
# "jarvis_bar" (the Jarvis bar). Alternatives: "mascot" (the Gigi mascot),
-# "voice_orb" (the procedural voice orb) or "none".
+# "voice_orb" (the procedural voice orb), "pet" (a desktop pet) or "none".
# This mirrors the built-in default — listed here so the bar is the obvious,
# self-documented out-of-the-box choice and never silently disappears.
orb_style = "jarvis_bar"
bar_persistent = true # keep the bar visible at all times (not only during a voice session)
+pet_id = "gigi" # desktop pet (orb_style = "pet"): built-in id, your own u… id, or "none"
+pet_scale = 1.0 # pet size multiplier, 0.5–2.0
+pet_bubble = true # show the pet's status bubble (what Jarvis is doing)
# ── Memory ──
[memory]
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index e7af6ffe45..4666aca7a7 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -38,6 +38,10 @@ from jarvis.live.config import LiveConfig
# wake-engine enum + the default phrase.
from jarvis.speech.wake_constants import DEFAULT_WAKE_PHRASE, WAKE_ENGINES
+# The pet vocabulary module has no imports at all (see its docstring), so it is
+# as safe here as wake_constants.
+from jarvis.ui.pets.states import DEFAULT_PET_ID
+
from .branding import CONFIG_FILE_NAME, KEYRING_SERVICE_NAME
from .instance import current_instance
from .protocols import RiskTier
@@ -423,6 +427,20 @@ class TriggerConfig(BaseModel):
# A macOS user can record a Command-based combination instead; the
# validator accepts `cmd+...` on darwin.
hotkey_paste_last: str = "ctrl+alt+v"
+ # Hide the desktop pet, or show it and bring it to the front (docs/pets.md).
+ # A no-op for every other overlay style. Ships bound, like the dictation
+ # keys, and curated the same way: ``alt+win+p`` passes ``validate_hotkey``
+ # on win32, darwin AND linux with no caution (Win+P alone is the Windows
+ # projection shortcut; with Alt held it is not a shell chord), and its
+ # normalized key set {alt, window, p} is neither a subset nor a superset of
+ # Call / Hangup / both dictation keys / paste-last, the kill switch
+ # (ctrl+alt+shift+k) or the Jarvis X keys (ctrl+shift+1..6), so
+ # ``combos_collide`` accepts all of them at once. It holds ONE Alt key, so
+ # it can never fire the both-Alt appshot gesture (``alt+alt``) either. On
+ # macOS the win token is Command (cmd+alt+p). An empty value disables it;
+ # on Wayland the compositor owns global shortcuts and this is a no-op.
+ # ``tests/unit/core/test_pet_config.py`` pins every one of these claims.
+ hotkey_pet_toggle: str = "alt+win+p"
wake_word: WakeWordConfig = Field(default_factory=WakeWordConfig)
# When false (default), the pipeline keeps the mic open after the
# response (conversation mode) and only hangs up via HANGUP_RE, the idle
@@ -981,6 +999,41 @@ def normalize_force_spawn_mode(value: object) -> str:
return mode if mode in FORCE_SPAWN_MODES else DEFAULT_FORCE_SPAWN_MODE
+#: The SHAPE every pet id has: a built-in slug (``gigi``), a user-created id
+#: (``u`` + 16 hex digits) or ``none``. The user-created form is a special case
+#: of the slug, so one pattern covers all three (docs/pets.md, sprite format).
+_PET_ID_SHAPE = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$")
+
+
+def normalize_pet_id(value: object) -> str | None:
+ """Lower-cased, trimmed pet id, or ``None`` when it cannot be one.
+
+ Shape only — whether the pet exists is decided where pets are listed. Also
+ the path-traversal guard for every route that turns an id into a folder:
+ the shape admits no separator, no dot and no drive letter.
+ """
+ if not isinstance(value, str):
+ return None
+ pet_id = value.strip().lower()
+ return pet_id if _PET_ID_SHAPE.fullmatch(pet_id) else None
+
+
+def clamp_pet_scale(value: object) -> float:
+ """The pet size multiplier, clamped to 0.5–2.0.
+
+ Same sanitizing as ``bar_size_scale``: a non-numeric or non-finite value
+ becomes 1.0. One definition for the config load, the TOML writer and the
+ pets route, so the three can never disagree about the range.
+ """
+ try:
+ f = float(value) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return 1.0
+ if f != f or f in (float("inf"), float("-inf")): # NaN / ±inf
+ return 1.0
+ return max(0.5, min(2.0, f))
+
+
class BrainRoutingConfig(BaseModel):
"""Heuristic rules for the deterministic force-spawn classification.
@@ -2143,6 +2196,17 @@ class UIConfig(BaseModel):
# a headless / Wayland host with no reliable per-monitor geometry keeps the
# single-monitor behaviour. See jarvis/ui/jarvisbar/interaction.py.
bar_follow_cursor_monitor: bool = True
+ # Desktop pet (orb_style = "pet", docs/pets.md). ``pet_id`` is a built-in
+ # id, a user-created ``u…`` id, or "none" (the control strip without a
+ # figure). An id that no longer exists on disk falls back to the default
+ # pet where it is resolved (pets routes / overlay), never here: the
+ # validator only sanitizes the SHAPE so a hand-edited value cannot brick
+ # the load. Vocabulary: jarvis.ui.pets.states.
+ pet_id: str = DEFAULT_PET_ID
+ # Pet size multiplier on top of the monitor DPI scale, 0.5–2.0.
+ pet_scale: float = 1.0
+ # Show the status bubble under the pet's control strip.
+ pet_bubble: bool = True
# Remembered "open with" choice for Outputs artifacts: an opener id
# ("default" = OS default app, "browser", or an editor key like "code").
# Empty = ask via the chooser dialog on first open. Desktop-only.
@@ -2174,6 +2238,19 @@ class UIConfig(BaseModel):
return 1.0
return max(0.5, min(2.0, f))
+ @field_validator("pet_id", mode="before")
+ @classmethod
+ def _sanitize_pet_id(cls, v: object) -> object:
+ # Lower-case and trim; anything that is not a valid pet id shape (a
+ # typo, a path, a non-string) falls back to the default pet so a
+ # corrupt jarvis.toml can never brick the load. "none" is a valid pick.
+ return normalize_pet_id(v) or DEFAULT_PET_ID
+
+ @field_validator("pet_scale", mode="before")
+ @classmethod
+ def _clamp_pet_scale(cls, v: object) -> object:
+ return clamp_pet_scale(v)
+
class DuckingConfig(BaseModel):
"""Audio ducking — "Mute music while dictating" (Taskbar section).
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 9445eac3db..f8d6ec8b3a 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -662,7 +662,7 @@ def set_codex_binary_path(binary_path: str, *, path: Path = DEFAULT_CONFIG_FILE)
# frontend (jarvis/ui/web/frontend/src/hooks/useHotkey.ts). Keep these layers in
# sync. The mapped value is BOTH the jarvis.toml key under [trigger] AND the
# TriggerConfig field name (they are intentionally identical).
-KEYBIND_ACTIONS = ("call", "hangup", "dictate", "dictate_toggle", "paste_last")
+KEYBIND_ACTIONS = ("call", "hangup", "dictate", "dictate_toggle", "paste_last", "pet_toggle")
KEYBIND_TOML_KEY = {
"call": "hotkey_call",
"hangup": "hotkey_hangup",
@@ -683,6 +683,9 @@ KEYBIND_TOML_KEY = {
# clipboard content and therefore takes the transcript back off the
# clipboard within a second.
"paste_last": "hotkey_paste_last",
+ # Hide the desktop pet, or show it and bring it forward (docs/pets.md).
+ # Ships bound; see TriggerConfig.hotkey_pet_toggle for the collision proof.
+ "pet_toggle": "hotkey_pet_toggle",
}
#: One-time marker under ``[trigger]`` recording that the dictation-shortcut
@@ -1428,6 +1431,39 @@ def set_bar_size_scale(scale: float, *, path: Path = DEFAULT_CONFIG_FILE) -> Non
_patch_table(path, "ui", "bar_size_scale", max(0.5, min(2.0, f)))
+def set_pet_id(pet_id: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[ui] pet_id`` (the active desktop pet, docs/pets.md).
+
+ TOML-only (not drift-guarded); the pets route applies it live. Whether the
+ pet exists is the caller's check; a value that is not even id-shaped is
+ refused here, so a bad request can never put a path or garbage into the
+ shared file.
+ """
+ from jarvis.core.config import normalize_pet_id # noqa: PLC0415
+
+ normalized = normalize_pet_id(pet_id)
+ if normalized is None:
+ raise ValueError(f"not a pet id: {pet_id!r}")
+ _patch_table(path, "ui", "pet_id", normalized)
+
+
+def set_pet_scale(scale: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[ui] pet_scale`` (the pet size slider), clamped to 0.5–2.0.
+
+ Same sanitizing as :func:`set_bar_size_scale` (``clamp_pet_scale``): a
+ non-numeric or non-finite value is stored as 1.0, never as an out-of-range
+ number.
+ """
+ from jarvis.core.config import clamp_pet_scale # noqa: PLC0415
+
+ _patch_table(path, "ui", "pet_scale", clamp_pet_scale(scale))
+
+
+def set_pet_bubble(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[ui] pet_bubble`` (show the pet's status bubble)."""
+ _patch_table(path, "ui", "pet_bubble", bool(enabled))
+
+
def set_bar_follow_cursor_monitor(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[ui] bar_follow_cursor_monitor`` (the 'follow the mouse to the
active monitor' toggle).
diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.py
index f50f281121..dce52be78f 100644
--- a/jarvis/plugins/tool/navigate.py
+++ b/jarvis/plugins/tool/navigate.py
@@ -73,6 +73,8 @@ KNOWN: frozenset[str] = frozenset(
# The marketplace, in the app: community plugins and skills in one
# storefront.
"marketplace",
+ # My Pets: the desktop pet, its look, and the pets the user created.
+ "pets",
}
)
@@ -260,6 +262,18 @@ _ALIASES: dict[str, str] = {
"marktplatz": "marketplace", # i18n-allow: input vocab
"mercado": "marketplace", # i18n-allow: input vocab
"tienda": "marketplace", # i18n-allow: input vocab
+ # My Pets. Only phrases that name the app's own pet: the bare word "pets"
+ # is already the section id, and anything broader ("animals") would pull
+ # ordinary questions about animals onto a settings page.
+ "my pets": "pets",
+ "my pet": "pets",
+ "desktop pet": "pets",
+ "desktop pets": "pets",
+ "haustier": "pets", # i18n-allow: input vocab
+ "meine pets": "pets", # i18n-allow: input vocab
+ "mein haustier": "pets", # i18n-allow: input vocab
+ "mis mascotas": "pets", # i18n-allow: input vocab
+ "mascota de escritorio": "pets", # i18n-allow: input vocab
}
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 40d3d342e0..d7045af4e0 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -73,6 +73,7 @@ from jarvis.core.events import (
ListeningStarted,
MessageSent,
ObservationCaptured,
+ PetVisibilityToggleRequested,
SpeechSpoken,
TranscriptFinal,
TranscriptionUpdate,
@@ -82,6 +83,7 @@ from jarvis.core.events import (
VoiceMuteToggleRequested,
VoiceSessionEnded,
VoiceSessionStarted,
+ VoiceSpeakerMuteChanged,
WakeCandidateDetected,
WakeWordDetected,
)
@@ -2315,6 +2317,10 @@ class SpeechPipeline:
# persisted, the UI showed the new combo, and the key did nothing —
# forever, restart included (the AP-4 trap: one layer never told).
paste_last_hotkeys: tuple[str, ...] = (),
+ # Hide / show the desktop pet ([trigger].hotkey_pet_toggle). Dispatched
+ # here like every other global shortcut; the pipeline only publishes
+ # ``PetVisibilityToggleRequested`` and the overlay bridge does the rest.
+ pet_toggle_hotkeys: tuple[str, ...] = (),
# Resolved DictationConfig (jarvis.core.config.DictationConfig) or None.
# None keeps every legacy call site and test on the built-in defaults.
dictation_config: Any = None,
@@ -2325,6 +2331,14 @@ class SpeechPipeline:
self._dictate_hotkeys = list(dictate_hotkeys)
self._dictate_toggle_hotkeys = list(dictate_toggle_hotkeys)
self._paste_last_hotkeys = list(paste_last_hotkeys)
+ self._pet_toggle_hotkeys = list(pet_toggle_hotkeys)
+ # Speaker mute = TTS volume 0. The muted-ness last broadcast as
+ # ``VoiceSpeakerMuteChanged``; ``set_tts_volume`` runs on the REST
+ # threadpool AND the overlay's Tk thread, so the compare-and-set that
+ # decides "did it flip?" holds this lock. ``None`` = nothing broadcast
+ # yet, so the first change is compared against the configured volume.
+ self._speaker_mute_lock = threading.Lock()
+ self._speaker_muted_last: bool | None = None
# One paste at a time — two overlapping ones race over the clipboard
# restore and the loser puts the wrong content back (see _on_paste_last).
self._paste_last_busy = False
@@ -3412,18 +3426,66 @@ class SpeechPipeline:
if callable(setter):
setter(_local_silence_window_ms(ms))
- def set_tts_volume(self, volume: float) -> None:
+ def set_tts_volume(self, volume: float, *, source: str = "") -> None:
"""Live-apply a new master TTS output volume (0.0–1.0) — no restart.
Delegates to ``AudioPlayer.set_volume`` so a Settings change is audible
on the next spoken sub-block. No-op-safe when the player is absent
(headless / not yet started) — the value still persisted and applies on
the next start.
+
+ Also the ONE place speaker mute is decided (mute = volume 0): when the
+ change flips the voice between silent and audible it broadcasts
+ ``VoiceSpeakerMuteChanged`` so every surface (the pet's speaker disc,
+ the in-app speaker button) mirrors it. Callers run on the REST
+ threadpool and on the overlay's Tk thread, so the flip is decided under
+ a lock and the publish is marshalled onto the pipeline's loop — this
+ never blocks and never awaits.
+ """
+ target = float(volume)
+ lock = getattr(self, "_speaker_mute_lock", None)
+ if lock is None:
+ # Pipelines built via ``__new__`` in tests skip ``__init__``.
+ lock = self._speaker_mute_lock = threading.Lock()
+ with lock:
+ last = getattr(self, "_speaker_muted_last", None)
+ was_muted = self.get_tts_volume() <= 0.0 if last is None else last
+ # Remembered even without a player, so a headless mute/unmute
+ # reads back what was asked for instead of the boot value.
+ self._tts_volume_requested = max(0.0, min(1.0, target))
+ player = getattr(self, "_player", None)
+ setter = getattr(player, "set_volume", None)
+ if callable(setter):
+ setter(target)
+ muted = target <= 0.0
+ self._speaker_muted_last = muted
+ if muted != was_muted:
+ log.info(
+ "Speaker %s (source=%s)", "muted" if muted else "unmuted", source or "unknown"
+ )
+ self._publish_event_soon(VoiceSpeakerMuteChanged(muted=muted, source=source))
+
+ def get_tts_volume(self) -> float:
+ """The master TTS output volume in effect right now (0.0–1.0).
+
+ The live player's volume when there is a player, else the last value
+ ``set_tts_volume`` was asked for, else the configured ``[tts].volume``,
+ else full volume. The orb/pet speaker disc reads this to decide whether
+ a click mutes or unmutes; without it every click read "audible" and the
+ voice could be muted but never brought back.
"""
player = getattr(self, "_player", None)
- setter = getattr(player, "set_volume", None)
- if callable(setter):
- setter(float(volume))
+ live = getattr(player, "_volume", None)
+ if isinstance(live, int | float) and not isinstance(live, bool):
+ return max(0.0, min(1.0, float(live)))
+ requested = getattr(self, "_tts_volume_requested", None)
+ if isinstance(requested, int | float):
+ return float(requested)
+ configured = getattr(getattr(getattr(self, "_config", None), "tts", None), "volume", None)
+ try:
+ return max(0.0, min(1.0, float(configured))) if configured is not None else 1.0
+ except (TypeError, ValueError):
+ return 1.0
def set_audio_devices(
self,
@@ -3672,6 +3734,7 @@ class SpeechPipeline:
dictate: list[str] | None = None,
dictate_toggle: list[str] | None = None,
paste_last: list[str] | None = None,
+ pet_toggle: list[str] | None = None,
) -> None:
"""Live-apply changed voice keybinds — no app/pipeline restart.
@@ -3706,15 +3769,18 @@ class SpeechPipeline:
self._dictate_toggle_hotkeys = list(dictate_toggle)
if paste_last is not None:
self._paste_last_hotkeys = list(paste_last)
+ if pet_toggle is not None:
+ self._pet_toggle_hotkeys = list(pet_toggle)
log.info(
"Keybinds live-switched: CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s] "
- "DICTATE-TOGGLE=[%s] PASTE-LAST=[%s]",
+ "DICTATE-TOGGLE=[%s] PASTE-LAST=[%s] PET-TOGGLE=[%s]",
", ".join(self._call_hotkeys),
", ".join(self._ptt_hotkeys) or "off",
", ".join(self._hangup_hotkeys),
", ".join(self._dictate_hotkeys) or "off",
", ".join(self._dictate_toggle_hotkeys) or "off",
", ".join(getattr(self, "_paste_last_hotkeys", None) or []) or "off",
+ ", ".join(getattr(self, "_pet_toggle_hotkeys", None) or []) or "off",
)
self._hotkey_reload_event.set()
@@ -3771,6 +3837,10 @@ class SpeechPipeline:
# Single-fire on release, like every non-hold action: holding the
# key must paste once, not once per polling tick.
bindings["paste_last"] = list(paste_last)
+ pet_toggle = getattr(self, "_pet_toggle_hotkeys", None) or []
+ if pet_toggle:
+ # Single-fire on release too: one press hides or shows the pet once.
+ bindings["pet_toggle"] = list(pet_toggle)
return bindings, edge_events
# ------------------------------------------------------------------
@@ -6293,7 +6363,7 @@ class SpeechPipeline:
hotkey_bindings, ptt_events = self._build_hotkey_bindings()
log.info(
"Pipeline ready. CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s/%s] "
- "DICTATE-TOGGLE=[%s] PASTE-LAST=[%s] OWW=%s "
+ "DICTATE-TOGGLE=[%s] PASTE-LAST=[%s] PET-TOGGLE=[%s] OWW=%s "
"WAKE=%s (threshold=%.2f) WHISPER-WAKE=%s TURN-MODE=%s",
", ".join(self._call_hotkeys),
", ".join(self._ptt_hotkeys) or "off",
@@ -6302,6 +6372,7 @@ class SpeechPipeline:
self._dictate_mode,
", ".join(getattr(self, "_dictate_toggle_hotkeys", None) or []) or "off",
", ".join(getattr(self, "_paste_last_hotkeys", None) or []) or "off",
+ ", ".join(getattr(self, "_pet_toggle_hotkeys", None) or []) or "off",
"on" if self._openwakeword_enabled else "off",
list(self._wake._keywords),
self._wake._threshold,
@@ -6839,6 +6910,8 @@ class SpeechPipeline:
self._on_dictate_toggle()
elif event_name == "paste_last":
self._on_paste_last()
+ elif event_name == "pet_toggle":
+ self._on_pet_toggle()
elif event_name == "hangup":
log.info("📵 HANGUP via Hotkey")
self._trigger_voice_hangup()
@@ -6953,6 +7026,18 @@ class SpeechPipeline:
target=self._configured_dictation_target(), source="toggle_key"
)
+ def _on_pet_toggle(self) -> None:
+ """Pet shortcut — hide the desktop pet, or show it and bring it forward.
+
+ The pipeline owns the shortcut, not the pet: it only announces the
+ press. ``OrbBusBridge`` turns ``PetVisibilityToggleRequested`` into
+ ``surface.toggle_visible()``, which every other overlay style ignores.
+ Scheduled, never awaited — this runs inside the hotkey loop, which must
+ not wait on bus subscribers.
+ """
+ log.info("Pet visibility toggle via hotkey")
+ self._publish_event_soon(PetVisibilityToggleRequested(source="hotkey"))
+
def _on_paste_last(self) -> None:
""""Insert the last dictation again" key — re-deliver the last transcript.
@@ -17815,6 +17900,11 @@ async def _main() -> None:
if config.trigger.hotkey_paste_last.strip()
else ()
),
+ pet_toggle_hotkeys=(
+ (config.trigger.hotkey_pet_toggle,)
+ if config.trigger.hotkey_pet_toggle.strip()
+ else ()
+ ),
dictate_mode=config.dictation.mode,
dictation_config=config.dictation,
hangup_hotkeys=(
diff --git a/jarvis/speech/watchdog.py b/jarvis/speech/watchdog.py
index 0238707028..5625df68b0 100644
--- a/jarvis/speech/watchdog.py
+++ b/jarvis/speech/watchdog.py
@@ -231,6 +231,13 @@ async def _main() -> None:
if config.trigger.hotkey_paste_last.strip()
else ()
),
+ # The pet shortcut: same reason as above — the rebuilt pipeline must
+ # arm it too, or it works until the first voice restart.
+ pet_toggle_hotkeys=(
+ (config.trigger.hotkey_pet_toggle,)
+ if config.trigger.hotkey_pet_toggle.strip()
+ else ()
+ ),
dictate_mode=config.dictation.mode,
dictation_config=config.dictation,
hangup_hotkeys=(
diff --git a/jarvis/ui/web/pets_routes.py b/jarvis/ui/web/pets_routes.py
new file mode 100644
index 0000000000..b9fdb98d5b
--- /dev/null
+++ b/jarvis/ui/web/pets_routes.py
@@ -0,0 +1,463 @@
+"""REST API for the desktop pets — the ``pet`` overlay style (docs/pets.md).
+
+Endpoints (mounted by the WebServer in ``_build_app()``):
+
+ GET /api/pets → active pet, look settings, visibility,
+ and every pet (built-in + user-created).
+ GET /api/pets/template.png → the blank sprite-sheet template.
+ GET /api/pets/{id}/sheet.png → a pet's sprite sheet.
+ PUT /api/pets/active → pick the active pet (or "none"); saved
+ to ``[ui] pet_id`` and applied live.
+ PUT /api/pets/settings → size and status bubble; saved, applied.
+ POST /api/pets/visibility → hide / show the pet (this run only).
+ POST /api/pets → create a pet from an uploaded sheet.
+ DELETE /api/pets/{id} → delete a user-created pet.
+
+Under the CLI-first contract every action here is also a
+``jarvis api pets <op>`` command. Every change that lands is announced as
+``PetChanged`` so every open settings page redraws from one event.
+
+Instances: both desktop instances read ONE ``jarvis.toml``, and only the
+default one draws the overlay (``jarvis.core.instance``). The two writes of
+the shared overlay settings — ``PUT /active`` and ``PUT /settings`` — answer
+409 on a dev instance for the same reason ``PUT /api/settings/overlay-style``
+does: a pick there would silently change the default app's pet on its next
+restart. User-created pets live in each instance's own data directory, so
+creating and deleting them is allowed everywhere; visibility is runtime-only.
+
+The pet engine (``jarvis.ui.pets``) decodes images with Pillow, so it is
+imported inside the handlers: nothing here loads on the boot path (AP-26).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
+from fastapi.responses import FileResponse
+from pydantic import BaseModel, Field
+
+from jarvis.core.config import clamp_pet_scale, normalize_pet_id
+from jarvis.ui.pets.states import DEFAULT_PET_ID, NO_PET_ID, PET_STATES
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/pets", tags=["pets"])
+
+#: A user-created pet's sheet never changes: a new upload gets a new id.
+_IMMUTABLE_CACHE = {"Cache-Control": "public, max-age=31536000, immutable"}
+#: A built-in sheet can change with an app update under the same URL, so the
+#: browser revalidates it (FileResponse answers with an ETag).
+_REVALIDATE_CACHE = {"Cache-Control": "no-cache"}
+_NOSNIFF = {"X-Content-Type-Options": "nosniff"}
+
+
+class ActiveBody(BaseModel):
+ pet_id: str = Field(..., min_length=1, max_length=40)
+
+
+class SettingsBody(BaseModel):
+ """Both optional; only the ones sent are changed."""
+
+ scale: float | None = Field(default=None, description="Size multiplier, 0.5–2.0")
+ bubble: bool | None = Field(default=None, description="Show the status bubble")
+
+
+class VisibilityBody(BaseModel):
+ visible: bool
+
+
+# ---------------------------------------------------------------------------
+# helpers
+# ---------------------------------------------------------------------------
+
+
+def _ui(request: Request) -> Any | None:
+ cfg = getattr(request.app.state, "config", None) or getattr(request.app.state, "cfg", None)
+ return getattr(cfg, "ui", None)
+
+
+def _desktop(request: Request) -> Any | None:
+ return getattr(request.app.state, "desktop_app", None)
+
+
+def _configured_pet_id(request: Request) -> str:
+ return normalize_pet_id(getattr(_ui(request), "pet_id", None)) or DEFAULT_PET_ID
+
+
+def _configured_scale(request: Request) -> float:
+ return clamp_pet_scale(getattr(_ui(request), "pet_scale", 1.0))
+
+
+def _configured_bubble(request: Request) -> bool:
+ return bool(getattr(_ui(request), "pet_bubble", True))
+
+
+def _pet_visible(request: Request) -> bool:
+ """Runtime visibility, asked of the running DesktopApp (True headless)."""
+ getter = getattr(_desktop(request), "pet_visible", None)
+ if not callable(getter):
+ return True
+ try:
+ return bool(getter())
+ except Exception: # noqa: BLE001 — a status read must never 500
+ log.debug("desktop_app.pet_visible() failed; reporting visible", exc_info=True)
+ return True
+
+
+def _config_path() -> Any:
+ """The ``jarvis.toml`` this process loaded (honours ``JARVIS_CONFIG``)."""
+ from jarvis.core.config import resolve_config_path
+
+ return resolve_config_path()
+
+
+def _set_ui_value(request: Request, field: str, value: object) -> None:
+ """Best-effort in-memory update so a later read agrees before a restart."""
+ ui = _ui(request)
+ if ui is None:
+ return
+ try:
+ setattr(ui, field, value)
+ except Exception as exc: # noqa: BLE001 — a frozen model is not an error
+ log.debug("in-memory ui.%s update skipped: %s", field, exc)
+
+
+def _refuse_on_secondary_instance() -> None:
+ from jarvis.core.instance import current_instance
+
+ instance = current_instance()
+ if not instance.owns_ambient_duties:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"The desktop pet belongs to the default app; the {instance.label} "
+ "instance draws no overlay and does not change the shared setting. "
+ "Change the pet in the regular Personal Jarvis app."
+ ),
+ )
+
+
+def _pet_exists(pet_id: str) -> bool:
+ """``none`` always exists; any other id must be a pet folder on disk."""
+ if pet_id == NO_PET_ID:
+ return True
+ from jarvis.ui.pets import loader
+
+ return loader.find_pet_dir(pet_id) is not None
+
+
+def _pet_json(manifest: Any) -> dict[str, Any]:
+ """One pet as the settings page needs it.
+
+ ``animations`` is resolved for EVERY state (a state the manifest leaves
+ out already carries its fallback's row), so no client has to repeat the
+ fallback table.
+ """
+ animations: dict[str, dict[str, Any]] = {}
+ for state in PET_STATES:
+ _resolved, spec = manifest.spec_for(state)
+ animations[state] = {
+ "row": spec.row,
+ "frames": spec.frames,
+ "fps": spec.fps,
+ "loop": spec.loop,
+ }
+ return {
+ "id": manifest.id,
+ "name": manifest.name,
+ "description": manifest.description,
+ "builtin": bool(manifest.builtin),
+ "frame_size": manifest.frame_size,
+ "animations": animations,
+ "sheet_url": f"/api/pets/{manifest.id}/sheet.png",
+ }
+
+
+async def _apply(request: Request, method: str, *args: Any) -> tuple[bool, str]:
+ """Call a DesktopApp pet method off the loop; ``(applied_live, detail)``.
+
+ Headless (no DesktopApp, or one without the method) is not an error: the
+ value is saved and the overlay reads it at its next start.
+ """
+ apply = getattr(_desktop(request), method, None)
+ if not callable(apply):
+ return False, ""
+ try:
+ result = await asyncio.to_thread(apply, *args)
+ except Exception as exc: # noqa: BLE001 — never fail a saved change on an apply hiccup
+ from jarvis.ui.web.error_text import LOG_HINT
+
+ log.warning("pet live-apply %s failed (saved; applies on restart): %s", method, exc)
+ return False, f"The change is saved but could not be applied live. {LOG_HINT}"
+ applied = bool(result.get("applied_live")) if isinstance(result, dict) else bool(result)
+ return applied, ""
+
+
+async def _publish_changed(request: Request, pet_id: str, *, source: str) -> None:
+ bus = getattr(request.app.state, "bus", None)
+ if bus is None:
+ return
+ from jarvis.core.events import PetChanged
+
+ try:
+ await bus.publish(
+ PetChanged(
+ pet_id=pet_id,
+ scale=_configured_scale(request),
+ bubble=_configured_bubble(request),
+ visible=_pet_visible(request),
+ source=source,
+ )
+ )
+ except Exception as exc: # noqa: BLE001 — a bus hiccup must not fail the change
+ log.warning("PetChanged publish failed: %s", exc)
+
+
+def _state(request: Request, active: str) -> dict[str, Any]:
+ return {
+ "active": active,
+ "scale": _configured_scale(request),
+ "bubble": _configured_bubble(request),
+ "visible": _pet_visible(request),
+ }
+
+
+# ---------------------------------------------------------------------------
+# routes
+# ---------------------------------------------------------------------------
+
+
+def list_pets(request: Request) -> dict[str, Any]:
+ """The active pet, its look, whether it is showing, and every pet."""
+ from jarvis.ui.pets import loader
+
+ manifests = loader.list_pets()
+ known = {m.id for m in manifests}
+ configured = _configured_pet_id(request)
+ # An id whose folder is gone (a deleted or broken pet) shows the default
+ # pet on screen, so the page must say the same.
+ active = configured if configured == NO_PET_ID or configured in known else DEFAULT_PET_ID
+ return {**_state(request, active), "pets": [_pet_json(m) for m in manifests]}
+
+
+#: The blank sprite-sheet template "Create pet" offers for download: seven
+#: tinted state rows in ``PET_STATES`` order, eight 48 px cells each.
+_TEMPLATE_PNG = Path(__file__).resolve().parents[1] / "pets" / "template" / "template.png"
+
+
[email protected]("/template.png", response_model=None)
+def pet_template() -> FileResponse:
+ """The sprite-sheet template for a user-drawn pet.
+
+ Registered before the ``/{pet_id}/...`` routes so no pet id can shadow it.
+ Ships with the app and changes only with an app update, so the browser
+ revalidates it like a built-in sheet.
+ """
+ if not _TEMPLATE_PNG.is_file():
+ raise HTTPException(status_code=404, detail="The template is not installed.")
+ return FileResponse(
+ str(_TEMPLATE_PNG),
+ media_type="image/png",
+ filename="pet-template.png",
+ headers={**_NOSNIFF, **_REVALIDATE_CACHE},
+ )
+
+
[email protected]("/{pet_id}/sheet.png", response_model=None)
+def pet_sheet(pet_id: str) -> FileResponse:
+ """A pet's sprite sheet. The id is shape-checked before any path is built."""
+ from jarvis.ui.pets import loader
+ from jarvis.ui.pets.manifest import PetManifestError
+
+ normalized = normalize_pet_id(pet_id)
+ found = loader.find_pet_dir(normalized) if normalized else None
+ if found is None:
+ raise HTTPException(status_code=404, detail="Unknown pet.")
+ folder, builtin = found
+ try:
+ manifest = loader.read_manifest(folder, builtin=builtin)
+ except PetManifestError as exc:
+ log.warning("pet %r sheet not served: %s", normalized, exc)
+ raise HTTPException(status_code=404, detail="Unknown pet.") from exc
+ return FileResponse(
+ str(folder / manifest.sheet),
+ media_type="image/png",
+ headers={**_NOSNIFF, **(_REVALIDATE_CACHE if builtin else _IMMUTABLE_CACHE)},
+ )
+
+
+async def put_active(body: ActiveBody, request: Request) -> dict[str, Any]:
+ """Pick the active pet: save ``[ui] pet_id``, swap the figure live."""
+ pet_id = normalize_pet_id(body.pet_id)
+ if pet_id is None:
+ raise HTTPException(status_code=400, detail=f"'{body.pet_id.strip()}' is not a pet id.")
+ if not await asyncio.to_thread(_pet_exists, pet_id):
+ raise HTTPException(status_code=404, detail=f"There is no pet '{pet_id}'.")
+ _refuse_on_secondary_instance()
+
+ _set_ui_value(request, "pet_id", pet_id)
+ persisted = False
+ try:
+ from jarvis.core import config_writer
+
+ await asyncio.to_thread(config_writer.set_pet_id, pet_id, path=_config_path())
+ persisted = True
+ except Exception as exc: # noqa: BLE001 — the live apply is still worth trying
+ log.warning("pet_id persist failed (live apply still attempted): %s", exc)
+
+ applied_live, detail = await _apply(request, "set_pet", pet_id)
+ await _publish_changed(request, pet_id, source="settings")
+ return {
+ "ok": True,
+ **_state(request, pet_id),
+ "persisted": persisted,
+ "applied_live": applied_live,
+ "detail": detail,
+ }
+
+
[email protected]("/settings")
+async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
+ """Change the pet's size and / or its status bubble; saved and applied live."""
+ if body.scale is None and body.bubble is None:
+ raise HTTPException(status_code=400, detail="Send 'scale', 'bubble' or both.")
+ _refuse_on_secondary_instance()
+
+ from jarvis.core import config_writer
+
+ persisted = True
+ if body.scale is not None:
+ scale = clamp_pet_scale(body.scale)
+ _set_ui_value(request, "pet_scale", scale)
+ try:
+ await asyncio.to_thread(config_writer.set_pet_scale, scale, path=_config_path())
+ except Exception as exc: # noqa: BLE001 — the live apply is still worth trying
+ persisted = False
+ log.warning("pet_scale persist failed (live apply still attempted): %s", exc)
+ if body.bubble is not None:
+ _set_ui_value(request, "pet_bubble", bool(body.bubble))
+ try:
+ await asyncio.to_thread(
+ config_writer.set_pet_bubble, bool(body.bubble), path=_config_path()
+ )
+ except Exception as exc: # noqa: BLE001 — the live apply is still worth trying
+ persisted = False
+ log.warning("pet_bubble persist failed (live apply still attempted): %s", exc)
+
+ applied_live, detail = await _apply(
+ request, "set_pet_look", _configured_scale(request), _configured_bubble(request)
+ )
+ active = _configured_pet_id(request)
+ await _publish_changed(request, active, source="settings")
+ return {
+ "ok": True,
+ **_state(request, active),
+ "persisted": persisted,
+ "applied_live": applied_live,
+ "detail": detail,
+ }
+
+
[email protected]("/visibility")
+async def post_visibility(body: VisibilityBody, request: Request) -> dict[str, Any]:
+ """Hide or show the pet for this run. Nothing is saved: the next start shows it."""
+ applied_live, detail = await _apply(request, "set_pet_visible", bool(body.visible))
+ active = _configured_pet_id(request)
+ await _publish_changed(request, active, source="settings")
+ return {
+ "ok": True,
+ **_state(request, active),
+ "applied_live": applied_live,
+ "detail": detail,
+ }
+
+
[email protected]("", status_code=201)
+async def create_pet(
+ sheet: UploadFile = File(...), # noqa: B008 — FastAPI dependency default
+ name: str = Form(""),
+ description: str = Form(""),
+ manifest: str | None = Form(None),
+ frame_size: str | None = Form(None),
+) -> dict[str, Any]:
+ """Create a pet from an uploaded sprite sheet (and optional ``pet.json``).
+
+ The sheet is read with a ceiling rather than whole — one byte over the
+ limit is enough for the store to refuse it. Every refusal is a 400 whose
+ detail is the store's own user-readable sentence.
+ """
+ from jarvis.ui.pets import loader
+ from jarvis.ui.pets.manifest import MAX_SHEET_BYTES, PetManifestError
+ from jarvis.ui.pets.store import PetStore
+
+ size: int | None = None
+ if frame_size is not None and frame_size.strip():
+ try:
+ size = int(frame_size.strip())
+ except ValueError:
+ raise HTTPException(
+ status_code=400, detail=f"'{frame_size.strip()}' is not a frame size."
+ ) from None
+
+ data = await sheet.read(MAX_SHEET_BYTES + 1)
+ store = PetStore(loader.custom_root())
+ try:
+ created = await asyncio.to_thread(
+ store.add,
+ sheet_bytes=data,
+ name=name,
+ description=description,
+ manifest_json=manifest,
+ frame_size=size,
+ )
+ except PetManifestError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ log.info("Pet %r created (%s).", created.id, created.name)
+ return _pet_json(created)
+
+
[email protected]("/{pet_id}", openapi_extra={"x-jarvis-dangerous": True})
+async def delete_pet(pet_id: str, request: Request) -> dict[str, Any]:
+ """Delete a user-created pet. Deleting the active one switches to the default."""
+ from jarvis.ui.pets import loader
+ from jarvis.ui.pets.manifest import USER_ID_RE
+ from jarvis.ui.pets.store import PetStore
+
+ normalized = normalize_pet_id(pet_id)
+ if normalized is None:
+ raise HTTPException(status_code=404, detail="Unknown pet.")
+ if not USER_ID_RE.match(normalized):
+ raise HTTPException(
+ status_code=400, detail="Built-in pets cannot be deleted, only pets you created."
+ )
+ store = PetStore(loader.custom_root())
+ if not await asyncio.to_thread(store.delete, normalized):
+ raise HTTPException(status_code=404, detail="Unknown pet.")
+ log.info("Pet %r deleted.", normalized)
+
+ active = _configured_pet_id(request)
+ if active != normalized:
+ return {"ok": True, "deleted": normalized, "active": active}
+
+ # The pet on screen is gone: fall back to the default pet. On a secondary
+ # instance the shared setting is not this instance's to change (its pets
+ # live in its own data directory, so the default app's pick is unaffected).
+ from jarvis.core.instance import current_instance
+
+ if current_instance().owns_ambient_duties:
+ _set_ui_value(request, "pet_id", DEFAULT_PET_ID)
+ try:
+ from jarvis.core import config_writer
+
+ await asyncio.to_thread(config_writer.set_pet_id, DEFAULT_PET_ID, path=_config_path())
+ except Exception as exc: # noqa: BLE001 — the live apply is still worth trying
+ log.warning("pet_id fallback persist failed: %s", exc)
+ await _apply(request, "set_pet", DEFAULT_PET_ID)
+ await _publish_changed(request, DEFAULT_PET_ID, source="pet_deleted")
+ return {"ok": True, "deleted": normalized, "active": DEFAULT_PET_ID}
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index e1feb290ca..b0860bb18b 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -383,6 +383,7 @@ class WebServer:
from .onboarding_routes import router as onboarding_router
from .outputs_routes import router as outputs_router
from .permissions_routes import router as permissions_router
+ from .pets_routes import router as pets_router
from .preview_routes import router as preview_router
from .profile_routes import router as profile_router
from .provider_routes import router as provider_router
@@ -544,6 +545,8 @@ class WebServer:
app.include_router(contacts_router)
# Settings -> Computers: the user's own servers and local VMs over SSH.
app.include_router(computers_router)
+ # Desktop pets — the `pet` overlay style's pets, look and visibility.
+ app.include_router(pets_router)
app.include_router(dictionary_router)
# Dictation mode — hold to speak, text lands in the focused field.
# Mounted so every action is also `jarvis api dictation <op>`, which is
diff --git a/tests/unit/core/test_pet_config.py b/tests/unit/core/test_pet_config.py
new file mode 100644
index 0000000000..9152710379
--- /dev/null
+++ b/tests/unit/core/test_pet_config.py
@@ -0,0 +1,204 @@
+"""Config contract of the desktop pet (docs/pets.md).
+
+Pins the four keys the pet adds — ``[ui] pet_id / pet_scale / pet_bubble`` and
+``[trigger] hotkey_pet_toggle`` — their sanitizing on load, their TOML writers,
+and the claims the shipped shortcut's comment makes: it validates on every
+platform and collides with no other shortcut the app ships.
+"""
+from __future__ import annotations
+
+import tomllib
+from pathlib import Path
+
+import pytest
+
+from jarvis.appshot.hotkey import BOTH_ALT, normalize_hotkey
+from jarvis.control.wiring import DEFAULT_KILL_HOTKEY
+from jarvis.core import config_writer
+from jarvis.core.config import (
+ AppshotConfig,
+ TriggerConfig,
+ UIConfig,
+ clamp_pet_scale,
+ normalize_pet_id,
+)
+from jarvis.trigger.hotkey import combos_collide, normalized_combo_tokens, validate_hotkey
+from jarvis.ui.pets.manifest import BUILTIN_ID_RE, USER_ID_RE
+from jarvis.ui.pets.states import DEFAULT_PET_ID, NO_PET_ID
+
+#: The Jarvis X keys (one per pane) — not configurable here, but a pet
+#: shortcut that fired inside one of them would be a collision all the same.
+_JARVIS_X_KEYS = tuple(f"ctrl+shift+{n}" for n in range(1, 7))
+
+
+# ---------------------------------------------------------------------------
+# [ui] pet_id / pet_scale / pet_bubble
+# ---------------------------------------------------------------------------
+
+
+def test_defaults() -> None:
+ ui = UIConfig()
+ assert ui.pet_id == DEFAULT_PET_ID
+ assert ui.pet_scale == 1.0
+ assert ui.pet_bubble is True
+
+
+ "raw,expected",
+ [
+ ("gigi", "gigi"),
+ (" Miso ", "miso"),
+ ("none", NO_PET_ID),
+ ("NONE", NO_PET_ID),
+ ("u0123456789abcdef", "u0123456789abcdef"),
+ # Anything that is not id-shaped falls back to the default pet: a
+ # corrupt jarvis.toml must never brick the load.
+ ("../../etc", DEFAULT_PET_ID),
+ ("C:\\pets\\gigi", DEFAULT_PET_ID),
+ ("", DEFAULT_PET_ID),
+ ("a" * 33, DEFAULT_PET_ID),
+ (7, DEFAULT_PET_ID),
+ (None, DEFAULT_PET_ID),
+ ],
+)
+def test_pet_id_is_sanitized_on_load(raw: object, expected: str) -> None:
+ assert UIConfig(pet_id=raw).pet_id == expected
+
+
+def test_pet_id_shape_matches_the_manifest_rules() -> None:
+ """One id shape across the config, the loader and the routes (AP-4)."""
+ for candidate in ("gigi", "bolt-2", "u0123456789abcdef", "none", "a" * 32):
+ assert normalize_pet_id(candidate) == candidate
+ assert BUILTIN_ID_RE.fullmatch(candidate)
+ for candidate in ("-gigi", "gi gi", "gigi.png", "a" * 33, "../x", "Gigi/"):
+ assert normalize_pet_id(candidate) is None
+ assert not BUILTIN_ID_RE.fullmatch(candidate.lower())
+ assert USER_ID_RE.fullmatch("u0123456789abcdef")
+
+
+ "raw,expected",
+ [
+ (1.0, 1.0),
+ ("1.5", 1.5),
+ (0.1, 0.5),
+ (9, 2.0),
+ ("big", 1.0),
+ (float("nan"), 1.0),
+ (float("inf"), 1.0),
+ (None, 1.0),
+ ],
+)
+def test_pet_scale_is_clamped(raw: object, expected: float) -> None:
+ assert UIConfig(pet_scale=raw).pet_scale == expected
+ assert clamp_pet_scale(raw) == expected
+
+
+# ---------------------------------------------------------------------------
+# Writers
+# ---------------------------------------------------------------------------
+
+
+def _ui_table(path: Path) -> dict:
+ return tomllib.loads(path.read_text(encoding="utf-8")).get("ui", {})
+
+
+def test_writers_persist_the_three_ui_keys(tmp_path: Path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text('[ui]\norb_style = "pet" # kept\n', encoding="utf-8")
+
+ config_writer.set_pet_id("Miso", path=toml)
+ config_writer.set_pet_scale(3.0, path=toml)
+ config_writer.set_pet_bubble(False, path=toml)
+
+ ui = _ui_table(toml)
+ assert ui["pet_id"] == "miso"
+ assert ui["pet_scale"] == 2.0 # clamped before it reaches the disk
+ assert ui["pet_bubble"] is False
+ assert ui["orb_style"] == "pet"
+ assert "# kept" in toml.read_text(encoding="utf-8") # comments survive
+
+
+def test_set_pet_scale_never_writes_a_non_finite_value(tmp_path: Path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("", encoding="utf-8")
+ config_writer.set_pet_scale(float("nan"), path=toml)
+ assert _ui_table(toml)["pet_scale"] == 1.0
+
+
+def test_set_pet_id_refuses_a_value_that_is_not_an_id(tmp_path: Path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("", encoding="utf-8")
+ with pytest.raises(ValueError):
+ config_writer.set_pet_id("../../somewhere", path=toml)
+ assert "pet_id" not in _ui_table(toml)
+
+
+# ---------------------------------------------------------------------------
+# [trigger] hotkey_pet_toggle
+# ---------------------------------------------------------------------------
+
+
+def test_pet_toggle_is_a_keybind_action() -> None:
+ assert "pet_toggle" in config_writer.KEYBIND_ACTIONS
+ assert config_writer.KEYBIND_TOML_KEY["pet_toggle"] == "hotkey_pet_toggle"
+ assert TriggerConfig().hotkey_pet_toggle == "alt+win+p"
+
+
+def test_set_keybind_persists_the_pet_toggle(tmp_path: Path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("", encoding="utf-8")
+ config_writer.set_keybind("pet_toggle", "ctrl+alt+shift+p", path=toml)
+ trigger = tomllib.loads(toml.read_text(encoding="utf-8"))["trigger"]
+ assert trigger["hotkey_pet_toggle"] == "ctrl+alt+shift+p"
+
+
[email protected]("platform", ["win32", "darwin", "linux"])
+def test_shipped_pet_toggle_validates_without_caution(platform: str) -> None:
+ verdict = validate_hotkey(TriggerConfig().hotkey_pet_toggle, platform=platform)
+ assert verdict.ok is True, verdict.reason
+ assert verdict.cautions == (), verdict.cautions
+
+
+def _other_shipped_shortcuts() -> dict[str, str]:
+ trigger = TriggerConfig()
+ shortcuts = {
+ field: getattr(trigger, field)
+ for field in config_writer.KEYBIND_TOML_KEY.values()
+ if field != "hotkey_pet_toggle"
+ }
+ shortcuts["kill_switch"] = DEFAULT_KILL_HOTKEY
+ shortcuts.update({f"jarvis_x_{n}": combo for n, combo in enumerate(_JARVIS_X_KEYS, 1)})
+ return shortcuts
+
+
+def test_shipped_pet_toggle_collides_with_no_other_shortcut() -> None:
+ """Neither the same key set nor a subset / superset of any shipped combo."""
+ pet = TriggerConfig().hotkey_pet_toggle
+ others = _other_shipped_shortcuts()
+ assert "hotkey_call" in others and "hotkey_paste_last" in others
+ for name, combo in others.items():
+ assert combo, name
+ assert not combos_collide(pet, combo), f"{pet} collides with {name}={combo}"
+
+
+def test_shipped_pet_toggle_cannot_fire_the_both_alt_appshot_gesture() -> None:
+ """``alt+alt`` is watched as BOTH Alt keys down; the pet holds only one.
+
+ ``combos_collide`` cannot judge this pair (the shared backends fold both
+ Alt keys into one token), so the gesture's own rule is checked instead.
+ """
+ pet = TriggerConfig().hotkey_pet_toggle
+ assert normalize_hotkey(AppshotConfig().hotkey) == BOTH_ALT
+ assert normalize_hotkey(pet) != BOTH_ALT
+ assert [part for part in pet.split("+") if "alt" in part] == ["alt"]
+ assert "window" in normalized_combo_tokens(pet) # win → Command on macOS
+
+
+def test_example_config_documents_the_pet_keys() -> None:
+ example = Path(__file__).resolve().parents[3] / "jarvis.toml.example"
+ data = tomllib.loads(example.read_text(encoding="utf-8"))
+ assert data["ui"]["pet_id"] == UIConfig().pet_id
+ assert data["ui"]["pet_scale"] == UIConfig().pet_scale
+ assert data["ui"]["pet_bubble"] == UIConfig().pet_bubble
+ assert data["trigger"]["hotkey_pet_toggle"] == TriggerConfig().hotkey_pet_toggle
diff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.py
index 1d25fd66df..0166e4ca6d 100644
--- a/tests/unit/dictation/test_dictate_keybind.py
+++ b/tests/unit/dictation/test_dictate_keybind.py
@@ -53,6 +53,7 @@ _ACTION_ATTR = {
"dictate": "_dictate_hotkeys",
"dictate_toggle": "_dictate_toggle_hotkeys",
"paste_last": "_paste_last_hotkeys",
+ "pet_toggle": "_pet_toggle_hotkeys",
}
diff --git a/tests/unit/plugins/tool/test_navigate.py b/tests/unit/plugins/tool/test_navigate.py
index f6df873e27..89ae90b202 100644
--- a/tests/unit/plugins/tool/test_navigate.py
+++ b/tests/unit/plugins/tool/test_navigate.py
@@ -69,6 +69,13 @@ async def test_canonical_id_publishes_navigate(tool: NavigateTool, bus: Recordin
("outputs", "visualization"),
("Ausgaben", "visualization"),
("ergebnisse", "visualization"),
+ # My Pets: the id itself and the phrases that name the app's own pet.
+ ("pets", "pets"),
+ ("My Pets", "pets"),
+ ("desktop pet", "pets"),
+ ("Haustier", "pets"), # i18n-allow: input vocab
+ ("meine pets", "pets"), # i18n-allow: input vocab
+ ("mis mascotas", "pets"), # i18n-allow: input vocab
],
)
async def test_alias_normalizes_to_id(
diff --git a/tests/unit/speech/test_speaker_mute_event.py b/tests/unit/speech/test_speaker_mute_event.py
new file mode 100644
index 0000000000..d48cba1d9e
--- /dev/null
+++ b/tests/unit/speech/test_speaker_mute_event.py
@@ -0,0 +1,216 @@
+"""Speaker mute on the real ``SpeechPipeline`` (docs/pets.md).
+
+Speaker mute is TTS volume 0. Two contracts live on the pipeline:
+
+* ``get_tts_volume`` reports the volume in effect. Without it the orb/pet
+ speaker disc read every volume as "audible", so a click could mute the voice
+ but never bring it back (the live bug this closes).
+* ``set_tts_volume`` — the one choke point every writer ends in — broadcasts
+ ``VoiceSpeakerMuteChanged`` exactly when the muted-ness FLIPS, from whatever
+ thread it is called on (the REST threadpool, the overlay's Tk thread), and
+ the event is delivered on the pipeline's own loop.
+
+Also covers the pet shortcut, which the pipeline dispatches like every other
+global hotkey and answers with ``PetVisibilityToggleRequested``.
+"""
+from __future__ import annotations
+
+import asyncio
+import threading
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+
+import pytest
+
+from jarvis.core import runtime_refs
+from jarvis.core.bus import EventBus
+from jarvis.core.events import PetVisibilityToggleRequested, VoiceSpeakerMuteChanged
+from jarvis.core.protocols import AudioChunk
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+@dataclass
+class FakeTTS:
+ name: str = "fake-tts"
+ supports_streaming: bool = True
+
+ async def synthesize(
+ self, text: str, voice: str | None = None, language_code: str | None = None
+ ) -> AsyncIterator[AudioChunk]:
+ if False: # pragma: no cover
+ yield # type: ignore[unreachable]
+
+
+@dataclass
+class VolumePlayer:
+ """The slice of ``AudioPlayer`` the volume path touches."""
+
+ _volume: float = 1.0
+ calls: list[float] = field(default_factory=list)
+
+ def set_volume(self, volume: float) -> None:
+ self.calls.append(volume)
+ self._volume = max(0.0, min(1.0, float(volume)))
+
+ def stop(self) -> None:
+ return None
+
+
+def _pipeline(bus: EventBus, *, volume: float = 1.0) -> tuple[SpeechPipeline, VolumePlayer]:
+ pipeline = SpeechPipeline(tts=FakeTTS(), bus=bus, enable_whisper_wake=False)
+ player = VolumePlayer(_volume=volume)
+ pipeline._player = player # type: ignore[assignment]
+ return pipeline, player
+
+
+def _collect(bus: EventBus, event_type: type) -> list:
+ """Subscribe an async recorder (typed bus handlers are awaited)."""
+ seen: list = []
+
+ async def _record(event) -> None:
+ seen.append(event)
+
+ bus.subscribe(event_type, _record)
+ return seen
+
+
+async def _drain() -> None:
+ """Let scheduled publish tasks run to completion."""
+ for _ in range(5):
+ await asyncio.sleep(0)
+
+
+# ---------------------------------------------------------------------------
+# get_tts_volume
+# ---------------------------------------------------------------------------
+
+
+def test_get_tts_volume_reads_the_live_player() -> None:
+ pipeline, player = _pipeline(EventBus(), volume=0.6)
+ assert pipeline.get_tts_volume() == pytest.approx(0.6)
+ player._volume = 0.0
+ assert pipeline.get_tts_volume() == 0.0
+
+
+def test_get_tts_volume_without_a_player_falls_back_to_what_was_asked() -> None:
+ pipeline = SpeechPipeline(tts=FakeTTS(), bus=None, enable_whisper_wake=False)
+ pipeline._player = None # type: ignore[assignment]
+ assert pipeline.get_tts_volume() == 1.0 # nothing configured, nothing asked
+ pipeline.set_tts_volume(0.0)
+ assert pipeline.get_tts_volume() == 0.0
+
+
+# ---------------------------------------------------------------------------
+# set_tts_volume → VoiceSpeakerMuteChanged
+# ---------------------------------------------------------------------------
+
+
+async def test_event_fires_only_when_the_muted_ness_flips() -> None:
+ bus = EventBus()
+ pipeline, player = _pipeline(bus, volume=0.8)
+ seen: list[VoiceSpeakerMuteChanged] = _collect(bus, VoiceSpeakerMuteChanged)
+
+ pipeline.set_tts_volume(0.5, source="settings") # audible → audible
+ await _drain()
+ assert seen == []
+
+ pipeline.set_tts_volume(0.0, source="pet") # audible → silent
+ await _drain()
+ assert [(e.muted, e.source) for e in seen] == [(True, "pet")]
+
+ pipeline.set_tts_volume(0.0, source="pet") # silent → silent
+ await _drain()
+ assert len(seen) == 1
+
+ pipeline.set_tts_volume(0.7, source="settings") # silent → audible
+ await _drain()
+ assert [(e.muted, e.source) for e in seen] == [(True, "pet"), (False, "settings")]
+ assert player.calls == [0.5, 0.0, 0.0, 0.7]
+
+
+async def test_a_pipeline_that_boots_silent_reports_the_unmute() -> None:
+ """The first change is compared against the volume in effect, not "audible"."""
+ bus = EventBus()
+ pipeline, _player = _pipeline(bus, volume=0.0)
+ seen: list[VoiceSpeakerMuteChanged] = _collect(bus, VoiceSpeakerMuteChanged)
+
+ pipeline.set_tts_volume(1.0)
+ await _drain()
+ assert [e.muted for e in seen] == [False]
+
+
+async def test_a_call_from_another_thread_publishes_on_the_pipeline_loop() -> None:
+ """The REST route and the Tk thread have no loop; the event must still
+ reach subscribers on the backend loop — never a throwaway one."""
+ bus = EventBus()
+ pipeline, _player = _pipeline(bus)
+ loop = asyncio.get_running_loop()
+ pipeline._runtime_loop = loop
+ delivered = asyncio.Event()
+ seen: list[tuple[bool, int]] = []
+
+ async def _record(event: VoiceSpeakerMuteChanged) -> None:
+ seen.append((event.muted, threading.get_ident()))
+ delivered.set()
+
+ bus.subscribe(VoiceSpeakerMuteChanged, _record)
+ await asyncio.to_thread(pipeline.set_tts_volume, 0.0, source="pet")
+ await asyncio.wait_for(delivered.wait(), timeout=2.0)
+
+ assert seen == [(True, threading.get_ident())]
+
+
+def test_without_a_bus_the_volume_still_applies() -> None:
+ pipeline = SpeechPipeline(tts=FakeTTS(), bus=None, enable_whisper_wake=False)
+ player = VolumePlayer()
+ pipeline._player = player # type: ignore[assignment]
+ pipeline.set_tts_volume(0.0)
+ assert player.calls == [0.0]
+ assert pipeline.get_tts_volume() == 0.0
+
+
+def test_the_speaker_disc_can_unmute_again(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The reported bug: the disc muted, and every later click muted again."""
+ from ui.orb import controls
+
+ pipeline, player = _pipeline(EventBus(), volume=0.9)
+ monkeypatch.setattr(runtime_refs, "_SPEECH_PIPELINE", [pipeline])
+
+ assert controls.toggle_speaker_mute() is True
+ assert player._volume == 0.0
+ assert controls.speaker_is_muted() is True
+
+ assert controls.toggle_speaker_mute() is False
+ assert player._volume == pytest.approx(0.9)
+ assert controls.speaker_is_muted() is False
+
+
+# ---------------------------------------------------------------------------
+# The pet shortcut
+# ---------------------------------------------------------------------------
+
+
+async def test_pet_toggle_hotkey_publishes_the_visibility_request() -> None:
+ bus = EventBus()
+ pipeline = SpeechPipeline(
+ tts=FakeTTS(), bus=bus, enable_whisper_wake=False, pet_toggle_hotkeys=("alt+win+p",)
+ )
+ seen: list[PetVisibilityToggleRequested] = _collect(bus, PetVisibilityToggleRequested)
+
+ pipeline._dispatch_hotkey_event("pet_toggle")
+ await _drain()
+
+ assert [e.source for e in seen] == ["hotkey"]
+
+
+def test_pet_toggle_is_armed_single_fire_and_only_when_bound() -> None:
+ pipeline = SpeechPipeline(
+ tts=FakeTTS(), bus=None, enable_whisper_wake=False, pet_toggle_hotkeys=("alt+win+p",)
+ )
+ bindings, edges = pipeline._build_hotkey_bindings()
+ assert bindings["pet_toggle"] == ["alt+win+p"]
+ assert "pet_toggle" not in edges
+
+ pipeline.set_keybinds(pet_toggle=[])
+ bindings, _edges = pipeline._build_hotkey_bindings()
+ assert "pet_toggle" not in bindings
diff --git a/tests/unit/ui/test_keybinds_route.py b/tests/unit/ui/test_keybinds_route.py
index e864e65437..de77e3040a 100644
--- a/tests/unit/ui/test_keybinds_route.py
+++ b/tests/unit/ui/test_keybinds_route.py
@@ -50,6 +50,7 @@ def test_get_returns_every_action_plus_defaults() -> None:
"dictate": "ctrl+right_alt+j",
"dictate_toggle": "ctrl+right_alt+space",
"paste_last": "ctrl+alt+v",
+ "pet_toggle": "alt+win+p",
}
assert body["defaults"] == {
"call": "f3+f4",
@@ -57,6 +58,7 @@ def test_get_returns_every_action_plus_defaults() -> None:
"dictate": "ctrl+right_alt+j",
"dictate_toggle": "ctrl+right_alt+space",
"paste_last": "ctrl+alt+v",
+ "pet_toggle": "alt+win+p",
}
assert "push_to_talk" not in body
assert body["restart_required"] is True
diff --git a/tests/unit/ui/test_orb_bus_bridge_pet.py b/tests/unit/ui/test_orb_bus_bridge_pet.py
new file mode 100644
index 0000000000..5ce7ffec1c
--- /dev/null
+++ b/tests/unit/ui/test_orb_bus_bridge_pet.py
@@ -0,0 +1,444 @@
+"""OrbBusBridge → desktop pet (docs/pets.md).
+
+The bridge drives every overlay style; the pet adds optional surface methods
+the bridge reaches through ``getattr``. These tests use a real ``EventBus`` and
+a hand-written pet surface and pin: the speaker-mute mirror, the shortcut, the
+one-shot outcomes, the rate-limited status lines (pet only), the pen control,
+the per-surface re-wiring on a live swap, and that the pet is never hidden
+when Jarvis goes idle.
+"""
+from __future__ import annotations
+
+import asyncio
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import runtime_refs
+from jarvis.core.bus import EventBus
+from jarvis.core.events import (
+ ActionExecuted,
+ ActionProposed,
+ AnnouncementRequested,
+ AssistantTextDelta,
+ ComposeRequested,
+ ErrorOccurred,
+ JarvisAgentAnnouncement,
+ JarvisAgentBackgroundCompleted,
+ PetVisibilityToggleRequested,
+ SpeechSpoken,
+ SystemStateChanged,
+ TranscriptionUpdate,
+ UiLanguageChanged,
+ VoiceSessionEnded,
+ VoiceSessionStarted,
+ VoiceSpeakerMuteChanged,
+ WakeCandidateDetected,
+)
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+if str(_REPO_ROOT) in sys.path:
+ sys.path.remove(str(_REPO_ROOT))
+sys.path.insert(0, str(_REPO_ROOT))
+sys.modules.pop("ui", None)
+
+try: # noqa: SIM105 — intentional try-import for the discovery quirk
+ from ui.orb import bus_bridge # type: ignore[import-not-found]
+ from ui.orb.bus_bridge import OrbBusBridge # type: ignore[import-not-found]
+except ModuleNotFoundError: # pragma: no cover
+ pytest.skip("ui.orb not available on the pytest PYTHONPATH.", allow_module_level=True)
+
+
+class _Surface:
+ """Records every call a surface can receive from the bridge."""
+
+ wants_status_lines = False
+ keeps_visible_when_idle = False
+
+ def __init__(self) -> None:
+ self.calls: list[tuple] = []
+ self.callbacks: dict[str, object] = {}
+ self._mode = "idle"
+
+ # the four-mode surface API every style has
+ def show(self, mode: str = "listen") -> None:
+ self._mode = mode
+ self.calls.append(("show", mode))
+
+ def hide(self) -> None:
+ self.calls.append(("hide",))
+
+ def play_animation(self, name: str) -> None:
+ self.calls.append(("play_animation", name))
+
+ def stop_animation(self, name: str) -> None:
+ self.calls.append(("stop_animation", name))
+
+ def set_level(self, level: float) -> None:
+ self.calls.append(("set_level", level))
+
+ def show_listening_transcript(self, text: str, duration_ms: int) -> None:
+ self.calls.append(("transcript", text))
+
+ # callback setters
+ def set_on_mute_toggle(self, cb) -> None:
+ self.callbacks["mute"] = cb
+
+ def set_on_prompt_mode_toggle(self, cb) -> None:
+ self.callbacks["prompt_mode"] = cb
+
+ def set_on_compose(self, cb) -> None:
+ self.callbacks["compose"] = cb
+
+ def set_feedback_publisher(self, cb) -> None:
+ self.callbacks["feedback"] = cb
+
+ def set_on_show_window(self, cb) -> None:
+ self.callbacks["show_window"] = cb
+
+ # mirrors
+ def set_muted(self, muted: bool) -> None:
+ self.calls.append(("set_muted", muted))
+
+ def set_speaker_muted(self, muted: bool) -> None:
+ self.calls.append(("set_speaker_muted", muted))
+
+ def set_prompt_mode(self, enabled: bool, paused: bool) -> None:
+ self.calls.append(("set_prompt_mode", enabled, paused))
+
+ # pet-only methods (a bar may have show_status too; the gate is the flag)
+ def set_pet_outcome(self, kind: str) -> None:
+ self.calls.append(("outcome", kind))
+
+ def show_status(self, header: str, line: str) -> None:
+ self.calls.append(("status", header, line))
+
+ def toggle_visible(self) -> None:
+ self.calls.append(("toggle_visible",))
+
+ def of(self, name: str) -> list[tuple]:
+ return [c for c in self.calls if c[0] == name]
+
+
+class _Pet(_Surface):
+ wants_status_lines = True
+ keeps_visible_when_idle = True
+
+
+class _FakePipeline:
+ """What the bridge reads off the live pipeline when it seeds a surface."""
+
+ def __init__(self, *, muted: bool, volume: float, language: str = "en") -> None:
+ self.is_muted = muted
+ self._volume = volume
+ self._dictation_cfg = None
+
+ class _Ui:
+ pass
+
+ class _Cfg:
+ ui = _Ui()
+
+ _Cfg.ui.language = language
+ self._config = _Cfg()
+
+ def get_tts_volume(self) -> float:
+ return self._volume
+
+
[email protected](autouse=True)
+def _no_live_pipeline(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(runtime_refs, "_SPEECH_PIPELINE", [])
+
+
+def fast_status(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Shrink the status rate limit so the flush path runs in milliseconds."""
+ monkeypatch.setattr(bus_bridge, "PET_STATUS_MIN_INTERVAL_S", 0.02)
+
+
+def _bridge(surface: _Surface, **kwargs) -> tuple[OrbBusBridge, EventBus]:
+ bus = EventBus()
+ bridge = OrbBusBridge(bus=bus, orb=surface, **kwargs) # type: ignore[arg-type]
+ bridge.attach()
+ return bridge, bus
+
+
+# ---------------------------------------------------------------------------
+# mirrors, shortcut, pen
+# ---------------------------------------------------------------------------
+
+
+async def test_speaker_mute_is_mirrored() -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(VoiceSpeakerMuteChanged(muted=True, source="pet"))
+ await bus.publish(VoiceSpeakerMuteChanged(muted=False, source="settings"))
+ assert pet.of("set_speaker_muted") == [
+ ("set_speaker_muted", True),
+ ("set_speaker_muted", False),
+ ]
+
+
+async def test_shortcut_toggles_the_pet() -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(PetVisibilityToggleRequested(source="hotkey"))
+ assert pet.of("toggle_visible") == [("toggle_visible",)]
+
+
+async def test_surfaces_without_pet_methods_ignore_every_pet_event() -> None:
+ class _Bar:
+ def show(self, mode: str = "listen") -> None:
+ pass
+
+ def hide(self) -> None:
+ pass
+
+ def set_level(self, level: float) -> None:
+ pass
+
+ _bridge_, bus = _bridge(_Bar()) # type: ignore[arg-type]
+ await bus.publish(PetVisibilityToggleRequested(source="hotkey"))
+ await bus.publish(VoiceSpeakerMuteChanged(muted=True))
+ await bus.publish(ActionExecuted(tool_name="x", success=True))
+ await bus.publish(ActionProposed(tool_name="web_search", rationale="Looking it up"))
+
+
+def test_attach_seeds_both_mutes_from_the_live_pipeline(monkeypatch) -> None:
+ monkeypatch.setattr(
+ runtime_refs, "_SPEECH_PIPELINE", [_FakePipeline(muted=True, volume=0.0)]
+ )
+ pet = _Pet()
+ _bridge(pet)
+ assert ("set_muted", True) in pet.calls
+ assert ("set_speaker_muted", True) in pet.calls
+
+
+def test_pen_publishes_compose_on_the_backend_loop() -> None:
+ backend = asyncio.new_event_loop()
+ thread = threading.Thread(target=backend.run_forever, daemon=True)
+ thread.start()
+ try:
+ seen: list[tuple[ComposeRequested, asyncio.AbstractEventLoop]] = []
+ done = threading.Event()
+ bus = EventBus()
+
+ async def _record(event: ComposeRequested) -> None:
+ seen.append((event, asyncio.get_running_loop()))
+ done.set()
+
+ bus.subscribe(ComposeRequested, _record)
+ pet = _Pet()
+ bridge = OrbBusBridge(bus=bus, orb=pet) # type: ignore[arg-type]
+ bridge.attach()
+ bridge._loop = backend # noqa: SLF001 — what attach() captures in the app
+
+ pet.callbacks["compose"]() # fired from this (loop-less) "Tk" thread
+
+ assert done.wait(timeout=2.0)
+ assert seen[0][0].source == "pet"
+ assert seen[0][1] is backend
+ finally:
+ backend.call_soon_threadsafe(backend.stop)
+ thread.join(timeout=2.0)
+ backend.close()
+
+
+def test_a_swapped_in_surface_gets_every_callback_and_the_live_mutes(monkeypatch) -> None:
+ old, new = _Surface(), _Pet()
+ bridge = OrbBusBridge(bus=EventBus(), orb=old) # type: ignore[arg-type]
+ bridge.attach()
+ monkeypatch.setattr(
+ runtime_refs, "_SPEECH_PIPELINE", [_FakePipeline(muted=False, volume=0.0)]
+ )
+
+ bridge.set_surface(new)
+
+ for name in ("mute", "prompt_mode", "compose", "feedback", "show_window"):
+ assert name in new.callbacks, name
+ assert ("set_muted", False) in new.calls
+ assert ("set_speaker_muted", True) in new.calls
+
+
+# ---------------------------------------------------------------------------
+# outcomes
+# ---------------------------------------------------------------------------
+
+
+ "event,expected",
+ [
+ (ActionExecuted(tool_name="open_app", success=True), "success"),
+ (ActionExecuted(tool_name="open_app", success=False), "error"),
+ (SpeechSpoken(text="Done.", spoken_kind="action_done"), "success"),
+ (SpeechSpoken(text="Finished.", spoken_kind="completion"), "success"),
+ (SpeechSpoken(text="Too slow.", spoken_kind="timeout"), "error"),
+ (SpeechSpoken(text="Offline.", spoken_kind="unavailable"), "error"),
+ (SpeechSpoken(text="Can't hear.", spoken_kind="stt_unavailable"), "error"),
+ (JarvisAgentBackgroundCompleted(success=True), "success"),
+ (ErrorOccurred(layer="brain", message="boom"), "error"),
+ (VoiceSessionEnded(session_id="s", hangup_reason="error"), "error"),
+ ],
+)
+async def test_outcomes_play_the_one_shot(event, expected: str) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(event)
+ assert pet.of("outcome") == [("outcome", expected)]
+
+
+ "event",
+ [
+ SpeechSpoken(text="Hello.", spoken_kind="reply"),
+ JarvisAgentBackgroundCompleted(success=False),
+ VoiceSessionEnded(session_id="s", hangup_reason="hotkey"),
+ VoiceSessionEnded(session_id="s", hangup_reason="idle_timeout"),
+ ],
+)
+async def test_ordinary_events_play_no_outcome(event) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(event)
+ assert pet.of("outcome") == []
+
+
+# ---------------------------------------------------------------------------
+# status lines
+# ---------------------------------------------------------------------------
+
+
+async def test_status_lines_reach_only_a_surface_that_wants_them() -> None:
+ bar = _Surface() # has show_status, but does not ask for lines
+ _bridge_, bus = _bridge(bar)
+ await bus.publish(SystemStateChanged(previous="IDLE", new_state="THINKING"))
+ await bus.publish(ActionProposed(tool_name="web_search", rationale="Checking the news"))
+ await bus.publish(AssistantTextDelta(text="Here it is.", done=True))
+ assert bar.of("status") == []
+
+
+async def test_thinking_shows_the_header_then_the_reason(fast_status) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(SystemStateChanged(previous="IDLE", new_state="THINKING"))
+ assert pet.of("status")[-1] == ("status", "Thinking …", "")
+
+ await asyncio.sleep(0.03)
+ await bus.publish(
+ ActionProposed(tool_name="web_search", rationale="Looking up the weather in Berlin")
+ )
+ assert pet.of("status")[-1] == ("status", "Thinking …", "Looking up the weather in Berlin")
+
+
+async def test_a_tool_without_a_reason_shows_its_name(fast_status) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(ActionProposed(tool_name="mcp__github__create_issue"))
+ assert pet.of("status")[-1] == ("status", "Thinking …", "Create issue")
+
+
+async def test_progress_announcements_are_thinking_lines(fast_status) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(AnnouncementRequested(text="Step 2 of 5 done.", kind="progress"))
+ await asyncio.sleep(0.03)
+ await bus.publish(AnnouncementRequested(text="All finished.", kind="completion"))
+ await asyncio.sleep(0.03)
+ # A spawn announcement's action is a bare clause fragment in the spawn
+ # tool's language — never a status line on its own.
+ await bus.publish(
+ JarvisAgentAnnouncement(action="eine Flask-App baut", target="auf Port 8000") # i18n-allow
+ )
+ assert [c[2] for c in pet.of("status")] == ["Step 2 of 5 done."]
+
+
+async def test_a_streamed_reply_shows_its_latest_complete_sentence(fast_status) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(AssistantTextDelta(text="It is sunny. Tomorrow it"))
+ assert pet.of("status")[-1] == ("status", "Answer", "It is sunny.")
+
+ await asyncio.sleep(0.03)
+ await bus.publish(AssistantTextDelta(text="It is sunny. Tomorrow it rains.", done=True))
+ assert pet.of("status")[-1] == ("status", "Answer", "Tomorrow it rains.")
+
+
+async def test_the_final_snapshot_beats_the_rate_limit() -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(AssistantTextDelta(text="First."))
+ await bus.publish(AssistantTextDelta(text="First. Second.", done=True))
+ assert [c[2] for c in pet.of("status")] == ["First.", "Second."]
+
+
+async def test_a_throttled_line_is_flushed_after_the_interval(fast_status) -> None:
+ pet = _Pet()
+ bridge, bus = _bridge(pet)
+ await bus.publish(VoiceSessionStarted(session_id="s1"))
+ bridge._last_state = "LISTENING" # noqa: SLF001
+ await bus.publish(TranscriptionUpdate(text="what is", is_final=False))
+ await bus.publish(TranscriptionUpdate(text="what is the weather", is_final=False))
+ await asyncio.sleep(0.08)
+ assert pet.of("status")[-1] == ("status", "Listening …", "what is the weather")
+
+
+async def test_a_new_session_starts_a_fresh_bubble() -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(VoiceSessionStarted(session_id="s1"))
+ await bus.publish(VoiceSessionStarted(session_id="s2"))
+ # The same header twice: the reset means the second is not a "repeat".
+ assert pet.of("status") == [
+ ("status", "Listening …", ""),
+ ("status", "Listening …", ""),
+ ]
+
+
+async def test_headers_follow_the_interface_language(fast_status) -> None:
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet, language="de")
+ await bus.publish(SystemStateChanged(previous="IDLE", new_state="THINKING"))
+ assert pet.of("status")[-1][1] == "Denke nach …" # i18n-allow
+
+ await bus.publish(UiLanguageChanged(language="es"))
+ await asyncio.sleep(0.03)
+ await bus.publish(AssistantTextDelta(text="Hola.", done=True)) # i18n-allow
+ assert pet.of("status")[-1][1] == "Respuesta" # i18n-allow
+
+
+async def test_the_language_falls_back_to_the_pipeline_config(monkeypatch) -> None:
+ monkeypatch.setattr(
+ runtime_refs,
+ "_SPEECH_PIPELINE",
+ [_FakePipeline(muted=False, volume=1.0, language="es")],
+ )
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet)
+ await bus.publish(SystemStateChanged(previous="IDLE", new_state="THINKING"))
+ assert pet.of("status")[-1][1] == "Pensando …" # i18n-allow
+
+
+# ---------------------------------------------------------------------------
+# idle visibility
+# ---------------------------------------------------------------------------
+
+
+async def test_the_pet_stays_on_screen_when_a_preview_is_retracted() -> None:
+ """``hide_on_idle`` is True for every non-bar style; the pet overrides it."""
+ pet = _Pet()
+ _bridge_, bus = _bridge(pet, hide_on_idle=True)
+ await bus.publish(WakeCandidateDetected(active=True))
+ await bus.publish(WakeCandidateDetected(active=False))
+ assert pet.of("hide") == []
+ assert pet.calls[-1] == ("show", "idle")
+
+
+async def test_a_mascot_still_hides_when_a_preview_is_retracted() -> None:
+ mascot = _Surface()
+ _bridge_, bus = _bridge(mascot, hide_on_idle=True)
+ await bus.publish(WakeCandidateDetected(active=True))
+ await bus.publish(WakeCandidateDetected(active=False))
+ assert mascot.calls[-1] == ("hide",)
diff --git a/tests/unit/ui/test_pets_routes.py b/tests/unit/ui/test_pets_routes.py
new file mode 100644
index 0000000000..4ede898950
--- /dev/null
+++ b/tests/unit/ui/test_pets_routes.py
@@ -0,0 +1,386 @@
+"""REST contract of the desktop pets (``jarvis/ui/web/pets_routes.py``, docs/pets.md).
+
+Everything runs against the real pet engine and the real TOML writers, pointed
+at a tmp directory: one hand-built "built-in" pet under a tmp built-in root,
+user pets under a tmp data directory, and ``JARVIS_CONFIG`` at a tmp
+``jarvis.toml``. The DesktopApp and the bus are hand-written recorders.
+"""
+from __future__ import annotations
+
+import io
+import json
+import tomllib
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from jarvis.core import config as config_module
+from jarvis.core.config import UIConfig
+from jarvis.core.events import PetChanged
+from jarvis.ui.pets import loader
+from jarvis.ui.pets.manifest import MAX_SHEET_BYTES
+from jarvis.ui.pets.states import DEFAULT_PET_ID, PET_STATES
+from jarvis.ui.web.pets_routes import router
+
+FRAME = 32
+
+
+def _sheet_png(rows: int = len(PET_STATES), cols: int = 2) -> bytes:
+ """A sheet whose every cell holds an opaque square (so rows are non-empty)."""
+ image = Image.new("RGBA", (cols * FRAME, rows * FRAME), (0, 0, 0, 0))
+ for row in range(rows):
+ for col in range(cols):
+ left, top = col * FRAME + 8, row * FRAME + 8
+ for x in range(left, left + 16):
+ for y in range(top, top + 16):
+ image.putpixel((x, y), (40 + row * 20, 120, 200, 255))
+ out = io.BytesIO()
+ image.save(out, "PNG")
+ return out.getvalue()
+
+
+def _write_builtin(root: Path, pet_id: str) -> None:
+ folder = root / pet_id
+ folder.mkdir(parents=True)
+ (folder / "sheet.png").write_bytes(_sheet_png(rows=1, cols=2))
+ (folder / "pet.json").write_text(
+ json.dumps(
+ {
+ "format": "jarvis-pet/1",
+ "id": pet_id,
+ "name": pet_id.title(),
+ "description": "A test pet.",
+ "frame_size": FRAME,
+ "sheet": "sheet.png",
+ "animations": {"idle": {"row": 0, "frames": 2, "fps": 4, "loop": True}},
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+class RecordingBus:
+ def __init__(self) -> None:
+ self.events: list[Any] = []
+
+ async def publish(self, event: Any) -> None:
+ self.events.append(event)
+
+
+class FakeDesktop:
+ """The DesktopApp surface the routes call (see docs/pets.md)."""
+
+ def __init__(self, *, applied_live: bool = True) -> None:
+ self.calls: list[tuple] = []
+ self.visible = True
+ self._applied = applied_live
+
+ def set_pet(self, pet_id: str) -> dict:
+ self.calls.append(("set_pet", pet_id))
+ return {"ok": True, "applied_live": self._applied}
+
+ def set_pet_look(self, scale: float, bubble: bool) -> dict:
+ self.calls.append(("set_pet_look", scale, bubble))
+ return {"ok": True, "applied_live": self._applied}
+
+ def set_pet_visible(self, visible: bool) -> dict:
+ self.calls.append(("set_pet_visible", visible))
+ self.visible = visible
+ return {"ok": True, "applied_live": self._applied}
+
+ def pet_visible(self) -> bool:
+ return self.visible
+
+
+def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ builtin = tmp_path / "builtin"
+ _write_builtin(builtin, DEFAULT_PET_ID)
+ _write_builtin(builtin, "miso")
+ monkeypatch.setattr(loader, "builtin_root", lambda: builtin)
+ data = tmp_path / "data"
+ data.mkdir()
+ monkeypatch.setattr(config_module, "DATA_DIR", data)
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("[ui]\norb_style = \"pet\"\n", encoding="utf-8")
+ monkeypatch.setenv("JARVIS_CONFIG", str(toml))
+ monkeypatch.delenv("JARVIS_INSTANCE", raising=False)
+
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(ui=UIConfig(orb_style="pet"))
+ app.state.bus = RecordingBus()
+ app.state.desktop_app = FakeDesktop()
+ return SimpleNamespace(
+ client=TestClient(app), app=app, toml=toml, data=data, builtin=builtin
+ )
+
+
+def _toml_ui(env: SimpleNamespace) -> dict:
+ return tomllib.loads(env.toml.read_text(encoding="utf-8")).get("ui", {})
+
+
+def _upload(env: SimpleNamespace, **fields: str) -> Any:
+ data = {"name": "Pixel", "description": "My own pet."}
+ data.update(fields)
+ return env.client.post(
+ "/api/pets",
+ files={"sheet": ("sheet.png", _sheet_png(), "image/png")},
+ data=data,
+ )
+
+
+# ---------------------------------------------------------------------------
+# GET
+# ---------------------------------------------------------------------------
+
+
+def test_list_returns_state_and_every_pet(env) -> None:
+ body = env.client.get("/api/pets").json()
+ assert body["active"] == DEFAULT_PET_ID
+ assert body["scale"] == 1.0
+ assert body["bubble"] is True
+ assert body["visible"] is True
+ ids = [p["id"] for p in body["pets"]]
+ assert ids[0] == DEFAULT_PET_ID # the default pet leads
+ assert "miso" in ids
+ gigi = body["pets"][0]
+ assert gigi["builtin"] is True
+ assert gigi["frame_size"] == FRAME
+ assert gigi["sheet_url"] == f"/api/pets/{DEFAULT_PET_ID}/sheet.png"
+ # Every state is resolved, so no client repeats the fallback table.
+ assert set(gigi["animations"]) == set(PET_STATES)
+ assert gigi["animations"]["sleeping"] == gigi["animations"]["idle"]
+ assert set(gigi) == {
+ "id", "name", "description", "builtin", "frame_size", "animations", "sheet_url"
+ }
+
+
+def test_list_reports_the_default_when_the_configured_pet_is_gone(env) -> None:
+ env.app.state.config.ui.pet_id = "u0123456789abcdef"
+ assert env.client.get("/api/pets").json()["active"] == DEFAULT_PET_ID
+ env.app.state.config.ui.pet_id = "none"
+ assert env.client.get("/api/pets").json()["active"] == "none"
+
+
+def test_sheet_is_served_with_safe_headers(env) -> None:
+ r = env.client.get(f"/api/pets/{DEFAULT_PET_ID}/sheet.png")
+ assert r.status_code == 200
+ assert r.headers["content-type"] == "image/png"
+ assert r.headers["x-content-type-options"] == "nosniff"
+ assert r.headers["cache-control"] == "no-cache" # built-ins change with updates
+ assert r.content == (env.builtin / DEFAULT_PET_ID / "sheet.png").read_bytes()
+
+
+def test_template_is_the_shipped_sheet_template(env) -> None:
+ r = env.client.get("/api/pets/template.png")
+ assert r.status_code == 200
+ assert r.headers["content-type"] == "image/png"
+ assert r.headers["x-content-type-options"] == "nosniff"
+ assert "pet-template.png" in r.headers["content-disposition"]
+ shipped = Path(loader.__file__).parent / "template" / "template.png"
+ assert r.content == shipped.read_bytes()
+
+
+ "pet_id", ["nope", "..", "..%2F..%2Fjarvis.toml", "none", "u0123456789abcdef", "GIGI.png"]
+)
+def test_unknown_or_malformed_sheet_ids_are_404(env, pet_id: str) -> None:
+ assert env.client.get(f"/api/pets/{pet_id}/sheet.png").status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# PUT /active
+# ---------------------------------------------------------------------------
+
+
+def test_put_active_saves_applies_and_announces(env) -> None:
+ r = env.client.put("/api/pets/active", json={"pet_id": "Miso"})
+ assert r.status_code == 200, r.text
+ body = r.json()
+ assert body["active"] == "miso"
+ assert body["persisted"] is True
+ assert body["applied_live"] is True
+ assert _toml_ui(env)["pet_id"] == "miso"
+ assert _toml_ui(env)["orb_style"] == "pet"
+ assert env.app.state.config.ui.pet_id == "miso"
+ assert env.app.state.desktop_app.calls == [("set_pet", "miso")]
+ (event,) = env.app.state.bus.events
+ assert isinstance(event, PetChanged)
+ assert (event.pet_id, event.scale, event.bubble, event.visible) == ("miso", 1.0, True, True)
+
+
+def test_put_active_accepts_none(env) -> None:
+ r = env.client.put("/api/pets/active", json={"pet_id": "none"})
+ assert r.status_code == 200
+ assert _toml_ui(env)["pet_id"] == "none"
+
+
+ "pet_id,status", [("does-not-exist", 404), ("../x", 400), ("u0123456789abcdef", 404)]
+)
+def test_put_active_refuses_what_is_not_a_pet(env, pet_id: str, status: int) -> None:
+ r = env.client.put("/api/pets/active", json={"pet_id": pet_id})
+ assert r.status_code == status
+ assert "pet_id" not in _toml_ui(env)
+ assert env.app.state.bus.events == []
+
+
+def test_put_active_headless_saves_and_waits_for_the_next_start(env) -> None:
+ env.app.state.desktop_app = None
+ r = env.client.put("/api/pets/active", json={"pet_id": "miso"})
+ assert r.status_code == 200
+ assert r.json()["applied_live"] is False
+ assert _toml_ui(env)["pet_id"] == "miso"
+
+
+def test_a_dev_instance_does_not_change_the_shared_pet(env, monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS_INSTANCE", "dev")
+ assert env.client.put("/api/pets/active", json={"pet_id": "miso"}).status_code == 409
+ assert env.client.put("/api/pets/settings", json={"scale": 1.5}).status_code == 409
+ assert "pet_id" not in _toml_ui(env)
+ assert "pet_scale" not in _toml_ui(env)
+
+
+# ---------------------------------------------------------------------------
+# PUT /settings, POST /visibility
+# ---------------------------------------------------------------------------
+
+
+def test_put_settings_clamps_saves_and_applies(env) -> None:
+ r = env.client.put("/api/pets/settings", json={"scale": 5, "bubble": False})
+ assert r.status_code == 200
+ body = r.json()
+ assert (body["scale"], body["bubble"]) == (2.0, False)
+ assert _toml_ui(env)["pet_scale"] == 2.0
+ assert _toml_ui(env)["pet_bubble"] is False
+ assert env.app.state.desktop_app.calls == [("set_pet_look", 2.0, False)]
+ (event,) = env.app.state.bus.events
+ assert (event.scale, event.bubble) == (2.0, False)
+
+
+def test_put_settings_changes_only_what_is_sent(env) -> None:
+ env.client.put("/api/pets/settings", json={"bubble": False})
+ assert "pet_scale" not in _toml_ui(env)
+ assert env.app.state.desktop_app.calls == [("set_pet_look", 1.0, False)]
+
+
+def test_put_settings_needs_something_to_change(env) -> None:
+ assert env.client.put("/api/pets/settings", json={}).status_code == 400
+
+
+def test_visibility_is_runtime_only(env) -> None:
+ before = env.toml.read_text(encoding="utf-8")
+ r = env.client.post("/api/pets/visibility", json={"visible": False})
+ assert r.status_code == 200
+ assert r.json()["visible"] is False
+ assert env.app.state.desktop_app.calls == [("set_pet_visible", False)]
+ assert env.toml.read_text(encoding="utf-8") == before
+ assert env.app.state.bus.events[-1].visible is False
+ assert env.client.get("/api/pets").json()["visible"] is False
+
+
+# ---------------------------------------------------------------------------
+# POST (create) and DELETE
+# ---------------------------------------------------------------------------
+
+
+def test_upload_creates_a_pet_that_lists_and_serves(env) -> None:
+ r = _upload(env)
+ assert r.status_code == 201, r.text
+ pet = r.json()
+ assert pet["id"].startswith("u") and len(pet["id"]) == 17
+ assert pet["name"] == "Pixel"
+ assert pet["builtin"] is False
+ assert pet["sheet_url"] == f"/api/pets/{pet['id']}/sheet.png"
+
+ ids = [p["id"] for p in env.client.get("/api/pets").json()["pets"]]
+ assert pet["id"] in ids
+ sheet = env.client.get(pet["sheet_url"])
+ assert sheet.status_code == 200
+ assert "immutable" in sheet.headers["cache-control"]
+
+
+def test_upload_with_a_manifest_and_frame_size(env) -> None:
+ manifest = json.dumps(
+ {"animations": {"idle": {"row": 0, "frames": 2, "fps": 6, "loop": True}}}
+ )
+ r = _upload(env, manifest=manifest, frame_size="32")
+ assert r.status_code == 201, r.text
+ assert r.json()["animations"]["idle"]["fps"] == 6
+
+
+ "sheet",
+ [b"", b"GIF89a not a png", b"\x89PNG\r\n\x1a\n" + b"x" * (MAX_SHEET_BYTES + 10)],
+ # Explicit ids: the default id of a 2 MB bytes value is the value itself,
+ # and pytest plugins put the test id into an environment variable, which
+ # Windows caps at 32 767 characters.
+ ids=["empty", "not-a-png", "oversize"],
+)
+def test_upload_refusals_are_400_with_a_sentence(env, sheet: bytes) -> None:
+ r = env.client.post(
+ "/api/pets",
+ files={"sheet": ("sheet.png", sheet, "image/png")},
+ data={"name": "Pixel", "description": ""},
+ )
+ assert r.status_code == 400
+ assert isinstance(r.json()["detail"], str) and r.json()["detail"]
+ assert not any(env.data.glob("pets/u*"))
+
+
+def test_upload_rejects_a_frame_size_that_is_not_a_number(env) -> None:
+ assert _upload(env, frame_size="big").status_code == 400
+
+
+def test_upload_rejects_a_manifest_that_is_not_json(env) -> None:
+ r = _upload(env, manifest="{not json")
+ assert r.status_code == 400
+ assert "JSON" in r.json()["detail"]
+
+
+def test_delete_removes_a_user_pet(env) -> None:
+ pet_id = _upload(env).json()["id"]
+ r = env.client.delete(f"/api/pets/{pet_id}")
+ assert r.status_code == 200
+ assert r.json() == {"ok": True, "deleted": pet_id, "active": DEFAULT_PET_ID}
+ assert env.client.get(f"/api/pets/{pet_id}/sheet.png").status_code == 404
+ assert env.app.state.bus.events == [] # the active pet did not change
+
+
+def test_deleting_the_active_pet_falls_back_to_the_default(env) -> None:
+ pet_id = _upload(env).json()["id"]
+ env.client.put("/api/pets/active", json={"pet_id": pet_id})
+ env.app.state.desktop_app.calls.clear()
+ env.app.state.bus.events.clear()
+
+ r = env.client.delete(f"/api/pets/{pet_id}")
+ assert r.status_code == 200
+ assert r.json()["active"] == DEFAULT_PET_ID
+ assert _toml_ui(env)["pet_id"] == DEFAULT_PET_ID
+ assert env.app.state.desktop_app.calls == [("set_pet", DEFAULT_PET_ID)]
+ (event,) = env.app.state.bus.events
+ assert (event.pet_id, event.source) == (DEFAULT_PET_ID, "pet_deleted")
+
+
+def test_built_in_pets_cannot_be_deleted(env) -> None:
+ r = env.client.delete(f"/api/pets/{DEFAULT_PET_ID}")
+ assert r.status_code == 400
+ assert (env.builtin / DEFAULT_PET_ID / "pet.json").is_file()
+
+
[email protected]("pet_id", ["u0123456789abcdef", "..", "none"])
+def test_deleting_something_that_is_not_a_user_pet_changes_nothing(env, pet_id: str) -> None:
+ assert env.client.delete(f"/api/pets/{pet_id}").status_code in (400, 404)
+
+
+def test_delete_is_flagged_dangerous_for_the_cli(env) -> None:
+ spec = env.app.openapi()
+ operation = spec["paths"]["/api/pets/{pet_id}"]["delete"]
+ assert operation.get("x-jarvis-dangerous") is True
+ assert operation["tags"] == ["pets"]
diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.py
index dae0fa5a07..e28ae865cf 100644
--- a/ui/orb/bus_bridge.py
+++ b/ui/orb/bus_bridge.py
@@ -36,7 +36,12 @@ import time
from typing import TYPE_CHECKING, Any
from jarvis.core.events import (
+ ActionExecuted,
+ ActionProposed,
+ AnnouncementRequested,
+ AssistantTextDelta,
AudioOutFirst,
+ ComposeRequested,
DictationCompleted,
DictationPromptModeChanged,
DictationPromptModePauseToggleRequested,
@@ -44,23 +49,37 @@ from jarvis.core.events import (
DictationStarted,
DictationTranscribing,
DictationTranscript,
+ ErrorOccurred,
JarvisAgentBackgroundCompleted,
ListeningStarted,
OrbResetRequested,
+ PetVisibilityToggleRequested,
ResponseGenerated,
ShowWindowRequested,
+ SpeechSpoken,
SystemStateChanged,
TranscriptionUpdate,
+ UiLanguageChanged,
UserVisibleFeedback,
VoiceBootStatus,
VoiceMuteChanged,
VoiceMuteToggleRequested,
VoiceSessionEnded,
VoiceSessionStarted,
+ VoiceSpeakerMuteChanged,
WakeCandidateDetected,
WakeWordDetected,
)
from jarvis.dictation.outcomes import was_delivered
+from jarvis.sessions.constants import (
+ HANGUP_ERROR,
+ SPOKEN_KIND_ACTION_DONE,
+ SPOKEN_KIND_COMPLETION,
+ SPOKEN_KIND_STT_UNAVAILABLE,
+ SPOKEN_KIND_TIMEOUT,
+ SPOKEN_KIND_UNAVAILABLE,
+)
+from jarvis.ui.pets.status_line import StatusFeed
from ui.orb.animations import IDLE_ANIMATION_POOL
if TYPE_CHECKING:
@@ -202,6 +221,83 @@ def _is_transcript_boilerplate(text: str) -> bool:
return _TRANSCRIPT_BOILERPLATE_RE.search(text) is not None
+# --- Desktop pet (docs/pets.md) ---------------------------------------------
+#
+# The pet reacts to OUTCOMES as well as states: a one-shot success or error
+# animation. Both sets come from the one spoken-kind vocabulary, so a kind that
+# is renamed there cannot silently stop reaching the pet (AP-4).
+PET_SUCCESS_SPOKEN_KINDS: frozenset[str] = frozenset(
+ {SPOKEN_KIND_ACTION_DONE, SPOKEN_KIND_COMPLETION}
+)
+PET_ERROR_SPOKEN_KINDS: frozenset[str] = frozenset(
+ {SPOKEN_KIND_TIMEOUT, SPOKEN_KIND_UNAVAILABLE, SPOKEN_KIND_STT_UNAVAILABLE}
+)
+
+# Headers of the pet's status bubble, per interface language ([ui] language).
+# User-facing product text drawn by the overlay, so every supported locale has
+# its own entry and none of them is a fallback for another.
+PET_STATUS_HEADERS: dict[str, dict[str, str]] = {
+ "listening": {
+ "en": "Listening …",
+ "de": "Ich höre zu …", # i18n-allow
+ "es": "Escuchando …", # i18n-allow
+ },
+ "thinking": {
+ "en": "Thinking …",
+ "de": "Denke nach …", # i18n-allow
+ "es": "Pensando …", # i18n-allow
+ },
+ "talking": {
+ "en": "Answer",
+ "de": "Antwort", # i18n-allow
+ "es": "Respuesta", # i18n-allow
+ },
+}
+PET_STATUS_LANGUAGES: tuple[str, ...] = ("en", "de", "es")
+
+# Minimum spacing of two status-bubble updates. A streamed reply produces a few
+# snapshots per second; repainting the bubble for each one is flicker.
+PET_STATUS_MIN_INTERVAL_S = 0.3
+
+# Announcement kinds that describe work in progress (the pet's "thinking" line).
+# A completion or a sub-agent readback is an ANSWER, and it is spoken anyway.
+_PET_THINKING_ANNOUNCEMENT_KINDS = frozenset({"preamble", "progress"})
+
+# A sentence ends at terminal punctuation followed by whitespace.
+_SENTENCE_BREAK_RE = re.compile(r"(?<=[.!?…])\s+")
+_SENTENCE_END_RE = re.compile(r"[.!?…][\"'»”)\]]*$")
+
+
+def _last_sentence(text: str, *, complete_only: bool = False) -> str:
+ """The last sentence of ``text`` (whitespace collapsed).
+
+ ``complete_only`` is for text still being produced: a reply streamed word
+ by word ends in a fragment most of the time, and showing "The" for a
+ moment between two full sentences is flicker, not information. Until the
+ fragment ends in punctuation the previous complete sentence stays; a reply
+ with no complete sentence yet shows the fragment.
+ """
+ flat = " ".join((text or "").split())
+ if not flat:
+ return ""
+ pieces = [piece for piece in _SENTENCE_BREAK_RE.split(flat) if piece]
+ if not pieces:
+ return ""
+ if complete_only and len(pieces) > 1 and not _SENTENCE_END_RE.search(pieces[-1]):
+ return pieces[-2]
+ return pieces[-1]
+
+
+def _humanize_tool_name(tool_name: str) -> str:
+ """``web_search`` → ``Web search``; ``mcp__github__create_issue`` → ``Create issue``."""
+ name = str(tool_name or "").strip().split("__")[-1]
+ words = name.replace("_", " ").replace("-", " ").split()
+ if not words:
+ return ""
+ phrase = " ".join(words)
+ return phrase[:1].upper() + phrase[1:]
+
+
# NOTE 2026-05-27 (bubble-pendulum Ep.3): the STT pipeline accumulates probe
# tails into a complete snapshot itself (jarvis/speech/pipeline.py:409
# ``_merge_partial_transcript`` over ``_probe_live_text``) and every
@@ -223,9 +319,20 @@ class OrbBusBridge:
orb: OrbOverlay,
idle_animations_enabled: bool = True,
hide_on_idle: bool = True,
+ language: str | None = None,
) -> None:
self._bus = bus
self._orb = orb
+ # Interface language for the pet's bubble headers. ``None`` = read it
+ # from the running pipeline's config when needed; ``UiLanguageChanged``
+ # overrides it live.
+ self._language: str | None = language if language in PET_STATUS_LANGUAGES else None
+ # ONE rate-limited feed for every status line the pet shows, so a burst
+ # of transcript, tool and reply updates cannot flood the Tk thread. A
+ # line the feed holds back is shown by ``_status_flush_task`` once the
+ # interval has passed, so the LAST update of a burst is never lost.
+ self._status_feed = StatusFeed(time.monotonic, min_interval_s=PET_STATUS_MIN_INTERVAL_S)
+ self._status_flush_task: asyncio.Task | None = None
self._mic_level_unsub = None # mic_level subscription (registered in attach)
self._tts_recency_unsub = None # level_tap subscription (TTS-active tracker)
# Monotonic time of the last TTS output level. The state label
@@ -305,6 +412,20 @@ class OrbBusBridge:
# on the backend loop, well before the orb is ever clickable).
self._loop: asyncio.AbstractEventLoop | None = None
+ def _hides_when_idle(self) -> bool:
+ """Does the CURRENT surface leave the screen when Jarvis goes idle?
+
+ ``hide_on_idle`` is set by whoever builds the bridge and is flipped by
+ the DesktopApp for the bar's persistence regime. A surface that must
+ stay on screen while idle whatever that regime says — the desktop pet
+ (docs/pets.md) — declares ``keeps_visible_when_idle`` and gets the idle
+ look instead of a hide. Asked per call, so a live style swap is honoured
+ at once.
+ """
+ if getattr(self._orb, "keeps_visible_when_idle", False) is True:
+ return False
+ return self._hide_on_idle
+
def _remember_loop(self) -> None:
"""Capture the running backend loop (idempotent). Called from async bus
handlers, which always run on that loop."""
@@ -402,6 +523,25 @@ class OrbBusBridge:
# The local_action_gate publishes OrbResetRequested when the
# user says "Orb zurück" / "wo bist du" / "reset orb". # i18n-allow
self._bus.subscribe(OrbResetRequested, self._on_reset_requested)
+ # Desktop pet (docs/pets.md). Every handler reaches the surface
+ # through ``getattr``, so the bar, the mascot and ``NullOverlay``
+ # ignore all of them. Speaker mute mirrors the pipeline the same way
+ # the microphone mute above does; the shortcut toggles visibility;
+ # the rest feeds the one-shot outcomes and the status bubble.
+ self._bus.subscribe(VoiceSpeakerMuteChanged, self._on_speaker_mute_changed)
+ self._bus.subscribe(PetVisibilityToggleRequested, self._on_pet_visibility_toggle)
+ self._bus.subscribe(UiLanguageChanged, self._on_ui_language_changed)
+ self._bus.subscribe(ActionProposed, self._on_action_proposed)
+ self._bus.subscribe(ActionExecuted, self._on_action_executed)
+ self._bus.subscribe(SpeechSpoken, self._on_speech_spoken)
+ self._bus.subscribe(ErrorOccurred, self._on_error_occurred)
+ # ``JarvisAgentAnnouncement`` is deliberately NOT a status source:
+ # its ``action`` is the spawn tool's bare relative-clause fragment
+ # in the tool schema's language, whatever the interface language,
+ # and reads as a broken sentence on its own. The spawn's
+ # ``ActionProposed`` already puts a thinking line up.
+ self._bus.subscribe(AnnouncementRequested, self._on_announcement)
+ self._bus.subscribe(AssistantTextDelta, self._on_assistant_text_delta)
# Wire the orb's double-double-click gesture to a bus publish.
# The orb requires two ``<Double-Button-1>`` events inside
# ``MUTE_GESTURE_WINDOW_MS`` (four clicks in <600 ms) before
@@ -420,6 +560,11 @@ class OrbBusBridge:
if prompt_setter is not None:
prompt_setter(self._publish_prompt_mode_toggle)
self._seed_prompt_mode()
+ # The pet's pen control asks for a fresh typed chat. Same marshal.
+ compose_setter = getattr(self._orb, "set_on_compose", None)
+ if compose_setter is not None:
+ compose_setter(self._publish_compose)
+ self._seed_mute_state()
# ADR-0016 visible-feedback contract: inject the publisher so
# the orb stays bus-agnostic. Defensive getattr keeps older
# orb test doubles working.
@@ -461,7 +606,7 @@ class OrbBusBridge:
"+ VoiceSessionEnded + ListeningStarted + TranscriptionUpdate "
"+ ResponseGenerated + AudioOutFirst + OrbResetRequested "
"+ mute-toggle gesture + show-window gesture "
- "+ visible-feedback contract."
+ "+ visible-feedback contract + pet events."
)
except Exception as exc: # noqa: BLE001
log.exception("OrbBridge.attach() failed: %s", exc)
@@ -543,6 +688,181 @@ class OrbBusBridge:
)
self._marshal_publish(coro, label="prompt-mode-pause")
+ def _publish_compose(self) -> None:
+ """Called from the surface's UI thread when the pet's pen is clicked.
+
+ Same marshal as ``_publish_mute_toggle``. The DesktopApp raises the
+ window and the frontend opens a new chat (``ComposeRequested``).
+ """
+ coro = self._bus.publish(ComposeRequested(source="pet"))
+ self._marshal_publish(coro, label="compose")
+
+ def _call_surface(self, name: str, *args: Any) -> None:
+ """Call an optional surface method; a surface without it is skipped.
+
+ Every pet method is optional by contract (docs/pets.md): the bar, the
+ mascot and ``NullOverlay`` simply do not have them. A surface that
+ raises gets a debug line, never a broken bus handler — a mirror update
+ is cosmetic.
+ """
+ method = getattr(self._orb, name, None)
+ if not callable(method):
+ return
+ try:
+ method(*args)
+ except Exception: # noqa: BLE001 — a surface update must never break the bus
+ log.debug("surface %s failed", name, exc_info=True)
+
+ def _seed_mute_state(self) -> None:
+ """Push the live microphone and speaker mute onto the surface.
+
+ Both mirrors are otherwise only updated by their change events, so a
+ surface attached or swapped in AFTER a mute would show the wrong icon
+ until the next flip. Before the pipeline is registered there is nothing
+ to read; ``_on_voice_boot_status`` runs this again once it is.
+ """
+ try:
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ except Exception: # noqa: BLE001 — a seed must never break the bridge
+ log.debug("mute seed: pipeline lookup failed", exc_info=True)
+ return
+ if pipeline is None:
+ return
+ self._call_surface("set_muted", bool(getattr(pipeline, "is_muted", False)))
+ getter = getattr(pipeline, "get_tts_volume", None)
+ if not callable(getter):
+ return
+ try:
+ speaker_muted = float(getter()) <= 0.0
+ except Exception: # noqa: BLE001 — an unreadable volume leaves the icon alone
+ log.debug("mute seed: get_tts_volume failed", exc_info=True)
+ return
+ self._call_surface("set_speaker_muted", speaker_muted)
+
+ def _status_language(self) -> str:
+ """The interface language for bubble headers (en / de / es)."""
+ if self._language is not None:
+ return self._language
+ try:
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ config = getattr(get_speech_pipeline(), "_config", None)
+ language = str(getattr(getattr(config, "ui", None), "language", "") or "")
+ except Exception: # noqa: BLE001 — English is a safe answer here
+ log.debug("status language lookup failed", exc_info=True)
+ return "en"
+ return language if language in PET_STATUS_LANGUAGES else "en"
+
+ def _offer_status(self, kind: str, line: str, *, force: bool = False) -> None:
+ """Feed one status line to a surface that shows them (the pet).
+
+ Gated on ``wants_status_lines`` so no other style pays for condensing
+ or rate limiting. ``kind`` picks the localized header; the feed decides
+ whether this update is shown now or dropped as too soon after the last.
+ """
+ if not getattr(self._orb, "wants_status_lines", False):
+ return
+ headers = PET_STATUS_HEADERS.get(kind)
+ if headers is None:
+ return
+ header = headers.get(self._status_language(), headers["en"])
+ try:
+ # The feed condenses both parts itself (markdown, paths, dumps).
+ shown = self._status_feed.offer(header, line or "", force=force)
+ except Exception: # noqa: BLE001 — a status line is cosmetic
+ log.debug("status feed rejected a line", exc_info=True)
+ return
+ if shown is not None:
+ self._call_surface("show_status", *shown)
+ else:
+ self._schedule_status_flush()
+
+ def _schedule_status_flush(self) -> None:
+ """Show the line the feed held back once the rate limit allows it.
+
+ Without this the last transcript or reply update of a burst would stay
+ in the feed until some later event happened to arrive — often never.
+ One pending flush at a time; it asks the feed, which returns nothing
+ when there is nothing held back.
+ """
+ task = self._status_flush_task
+ if task is not None and not task.done():
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ # Only bus handlers offer lines, and they run on the loop.
+ log.debug("status flush skipped: no running loop")
+ return
+
+ async def _flush() -> None:
+ try:
+ await asyncio.sleep(PET_STATUS_MIN_INTERVAL_S)
+ except asyncio.CancelledError:
+ return
+ if not getattr(self._orb, "wants_status_lines", False):
+ return
+ shown = self._status_feed.flush()
+ if shown is not None:
+ self._call_surface("show_status", *shown)
+
+ self._status_flush_task = loop.create_task(_flush(), name="orb-pet-status-flush")
+
+ def _pet_outcome(self, kind: str) -> None:
+ """Play the pet's one-shot ``success`` / ``error`` (no-op elsewhere)."""
+ self._call_surface("set_pet_outcome", kind)
+
+ async def _on_speaker_mute_changed(self, event: VoiceSpeakerMuteChanged) -> None:
+ """Mirror the pipeline's speaker mute (TTS volume 0) on the surface."""
+ self._call_surface("set_speaker_muted", bool(event.muted))
+
+ async def _on_pet_visibility_toggle(self, event: PetVisibilityToggleRequested) -> None:
+ """The pet shortcut: hide the pet, or show it and bring it forward."""
+ log.info("OrbBridge pet visibility toggle (source=%s)", event.source or "unknown")
+ self._call_surface("toggle_visible")
+
+ async def _on_ui_language_changed(self, event: UiLanguageChanged) -> None:
+ language = (event.language or "").strip().lower()
+ if language in PET_STATUS_LANGUAGES:
+ self._language = language
+
+ async def _on_action_proposed(self, event: ActionProposed) -> None:
+ """A tool is about to run: its reason (else its name) is the thinking line."""
+ line = (event.rationale or "").strip() or _humanize_tool_name(event.tool_name)
+ if line:
+ self._offer_status("thinking", line)
+
+ async def _on_action_executed(self, event: ActionExecuted) -> None:
+ self._pet_outcome("success" if event.success else "error")
+
+ async def _on_speech_spoken(self, event: SpeechSpoken) -> None:
+ kind = event.spoken_kind or ""
+ if kind in PET_SUCCESS_SPOKEN_KINDS:
+ self._pet_outcome("success")
+ elif kind in PET_ERROR_SPOKEN_KINDS:
+ self._pet_outcome("error")
+
+ async def _on_error_occurred(self, _event: ErrorOccurred) -> None:
+ self._pet_outcome("error")
+
+ async def _on_announcement(self, event: AnnouncementRequested) -> None:
+ """A preamble or a progress milestone is work in progress: show it."""
+ if event.kind in _PET_THINKING_ANNOUNCEMENT_KINDS and (event.text or "").strip():
+ self._offer_status("thinking", event.text)
+
+ async def _on_assistant_text_delta(self, event: AssistantTextDelta) -> None:
+ """The reply as it streams in: the latest sentence, rate-limited.
+
+ ``text`` is the cumulative snapshot, so only its last sentence matters.
+ The final snapshot (``done``) is forced through the rate limit, or the
+ bubble could stop one sentence short of the answer.
+ """
+ line = _last_sentence(event.text, complete_only=not event.done)
+ if line:
+ self._offer_status("talking", line, force=bool(event.done))
+
def _publish_visible_feedback(self, mode: str, observed: dict) -> None:
"""Called from the orb's Tk thread after a deiconify. Builds and
publishes ``UserVisibleFeedback`` onto the asyncio bus.
@@ -637,7 +957,7 @@ class OrbBusBridge:
if self._voice_session_active:
return
self._last_state = self._wake_preview_origin_state
- if self._hide_on_idle:
+ if self._hides_when_idle():
self._orb.hide()
else:
self._orb.show(mode="idle")
@@ -724,6 +1044,10 @@ class OrbBusBridge:
self._show_listening_transcript("")
self._completion_continuation = False
self._cancel_idle_scheduler()
+ # A new conversation starts a new bubble: nothing from the previous
+ # one may be rate-limited against, or linger in, this one.
+ self._status_feed.reset()
+ self._offer_status("listening", "", force=True)
async def _on_session_ended(self, event: VoiceSessionEnded) -> None:
"""A voice session ended (hangup / idle-timeout / shutdown / error).
@@ -744,6 +1068,8 @@ class OrbBusBridge:
event.hangup_reason,
)
self._suppress_show_until_session = True
+ if event.hangup_reason == HANGUP_ERROR:
+ self._pet_outcome("error")
# Defense in depth: a persistent (always-on) bar must drop to its idle
# look the instant a session ends, not only when the follow-up
# SystemStateChanged(IDLE) arrives. That state edge can be skipped or
@@ -755,7 +1081,7 @@ class OrbBusBridge:
# suppression latch (that only blocks ACTIVE-state repaints), so the
# genuine IDLE transition, if it still arrives, is a harmless same-mode
# repaint. The idle-animation scheduler stays owned by that transition.
- if not self._hide_on_idle:
+ if not self._hides_when_idle():
try:
self._orb.show(mode="idle")
except Exception as exc: # noqa: BLE001
@@ -775,6 +1101,7 @@ class OrbBusBridge:
# The pipeline is registered by now, so the bar can learn where the
# user left the Prompt Mode switch (attach() may have run too early).
self._seed_prompt_mode()
+ self._seed_mute_state()
self._release_bar_startup_gate(event.detail or "voice-ready")
def _release_bar_startup_gate(self, reason: str) -> None:
@@ -789,7 +1116,7 @@ class OrbBusBridge:
# withdrawn while idle. Mascot/Null surfaces expose no gate and stay
# untouched. An already-visible legacy bar gets the existing safe
# z-order repair instead.
- if not self._hide_on_idle and not was_gated:
+ if not self._hides_when_idle() and not was_gated:
reassert = getattr(self._orb, "reassert_z_order", None)
if callable(reassert):
reassert()
@@ -924,6 +1251,7 @@ class OrbBusBridge:
# happening). A reply arriving mid-THINKING swaps it in via
# _on_response_generated.
self._refresh_voice_bubble()
+ self._offer_status("thinking", "", force=True)
self._cancel_idle_scheduler()
elif state == "SPEAKING":
# TTS synthesis is often still running here — the state flips to
@@ -951,7 +1279,7 @@ class OrbBusBridge:
except Exception as exc: # noqa: BLE001
log.debug("hide_comment failed: %s", exc)
- if not self._hide_on_idle:
+ if not self._hides_when_idle():
# Persistent "show at all times" bar: a standalone always-on
# element. EVERY non-active state (IDLE, and also ERROR / PAUSED)
# shows the idle pill and NEVER withdraws the bar. Hiding it on
@@ -1033,6 +1361,7 @@ class OrbBusBridge:
# diverge.
self._listening_transcript_text = event.text.strip()
self._show_listening_transcript(self._listening_transcript_text)
+ self._offer_status("listening", _last_sentence(self._listening_transcript_text))
async def _on_response_generated(self, event: ResponseGenerated) -> None:
"""Capture Jarvis's reply so the orb bubble can show it while speaking.
@@ -1046,6 +1375,12 @@ class OrbBusBridge:
self._last_response_text = (event.text or "").strip()
if self._last_state in ("THINKING", "SPEAKING"):
self._refresh_voice_bubble()
+ # The pet's talking line, for reply paths that stream no
+ # ``AssistantTextDelta``; after a streamed reply this is the same
+ # sentence again and the feed treats it as such.
+ line = _last_sentence(self._last_response_text)
+ if line:
+ self._offer_status("talking", line)
def _refresh_voice_bubble(self) -> None:
"""Render the right bubble text for the current voice state.
@@ -1392,7 +1727,7 @@ class OrbBusBridge:
self._show_listening_transcript("")
restore = self._current_voice_mode() if self._voice_session_active else "idle"
try:
- if restore == "idle" and self._hide_on_idle:
+ if restore == "idle" and self._hides_when_idle():
self._orb.hide()
else:
self._orb.show(mode=restore)
@@ -1453,7 +1788,7 @@ class OrbBusBridge:
# situation this fail-safe exists for.
self._show_listening_transcript("")
try:
- if self._hide_on_idle:
+ if self._hides_when_idle():
self._orb.hide()
else:
self._orb.show(mode="idle")
@@ -1482,7 +1817,7 @@ class OrbBusBridge:
return
self._show_listening_transcript("")
try:
- if self._hide_on_idle:
+ if self._hides_when_idle():
self._orb.hide()
else:
self._orb.show(mode="idle")
@@ -1544,7 +1879,7 @@ class OrbBusBridge:
"""
try:
await asyncio.sleep(delay_s)
- if self._hide_on_idle:
+ if self._hides_when_idle():
self._orb.hide()
else:
self._orb.show(mode="idle")
@@ -1555,12 +1890,15 @@ class OrbBusBridge:
except asyncio.CancelledError:
pass
- async def _on_background_completed(self, _event: JarvisAgentBackgroundCompleted) -> None:
+ async def _on_background_completed(self, event: JarvisAgentBackgroundCompleted) -> None:
"""Briefly surface the mascot when an async task finishes.
This is UI-only. It does not start or end the speech session, so the
- conversation/task context remains untouched.
+ conversation/task context remains untouched. A successful task also
+ plays the pet's one-shot success, whatever the voice state.
"""
+ if event.success:
+ self._pet_outcome("success")
if self._last_state not in ("IDLE", "ERROR", "PAUSED"):
return
self._orb.show(mode="speak")
@@ -1715,6 +2053,18 @@ class OrbBusBridge:
show_window_setter = getattr(surface, "set_on_show_window", None)
if callable(show_window_setter):
show_window_setter(self._publish_show_window)
+ # The sparkle and the pet's pen were only wired in attach(), so a
+ # surface swapped in later had dead buttons until the next restart.
+ prompt_setter = getattr(surface, "set_on_prompt_mode_toggle", None)
+ if callable(prompt_setter):
+ prompt_setter(self._publish_prompt_mode_toggle)
+ compose_setter = getattr(surface, "set_on_compose", None)
+ if callable(compose_setter):
+ compose_setter(self._publish_compose)
+ # A fresh surface starts with default icons; show it the live state.
+ self._seed_prompt_mode()
+ self._seed_mute_state()
+ self._status_feed.reset()
if self._voice_usable:
self._release_bar_startup_gate("voice-ready surface swap")
log.info("OrbBridge surface swapped (last_state=%s)", self._last_state)