Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(pets): pet engine and six built-in pixel pets
rubenluetke10-beep46e82014b355
diff --git a/jarvis/ui/pets/builtin/bolt/pet.json b/jarvis/ui/pets/builtin/bolt/pet.jsonnew file mode 100644index 0000000000..dde0157b5e--- /dev/null+++ b/jarvis/ui/pets/builtin/bolt/pet.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "bolt",+ "name": "Bolt",+ "description": "A plucky battery that charges up while it thinks and runs flat when it sleeps.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 8,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/builtin/bolt/sheet.png b/jarvis/ui/pets/builtin/bolt/sheet.pngnew file mode 100644index 0000000000..6e33f894a6Binary files /dev/null and b/jarvis/ui/pets/builtin/bolt/sheet.png differdiff --git a/jarvis/ui/pets/builtin/brew/pet.json b/jarvis/ui/pets/builtin/brew/pet.jsonnew file mode 100644index 0000000000..7ea56b6d47--- /dev/null+++ b/jarvis/ui/pets/builtin/brew/pet.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "brew",+ "name": "Brew",+ "description": "A little teapot that steams while it thinks and whistles when it answers.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 6,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/builtin/brew/sheet.png b/jarvis/ui/pets/builtin/brew/sheet.pngnew file mode 100644index 0000000000..c6e6d280abBinary files /dev/null and b/jarvis/ui/pets/builtin/brew/sheet.png differdiff --git a/jarvis/ui/pets/builtin/gigi/pet.json b/jarvis/ui/pets/builtin/gigi/pet.jsonnew file mode 100644index 0000000000..7ec9b00a86--- /dev/null+++ b/jarvis/ui/pets/builtin/gigi/pet.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "gigi",+ "name": "Gigi",+ "description": "The Jarvis ghost, eight bits tall, with glowing golden eyes.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 6,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/builtin/gigi/sheet.png b/jarvis/ui/pets/builtin/gigi/sheet.pngnew file mode 100644index 0000000000..245a198b6bBinary files /dev/null and b/jarvis/ui/pets/builtin/gigi/sheet.png differdiff --git a/jarvis/ui/pets/builtin/miso/pet.json b/jarvis/ui/pets/builtin/miso/pet.jsonnew file mode 100644index 0000000000..48ea50913f--- /dev/null+++ b/jarvis/ui/pets/builtin/miso/pet.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "miso",+ "name": "Miso",+ "description": "A ginger cat whose ears perk up when you talk and who naps curled in a loaf.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 6,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/builtin/miso/sheet.png b/jarvis/ui/pets/builtin/miso/sheet.pngnew file mode 100644index 0000000000..780d9bf31aBinary files /dev/null and b/jarvis/ui/pets/builtin/miso/sheet.png differdiff --git a/jarvis/ui/pets/builtin/mochi/pet.json b/jarvis/ui/pets/builtin/mochi/pet.jsonnew file mode 100644index 0000000000..9366847cb7--- /dev/null+++ b/jarvis/ui/pets/builtin/mochi/pet.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "mochi",+ "name": "Mochi",+ "description": "A soft jelly blob that wobbles when it listens and squishes when it talks.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 6,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/builtin/mochi/sheet.png b/jarvis/ui/pets/builtin/mochi/sheet.pngnew file mode 100644index 0000000000..1261f02286Binary files /dev/null and b/jarvis/ui/pets/builtin/mochi/sheet.png differdiff --git a/jarvis/ui/pets/builtin/shelly/pet.json b/jarvis/ui/pets/builtin/shelly/pet.jsonnew file mode 100644index 0000000000..06dbb9512e--- /dev/null+++ b/jarvis/ui/pets/builtin/shelly/pet.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "shelly",+ "name": "Shelly",+ "description": "A patient snail whose shell spins while it thinks and who hides inside to sleep.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 6,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/builtin/shelly/sheet.png b/jarvis/ui/pets/builtin/shelly/sheet.pngnew file mode 100644index 0000000000..aa702df387Binary files /dev/null and b/jarvis/ui/pets/builtin/shelly/sheet.png differdiff --git a/jarvis/ui/pets/loader.py b/jarvis/ui/pets/loader.pynew file mode 100644index 0000000000..fc7d59d321--- /dev/null+++ b/jarvis/ui/pets/loader.py@@ -0,0 +1,300 @@+"""Find, validate and decode pet packs (``docs/pets.md``).++Built-in pets ship under ``jarvis/ui/pets/builtin/<id>/``; user-created pets+live under ``<DATA_DIR>/pets/<u…id>/``. :func:`load_pet` turns a folder into a+:class:`PetPack` whose frames are ready for the overlay: RGBA at source size,+binary alpha, and no pixel in the overlay's exact colour key.++Pure Pillow, no OS-specific code: the same loader runs in the Tk overlay, the+macOS companion process and the REST routes.+"""++from __future__ import annotations++import json+import logging+from collections.abc import Mapping+from dataclasses import dataclass+from pathlib import Path+from types import MappingProxyType++from PIL import Image, ImageChops++from jarvis.ui.pets.manifest import (+ BUILTIN_ID_RE,+ MAX_SHEET_BYTES,+ USER_ID_RE,+ PetManifest,+ PetManifestError,+ check_cells,+ check_sheet_size,+ parse_manifest,+)+from jarvis.ui.pets.states import DEFAULT_PET_ID, NO_PET_ID, PET_STATES++_log = logging.getLogger(__name__)++MANIFEST_NAME = "pet.json"++#: The overlay's transparent colour (pure magenta). Sprites never use it.+COLOR_KEY: tuple[int, int, int] = (255, 0, 255)++#: Alpha at or above this counts as opaque; everything else is gone.+ALPHA_THRESHOLD = 128++#: A pet.json larger than this is not a manifest.+_MAX_MANIFEST_BYTES = 64 * 1024+++@dataclass(frozen=True)+class PetPack:+ """A loaded pet: its manifest plus decoded frames for every state.++ ``frames`` has an entry for EVERY state in ``PET_STATES``; a state the+ manifest does not declare shares its fallback's tuple.+ """++ manifest: PetManifest+ directory: Path+ frames: Mapping[str, tuple[Image.Image, ...]]+++def builtin_root() -> Path:+ """Folder holding the built-in pets (``jarvis/ui/pets/builtin``)."""+ return Path(__file__).resolve().parent / "builtin"+++def custom_root(data_dir: Path | None = None) -> Path:+ """Folder holding user-created pets: ``<DATA_DIR>/pets``. Not created here."""+ if data_dir is None:+ from jarvis.core import config # lazy: the overlay may run without it loaded++ data_dir = config.DATA_DIR+ return Path(data_dir) / "pets"+++def find_pet_dir(pet_id: str, *, data_dir: Path | None = None) -> tuple[Path, bool] | None:+ """Return ``(folder, builtin)`` for ``pet_id``, or ``None``.++ Built-in pets win over user pets. ``"none"``, an unknown id and anything+ that is not a well-formed id return ``None``; ids are matched against+ strict patterns before they touch the filesystem, so no id can escape+ the pet folders.+ """+ if not isinstance(pet_id, str) or pet_id == NO_PET_ID:+ return None+ if BUILTIN_ID_RE.match(pet_id) and not USER_ID_RE.match(pet_id):+ folder = builtin_root() / pet_id+ if (folder / MANIFEST_NAME).is_file():+ return folder, True+ if USER_ID_RE.match(pet_id):+ folder = custom_root(data_dir) / pet_id+ if (folder / MANIFEST_NAME).is_file():+ return folder, False+ return None+++def read_manifest(pet_dir: Path, *, builtin: bool) -> PetManifest:+ """Parse ``pet.json`` in ``pet_dir`` and check it against its sheet's size.++ Reads only the PNG header, so listing many pets stays cheap. Raises+ :class:`PetManifestError` for any broken rule or unreadable file.+ """+ pet_dir = Path(pet_dir)+ manifest_path = pet_dir / MANIFEST_NAME+ try:+ if manifest_path.stat().st_size > _MAX_MANIFEST_BYTES:+ raise PetManifestError("pet.json is too large.")+ data = json.loads(manifest_path.read_text(encoding="utf-8-sig"))+ except FileNotFoundError as exc:+ raise PetManifestError("The pet folder has no pet.json.") from exc+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise PetManifestError("pet.json could not be read as JSON.") from exc+ manifest = parse_manifest(data, builtin=builtin)+ if manifest.id != pet_dir.name:+ raise PetManifestError(+ f"pet.json names the id '{manifest.id}' but its folder is '{pet_dir.name}'."+ )+ sheet_path = pet_dir / manifest.sheet+ try:+ if sheet_path.stat().st_size > MAX_SHEET_BYTES:+ raise PetManifestError("The sprite sheet is larger than 2 MB.")+ with Image.open(sheet_path) as probe:+ if probe.format != "PNG":+ raise PetManifestError("The sprite sheet must be a PNG image.")+ width, height = probe.size+ except FileNotFoundError as exc:+ raise PetManifestError(f"The sprite sheet '{manifest.sheet}' is missing.") from exc+ except (OSError, SyntaxError, Image.DecompressionBombError) as exc:+ raise PetManifestError("The sprite sheet could not be read as a PNG.") from exc+ check_cells(manifest, width, height)+ return manifest+++def normalize_sheet(image: Image.Image) -> Image.Image:+ """Return ``image`` as RGBA with binary alpha and no exact colour-key pixel.++ Alpha at or above :data:`ALPHA_THRESHOLD` becomes 255, everything else+ becomes fully transparent black. An opaque pixel that is exactly+ ``#FF00FF`` is nudged to ``#FE00FE`` so the overlay's colour key never+ punches a hole into the sprite.+ """+ rgba = image.convert("RGBA")+ alpha = rgba.getchannel("A").point(lambda v: 255 if v >= ALPHA_THRESHOLD else 0)+ clean = Image.new("RGBA", rgba.size, (0, 0, 0, 0))+ clean.paste(rgba.convert("RGB"), mask=alpha)+ clean.putalpha(alpha)+ key_mask = _exact_color_mask(clean, COLOR_KEY, alpha)+ if key_mask.getbbox() is not None:+ clean.paste(_nudged(COLOR_KEY) + (255,), mask=key_mask)+ return clean+++def load_pet(pet_dir: Path, *, builtin: bool) -> PetPack:+ """Load and decode the pet in ``pet_dir``. Raises :class:`PetManifestError`."""+ pet_dir = Path(pet_dir)+ manifest = read_manifest(pet_dir, builtin=builtin)+ try:+ with Image.open(pet_dir / manifest.sheet) as raw:+ raw.load()+ sheet = normalize_sheet(raw)+ except (OSError, SyntaxError, Image.DecompressionBombError) as exc:+ raise PetManifestError("The sprite sheet could not be decoded.") from exc+ check_sheet_size(*sheet.size)++ size = manifest.frame_size+ by_row: dict[str, tuple[Image.Image, ...]] = {}+ frames: dict[str, tuple[Image.Image, ...]] = {}+ for state in PET_STATES:+ resolved, spec = manifest.spec_for(state)+ if resolved not in by_row:+ top = spec.row * size+ by_row[resolved] = tuple(+ sheet.crop((col * size, top, (col + 1) * size, top + size))+ for col in range(spec.frames)+ )+ frames[state] = by_row[resolved]+ return PetPack(manifest=manifest, directory=pet_dir, frames=MappingProxyType(frames))+++def load_default_pet() -> PetPack | None:+ """The :data:`DEFAULT_PET_ID` pack, or ``None`` when even that is broken."""+ try:+ return load_pet(builtin_root() / DEFAULT_PET_ID, builtin=True)+ except PetManifestError as exc:+ # A broken default is a packaging bug; the strip without a figure+ # still works, so the overlay degrades instead of crashing.+ _log.error("default pet %r failed to load: %s", DEFAULT_PET_ID, exc)+ return None+++def load_pet_by_id(pet_id: str, *, data_dir: Path | None = None) -> PetPack | None:+ """Load a pet by id.++ ``"none"`` returns ``None`` (strip without a figure). An unknown or broken+ id logs a warning and returns the :data:`DEFAULT_PET_ID` pack instead.+ """+ if pet_id == NO_PET_ID:+ return None+ found = find_pet_dir(pet_id, data_dir=data_dir)+ if found is None:+ _log.warning("pet %r not found; showing %r", pet_id, DEFAULT_PET_ID)+ return load_default_pet()+ folder, builtin = found+ try:+ return load_pet(folder, builtin=builtin)+ except PetManifestError as exc:+ _log.warning("pet %r is broken (%s); showing %r", pet_id, exc, DEFAULT_PET_ID)+ return load_default_pet()+++def _builtin_manifests() -> list[PetManifest]:+ root = builtin_root()+ try:+ folders = [p for p in root.iterdir() if p.is_dir() and BUILTIN_ID_RE.match(p.name)]+ except OSError as exc:+ _log.error("built-in pets folder %s is unreadable: %s", root, exc)+ return []+ # Stable order: the default pet first, the rest alphabetically.+ folders.sort(key=lambda p: (p.name != DEFAULT_PET_ID, p.name))+ manifests: list[PetManifest] = []+ for folder in folders:+ try:+ manifests.append(read_manifest(folder, builtin=True))+ except PetManifestError as exc:+ _log.warning("built-in pet %r skipped: %s", folder.name, exc)+ return manifests+++def list_custom(root: Path) -> list[PetManifest]:+ """Every valid user pet under ``root``; broken ones are skipped with a warning."""+ root = Path(root)+ try:+ folders = [p for p in root.iterdir() if p.is_dir() and USER_ID_RE.match(p.name)]+ except FileNotFoundError:+ return []+ except OSError as exc:+ _log.warning("pets folder %s is unreadable: %s", root, exc)+ return []+ manifests: list[PetManifest] = []+ for folder in folders:+ try:+ manifests.append(read_manifest(folder, builtin=False))+ except PetManifestError as exc:+ _log.warning("user pet %r skipped: %s", folder.name, exc)+ manifests.sort(key=lambda m: (m.name.casefold(), m.id))+ return manifests+++def list_pets(*, data_dir: Path | None = None) -> list[PetManifest]:+ """Built-in pets (default first) followed by user pets. Never raises."""+ return _builtin_manifests() + list_custom(custom_root(data_dir))+++def to_color_key(+ frame: Image.Image, scale: int, key: tuple[int, int, int] = COLOR_KEY+) -> Image.Image:+ """Scale ``frame`` by an integer factor onto a solid colour-key background.++ Returns an RGB image ``scale`` times the source size, scaled with+ nearest-neighbour so no pixel blends into the key. Transparent pixels+ become exactly ``key``; an opaque pixel that happens to equal ``key`` is+ nudged by one step so it stays visible.+ """+ if isinstance(scale, bool) or not isinstance(scale, int) or scale < 1:+ raise ValueError("scale must be a positive whole number")+ rgba = frame.convert("RGBA")+ alpha = rgba.getchannel("A").point(lambda v: 255 if v >= ALPHA_THRESHOLD else 0)+ rgb = rgba.convert("RGB")+ key_mask = _exact_color_mask(rgb, key, alpha)+ if key_mask.getbbox() is not None:+ rgb.paste(_nudged(key), mask=key_mask)+ out = Image.new("RGB", rgba.size, key)+ out.paste(rgb, mask=alpha)+ if scale == 1:+ return out+ width, height = out.size+ return out.resize((width * scale, height * scale), Image.Resampling.NEAREST)+++def _nudged(key: tuple[int, int, int]) -> tuple[int, int, int]:+ """The nearest colour that is not ``key``: every lit channel one step darker.++ ``#FF00FF`` becomes ``#FE00FE`` (docs/pets.md); a black key becomes+ ``#010101``.+ """+ nudged = tuple(v - 1 if v > 0 else 0 for v in key)+ if nudged == tuple(key):+ return (1, 1, 1)+ return nudged # type: ignore[return-value]+++def _exact_color_mask(+ image: Image.Image, color: tuple[int, int, int], alpha: Image.Image+) -> Image.Image:+ """An ``L`` mask: 255 where ``image`` is exactly ``color`` and ``alpha`` is opaque."""+ mask = alpha+ for channel, value in zip(image.convert("RGB").split(), color, strict=True):+ hit = channel.point(lambda v, value=value: 255 if v == value else 0)+ mask = ImageChops.multiply(mask, hit)+ return maskdiff --git a/jarvis/ui/pets/manifest.py b/jarvis/ui/pets/manifest.pynew file mode 100644index 0000000000..8a9e6a00cb--- /dev/null+++ b/jarvis/ui/pets/manifest.py@@ -0,0 +1,241 @@+"""The ``pet.json`` manifest: parsing, validation and fallback resolution.++A pet is a folder with ``pet.json`` and a sprite sheet (``docs/pets.md``,+format ``jarvis-pet/1``). This module owns every rule a manifest must satisfy+on its own; the rules that need the decoded sheet (cells inside the image)+live in :func:`check_cells`, which the loader and the store call once they+know the sheet's size.++Every rejection raises :class:`PetManifestError` with a short, user-readable+English sentence: the message reaches the settings page verbatim when a+user uploads a broken pet.+"""++from __future__ import annotations++import re+from collections.abc import Mapping+from dataclasses import dataclass+from types import MappingProxyType++from jarvis.ui.pets.states import (+ FRAME_SIZES,+ MAX_FRAMES_PER_STATE,+ NO_PET_ID,+ ONE_SHOT_STATES,+ PET_FORMAT,+ PET_STATES,+ STATE_FALLBACKS,+)++#: Id of a built-in pet (the folder name under ``jarvis/ui/pets/builtin``).+BUILTIN_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$")++#: Id of a user-created pet: ``u`` plus 16 hex digits (``PetStore.add``).+USER_ID_RE = re.compile(r"^u[0-9a-f]{16}$")++#: A sheet is a plain PNG file name inside the pet folder, never a path.+_SHEET_NAME_RE = re.compile(r"^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,63}\.png$")++MAX_NAME_CHARS = 40+MAX_DESCRIPTION_CHARS = 140+MIN_FPS = 1+MAX_FPS = 12++#: Largest sheet edge in pixels, and the largest sheet file in bytes.+MAX_SHEET_EDGE = 512+MAX_SHEET_BYTES = 2 * 1024 * 1024+++class PetManifestError(ValueError):+ """A pet pack breaks a rule of the ``jarvis-pet/1`` format."""+++@dataclass(frozen=True)+class AnimationSpec:+ """One state's animation: a row of ``frames`` cells played at ``fps``."""++ row: int+ frames: int+ fps: int+ loop: bool+++@dataclass(frozen=True)+class PetManifest:+ """A validated ``pet.json``.++ ``animations`` holds only the states the file declares; use+ :meth:`spec_for` to resolve a missing state through ``STATE_FALLBACKS``.+ """++ id: str+ name: str+ description: str+ frame_size: int+ sheet: str+ animations: Mapping[str, AnimationSpec]+ builtin: bool = False++ def spec_for(self, state: str) -> tuple[str, AnimationSpec]:+ """Return ``(resolved_state, spec)`` for ``state``.++ A state the manifest does not declare borrows its fallback's row;+ every fallback chain ends at ``idle``, which a valid manifest always+ has. Raises ``KeyError`` for a name outside ``PET_STATES``.+ """+ if state not in PET_STATES:+ raise KeyError(f"unknown pet state {state!r}")+ resolved = state+ seen: set[str] = set()+ while resolved not in self.animations:+ seen.add(resolved)+ resolved = STATE_FALLBACKS.get(resolved, "idle")+ if resolved in seen: # defensive: a cyclic table must not hang+ resolved = "idle"+ break+ return resolved, self.animations[resolved]++ def to_json(self) -> dict:+ """The ``pet.json`` shape (``builtin`` is not part of the file)."""+ return {+ "format": PET_FORMAT,+ "id": self.id,+ "name": self.name,+ "description": self.description,+ "frame_size": self.frame_size,+ "sheet": self.sheet,+ "animations": {+ state: {+ "row": spec.row,+ "frames": spec.frames,+ "fps": spec.fps,+ "loop": spec.loop,+ }+ for state in PET_STATES+ if (spec := self.animations.get(state)) is not None+ },+ }+++def _int_field(data: Mapping, key: str, where: str) -> int:+ value = data.get(key)+ # bool is an int subclass; "frames": true is a typo, not a count.+ if not isinstance(value, int) or isinstance(value, bool):+ raise PetManifestError(f"{where}: '{key}' must be a whole number.")+ return value+++def _parse_animation(state: str, raw: object) -> AnimationSpec:+ where = f"Animation '{state}'"+ if not isinstance(raw, Mapping):+ raise PetManifestError(f"{where} must be an object with row, frames and fps.")+ row = _int_field(raw, "row", where)+ frames = _int_field(raw, "frames", where)+ fps = _int_field(raw, "fps", where)+ if row < 0:+ raise PetManifestError(f"{where}: 'row' cannot be negative.")+ if not 1 <= frames <= MAX_FRAMES_PER_STATE:+ raise PetManifestError(f"{where}: 'frames' must be between 1 and {MAX_FRAMES_PER_STATE}.")+ if not MIN_FPS <= fps <= MAX_FPS:+ raise PetManifestError(f"{where}: 'fps' must be between {MIN_FPS} and {MAX_FPS}.")+ loop = raw.get("loop", state not in ONE_SHOT_STATES)+ if not isinstance(loop, bool):+ raise PetManifestError(f"{where}: 'loop' must be true or false.")+ return AnimationSpec(row=row, frames=frames, fps=fps, loop=loop)+++def parse_manifest(data: object, *, builtin: bool) -> PetManifest:+ """Validate a decoded ``pet.json`` and return the manifest.++ ``builtin`` selects the id rule: a built-in id is a short slug, a+ user-created one is ``u`` plus 16 hex digits. Raises+ :class:`PetManifestError` on the first broken rule.+ """+ if not isinstance(data, Mapping):+ raise PetManifestError("pet.json must be a JSON object.")+ if data.get("format") != PET_FORMAT:+ raise PetManifestError(f'pet.json must declare "format": "{PET_FORMAT}".')++ pet_id = data.get("id")+ if not isinstance(pet_id, str) or pet_id == NO_PET_ID:+ raise PetManifestError("The pet id is missing or reserved.")+ if builtin:+ if not BUILTIN_ID_RE.match(pet_id) or USER_ID_RE.match(pet_id):+ raise PetManifestError(+ "A built-in pet id uses 1-32 lowercase letters, digits and dashes."+ )+ elif not USER_ID_RE.match(pet_id):+ raise PetManifestError("A user pet id is 'u' followed by 16 hex digits.")++ name = data.get("name")+ if not isinstance(name, str) or not name.strip():+ raise PetManifestError("The pet needs a name.")+ name = name.strip()+ if len(name) > MAX_NAME_CHARS:+ raise PetManifestError(f"The name is longer than {MAX_NAME_CHARS} characters.")++ description = data.get("description", "")+ if not isinstance(description, str):+ raise PetManifestError("The description must be text.")+ description = description.strip()+ if len(description) > MAX_DESCRIPTION_CHARS:+ raise PetManifestError(+ f"The description is longer than {MAX_DESCRIPTION_CHARS} characters."+ )++ frame_size = data.get("frame_size")+ if (+ not isinstance(frame_size, int)+ or isinstance(frame_size, bool)+ or frame_size not in FRAME_SIZES+ ):+ sizes = ", ".join(str(size) for size in FRAME_SIZES)+ raise PetManifestError(f"'frame_size' must be one of {sizes}.")++ sheet = data.get("sheet")+ if not isinstance(sheet, str) or not _SHEET_NAME_RE.match(sheet) or ".." in sheet:+ raise PetManifestError("'sheet' must be a PNG file name inside the pet folder.")++ raw_animations = data.get("animations")+ if not isinstance(raw_animations, Mapping) or not raw_animations:+ raise PetManifestError("pet.json needs an 'animations' object.")+ unknown = sorted(str(key) for key in raw_animations if key not in PET_STATES)+ if unknown:+ raise PetManifestError(f"Unknown animation state '{unknown[0]}'.")+ if "idle" not in raw_animations:+ raise PetManifestError("The 'idle' animation is required.")+ animations = {+ state: _parse_animation(state, raw_animations[state])+ for state in PET_STATES+ if state in raw_animations+ }++ return PetManifest(+ id=pet_id,+ name=name,+ description=description,+ frame_size=frame_size,+ sheet=sheet,+ animations=MappingProxyType(animations),+ builtin=builtin,+ )+++def check_sheet_size(width: int, height: int) -> None:+ """Reject a sheet larger than ``MAX_SHEET_EDGE`` on either side."""+ if width < 1 or height < 1:+ raise PetManifestError("The sprite sheet is empty.")+ if width > MAX_SHEET_EDGE or height > MAX_SHEET_EDGE:+ raise PetManifestError(+ f"The sprite sheet is larger than {MAX_SHEET_EDGE} x {MAX_SHEET_EDGE} pixels."+ )+++def check_cells(manifest: PetManifest, width: int, height: int) -> None:+ """Reject a manifest whose animations reach outside a ``width x height`` sheet."""+ check_sheet_size(width, height)+ size = manifest.frame_size+ for state, spec in manifest.animations.items():+ if (spec.row + 1) * size > height or spec.frames * size > width:+ raise PetManifestError(f"Animation '{state}' reaches outside the sprite sheet.")diff --git a/jarvis/ui/pets/state_machine.py b/jarvis/ui/pets/state_machine.pynew file mode 100644index 0000000000..32189ab7b0--- /dev/null+++ b/jarvis/ui/pets/state_machine.py@@ -0,0 +1,139 @@+"""Which animation the pet shows, derived from the overlay's coarse modes.++The bridge already tells every overlay what to *be* through the bar's coarse+modes (``jarvis.ui.jarvisbar.modes``). The pet maps them onto its own states+(``jarvis.ui.pets.states``) and adds the two things a mode cannot say: the+one-shot outcomes (``success`` / ``error``) and falling asleep after a long+quiet spell.++The machine is pure and clock-driven: nothing here starts a timer. The+overlay asks :meth:`PetStateMachine.state` when it paints and sleeps for+:meth:`PetStateMachine.next_change_in` at most, so an idle pet wakes up only+when something can actually change.+"""++from __future__ import annotations++import logging+import time+from collections.abc import Callable++from jarvis.ui.jarvisbar.modes import NOTICE_MODES+from jarvis.ui.pets.states import ONE_SHOT_SECONDS, ONE_SHOT_STATES, SLEEP_AFTER_SECONDS++_log = logging.getLogger(__name__)++#: Coarse overlay mode -> the pet state it shows. ``notice`` is not here: it+#: plays the ``error`` one-shot on top of whatever the pet was doing.+MODE_STATES: dict[str, str] = {+ "idle": "idle",+ "listen": "listening",+ "dictate": "listening",+ "think": "thinking",+ "dictate_transcribing": "thinking",+ "speak": "talking",+}++#: The one-shot a ``notice`` mode plays.+NOTICE_OUTCOME = "error"+++class PetStateMachine:+ """Turns overlay modes, outcomes and activity into one pet state."""++ def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:+ self._clock = clock+ now = clock()+ self._base = "idle"+ self._last_activity = now+ self._one_shot: str | None = None+ self._one_shot_until = now+ self._shown = "idle"+ self._shown_since = now++ # -- inputs ---------------------------------------------------------++ def on_mode(self, mode: str) -> None:+ """Follow the overlay's coarse mode (``jarvis.ui.jarvisbar.modes``)."""+ if mode in NOTICE_MODES:+ self.on_outcome(NOTICE_OUTCOME)+ return+ state = MODE_STATES.get(mode)+ if state is None:+ _log.debug("pet state machine ignores unknown mode %r", mode)+ return+ now = self._clock()+ self._settle(now)+ self._last_activity = now+ self._base = state+ if self._one_shot is None:+ self._set_shown(state, now)++ def on_outcome(self, kind: str) -> None:+ """Play the ``success`` or ``error`` one-shot, then return to the mode state."""+ if kind not in ONE_SHOT_STATES:+ _log.debug("pet state machine ignores unknown outcome %r", kind)+ return+ now = self._clock()+ self._settle(now)+ self._last_activity = now+ self._one_shot = kind+ self._one_shot_until = now + ONE_SHOT_SECONDS[kind]+ # Set directly, not through _set_shown: a repeated outcome restarts+ # its animation even though the state name does not change.+ self._shown = kind+ self._shown_since = now++ def on_activity(self) -> None:+ """Any Jarvis event: wake from sleep and restart the sleep countdown."""+ now = self._clock()+ self._settle(now)+ self._last_activity = now+ if self._one_shot is None:+ self._set_shown(self._base, now)++ # -- outputs --------------------------------------------------------++ def state(self) -> str:+ """The state to show now (one of ``PET_STATES``)."""+ self._settle(self._clock())+ return self._shown++ def state_started_at(self) -> float:+ """Clock time the current state began; animations count frames from here."""+ self._settle(self._clock())+ return self._shown_since++ def next_change_in(self) -> float | None:+ """Seconds until a timer-driven change, or ``None`` when none is pending.++ Timer-driven changes are the end of a one-shot and falling asleep.+ """+ now = self._clock()+ self._settle(now)+ if self._one_shot is not None:+ return max(0.0, self._one_shot_until - now)+ if self._base == "idle" and self._shown != "sleeping":+ return max(0.0, self._last_activity + SLEEP_AFTER_SECONDS - now)+ return None++ # -- internals ------------------------------------------------------++ def _settle(self, now: float) -> None:+ """Apply the timer-driven changes that fell due by ``now``.++ Each change is stamped with the moment it fell due, not the moment+ someone asked, so a late poll does not shift the animation's phase.+ """+ if self._one_shot is not None and now >= self._one_shot_until:+ self._one_shot = None+ self._set_shown(self._base, self._one_shot_until)+ if self._one_shot is None and self._base == "idle":+ asleep_at = self._last_activity + SLEEP_AFTER_SECONDS+ if now >= asleep_at:+ self._set_shown("sleeping", max(asleep_at, self._shown_since))++ def _set_shown(self, state: str, since: float) -> None:+ if state != self._shown:+ self._shown = state+ self._shown_since = sincediff --git a/jarvis/ui/pets/status_line.py b/jarvis/ui/pets/status_line.pynew file mode 100644index 0000000000..38872370d3--- /dev/null+++ b/jarvis/ui/pets/status_line.py@@ -0,0 +1,206 @@+"""Condense what Jarvis is doing into one short line for the pet's status bubble.++The bubble sits under a small floating figure, so it shows a *gist*: the first+sentence of a reply, the current tool, the live transcript. Everything a+human would skip when glancing over is stripped: markdown syntax, code+blocks, URLs, file paths and JSON / dict dumps. :class:`StatusFeed` then+drops repeats and rate-limits updates so a fast token stream does not make+the bubble flicker.+"""++from __future__ import annotations++import re+import time+from collections.abc import Callable++ELLIPSIS = "\u2026"++_FENCE_RE = re.compile(r"(```|~~~).*?(?:\1|\Z)", re.DOTALL)+_INLINE_CODE_RE = re.compile(r"`([^`\n]*)`")+_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\([^)]*\)")+_LINK_RE = re.compile(r"\[([^\]]+)\]\([^)]*\)")+_URL_RE = re.compile(r"(?:\b[a-zA-Z][a-zA-Z0-9+.-]*://|\bwww\.)\S+")+_WIN_PATH_RE = re.compile(r"(?<![\w/])(?:[A-Za-z]:[\\/]|\\\\)[^\s,;)\]}'\"]*")+_POSIX_PATH_RE = re.compile(r"(?<![\w.])(?:~|\.{1,2})?/(?:[\w.@+-]+/)*[\w.@+-]+/?")+_REL_PATH_RE = re.compile(r"(?<![\w/])[\w.@-]+(?:[\\/][\w.@-]+)+\.[A-Za-z0-9]{1,8}\b")+_DICT_RE = re.compile(r"\{[^{}]*\}")+_LIST_RE = re.compile(r"\[[^\[\]]*[\"':,{][^\[\]]*\]")+_OPEN_DUMP_RE = re.compile(r"[\[{]\s*[\"'{\[].*\Z", re.DOTALL)+_HEADING_RE = re.compile(r"^\s{0,3}#{1,6}\s+")+_QUOTE_RE = re.compile(r"^\s*(?:>\s*)+")+_BULLET_RE = re.compile(r"^\s*(?:[-*+•]|\d{1,3}[.)])\s+")+_RULE_RE = re.compile(r"^\s*(?:[-*_=]\s*){3,}$")+_TABLE_RULE_RE = re.compile(r"^\s*\|?\s*:?-{2,}")+_EMPHASIS_RE = re.compile(r"(\*\*|__|\*|~~)(?=\S)(.+?)(?<=\S)\1")+_UNDERSCORE_EM_RE = re.compile(r"(?<!\w)_(?=\S)(.+?)(?<=\S)_(?!\w)")+_HTML_TAG_RE = re.compile(r"</?[A-Za-z][^<>]{0,80}>")+_STRAY_MARKS_RE = re.compile(r"(?:\*\*|__|~~|`)")+_EMPTY_BRACKETS_RE = re.compile(r"\(\s*\)|\[\s*\]|\{\s*\}")+_SPACE_BEFORE_PUNCT_RE = re.compile(r"\s+([,.;:!?])")+_REPEATED_PUNCT_RE = re.compile(r"([,;:])(?:\s*[,;:])+")+_SENTENCE_END_RE = re.compile(r"(?<=[.!?\u2026])\s+(?=\S)")+_WS_RE = re.compile(r"\s+")+_PATH_SPLIT_RE = re.compile(r"[\\/]")+_FILE_NAME_RE = re.compile(r"^[\w@+-][\w.@+-]{0,39}\.[A-Za-z0-9]{1,8}$")++#: Inline code longer than this is a snippet, not a word worth showing.+_MAX_INLINE_CODE = 30++#: A first sentence shorter than this borrows the next one (clipped if needed).+_SHORT_SENTENCE = 20++_SENTENCE_MARKS = ".!?:" + ELLIPSIS+++def _inline_code(match: re.Match[str]) -> str:+ content = match.group(1).strip()+ return content if len(content) <= _MAX_INLINE_CODE else " "+++def _path_to_name(match: re.Match[str]) -> str:+ """A file path shrinks to its file name; a folder path disappears."""+ name = _PATH_SPLIT_RE.split(match.group(0).rstrip("/\\"))[-1]+ return name if _FILE_NAME_RE.match(name) else " "+++def _clean_line(line: str) -> str:+ line = _QUOTE_RE.sub("", line)+ line = _BULLET_RE.sub("", line)+ line = line.replace("|", " ")+ return line+++def _strip_blocks(text: str) -> str:+ """Remove what can span lines: fenced code and JSON / dict / list dumps."""+ text = _FENCE_RE.sub("\n", text)+ previous = None+ while previous != text: # nested dumps: remove the innermost level each pass+ previous = text+ text = _DICT_RE.sub(" ", text)+ text = _LIST_RE.sub(" ", text)+ return _OPEN_DUMP_RE.sub(" ", text)+++def _strip_noise(text: str) -> str:+ """Clean one line: links, URLs, code, paths and markdown emphasis."""+ text = _IMAGE_RE.sub(lambda m: m.group(1), text)+ text = _LINK_RE.sub(lambda m: m.group(1), text)+ text = _URL_RE.sub(" ", text)+ text = _INLINE_CODE_RE.sub(_inline_code, text)+ text = _HTML_TAG_RE.sub(" ", text)+ text = _WIN_PATH_RE.sub(_path_to_name, text)+ text = _REL_PATH_RE.sub(_path_to_name, text)+ text = _POSIX_PATH_RE.sub(_path_to_name, text)+ for _ in range(2): # **bold *italic*** needs two passes+ text = _EMPHASIS_RE.sub(lambda m: m.group(2), text)+ text = _UNDERSCORE_EM_RE.sub(lambda m: m.group(1), text)+ text = _STRAY_MARKS_RE.sub("", text)+ text = _EMPTY_BRACKETS_RE.sub(" ", text)+ text = _WS_RE.sub(" ", text)+ text = _SPACE_BEFORE_PUNCT_RE.sub(r"\1", text)+ text = _REPEATED_PUNCT_RE.sub(r"\1", text)+ return text.strip(" ,;:-")+++def _clip(text: str, max_chars: int) -> str:+ if len(text) <= max_chars:+ return text+ room = max(1, max_chars - 1)+ cut = text[:room]+ space = cut.rfind(" ")+ if space > room // 3:+ cut = cut[:space]+ cut = cut.rstrip(" ,;:-([{")+ return f"{cut}{ELLIPSIS}" if cut else ""+++def condense(text: str, *, max_chars: int = 90) -> str:+ """Return the gist of ``text`` in at most ``max_chars`` characters.++ Takes the first sentence (plus the next one when the first is very short),+ strips markdown syntax, fenced and long inline code, URLs, file paths and+ JSON / dict dumps, collapses whitespace, and clips at a word boundary with+ an ellipsis. Returns ``""`` when nothing readable is left.+ """+ if not isinstance(text, str) or not text.strip() or max_chars < 1:+ return ""+ text = _strip_blocks(text)++ headings: list[str] = []+ body: list[str] = []+ for raw in text.splitlines():+ if _RULE_RE.match(raw) or _TABLE_RULE_RE.match(raw):+ continue+ target = headings if _HEADING_RE.match(raw) else body+ cleaned = _strip_noise(_clean_line(_HEADING_RE.sub("", raw)))+ if cleaned and any(ch.isalnum() for ch in cleaned):+ target.append(cleaned)+ # A heading is a label; show it only when there is nothing else.+ lines = body or headings+ if not lines:+ return ""++ # A line break ends a sentence even without punctuation.+ sentences: list[str] = []+ for line in lines:+ sentences.extend(part for part in _SENTENCE_END_RE.split(line) if part)+ gist = sentences[0]+ if len(gist) < _SHORT_SENTENCE and len(sentences) > 1:+ glue = " " if gist[-1] in _SENTENCE_MARKS else ". "+ gist = f"{gist}{glue}{sentences[1]}"+ return _clip(gist, max_chars)+++class StatusFeed:+ """Dedupe and rate-limit the lines the status bubble shows."""++ def __init__(+ self, clock: Callable[[], float] = time.monotonic, min_interval_s: float = 0.3+ ) -> None:+ self._clock = clock+ self._min_interval = max(0.0, float(min_interval_s))+ self._last: tuple[str, str] | None = None+ self._last_at: float | None = None+ self._pending: tuple[str, str] | None = None++ def offer(self, header: str, line: str, *, force: bool = False) -> tuple[str, str] | None:+ """Condense ``(header, line)`` and return it when it should be shown.++ Returns ``None`` for an empty pair, a repeat of the last shown pair, or+ (unless ``force``) a pair arriving within ``min_interval_s`` of the+ last shown one. A throttled pair is kept; :meth:`flush` returns it+ once the interval has passed.+ """+ pair = (condense(header, max_chars=40), condense(line))+ if not pair[0] and not pair[1]:+ return None+ if pair == self._last:+ self._pending = None+ return None+ now = self._clock()+ if not force and self._last_at is not None and now - self._last_at < self._min_interval:+ self._pending = pair+ return None+ return self._show(pair, now)++ def flush(self) -> tuple[str, str] | None:+ """The newest throttled pair once its interval has passed, else ``None``."""+ if self._pending is None:+ return None+ now = self._clock()+ if self._last_at is not None and now - self._last_at < self._min_interval:+ return None+ return self._show(self._pending, now)++ def reset(self) -> None:+ """Forget the last shown and the throttled pair."""+ self._last = None+ self._last_at = None+ self._pending = None++ def _show(self, pair: tuple[str, str], now: float) -> tuple[str, str]:+ self._last = pair+ self._last_at = now+ self._pending = None+ return pairdiff --git a/jarvis/ui/pets/store.py b/jarvis/ui/pets/store.pynew file mode 100644index 0000000000..1885404763--- /dev/null+++ b/jarvis/ui/pets/store.py@@ -0,0 +1,257 @@+"""User-created pets under ``<DATA_DIR>/pets`` (``docs/pets.md``).++An upload is untrusted: the sheet is decoded with Pillow, checked against the+format's limits and RE-ENCODED, so the raw upload bytes never reach the disk.+Each pet is staged in a hidden folder and moved into place with one rename,+so a crash never leaves a half-written pet that the loader would list.+"""++from __future__ import annotations++import io+import json+import logging+import os+import secrets+import shutil+import tempfile+from pathlib import Path++from PIL import Image++from jarvis.ui.pets.loader import MANIFEST_NAME, list_custom, normalize_sheet+from jarvis.ui.pets.manifest import (+ MAX_SHEET_BYTES,+ USER_ID_RE,+ PetManifest,+ PetManifestError,+ check_cells,+ check_sheet_size,+ parse_manifest,+)+from jarvis.ui.pets.states import (+ FRAME_SIZES,+ MAX_FRAMES_PER_STATE,+ ONE_SHOT_STATES,+ PET_FORMAT,+ PET_STATES,+)++_log = logging.getLogger(__name__)++SHEET_NAME = "sheet.png"+_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+_MAX_MANIFEST_CHARS = 64 * 1024++#: The frame size tried first when an upload does not name one (the template's).+_PREFERRED_FRAME_SIZE = 48++#: Frame rate of an inferred animation, per state; unnamed states use 8.+_DEFAULT_FPS: dict[str, int] = {"idle": 4, "sleeping": 2}+_ACTIVE_FPS = 8+++class PetStore:+ """Create, list and delete user pets in one folder."""++ MAX_SHEET_BYTES = MAX_SHEET_BYTES++ def __init__(self, root: Path) -> None:+ self.root = Path(root)++ def list(self) -> list[PetManifest]:+ """Every valid user pet; broken ones are skipped with a warning."""+ return list_custom(self.root)++ def directory(self, pet_id: str) -> Path | None:+ """The folder of an existing user pet, or ``None``."""+ if not isinstance(pet_id, str) or not USER_ID_RE.match(pet_id):+ return None+ folder = self.root / pet_id+ return folder if (folder / MANIFEST_NAME).is_file() else None++ def add(+ self,+ *,+ sheet_bytes: bytes,+ name: str,+ description: str,+ manifest_json: str | None = None,+ frame_size: int | None = None,+ ) -> PetManifest:+ """Validate an upload, store it as a new pet and return its manifest.++ Without ``manifest_json`` the rows are read in ``PET_STATES`` order and+ each row's frame count is its run of non-empty cells from the left.+ Raises :class:`PetManifestError` with a user-readable message.+ """+ sheet = _decode_sheet(sheet_bytes)+ width, height = sheet.size+ pet_id = "u" + secrets.token_hex(8)++ data: dict = {}+ if manifest_json is not None and manifest_json.strip():+ data = _manifest_data(manifest_json)+ if frame_size is None and "frame_size" in data:+ frame_size = data["frame_size"]+ size = _pick_frame_size(width, height, frame_size)+ if "animations" not in data:+ data["animations"] = _infer_animations(sheet, size)+ # The form fields win; an uploaded pet.json fills in what they leave empty.+ if isinstance(name, str) and name.strip():+ data["name"] = name+ if isinstance(description, str) and description.strip():+ data["description"] = description+ data.update(+ {+ "format": PET_FORMAT,+ "id": pet_id,+ "frame_size": size,+ "sheet": SHEET_NAME,+ }+ )+ manifest = parse_manifest(data, builtin=False)+ check_cells(manifest, width, height)+ self._write(manifest, sheet)+ return manifest++ def delete(self, pet_id: str) -> bool:+ """Remove a user pet. Only ``u…`` ids; never touches anything outside the root."""+ if not isinstance(pet_id, str) or not USER_ID_RE.match(pet_id):+ return False+ folder = self.root / pet_id+ try:+ if folder.is_symlink():+ # A link planted in the pets folder: drop the link, never its target.+ folder.unlink()+ return True+ if not folder.is_dir():+ return False+ if folder.resolve().parent != self.root.resolve():+ return False+ shutil.rmtree(folder)+ except OSError as exc:+ _log.warning("could not delete pet %r: %s", pet_id, exc)+ return False+ return True++ # -- internals ------------------------------------------------------++ def _write(self, manifest: PetManifest, sheet: Image.Image) -> None:+ self.root.mkdir(parents=True, exist_ok=True)+ staging = Path(tempfile.mkdtemp(prefix=".staging-", dir=self.root))+ try:+ _write_atomic(staging / SHEET_NAME, _encode_png(sheet))+ text = json.dumps(manifest.to_json(), indent=2, ensure_ascii=False) + "\n"+ _write_atomic(staging / MANIFEST_NAME, text.encode("utf-8"))+ os.replace(staging, self.root / manifest.id)+ except OSError as exc:+ shutil.rmtree(staging, ignore_errors=True)+ raise PetManifestError("The pet could not be saved.") from exc+++def _decode_sheet(sheet_bytes: bytes) -> Image.Image:+ if not isinstance(sheet_bytes, bytes | bytearray) or not sheet_bytes:+ raise PetManifestError("The sprite sheet is empty.")+ if len(sheet_bytes) > MAX_SHEET_BYTES:+ raise PetManifestError("The sprite sheet is larger than 2 MB.")+ if not bytes(sheet_bytes[:8]) == _PNG_SIGNATURE:+ raise PetManifestError("The sprite sheet must be a PNG image.")+ try:+ with Image.open(io.BytesIO(sheet_bytes)) as probe:+ if probe.format != "PNG":+ raise PetManifestError("The sprite sheet must be a PNG image.")+ # Size comes from the header: reject a huge sheet before decoding it.+ check_sheet_size(*probe.size)+ probe.load()+ return normalize_sheet(probe)+ except PetManifestError:+ raise+ except (OSError, SyntaxError, ValueError, Image.DecompressionBombError) as exc:+ raise PetManifestError("The sprite sheet could not be read as a PNG.") from exc+++def _manifest_data(manifest_json: str) -> dict:+ if len(manifest_json) > _MAX_MANIFEST_CHARS:+ raise PetManifestError("pet.json is too large.")+ try:+ data = json.loads(manifest_json)+ except json.JSONDecodeError as exc:+ raise PetManifestError("pet.json is not valid JSON.") from exc+ if not isinstance(data, dict):+ raise PetManifestError("pet.json must be a JSON object.")+ return data+++def _pick_frame_size(width: int, height: int, requested: object) -> int:+ """The cell size for a ``width x height`` sheet; the grid must divide it exactly."""+ if requested is not None:+ if (+ not isinstance(requested, int)+ or isinstance(requested, bool)+ or requested not in FRAME_SIZES+ ):+ sizes = ", ".join(str(size) for size in FRAME_SIZES)+ raise PetManifestError(f"'frame_size' must be one of {sizes}.")+ if width % requested or height % requested:+ raise PetManifestError(+ f"The sheet is not a grid of {requested} x {requested} pixel cells."+ )+ return requested+ fitting = [+ size+ for size in FRAME_SIZES+ if width % size == 0+ and height % size == 0+ and width // size <= MAX_FRAMES_PER_STATE+ and height // size <= len(PET_STATES)+ ]+ if not fitting:+ sizes = ", ".join(str(size) for size in FRAME_SIZES)+ raise PetManifestError(+ f"The sheet is not a grid of {sizes} pixel cells with at most "+ f"{MAX_FRAMES_PER_STATE} columns and {len(PET_STATES)} rows."+ )+ return _PREFERRED_FRAME_SIZE if _PREFERRED_FRAME_SIZE in fitting else max(fitting)+++def _infer_animations(sheet: Image.Image, size: int) -> dict[str, dict]:+ """Read rows in ``PET_STATES`` order; frames = leading run of non-empty cells."""+ alpha = sheet.getchannel("A")+ columns = min(sheet.width // size, MAX_FRAMES_PER_STATE)+ rows = min(sheet.height // size, len(PET_STATES))+ animations: dict[str, dict] = {}+ for row, state in enumerate(PET_STATES[:rows]):+ frames = 0+ for col in range(columns):+ box = (col * size, row * size, (col + 1) * size, (row + 1) * size)+ if alpha.crop(box).getbbox() is None:+ break+ frames += 1+ if frames:+ animations[state] = {+ "row": row,+ "frames": frames,+ "fps": _DEFAULT_FPS.get(state, _ACTIVE_FPS),+ "loop": state not in ONE_SHOT_STATES,+ }+ if "idle" not in animations:+ raise PetManifestError("The first row (idle) is empty.")+ return animations+++def _encode_png(image: Image.Image) -> bytes:+ buffer = io.BytesIO()+ image.save(buffer, format="PNG", optimize=True)+ return buffer.getvalue()+++def _write_atomic(path: Path, payload: bytes) -> None:+ fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)+ try:+ with os.fdopen(fd, "wb") as handle:+ handle.write(payload)+ os.replace(tmp, path)+ except BaseException:+ Path(tmp).unlink(missing_ok=True)+ raisediff --git a/jarvis/ui/pets/template/template.json b/jarvis/ui/pets/template/template.jsonnew file mode 100644index 0000000000..dfef634553--- /dev/null+++ b/jarvis/ui/pets/template/template.json@@ -0,0 +1,52 @@+{+ "format": "jarvis-pet/1",+ "id": "template",+ "name": "My pet",+ "description": "Draw one state per row, frames from left to right.",+ "frame_size": 48,+ "sheet": "template.png",+ "animations": {+ "idle": {+ "row": 0,+ "frames": 8,+ "fps": 4,+ "loop": true+ },+ "listening": {+ "row": 1,+ "frames": 4,+ "fps": 8,+ "loop": true+ },+ "thinking": {+ "row": 2,+ "frames": 6,+ "fps": 8,+ "loop": true+ },+ "talking": {+ "row": 3,+ "frames": 4,+ "fps": 10,+ "loop": true+ },+ "success": {+ "row": 4,+ "frames": 6,+ "fps": 10,+ "loop": false+ },+ "error": {+ "row": 5,+ "frames": 4,+ "fps": 8,+ "loop": false+ },+ "sleeping": {+ "row": 6,+ "frames": 4,+ "fps": 2,+ "loop": true+ }+ }+}diff --git a/jarvis/ui/pets/template/template.png b/jarvis/ui/pets/template/template.pngnew file mode 100644index 0000000000..bf60cf9813Binary files /dev/null and b/jarvis/ui/pets/template/template.png differdiff --git a/pyproject.toml b/pyproject.tomlindex a6a714a171..55d1694c36 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -869,6 +869,13 @@ jarvis = [# Wiki bootstrap templates for a new vault (memory/wiki/__init__.py's# TEMPLATES_DIR + integration.py's schema.md read)."memory/wiki/templates/*.md",+ # Built-in desktop pets and the sprite-sheet template, read at runtime via+ # Path(__file__) (jarvis/ui/pets/loader.py). Scoped to the two file kinds+ # a pet folder holds.+ "ui/pets/builtin/*/*.json",+ "ui/pets/builtin/*/*.png",+ "ui/pets/template/*.json",+ "ui/pets/template/*.png",# Built-in skills: SKILL.md plus their reference/asset/script support# files (e.g. skill-creator ships references/, scripts/, agents/,# assets/ alongside its SKILL.md). Extension-scoped rather thandiff --git a/scripts/pets/build_pets.py b/scripts/pets/build_pets.pynew file mode 100644index 0000000000..f47704be41--- /dev/null+++ b/scripts/pets/build_pets.py@@ -0,0 +1,1271 @@+#!/usr/bin/env python3+"""Generate the built-in desktop pets and the sprite-sheet template from pixel data.++Every pet is drawn procedurally into 48 x 48 cells: shape helpers build+masks, a shared shading pass gives every body the same light/dark rim, and a+per-state pose table moves the figure (bob, hop, shake). One row per state in+``PET_STATES`` order, one ``pet.json`` per pet (``docs/pets.md``).++The output is deterministic: no randomness, no timestamps, a fixed PNG+encoder setting. ``tests/unit/ui/pets/test_builtin_pets.py`` regenerates+everything into a temp folder and compares it with the committed files, so+edit this script and re-run it instead of touching a PNG by hand.++Usage::++ python scripts/pets/build_pets.py # write jarvis/ui/pets/{builtin,template}+ python scripts/pets/build_pets.py --out DIR # write DIR/builtin and DIR/template+"""++from __future__ import annotations++import argparse+import json+import math+import sys+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence+from contextlib import contextmanager+from dataclasses import dataclass, field+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+# Run from anywhere: import THIS checkout's jarvis, never an installed copy.+sys.path.insert(0, str(REPO_ROOT))++from PIL import Image # noqa: E402++from jarvis.ui.pets.states import ( # noqa: E402+ MAX_FRAMES_PER_STATE,+ ONE_SHOT_STATES,+ PET_FORMAT,+ PET_STATES,+)++CELL = 48+#: The vertical centre line of a cell lies between pixel columns 23 and 24.+CX = 24++Px = tuple[int, int]+RGBA = tuple[int, int, int, int]+Mask = set[Px]+++def hexc(value: str) -> RGBA:+ value = value.lstrip("#")+ return (int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16), 255)+++# ---------------------------------------------------------------------------+# Shared palette: one outline and one set of effect colours for every pet.+# ---------------------------------------------------------------------------++OUTLINE = hexc("#1b1622")+FX_WHITE = hexc("#f7f7fb")+FX_DIM = hexc("#aeb6c8")+SPARK = hexc("#ffd23f")+SPARK_CORE = hexc("#fff8d6")+RED = hexc("#e5383b")+Z_BLUE = hexc("#a5c8ff")+#: Sound arcs are 1 px strokes; an outline around each would read as hatching+#: on a light desktop, so they are a mid blue that holds on dark AND light.+ARC = hexc("#3d9be0")+BLUSH = hexc("#ff8fa3")+MOUTH_DARK = hexc("#3b1f2b")+TONGUE = hexc("#ff7a8a")+++# ---------------------------------------------------------------------------+# Shapes. Every helper returns a set of (x, y) pixels in cell coordinates.+# ---------------------------------------------------------------------------+++def ellipse(cx: float, cy: float, rx: float, ry: float) -> Mask:+ """Pixels whose centre lies inside the ellipse."""+ out: Mask = set()+ for y in range(int(cy - ry) - 1, int(cy + ry) + 2):+ for x in range(int(cx - rx) - 1, int(cx + rx) + 2):+ nx = (x + 0.5 - cx) / rx+ ny = (y + 0.5 - cy) / ry+ if nx * nx + ny * ny <= 1.0:+ out.add((x, y))+ return out+++def rect(x0: int, y0: int, x1: int, y1: int) -> Mask:+ """Inclusive rectangle."""+ return {(x, y) for y in range(y0, y1 + 1) for x in range(x0, x1 + 1)}+++def line(x0: int, y0: int, x1: int, y1: int) -> Mask:+ """Bresenham line, both ends included."""+ out: Mask = set()+ dx, dy = abs(x1 - x0), -abs(y1 - y0)+ sx, sy = (1 if x0 < x1 else -1), (1 if y0 < y1 else -1)+ err = dx + dy+ while True:+ out.add((x0, y0))+ if x0 == x1 and y0 == y1:+ return out+ e2 = 2 * err+ if e2 >= dy:+ err += dy+ x0 += sx+ if e2 <= dx:+ err += dx+ y0 += sy+++def polyline(points: Sequence[Px]) -> Mask:+ out: Mask = set()+ for a, b in zip(points, points[1:], strict=False):+ out |= line(*a, *b)+ return out+++def polygon(points: Sequence[tuple[float, float]]) -> Mask:+ """Pixels whose centre lies inside the polygon (even-odd rule)."""+ xs = [p[0] for p in points]+ ys = [p[1] for p in points]+ out: Mask = set()+ for y in range(int(min(ys)) - 1, int(max(ys)) + 2):+ for x in range(int(min(xs)) - 1, int(max(xs)) + 2):+ px, py = x + 0.5, y + 0.5+ inside = False+ for (ax, ay), (bx, by) in zip(points, [*points[1:], points[0]], strict=True):+ if (ay > py) != (by > py) and px < ax + (py - ay) * (bx - ax) / (by - ay):+ inside = not inside+ if inside:+ out.add((x, y))+ return out+++def shifted(pixels: Iterable[Px], dx: int, dy: int) -> Mask:+ return {(x + dx, y + dy) for x, y in pixels}+++def mirrored(pixels: Iterable[Px], axis: int = CX) -> Mask:+ """Mirror across the vertical line between columns ``axis - 1`` and ``axis``."""+ return {(2 * axis - 1 - x, y) for x, y in pixels}+++def from_rows(x: int, y: int, rows: Sequence[str], char: str = "#") -> Mask:+ """Pixels marked with ``char`` in ASCII ``rows`` placed at ``(x, y)``."""+ return {+ (x + col, y + row)+ for row, text in enumerate(rows)+ for col, mark in enumerate(text)+ if mark == char+ }+++_N4 = ((1, 0), (-1, 0), (0, 1), (0, -1))+++def outer_ring(mask: Mask) -> Mask:+ """The 1 px outline around ``mask`` (4-neighbourhood, so corners stay round)."""+ return {(x + dx, y + dy) for x, y in mask for dx, dy in _N4} - mask+++def eroded(mask: Mask, steps: int = 1) -> Mask:+ """``mask`` shrunk by ``steps`` pixels (4-neighbourhood)."""+ out = set(mask)+ for _ in range(steps):+ out = {(x, y) for x, y in out if all((x + dx, y + dy) in out for dx, dy in _N4)}+ return out+++def thick(mask: Mask) -> Mask:+ """A 1 px stroke widened to 2 px (right and down)."""+ return mask | shifted(mask, 1, 0) | shifted(mask, 0, 1)+++def rounded_rect(x0: int, y0: int, x1: int, y1: int, r: int = 2) -> Mask:+ """Inclusive rectangle with ``r``-step stair corners."""+ box = rect(x0, y0, x1, y1)+ for k in range(r):+ for j in range(r - k):+ box -= {(x0 + j, y0 + k), (x1 - j, y0 + k), (x0 + j, y1 - k), (x1 - j, y1 - k)}+ return box+++def shade(+ mask: Mask,+ base: RGBA,+ *,+ light: RGBA | None = None,+ dark: RGBA | None = None,+ rim: RGBA | None = None,+ dark_depth: int = 2,+) -> dict[Px, RGBA]:+ """The shared shading pass.++ ``rim`` paints every inner edge pixel (dark bodies, so they read on a+ dark desktop); otherwise the top/left inner edge gets ``light`` and the+ bottom/right band ``dark_depth`` pixels deep gets ``dark``.+ """+ out: dict[Px, RGBA] = {}+ for x, y in mask:+ up = (x, y - 1) not in mask+ left = (x - 1, y) not in mask+ down = any((x, y + k) not in mask for k in range(1, dark_depth + 1))+ right = (x + 1, y) not in mask+ color = base+ if rim is not None and (up or left or right or (x, y + 1) not in mask):+ color = rim+ elif light is not None and (up or left):+ color = light+ elif dark is not None and (down or right):+ color = dark+ out[(x, y)] = color+ return out+++# ---------------------------------------------------------------------------+# The frame canvas.+# ---------------------------------------------------------------------------+++class Frame:+ """One 48 x 48 cell being painted, with a movable origin."""++ def __init__(self) -> None:+ self.px: dict[Px, RGBA] = {}+ self._dx = 0+ self._dy = 0++ @contextmanager+ def offset(self, dx: int, dy: int) -> Iterator[None]:+ saved = (self._dx, self._dy)+ self._dx += dx+ self._dy += dy+ try:+ yield+ finally:+ self._dx, self._dy = saved++ def paint(self, pixels: Iterable[Px], color: RGBA) -> None:+ for x, y in pixels:+ self.px[(x + self._dx, y + self._dy)] = color++ def paint_map(self, colors: Mapping[Px, RGBA]) -> None:+ for (x, y), color in colors.items():+ self.px[(x + self._dx, y + self._dy)] = color++ def erase(self, pixels: Iterable[Px]) -> None:+ for x, y in pixels:+ self.px.pop((x + self._dx, y + self._dy), None)++ def part(self, mask: Mask, fill: RGBA | Mapping[Px, RGBA], outline: RGBA = OUTLINE) -> None:+ """Outline ``mask`` over whatever is below, then fill it."""+ self.paint(outer_ring(mask), outline)+ if isinstance(fill, Mapping):+ self.paint_map(fill)+ else:+ self.paint(mask, fill)++ def glyph(self, x: int, y: int, rows: Sequence[str], palette: Mapping[str, RGBA]) -> None:+ """Paint an outlined ASCII glyph; ``.`` is transparent."""+ cells: dict[Px, RGBA] = {}+ for row, text in enumerate(rows):+ for col, mark in enumerate(text):+ if mark in palette:+ cells[(x + col, y + row)] = palette[mark]+ self.paint(outer_ring(set(cells)), OUTLINE)+ self.paint_map(cells)++ def image(self) -> Image.Image:+ img = Image.new("RGBA", (CELL, CELL), (0, 0, 0, 0))+ for (x, y), color in self.px.items():+ if not (0 <= x < CELL and 0 <= y < CELL):+ raise ValueError(f"pixel {(x, y)} lies outside the {CELL} px cell")+ img.putpixel((x, y), color)+ return img+++# ---------------------------------------------------------------------------+# Poses: the per-state motion every pet shares.+# ---------------------------------------------------------------------------++FRAME_COUNTS: dict[str, int] = {+ "idle": 8,+ "listening": 4,+ "thinking": 6,+ "talking": 4,+ "success": 6,+ "error": 4,+ "sleeping": 4,+}+FPS: dict[str, int] = {+ "idle": 4,+ "listening": 8,+ "thinking": 8,+ "talking": 10,+ "success": 10,+ "error": 8,+ "sleeping": 2,+}+IDLE_BOB = (0, 0, -1, -1, 0, 0, -1, -1)+IDLE_BLINK_FRAME = 5+HOP = (0, -3, -5, -3, 0, 0)+SHAKE = (-2, 2, -2, 0)+TALK_MOUTHS = ("closed", "half", "open", "half")+++@dataclass(frozen=True)+class Pose:+ state: str+ i: int+ dx: int = 0+ dy: int = 0+ eyes: str = "open"+ mouth: str = "rest"+++def base_pose(state: str, i: int) -> Pose:+ if state == "idle":+ eyes = "closed" if i == IDLE_BLINK_FRAME else "open"+ return Pose(state, i, dy=IDLE_BOB[i], eyes=eyes)+ if state == "listening":+ return Pose(state, i, dy=-1, eyes="wide")+ if state == "thinking":+ return Pose(+ state, i, dy=0 if i < 3 else -1, eyes="up_left" if i < 3 else "up_right", mouth="closed"+ )+ if state == "talking":+ return Pose(state, i, dy=0 if i % 2 == 0 else -1, mouth=TALK_MOUTHS[i])+ if state == "success":+ return Pose(state, i, dy=HOP[i], eyes="happy", mouth="smile")+ if state == "error":+ return Pose(state, i, dx=SHAKE[i], eyes="x", mouth="frown")+ if state == "sleeping":+ return Pose(state, i, dy=1, eyes="sleep", mouth="closed")+ raise KeyError(state)+++# ---------------------------------------------------------------------------+# Face parts every pet draws with its own sizes and colours.+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class EyeStyle:+ w: int+ h: int+ iris: RGBA+ pupil: RGBA | None = None+ glint: RGBA | None = FX_WHITE+ lid: RGBA = OUTLINE+++def _oval(x: int, y: int, w: int, h: int) -> Mask:+ box = rect(x, y, x + w - 1, y + h - 1)+ if w >= 3 and h >= 4:+ box -= {(x, y), (x + w - 1, y), (x, y + h - 1), (x + w - 1, y + h - 1)}+ return box+++def draw_eye(f: Frame, style: str, x: int, y: int, e: EyeStyle, *, right: bool) -> None:+ """One eye in its ``e.w x e.h`` box at ``(x, y)``; ``right`` mirrors asymmetric looks."""+ w, h = e.w, e.h+ mid = y + h // 2+ if style in ("open", "wide", "up_left", "up_right"):+ top, height = (y - 1, h + 1) if style == "wide" else (y, h)+ f.paint(_oval(x, top, w, height), e.iris)+ if e.pupil is not None:+ pw, ph = max(1, w // 2), max(1, (h + 1) // 2)+ if style == "wide":+ ph = max(1, ph - 1)+ px = x + (w - pw) // 2+ py = top + height - ph - 1+ if style.startswith("up"):+ py = top + 1+ px = x if style == "up_left" else x + w - pw+ f.paint(rect(px, py, px + pw - 1, py + ph - 1), e.pupil)+ if e.glint is not None:+ f.paint({(px + pw - 1, py)}, e.glint)+ elif e.glint is not None:+ gx = x + w - 2 if w >= 3 else x + w - 1+ gy = top + 1 if not style.startswith("up") else top+ if style == "up_left":+ gx = x+ f.paint({(gx, gy)}, e.glint)+ elif style == "closed":+ f.paint(rect(x, mid, x + w - 1, mid), e.lid)+ elif style == "sleep":+ f.paint(+ {(x, mid - 1), (x + w - 1, mid - 1)} | rect(x + 1, mid, x + w - 2, mid)+ if w >= 3+ else rect(x, mid, x + w - 1, mid),+ e.lid,+ )+ elif style == "happy":+ f.paint(+ {(x, mid), (x + w - 1, mid)} | rect(x + 1, mid - 1, x + w - 2, mid - 1)+ if w >= 3+ else rect(x, mid - 1, x + w - 1, mid - 1),+ e.lid,+ )+ elif style == "x":+ rows = min(h, 5) | 1+ top = y + (h - rows) // 2+ pixels: Mask = set()+ for r in range(rows):+ step = min(r, rows - 1 - r)+ for c in (step, step + 1):+ if c < w:+ pixels.add((x + w - 1 - c, top + r) if right else (x + c, top + r))+ f.paint(pixels, e.lid)+ else:+ raise KeyError(style)+++def draw_eyes(f: Frame, style: str, left: Px, right: Px, e: EyeStyle) -> None:+ draw_eye(f, style, *left, e, right=False)+ draw_eye(f, style, *right, e, right=True)+++def draw_mouth(+ f: Frame,+ style: str,+ x: int,+ y: int,+ w: int,+ color: RGBA = OUTLINE,+ inside: RGBA = MOUTH_DARK,+) -> None:+ """A mouth ``w`` px wide whose top row is ``y``."""+ if style in ("rest", "smile"):+ f.paint({(x, y), (x + w - 1, y)} | rect(x + 1, y + 1, x + w - 2, y + 1), color)+ elif style == "closed":+ f.paint(rect(x, y + 1, x + w - 1, y + 1), color)+ elif style == "frown":+ f.paint({(x, y + 1), (x + w - 1, y + 1)} | rect(x + 1, y, x + w - 2, y), color)+ elif style == "half":+ f.paint(rect(x, y, x + w - 1, y + 1), inside)+ f.paint(rect(x, y, x + w - 1, y), color)+ elif style == "open":+ f.paint(rect(x, y, x + w - 1, y + 2) - {(x, y + 2), (x + w - 1, y + 2)}, inside)+ f.paint(rect(x + 1, y + 2, x + w - 2, y + 2), TONGUE)+ f.paint(rect(x, y, x + w - 1, y), color)+ else:+ raise KeyError(style)+++# ---------------------------------------------------------------------------+# Effects: sound arcs, thinking dots, sparkles, z marks, the red "!".+# ---------------------------------------------------------------------------++_ARC_S = ((0, -2), (1, -1), (1, 0), (0, 1))+_ARC_M = ((0, -3), (1, -2), (2, -1), (2, 0), (1, 1), (0, 2))+_ARC_L = ((0, -4), (1, -3), (2, -2), (2, -1), (2, 0), (2, 1), (1, 2), (0, 3))+_ARCS = ((0, _ARC_S), (3, _ARC_M), (6, _ARC_L))+#: Which arcs show in listening frame i: a ripple moving outward.+_ARC_PHASES = ((0,), (0, 1), (0, 1, 2), (1, 2))+++def fx_arcs(f: Frame, i: int, left: Px, right: Px) -> None:+ """Sound arcs rippling out from ``left`` (leftwards) and ``right`` (rightwards)."""+ shown: Mask = set()+ for index in _ARC_PHASES[i % len(_ARC_PHASES)]:+ off, arc = _ARCS[index]+ shown |= {(right[0] + off + ax, right[1] + ay) for ax, ay in arc}+ shown |= {(left[0] - off - ax, left[1] + ay) for ax, ay in arc}+ f.paint(shown, ARC)+++def fx_dots(f: Frame, i: int, x: int, y: int) -> None:+ """Three thinking dots starting at ``(x, y)``; one hops per frame."""+ active = i % 3+ dots: dict[Px, RGBA] = {}+ for k in range(3):+ lift = 1 if k == active else 0+ color = FX_WHITE if k == active else FX_DIM+ for p in rect(x + 4 * k, y - lift, x + 4 * k + 1, y - lift + 1):+ dots[p] = color+ f.part(set(dots), dots)+++_SPARK_S = (".#.", "#o#", ".#.")+_SPARK_L = ("..#..", "..#..", "##o##", "..#..", "..#..")+_SPARK_PALETTE = {"#": SPARK, "o": SPARK_CORE}+++def fx_sparkles(f: Frame, i: int, spots: Sequence[tuple[int, int, int]]) -> None:+ """Sparkles at ``(x, y, first_frame)`` centres: small, big, then small again."""+ for x, y, start in spots:+ age = i - start+ if age < 0:+ continue+ rows = _SPARK_L if age in (1, 2) else _SPARK_S+ half = len(rows) // 2+ f.glyph(x - half, y - half, rows, _SPARK_PALETTE)+++_Z_SMALL = ("####", "..#.", ".#..", "####")+_Z_BIG = ("#####", "...#.", "..#..", ".#...", "#####")+_Z_PALETTE = {"#": Z_BLUE}+#: (dx, dy, glyph) of each z relative to the anchor, lowest first.+_ZS = ((0, 0, _Z_SMALL), (5, -6, _Z_BIG), (2, -12, _Z_SMALL))+#: Which z marks show in sleeping frame i: they rise one by one.+_Z_PHASES = ((0,), (0, 1), (0, 1, 2), (1, 2))+++def fx_zzz(f: Frame, i: int, x: int, y: int) -> None:+ for index in _Z_PHASES[i % len(_Z_PHASES)]:+ dx, dy, rows = _ZS[index]+ f.glyph(x + dx, y + dy, rows, _Z_PALETTE)+++_BANG = ("##", "##", "##", "##", "..", "##")+++def fx_bang(f: Frame, x: int, y: int) -> None:+ f.glyph(x, y, _BANG, {"#": RED})+++@dataclass(frozen=True)+class Anchors:+ """Where a pet's effects go (cell coordinates, before the pose offset)."""++ arcs_left: Px+ arcs_right: Px+ dots: Px+ zzz: Px+ bang: Px+ sparkles: tuple[tuple[int, int, int], ...]+++def draw_effects(f: Frame, pose: Pose, a: Anchors) -> None:+ """The state's shared effect; it moves with the body's bob but not its hop."""+ if pose.state == "listening":+ with f.offset(pose.dx, pose.dy):+ fx_arcs(f, pose.i, a.arcs_left, a.arcs_right)+ elif pose.state == "thinking":+ with f.offset(pose.dx, pose.dy):+ fx_dots(f, pose.i, *a.dots)+ elif pose.state == "success":+ fx_sparkles(f, pose.i, a.sparkles)+ elif pose.state == "error":+ fx_bang(f, *a.bang)+ elif pose.state == "sleeping":+ fx_zzz(f, pose.i, *a.zzz)+++# ---------------------------------------------------------------------------+# The pets.+# ---------------------------------------------------------------------------+++Effect = Callable[[Frame, Pose], None]+++@dataclass(frozen=True)+class PetDesign:+ id: str+ name: str+ description: str+ draw: Callable[[Frame, Pose], None]+ anchors: Anchors+ pose: Callable[[str, int], Pose] = base_pose+ frame_counts: Mapping[str, int] | None = None+ fps: Mapping[str, int] | None = None+ #: Per-state effects that replace the shared one (a pet's own motif).+ fx: Mapping[str, Effect] = field(default_factory=dict)++ def counts(self) -> Mapping[str, int]:+ return {**FRAME_COUNTS, **(self.frame_counts or {})}+++# -- Gigi: the Jarvis ghost ---------------------------------------------------++GIGI_BODY = hexc("#262a33")+GIGI_RIM = hexc("#e2ad3a")+GIGI_PLATE = hexc("#14161c")+GIGI_GLOSS = hexc("#4d5465")+GIGI_BELT = hexc("#9a7a30")+GIGI_GOLD = hexc("#ffcf45")+GIGI_EYES = EyeStyle(+ w=4, h=6, iris=GIGI_GOLD, pupil=hexc("#0b0c10"), glint=hexc("#fffbe6"), lid=GIGI_GOLD+)+++def _gigi_body(phase: int) -> Mask:+ dome = {p for p in ellipse(CX, 25, 14, 14) if p[1] <= 24}+ torso = rect(10, 25, 37, 38)+ teeth: Mask = set()+ for k in range(4):+ apex = 13 + 7 * k + phase+ for r in range(4):+ for x in range(apex - (3 - r), apex + (3 - r) + 1):+ if 10 <= x <= 37:+ teeth.add((x, 39 + r))+ return dome | torso | teeth+++_GIGI_ARMS = {+ "rest": from_rows(6, 29, ("###.", "####", "####", ".###")),+ "up": from_rows(5, 19, ("##..", "###.", ".###", "..##")),+ "droop": from_rows(7, 32, ("###", "###", "###", ".##")),+}+++def _gigi_arm_style(pose: Pose) -> str:+ return {"success": "up", "sleeping": "droop"}.get(pose.state, "rest")+++def draw_gigi(f: Frame, pose: Pose) -> None:+ phase = (pose.i // 2) % 2 if pose.state in ("idle", "sleeping") else pose.i % 2+ with f.offset(pose.dx, pose.dy):+ arm = _GIGI_ARMS[_gigi_arm_style(pose)]+ f.part(arm, GIGI_GOLD)+ f.part(mirrored(arm), GIGI_GOLD)+ body = _gigi_body(phase)+ f.part(body, shade(body, GIGI_BODY, rim=GIGI_RIM))+ f.paint(ellipse(CX, 22, 10, 7), GIGI_PLATE)+ f.paint({(14, 16), (15, 15), (16, 14), (17, 14), (18, 13)}, GIGI_GLOSS)+ f.paint(rect(11, 31, 36, 31), GIGI_BELT)+ draw_eyes(f, pose.eyes, (17, 18), (27, 18), GIGI_EYES)+ _gigi_mouth(f, pose.mouth)+++def _gigi_mouth(f: Frame, style: str) -> None:+ ring = from_rows(22, 34, (".##.", "#..#", ".##."))+ if style == "rest":+ f.paint(ring, GIGI_GOLD)+ elif style == "closed":+ f.paint(rect(22, 35, 25, 35), GIGI_GOLD)+ elif style == "half":+ f.paint(ring, GIGI_GOLD)+ f.paint(rect(23, 35, 24, 35), GIGI_PLATE)+ elif style == "open":+ big = from_rows(22, 33, (".##.", "#..#", "#..#", "#..#", ".##."))+ f.paint(rect(23, 34, 24, 36), GIGI_PLATE)+ f.paint(big, GIGI_GOLD)+ elif style == "smile":+ f.paint(from_rows(21, 34, ("#....#", ".####.")), GIGI_GOLD)+ elif style == "frown":+ f.paint(from_rows(21, 34, (".####.", "#....#")), GIGI_GOLD)+ else:+ raise KeyError(style)+++GIGI = PetDesign(+ id="gigi",+ name="Gigi",+ description="The Jarvis ghost, eight bits tall, with glowing golden eyes.",+ draw=draw_gigi,+ anchors=Anchors(+ arcs_left=(10, 15),+ arcs_right=(37, 15),+ dots=(19, 5),+ zzz=(37, 14),+ bang=(40, 5),+ sparkles=((6, 12, 1), (41, 9, 2), (5, 32, 3), (42, 30, 3)),+ ),+)+++def _shade(mask: Mask, base: RGBA, light: RGBA, dark: RGBA, depth: int = 2) -> dict[Px, RGBA]:+ return shade(mask, base, light=light, dark=dark, dark_depth=depth)+++# -- Miso: the cat ------------------------------------------------------------++MISO_FUR = hexc("#f2a65a")+MISO_LIGHT = hexc("#ffd08f")+MISO_DARK = hexc("#c8743a")+MISO_CREAM = hexc("#fff0d9")+MISO_EAR = hexc("#ff9fb2")+MISO_STRIPE = hexc("#a95a26")+MISO_NOSE = hexc("#ff7a8a")+MISO_EYES = EyeStyle(w=3, h=4, iris=hexc("#6fcf7f"), pupil=hexc("#123524"), glint=FX_WHITE)++#: Left ear tip per look; the ear's base sits on the head outline.+_MISO_EAR_TIPS: dict[str, tuple[float, float]] = {+ "rest": (13.5, 5.5),+ "perk": (12.5, 2.5),+ "flat": (8.5, 11.5),+}+++def _miso_ear(tip: tuple[float, float]) -> Mask:+ return polygon([(11.5, 18.0), tip, (21.5, 12.5)])+++def _miso_tail(sway: int) -> Mask:+ return thick(polyline([(33, 41), (37, 40), (40, 37), (41 + sway, 33), (40 + sway, 29)]))+++def draw_miso(f: Frame, pose: Pose) -> None:+ if pose.state == "sleeping":+ _draw_miso_curled(f, pose)+ return+ ear_look = {"listening": "perk", "error": "flat"}.get(pose.state, "rest")+ swaying = pose.state in ("idle", "listening", "talking")+ sway = (0, 1, 1, 0)[(pose.i // 2) % 4] if swaying else 0+ with f.offset(pose.dx, pose.dy):+ tail = _miso_tail(sway)+ f.part(tail, _shade(tail, MISO_FUR, MISO_LIGHT, MISO_DARK, 1))+ body = ellipse(CX, 37, 10, 7)+ f.part(body, _shade(body, MISO_FUR, MISO_LIGHT, MISO_DARK))+ f.paint(ellipse(CX, 38, 5, 4), MISO_CREAM)+ paw = ellipse(19.5, 43, 3, 2)+ f.part(paw, MISO_CREAM)+ f.part(mirrored(paw), MISO_CREAM)+ ear = _miso_ear(_MISO_EAR_TIPS[ear_look])+ for mask in (ear, mirrored(ear)):+ f.part(mask, _shade(mask, MISO_FUR, MISO_LIGHT, MISO_DARK, 1))+ f.paint(eroded(mask, 2), MISO_EAR)+ head = ellipse(CX, 22, 13, 10)+ f.part(head, _shade(head, MISO_FUR, MISO_LIGHT, MISO_DARK))+ stripes = rect(23, 13, 24, 15) | rect(19, 14, 20, 15)+ f.paint(stripes | mirrored(stripes), MISO_STRIPE)+ f.paint(ellipse(CX, 27, 5, 3), MISO_CREAM)+ whiskers = line(12, 25, 16, 26) | line(12, 28, 16, 27)+ f.paint(whiskers | mirrored(whiskers), MISO_DARK)+ draw_eyes(f, pose.eyes, (16, 19), (29, 19), MISO_EYES)+ f.paint(rect(23, 25, 24, 25), MISO_NOSE)+ draw_mouth(f, pose.mouth, 22, 26, 4)+++def _draw_miso_curled(f: Frame, pose: Pose) -> None:+ """Asleep: a loaf with the head tucked on the front paws and the tail wrapped round."""+ with f.offset(pose.dx, pose.dy):+ loaf = ellipse(CX, 37, 16, 7)+ f.part(loaf, _shade(loaf, MISO_FUR, MISO_LIGHT, MISO_DARK))+ f.paint(rect(29, 32, 30, 34) | rect(34, 33, 35, 35), MISO_STRIPE)+ tail = thick(polyline([(39, 38), (36, 42), (28, 43), (19, 43)]))+ f.part(tail, _shade(tail, MISO_FUR, MISO_LIGHT, MISO_DARK, 1))+ for ear in (+ polygon([(8.5, 30.5), (9.5, 22.5), (14.5, 26.5)]),+ polygon([(19.5, 26.5), (23.5, 21.5), (25.5, 29.5)]),+ ):+ f.part(ear, _shade(ear, MISO_FUR, MISO_LIGHT, MISO_DARK, 1))+ f.paint(eroded(ear, 2), MISO_EAR)+ head = ellipse(17, 32, 9, 7)+ f.part(head, _shade(head, MISO_FUR, MISO_LIGHT, MISO_DARK))+ f.paint(ellipse(16.5, 35, 4, 2), MISO_CREAM)+ draw_eye(f, "sleep", 11, 30, MISO_EYES, right=False)+ draw_eye(f, "sleep", 19, 30, MISO_EYES, right=True)+ f.paint(rect(16, 34, 17, 34), MISO_NOSE)+++MISO = PetDesign(+ id="miso",+ name="Miso",+ description="A ginger cat whose ears perk up when you talk and who naps curled in a loaf.",+ draw=draw_miso,+ anchors=Anchors(+ arcs_left=(10, 18),+ arcs_right=(37, 18),+ dots=(19, 3),+ zzz=(31, 22),+ bang=(40, 4),+ sparkles=((6, 12, 1), (41, 9, 2), (5, 32, 3), (42, 30, 3)),+ ),+)+++# -- Brew: the teapot -----------------------------------------------------------++BREW_BASE = hexc("#6cc7b3")+BREW_LIGHT = hexc("#a9ecdc")+BREW_DARK = hexc("#3e8f80")+BREW_RIM = hexc("#2c6d62")+BREW_GOLD = hexc("#ffcf45")+BREW_STEAM = hexc("#e8eef7")+BREW_BLUSH = hexc("#ff8fa3")+BREW_INK = hexc("#22303a")+BREW_EYES = EyeStyle(w=3, h=4, iris=BREW_INK, glint=FX_WHITE, lid=BREW_INK)+#: Brew's face is centred on column 22 (the spout takes the right side).+BREW_AXIS = 22+++def _brew_lid_lift(pose: Pose) -> int:+ if pose.state == "talking" and pose.i % 2 == 1:+ return 2+ if pose.state == "success" and pose.i in (1, 2, 3):+ return 2+ return 0+++def draw_brew(f: Frame, pose: Pose) -> None:+ with f.offset(pose.dx, pose.dy):+ ring = ellipse(9, 31, 6, 6) - ellipse(9, 31, 3, 3)+ handle = {p for p in ring if p[0] <= 11}+ f.part(handle, _shade(handle, BREW_BASE, BREW_LIGHT, BREW_DARK, 1))+ spout = polygon([(32, 29), (35, 34), (44.5, 22.5), (42.5, 19.5)])+ f.part(spout, _shade(spout, BREW_BASE, BREW_LIGHT, BREW_DARK, 1))+ f.paint({(43, 20), (42, 20)}, BREW_RIM)+ foot = rect(16, 41, 28, 43)+ f.part(foot, _shade(foot, BREW_BASE, BREW_LIGHT, BREW_DARK, 1))+ body = ellipse(BREW_AXIS, 32, 13, 10)+ f.part(body, _shade(body, BREW_BASE, BREW_LIGHT, BREW_DARK, 3))+ f.paint({(14, 26), (15, 25), (16, 25)}, FX_WHITE)+ f.paint(rect(13, 22, 30, 23), BREW_RIM)+ with f.offset(0, -_brew_lid_lift(pose)):+ dome = {p for p in ellipse(BREW_AXIS, 23, 9, 5) if p[1] <= 21}+ f.part(dome, _shade(dome, BREW_BASE, BREW_LIGHT, BREW_DARK, 1))+ f.part(ellipse(BREW_AXIS, 16, 2, 2), BREW_GOLD)+ draw_eyes(f, pose.eyes, (15, 28), (26, 28), BREW_EYES)+ f.paint(rect(12, 33, 13, 33) | rect(30, 33, 31, 33), BREW_BLUSH)+ draw_mouth(f, pose.mouth, 20, 34, 4, color=BREW_INK)+++def _brew_puffs(f: Frame, puffs: Iterable[tuple[int, int, bool]]) -> None:+ for x, y, big in puffs:+ f.part(ellipse(x, y, 1.6, 1.6) if big else rect(x, y, x + 1, y + 1), BREW_STEAM)+++def brew_thinking(f: Frame, pose: Pose) -> None:+ """Thinking dots plus slow steam rising from the spout."""+ with f.offset(pose.dx, pose.dy):+ fx_dots(f, pose.i, 14, 7)+ puffs = []+ for k in range(3):+ phase = (pose.i + 2 * k) % 6+ puffs.append((42 + phase % 2, 16 - 2 * phase, phase >= 2))+ _brew_puffs(f, puffs)+++def brew_talking(f: Frame, pose: Pose) -> None:+ """The whistle: a quick jet of steam from the spout while the lid rattles."""+ with f.offset(pose.dx, pose.dy):+ if pose.i % 2:+ _brew_puffs(f, ((43, 16, False), (44, 12, True)))+ else:+ _brew_puffs(f, ((43, 16, True), (45, 12, False)))+++BREW = PetDesign(+ id="brew",+ name="Brew",+ description="A little teapot that steams while it thinks and whistles when it answers.",+ draw=draw_brew,+ anchors=Anchors(+ arcs_left=(11, 17),+ arcs_right=(32, 17),+ dots=(14, 7),+ zzz=(31, 14),+ bang=(38, 4),+ sparkles=((5, 14, 1), (40, 10, 2), (4, 40, 3), (41, 34, 3)),+ ),+ fx={"thinking": brew_thinking, "talking": brew_talking},+)+++# -- Bolt: the battery ----------------------------------------------------------++BOLT_CASE = (hexc("#3fa7d6"), hexc("#86d3f2"), hexc("#2a78a3"))+#: Asleep the battery is flat: the same casing, dimmed.+BOLT_CASE_FLAT = (hexc("#2f6f90"), hexc("#4f8fae"), hexc("#23516a"))+BOLT_METAL = hexc("#cfd4de")+BOLT_METAL_DARK = hexc("#8d95a6")+BOLT_WINDOW = hexc("#1c2733")+BOLT_GREEN = hexc("#6ee07a")+BOLT_EYES = EyeStyle(w=4, h=5, iris=FX_WHITE, pupil=OUTLINE, glint=None, lid=OUTLINE)+BOLT_THINK_FRAMES = 8+#: Charge segments lit per state (0-4); thinking fills up frame by frame.+BOLT_LEVELS: dict[str, int] = {+ "idle": 3,+ "listening": 3,+ "talking": 3,+ "success": 4,+ "error": 1,+ "sleeping": 0,+}+BOLT_THINK_LEVELS = (1, 1, 2, 2, 3, 3, 4, 4)+++def bolt_pose(state: str, i: int) -> Pose:+ if state == "thinking":+ early = i < BOLT_THINK_FRAMES // 2+ return Pose(+ state, i, dy=0 if early else -1, eyes="up_left" if early else "up_right", mouth="closed"+ )+ return base_pose(state, i)+++def _bolt_segment(k: int) -> Mask:+ top = 38 - 4 * k+ return rect(18, top, 29, top + 2)+++def draw_bolt(f: Frame, pose: Pose) -> None:+ base, light, dark = BOLT_CASE_FLAT if pose.state == "sleeping" else BOLT_CASE+ if pose.state == "thinking":+ level = BOLT_THINK_LEVELS[pose.i % len(BOLT_THINK_LEVELS)]+ else:+ level = BOLT_LEVELS[pose.state]+ with f.offset(pose.dx, pose.dy):+ if pose.state == "success":+ arm = rounded_rect(8, 17, 11, 23, 1) # arms up+ else:+ arm = rounded_rect(9, 26, 12, 31, 1)+ f.part(arm, _shade(arm, BOLT_METAL, FX_WHITE, BOLT_METAL_DARK, 1))+ f.part(mirrored(arm), _shade(mirrored(arm), BOLT_METAL, FX_WHITE, BOLT_METAL_DARK, 1))+ feet = rect(16, 44, 20, 45)+ f.part(feet | mirrored(feet), BOLT_METAL_DARK)+ cap = rounded_rect(19, 7, 28, 10, 1)+ f.part(cap, _shade(cap, BOLT_METAL, FX_WHITE, BOLT_METAL_DARK, 1))+ case = rounded_rect(13, 11, 34, 43, 2)+ f.part(case, _shade(case, base, light, dark))+ f.paint(rounded_rect(16, 24, 31, 41, 1), BOLT_WINDOW)+ color = BOLT_GREEN if level >= 3 else SPARK if level == 2 else RED+ for k in range(level):+ f.paint(_bolt_segment(k), color)+ if pose.state == "sleeping" and pose.i % 2 == 0:+ f.paint(outer_ring(eroded(_bolt_segment(0))) & _bolt_segment(0), RED)+ draw_eyes(f, pose.eyes, (17, 14), (27, 14), BOLT_EYES)+ draw_mouth(f, pose.mouth, 22, 20, 4)+++_BOLT_GLYPH = ("..##", ".##.", "####", ".##.", "##..", "#...")+++def bolt_thinking(f: Frame, pose: Pose) -> None:+ """A little lightning bolt that flickers while the charge fills up."""+ with f.offset(pose.dx, pose.dy):+ tint = SPARK if pose.i % 2 == 0 else SPARK_CORE+ f.glyph(37, 3, _BOLT_GLYPH, {"#": tint})+++BOLT = PetDesign(+ id="bolt",+ name="Bolt",+ description="A plucky battery that charges up while it thinks and runs flat when it sleeps.",+ draw=draw_bolt,+ anchors=Anchors(+ arcs_left=(12, 15),+ arcs_right=(35, 15),+ dots=(19, 2),+ zzz=(36, 14),+ bang=(38, 3),+ sparkles=((6, 10, 1), (41, 8, 2), (5, 36, 3), (42, 34, 3)),+ ),+ pose=bolt_pose,+ frame_counts={"thinking": BOLT_THINK_FRAMES},+ fx={"thinking": bolt_thinking},+)+++# -- Mochi: the jelly blob --------------------------------------------------------++MOCHI_BASE = hexc("#ff9fcb")+MOCHI_LIGHT = hexc("#ffd3e8")+MOCHI_DARK = hexc("#e06aa2")+MOCHI_BLUSH = hexc("#ff5f9a")+MOCHI_INK = hexc("#3b1f2b")+MOCHI_EYES = EyeStyle(w=3, h=4, iris=MOCHI_INK, glint=FX_WHITE, lid=MOCHI_INK)++#: (wider, lower, sway) per listening frame: the wobble.+_MOCHI_WOBBLE = ((0, 0, 0), (1, 1, 1), (0, 0, 0), (-1, -1, -1))+#: (wider, lower) per talking frame: squish with every syllable.+_MOCHI_SQUISH = ((0, 0), (1, 1), (2, 2), (1, 1))+++def mochi_pose(state: str, i: int) -> Pose:+ pose = base_pose(state, i)+ if state == "talking":+ # Mochi squishes instead of bobbing: the body gets lower, not higher.+ return Pose(state, i, mouth=pose.mouth)+ return pose+++def _mochi_shape(pose: Pose) -> tuple[int, int, int]:+ """(wider, lower, sway) of the blob for this frame."""+ if pose.state == "listening":+ return _MOCHI_WOBBLE[pose.i % len(_MOCHI_WOBBLE)]+ if pose.state == "talking":+ return (*_MOCHI_SQUISH[pose.i % len(_MOCHI_SQUISH)], 0)+ if pose.state == "success":+ if pose.dy < 0:+ return (-1, -2, 0)+ return (2, 2, 0) if pose.i == 4 else (0, 0, 0)+ if pose.state == "sleeping":+ return (2, 3, 0)+ if pose.state == "idle" and pose.dy < 0:+ return (-1, -1, 0)+ return (0, 0, 0)+++def _mochi_body(wider: int, lower: int, sway: int) -> Mask:+ """A daifuku-round blob; ``sway`` leans its soft dome sideways."""+ blob = {p for p in ellipse(CX, 33, 15 + wider, 11 - lower) if p[1] <= 43}+ dome = ellipse(CX + sway, 28 + lower, 11 + max(0, wider), 7)+ return blob | dome+++def draw_mochi(f: Frame, pose: Pose) -> None:+ wider, lower, sway = _mochi_shape(pose)+ with f.offset(pose.dx, pose.dy):+ body = _mochi_body(wider, lower, sway)+ f.part(body, _shade(body, MOCHI_BASE, MOCHI_LIGHT, MOCHI_DARK, 3))+ glint = {(15, 25 + lower), (16, 24 + lower), (17, 24 + lower), (14, 26 + lower)}+ f.paint(glint & eroded(body, 1), FX_WHITE)+ eye_y = 30 + max(0, lower) // 2+ draw_eyes(f, pose.eyes, (17, eye_y), (28, eye_y), MOCHI_EYES)+ blush = rect(13, eye_y + 4, 15, eye_y + 4)+ f.paint(blush | mirrored(blush), MOCHI_BLUSH)+ draw_mouth(f, pose.mouth, 22, eye_y + 5, 4, color=MOCHI_INK)+++MOCHI = PetDesign(+ id="mochi",+ name="Mochi",+ description="A soft jelly blob that wobbles when it listens and squishes when it talks.",+ draw=draw_mochi,+ anchors=Anchors(+ arcs_left=(8, 24),+ arcs_right=(39, 24),+ dots=(19, 15),+ zzz=(34, 17),+ bang=(39, 7),+ sparkles=((6, 14, 1), (41, 12, 2), (4, 38, 3), (43, 36, 3)),+ ),+ pose=mochi_pose,+)+++# -- Shelly: the snail ------------------------------------------------------------++SHELLY_BODY = hexc("#c3de7a")+SHELLY_BODY_LIGHT = hexc("#e3f4a9")+SHELLY_BODY_DARK = hexc("#8eae4c")+SHELLY_SHELL = hexc("#e08a4f")+SHELLY_SHELL_LIGHT = hexc("#f5b884")+SHELLY_SHELL_DARK = hexc("#a95a2c")+SHELLY_SPIRAL = hexc("#6b3417")+SHELLY_BLUSH = hexc("#ff8fa3")+SHELLY_EYES = EyeStyle(w=5, h=5, iris=FX_WHITE, pupil=OUTLINE, glint=None, lid=OUTLINE)++#: Eye-stalk tips (left, right) per look; the stalks grow from the head top.+_SHELLY_TIPS: dict[str, tuple[Px, Px]] = {+ "rest": ((8, 15), (17, 14)),+ "perk": ((7, 12), (18, 11)),+ "droop": ((5, 20), (19, 19)),+}+_SHELLY_STALK_BASES: tuple[Px, Px] = ((10, 26), (15, 26))+_SHELLY_OPEN_EYES = ("open", "wide", "up_left", "up_right")+++def _spiral(cx: float, cy: float, phase: float, r_max: float = 8.5, turns: float = 2.25) -> Mask:+ """A 1 px Archimedean spiral; values are rounded before flooring so the+ same pixels come out on every platform's libm."""+ out: Mask = set()+ steps = 160+ for s in range(steps + 1):+ t = s / steps+ r = 1.0 + (r_max - 1.0) * t+ a = phase + 2.0 * math.pi * turns * t+ x = math.floor(round(cx + r * math.cos(a), 6))+ y = math.floor(round(cy + r * math.sin(a), 6))+ out.add((x, y))+ return out+++#: Pupil offset inside the 5 x 5 eyeball per look; Shelly faces left.+_SHELLY_PUPILS: dict[str, Px] = {+ "open": (1, 2),+ "wide": (1, 2),+ "up_left": (0, 0),+ "up_right": (3, 0),+}+++def _shelly_eye(f: Frame, style: str, tip: Px, *, right: bool) -> None:+ x, y = tip[0] - 2, tip[1] - 2+ ball = _oval(x, y, 5, 5)+ if style in _SHELLY_OPEN_EYES:+ f.part(ball, FX_WHITE)+ dx, dy = _SHELLY_PUPILS[style]+ f.paint(rect(x + dx, y + dy, x + dx + 1, y + dy + 1), OUTLINE)+ return+ f.part(ball, SHELLY_BODY)+ draw_eye(f, style, x, y, SHELLY_EYES, right=right)+++def draw_shelly(f: Frame, pose: Pose) -> None:+ if pose.state == "sleeping":+ _draw_shelly_withdrawn(f, pose)+ return+ look = {"listening": "perk", "success": "perk", "error": "droop"}.get(pose.state, "rest")+ sway = (0, 1, 1, 0)[(pose.i // 2) % 4] if pose.state == "idle" else 0+ tips = tuple((x + sway, y) for x, y in _SHELLY_TIPS[look])+ phase = -pose.i * (2.0 * math.pi / 6.0) if pose.state == "thinking" else 0.0+ with f.offset(pose.dx, pose.dy):+ for base, tip in zip(_SHELLY_STALK_BASES, tips, strict=True):+ f.part(line(*base, *tip), SHELLY_BODY)+ body = ellipse(26, 41, 17, 3.2) | ellipse(13, 33, 6, 8)+ f.part(body, _shade(body, SHELLY_BODY, SHELLY_BODY_LIGHT, SHELLY_BODY_DARK, 1))+ shell = ellipse(28, 28, 11, 11)+ f.part(shell, _shade(shell, SHELLY_SHELL, SHELLY_SHELL_LIGHT, SHELLY_SHELL_DARK))+ f.paint(_spiral(28.0, 28.0, phase) & eroded(shell, 1), SHELLY_SPIRAL)+ f.paint(rect(12, 37, 13, 37), SHELLY_BLUSH)+ draw_mouth(f, pose.mouth, 8, 34, 3)+ _shelly_eye(f, pose.eyes, tips[0], right=False)+ _shelly_eye(f, pose.eyes, tips[1], right=True)+++def _draw_shelly_withdrawn(f: Frame, pose: Pose) -> None:+ """Asleep: tucked into the shell, only a sliver of foot peeking out."""+ with f.offset(pose.dx, pose.dy):+ foot = ellipse(26, 43, 13, 1.6)+ f.part(foot, SHELLY_BODY_DARK)+ shell = ellipse(26, 32, 11, 10.5)+ f.part(shell, _shade(shell, SHELLY_SHELL, SHELLY_SHELL_LIGHT, SHELLY_SHELL_DARK))+ f.paint(_spiral(26.0, 32.0, 0.0, r_max=8.0) & eroded(shell, 1), SHELLY_SPIRAL)+ f.paint(ellipse(17.5, 38.5, 2, 2) & shell, SHELLY_SPIRAL)+++SHELLY = PetDesign(+ id="shelly",+ name="Shelly",+ description="A patient snail whose shell spins while it thinks and who hides inside to sleep.",+ draw=draw_shelly,+ anchors=Anchors(+ arcs_left=(8, 6),+ arcs_right=(21, 7),+ dots=(27, 8),+ zzz=(35, 15),+ bang=(40, 4),+ sparkles=((3, 26, 1), (41, 10, 2), (3, 40, 3), (44, 28, 3)),+ ),+)++PETS: tuple[PetDesign, ...] = (GIGI, MISO, BREW, BOLT, MOCHI, SHELLY)+++# ---------------------------------------------------------------------------+# Sheets, manifests and the template.+# ---------------------------------------------------------------------------+++def render_frame(pet: PetDesign, state: str, i: int) -> Image.Image:+ pose = pet.pose(state, i)+ f = Frame()+ pet.draw(f, pose)+ own = pet.fx.get(state)+ if own is not None:+ own(f, pose)+ else:+ draw_effects(f, pose, pet.anchors)+ return f.image()+++def build_sheet(pet: PetDesign) -> Image.Image:+ sheet = Image.new("RGBA", (CELL * MAX_FRAMES_PER_STATE, CELL * len(PET_STATES)), (0, 0, 0, 0))+ counts = pet.counts()+ for row, state in enumerate(PET_STATES):+ for i in range(counts[state]):+ sheet.paste(render_frame(pet, state, i), (i * CELL, row * CELL))+ return sheet+++def build_manifest(pet: PetDesign) -> dict:+ counts = pet.counts()+ fps = {**FPS, **(pet.fps or {})}+ return {+ "format": PET_FORMAT,+ "id": pet.id,+ "name": pet.name,+ "description": pet.description,+ "frame_size": CELL,+ "sheet": "sheet.png",+ "animations": {+ state: {+ "row": row,+ "frames": counts[state],+ "fps": fps[state],+ "loop": state not in ONE_SHOT_STATES,+ }+ for row, state in enumerate(PET_STATES)+ },+ }+++#: Row tints of the template, one per state (alpha stays below the loader's+#: opacity threshold, so an untouched cell reads as empty).+TEMPLATE_TINTS: dict[str, tuple[int, int, int]] = {+ "idle": (148, 163, 184),+ "listening": (56, 189, 248),+ "thinking": (167, 139, 250),+ "talking": (52, 211, 153),+ "success": (250, 204, 21),+ "error": (248, 113, 113),+ "sleeping": (129, 140, 248),+}+TEMPLATE_ALPHA = (40, 64)+++def build_template() -> tuple[Image.Image, dict]:+ """A transparent sheet with a faint tint band per state row and alternating cells."""+ sheet = Image.new("RGBA", (CELL * MAX_FRAMES_PER_STATE, CELL * len(PET_STATES)), (0, 0, 0, 0))+ for row, state in enumerate(PET_STATES):+ for col in range(MAX_FRAMES_PER_STATE):+ alpha = TEMPLATE_ALPHA[(row + col) % 2]+ cell = Image.new("RGBA", (CELL, CELL), (*TEMPLATE_TINTS[state], alpha))+ sheet.paste(cell, (col * CELL, row * CELL))+ manifest = {+ "format": PET_FORMAT,+ "id": "template",+ "name": "My pet",+ "description": "Draw one state per row, frames from left to right.",+ "frame_size": CELL,+ "sheet": "template.png",+ "animations": {+ state: {+ "row": row,+ "frames": FRAME_COUNTS[state],+ "fps": FPS[state],+ "loop": state not in ONE_SHOT_STATES,+ }+ for row, state in enumerate(PET_STATES)+ },+ }+ return sheet, manifest+++def save_png(image: Image.Image, path: Path) -> None:+ """Fixed encoder settings and no metadata chunks: the same pixels give the same bytes."""+ image.save(path, format="PNG", optimize=False, compress_level=9)+++def save_json(data: dict, path: Path) -> None:+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8", newline="\n")+++def build_all(out_dir: Path) -> list[Path]:+ """Write ``out_dir/builtin/<id>/`` for every pet and ``out_dir/template/``."""+ written: list[Path] = []+ for pet in PETS:+ folder = out_dir / "builtin" / pet.id+ folder.mkdir(parents=True, exist_ok=True)+ save_png(build_sheet(pet), folder / "sheet.png")+ save_json(build_manifest(pet), folder / "pet.json")+ written += [folder / "sheet.png", folder / "pet.json"]+ folder = out_dir / "template"+ folder.mkdir(parents=True, exist_ok=True)+ sheet, manifest = build_template()+ save_png(sheet, folder / "template.png")+ save_json(manifest, folder / "template.json")+ written += [folder / "template.png", folder / "template.json"]+ return written+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument(+ "--out",+ type=Path,+ default=REPO_ROOT / "jarvis" / "ui" / "pets",+ help="folder that receives builtin/ and template/ (default: the package)",+ )+ args = parser.parse_args(argv)+ for path in build_all(args.out):+ print(path)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/pets/contact_sheet.py b/scripts/pets/contact_sheet.pynew file mode 100644index 0000000000..6f38e7575c--- /dev/null+++ b/scripts/pets/contact_sheet.py@@ -0,0 +1,117 @@+#!/usr/bin/env python3+"""Render every built-in pet x state x frame for a visual check.++Frames go through the REAL runtime path: :func:`jarvis.ui.pets.loader.load_pet`+decodes the committed sheet and :func:`~jarvis.ui.pets.loader.to_color_key`+scales it onto the overlay's colour key, which is then replaced by a dark+(``#1e1e1e``) and a light (``#f2f2f2``) desktop colour. One PNG per background.++Usage::++ python scripts/pets/contact_sheet.py --out DIR [--scale 4] [--pets gigi,miso] [--split]++``--split`` additionally writes one image per pet and background, which is+easier to inspect than the tall combined sheet.+"""++from __future__ import annotations++import argparse+import sys+from collections.abc import Sequence+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[2]+# Run from anywhere: import THIS checkout's jarvis, never an installed copy.+sys.path.insert(0, str(REPO_ROOT))++from PIL import Image, ImageChops, ImageDraw, ImageFont # noqa: E402++from jarvis.ui.pets.loader import ( # noqa: E402+ COLOR_KEY,+ PetPack,+ builtin_root,+ list_pets,+ load_pet,+ to_color_key,+)+from jarvis.ui.pets.states import MAX_FRAMES_PER_STATE, PET_STATES # noqa: E402++BACKGROUNDS: dict[str, tuple[int, int, int]] = {+ "dark": (0x1E, 0x1E, 0x1E),+ "light": (0xF2, 0xF2, 0xF2),+}+LABEL_WIDTH = 150+GAP = 6+++def _keyed_to_background(keyed: Image.Image, background: tuple[int, int, int]) -> Image.Image:+ """Replace the exact colour key with ``background`` (what the overlay window does)."""+ mask = Image.new("L", keyed.size, 255)+ for channel, value in zip(keyed.split(), COLOR_KEY, strict=True):+ hit = channel.point(lambda v, value=value: 255 if v == value else 0)+ mask = ImageChops.multiply(mask, hit)+ out = keyed.copy()+ out.paste(background, mask=mask)+ return out+++def render(packs: Sequence[PetPack], background: tuple[int, int, int], scale: int) -> Image.Image:+ cell = 48 * scale+ rows = len(packs) * len(PET_STATES)+ width = LABEL_WIDTH + MAX_FRAMES_PER_STATE * (cell + GAP)+ height = rows * (cell + GAP) + GAP+ sheet = Image.new("RGB", (width, height), background)+ draw = ImageDraw.Draw(sheet)+ font = ImageFont.load_default()+ ink = (230, 230, 230) if sum(background) < 384 else (40, 40, 40)+ row = 0+ for pack in packs:+ for state in PET_STATES:+ top = GAP + row * (cell + GAP)+ resolved, spec = pack.manifest.spec_for(state)+ label = f"{pack.manifest.id}\n{state}\n{spec.frames}f @ {spec.fps}fps"+ if resolved != state:+ label += f"\n(uses {resolved})"+ draw.multiline_text((8, top + 8), label, fill=ink, font=font)+ for col, frame in enumerate(pack.frames[state]):+ frame_size = pack.manifest.frame_size+ keyed = to_color_key(frame, scale * 48 // frame_size)+ tile = _keyed_to_background(keyed, background)+ sheet.paste(tile, (LABEL_WIDTH + col * (cell + GAP), top))+ row += 1+ return sheet+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--out", type=Path, required=True, help="output folder")+ parser.add_argument("--scale", type=int, default=4, help="integer zoom (default 4)")+ parser.add_argument("--pets", default="", help="comma-separated ids (default: all)")+ parser.add_argument("--split", action="store_true", help="also write one image per pet")+ args = parser.parse_args(argv)++ wanted = {p for p in args.pets.split(",") if p}+ packs = [+ load_pet(builtin_root() / m.id, builtin=True)+ for m in list_pets()+ if m.builtin and (not wanted or m.id in wanted)+ ]+ if not packs:+ print("no matching built-in pets", file=sys.stderr)+ return 1+ args.out.mkdir(parents=True, exist_ok=True)+ for name, background in BACKGROUNDS.items():+ path = args.out / f"pets-{name}.png"+ render(packs, background, args.scale).save(path)+ print(path)+ if args.split:+ for pack in packs:+ path = args.out / f"{pack.manifest.id}-{name}.png"+ render([pack], background, args.scale).save(path)+ print(path)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/unit/ui/pets/__init__.py b/tests/unit/ui/pets/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/ui/pets/test_builtin_pets.py b/tests/unit/ui/pets/test_builtin_pets.pynew file mode 100644index 0000000000..23a6f069fd--- /dev/null+++ b/tests/unit/ui/pets/test_builtin_pets.py@@ -0,0 +1,106 @@+"""The shipped pets: complete, loadable, and exactly what the generator draws."""++from __future__ import annotations++import importlib.util+import json+import sys+from pathlib import Path+from types import ModuleType++import pytest+from PIL import Image++from jarvis.ui.pets.loader import COLOR_KEY, builtin_root, list_pets, load_pet+from jarvis.ui.pets.states import DEFAULT_PET_ID, PET_STATES++REPO_ROOT = Path(__file__).resolve().parents[4]+BUILD_SCRIPT = REPO_ROOT / "scripts" / "pets" / "build_pets.py"+PACKAGE_DIR = REPO_ROOT / "jarvis" / "ui" / "pets"+EXPECTED_PETS = ("gigi", "miso", "brew", "bolt", "mochi", "shelly")+++def _builder() -> ModuleType:+ spec = importlib.util.spec_from_file_location("jarvis_build_pets", BUILD_SCRIPT)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module # dataclasses resolve their module by name+ try:+ spec.loader.exec_module(module)+ finally:+ sys.modules.pop(spec.name, None)+ return module++[email protected](scope="module")+def generated(tmp_path_factory: pytest.TempPathFactory) -> Path:+ out = tmp_path_factory.mktemp("pets-build")+ _builder().build_all(out)+ return out+++def test_the_six_builtin_pets_ship() -> None:+ ids = [m.id for m in list_pets() if m.builtin]+ assert ids[0] == DEFAULT_PET_ID+ assert sorted(ids) == sorted(EXPECTED_PETS)++[email protected]("pet_id", EXPECTED_PETS)+def test_builtin_pet_is_complete(pet_id: str) -> None:+ pack = load_pet(builtin_root() / pet_id, builtin=True)+ manifest = pack.manifest+ assert manifest.frame_size == 48+ assert set(manifest.animations) == set(PET_STATES), "every state is drawn, none borrowed"+ assert manifest.name and manifest.description.endswith(".")+ assert len(manifest.description) <= 140+ for state in PET_STATES:+ assert pack.frames[state], state+ for frame in pack.frames[state]:+ assert frame.getchannel("A").getbbox() is not None, f"{state} has an empty frame"+ raw = frame.tobytes()+ opaque = {raw[i : i + 3] for i in range(0, len(raw), 4) if raw[i + 3] == 255}+ assert bytes(COLOR_KEY) not in opaque++[email protected]("pet_id", EXPECTED_PETS)+def test_states_look_different(pet_id: str) -> None:+ """Every state's first frame differs from idle's, so each reads on its own."""+ pack = load_pet(builtin_root() / pet_id, builtin=True)+ idle = pack.frames["idle"][0].tobytes()+ for state in PET_STATES[1:]:+ assert pack.frames[state][0].tobytes() != idle, state+++def _pixels(path: Path) -> tuple[tuple[int, int], bytes]:+ with Image.open(path) as image:+ rgba = image.convert("RGBA")+ return rgba.size, rgba.tobytes()++[email protected]("pet_id", EXPECTED_PETS)+def test_committed_pet_matches_the_generator(generated: Path, pet_id: str) -> None:+ # Pixels and manifest text, not PNG bytes: the encoder's output may differ+ # across Pillow / zlib versions while the art stays identical.+ ours = PACKAGE_DIR / "builtin" / pet_id+ fresh = generated / "builtin" / pet_id+ assert _pixels(ours / "sheet.png") == _pixels(fresh / "sheet.png"), (+ f"{pet_id}: run `python scripts/pets/build_pets.py` and commit the result"+ )+ assert (ours / "pet.json").read_text(encoding="utf-8") == (fresh / "pet.json").read_text(+ encoding="utf-8"+ )+++def test_committed_template_matches_the_generator(generated: Path) -> None:+ ours = PACKAGE_DIR / "template"+ fresh = generated / "template"+ assert _pixels(ours / "template.png") == _pixels(fresh / "template.png")+ ours_manifest = json.loads((ours / "template.json").read_text(encoding="utf-8"))+ assert ours_manifest == json.loads((fresh / "template.json").read_text(encoding="utf-8"))+++def test_template_cells_read_as_empty() -> None:+ """An untouched template cell must not count as a drawn frame on upload."""+ with Image.open(PACKAGE_DIR / "template" / "template.png") as image:+ alpha = image.convert("RGBA").getchannel("A")+ assert max(alpha.tobytes()) < 128diff --git a/tests/unit/ui/pets/test_loader.py b/tests/unit/ui/pets/test_loader.pynew file mode 100644index 0000000000..a1b22080a3--- /dev/null+++ b/tests/unit/ui/pets/test_loader.py@@ -0,0 +1,199 @@+"""Finding and decoding pet packs, and the colour-key conversion the overlay uses."""++from __future__ import annotations++import json+import logging+from pathlib import Path++import pytest+from PIL import Image++from jarvis.ui.pets import loader+from jarvis.ui.pets.loader import (+ COLOR_KEY,+ builtin_root,+ custom_root,+ find_pet_dir,+ list_pets,+ load_pet,+ load_pet_by_id,+ normalize_sheet,+ to_color_key,+)+from jarvis.ui.pets.manifest import PetManifestError+from jarvis.ui.pets.states import DEFAULT_PET_ID, PET_FORMAT, PET_STATES++USER_ID = "u0123456789abcdef"+++def _write_pet(+ folder: Path,+ *,+ pet_id: str,+ sheet: Image.Image,+ animations: dict | None = None,+ frame_size: int = 32,+) -> Path:+ folder.mkdir(parents=True)+ sheet.save(folder / "sheet.png")+ manifest = {+ "format": PET_FORMAT,+ "id": pet_id,+ "name": "Test pet",+ "description": "",+ "frame_size": frame_size,+ "sheet": "sheet.png",+ "animations": animations+ or {+ "idle": {"row": 0, "frames": 2, "fps": 4},+ "talking": {"row": 1, "frames": 1, "fps": 8},+ },+ }+ (folder / "pet.json").write_text(json.dumps(manifest), encoding="utf-8")+ return folder+++def _two_row_sheet() -> Image.Image:+ sheet = Image.new("RGBA", (64, 64), (0, 0, 0, 0))+ sheet.paste((10, 20, 30, 255), (0, 0, 32, 32)) # idle frame 0+ sheet.paste((40, 50, 60, 255), (32, 0, 64, 32)) # idle frame 1+ sheet.paste((70, 80, 90, 255), (0, 32, 32, 64)) # talking frame 0+ return sheet+++def user_pet(tmp_path: Path) -> Path:+ return _write_pet(tmp_path / "pets" / USER_ID, pet_id=USER_ID, sheet=_two_row_sheet())+++def test_load_pet_has_frames_for_every_state(user_pet: Path) -> None:+ pack = load_pet(user_pet, builtin=False)+ assert set(pack.frames) == set(PET_STATES)+ assert len(pack.frames["idle"]) == 2+ assert len(pack.frames["talking"]) == 1+ # Undeclared states share their fallback's frames (listening -> idle).+ assert pack.frames["listening"] is pack.frames["idle"]+ assert pack.frames["thinking"] is pack.frames["idle"]+ for frames in pack.frames.values():+ for frame in frames:+ assert frame.mode == "RGBA"+ assert frame.size == (32, 32)+ assert pack.frames["idle"][1].getpixel((5, 5)) == (40, 50, 60, 255)+++def test_normalize_sheet_makes_alpha_binary_and_avoids_the_key() -> None:+ image = Image.new("RGBA", (4, 1))+ image.putpixel((0, 0), (1, 2, 3, 127)) # below threshold: gone+ image.putpixel((1, 0), (4, 5, 6, 128)) # at threshold: opaque+ image.putpixel((2, 0), (*COLOR_KEY, 255)) # exact key: nudged+ image.putpixel((3, 0), (*COLOR_KEY, 0)) # transparent key: just gone+ clean = normalize_sheet(image)+ assert clean.getpixel((0, 0)) == (0, 0, 0, 0)+ assert clean.getpixel((1, 0)) == (4, 5, 6, 255)+ assert clean.getpixel((2, 0)) == (0xFE, 0x00, 0xFE, 255)+ assert clean.getpixel((3, 0)) == (0, 0, 0, 0)+ assert set(clean.getchannel("A").tobytes()) <= {0, 255}+++def test_to_color_key_scales_with_hard_edges() -> None:+ frame = Image.new("RGBA", (2, 2), (0, 0, 0, 0))+ frame.putpixel((0, 0), (200, 10, 10, 255))+ frame.putpixel((1, 1), (*COLOR_KEY, 255))+ frame.putpixel((1, 0), (9, 9, 9, 100)) # half-transparent: keyed out+ keyed = to_color_key(frame, 3)+ assert keyed.mode == "RGB"+ assert keyed.size == (6, 6)+ colors = {keyed.getpixel((x, y)) for x in range(6) for y in range(6)}+ # Only the sprite's own colours and the exact key; no blends.+ assert colors == {(200, 10, 10), COLOR_KEY, (0xFE, 0x00, 0xFE)}+ assert keyed.getpixel((2, 2)) == (200, 10, 10)+ assert keyed.getpixel((3, 0)) == COLOR_KEY+ assert keyed.getpixel((5, 5)) == (0xFE, 0x00, 0xFE)+++def test_to_color_key_honours_another_key() -> None:+ frame = Image.new("RGBA", (1, 1), (0, 0, 0, 0))+ assert to_color_key(frame, 1, key=(0, 255, 0)).getpixel((0, 0)) == (0, 255, 0)++[email protected]("scale", [0, -2, 1.5, True])+def test_to_color_key_rejects_bad_scale(scale: object) -> None:+ with pytest.raises(ValueError):+ to_color_key(Image.new("RGBA", (1, 1)), scale) # type: ignore[arg-type]+++def test_find_pet_dir(tmp_path: Path, user_pet: Path) -> None:+ folder, builtin = find_pet_dir(DEFAULT_PET_ID, data_dir=tmp_path) # type: ignore[misc]+ assert builtin is True+ assert folder == builtin_root() / DEFAULT_PET_ID+ assert find_pet_dir(USER_ID, data_dir=tmp_path) == (user_pet, False)+ for bad in ("none", "nope", "../gigi", "..", "u0123456789ABCDEF", "", 3):+ assert find_pet_dir(bad, data_dir=tmp_path) is None # type: ignore[arg-type]+++def test_custom_root_uses_data_dir(tmp_path: Path) -> None:+ assert custom_root(tmp_path) == tmp_path / "pets"+ assert not (tmp_path / "pets").exists()+++def test_load_pet_by_id(tmp_path: Path, user_pet: Path, caplog: pytest.LogCaptureFixture) -> None:+ assert load_pet_by_id("none", data_dir=tmp_path) is None+ assert load_pet_by_id(USER_ID, data_dir=tmp_path).manifest.id == USER_ID # type: ignore[union-attr]+ with caplog.at_level(logging.WARNING, logger=loader.__name__):+ fallback = load_pet_by_id("u" + "f" * 16, data_dir=tmp_path)+ assert fallback is not None and fallback.manifest.id == DEFAULT_PET_ID+ assert "not found" in caplog.text+++def test_broken_pet_falls_back_to_default(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:+ folder = _write_pet(+ tmp_path / "pets" / USER_ID,+ pet_id=USER_ID,+ sheet=Image.new("RGBA", (32, 32)),+ animations={"idle": {"row": 3, "frames": 1, "fps": 4}}, # row outside the sheet+ )+ with pytest.raises(PetManifestError):+ load_pet(folder, builtin=False)+ with caplog.at_level(logging.WARNING, logger=loader.__name__):+ pack = load_pet_by_id(USER_ID, data_dir=tmp_path)+ assert pack is not None and pack.manifest.id == DEFAULT_PET_ID+ assert "broken" in caplog.text+++def test_folder_name_must_match_id(tmp_path: Path) -> None:+ folder = _write_pet(tmp_path / "u1111111111111111", pet_id=USER_ID, sheet=_two_row_sheet())+ with pytest.raises(PetManifestError, match="folder"):+ load_pet(folder, builtin=False)+++def test_non_png_sheet_is_rejected(tmp_path: Path) -> None:+ folder = _write_pet(tmp_path / USER_ID, pet_id=USER_ID, sheet=_two_row_sheet())+ Image.new("RGB", (64, 64)).save(folder / "sheet.png", format="BMP")+ with pytest.raises(PetManifestError, match="PNG"):+ load_pet(folder, builtin=False)+++def test_bad_json_is_rejected(tmp_path: Path) -> None:+ folder = _write_pet(tmp_path / USER_ID, pet_id=USER_ID, sheet=_two_row_sheet())+ (folder / "pet.json").write_text("{nope", encoding="utf-8")+ with pytest.raises(PetManifestError, match="JSON"):+ load_pet(folder, builtin=False)+++def test_list_pets_orders_default_first_and_skips_broken(tmp_path: Path, user_pet: Path) -> None:+ broken = tmp_path / "pets" / "u2222222222222222"+ broken.mkdir()+ (broken / "pet.json").write_text("{}", encoding="utf-8")+ (tmp_path / "pets" / "not-a-user-id").mkdir()+ pets = list_pets(data_dir=tmp_path)+ ids = [m.id for m in pets]+ assert ids[0] == DEFAULT_PET_ID+ assert USER_ID in ids+ assert "u2222222222222222" not in ids+ assert all(m.builtin for m in pets if m.id != USER_ID)+ assert ids[-1] == USER_ID+++def test_list_pets_without_custom_folder(tmp_path: Path) -> None:+ assert all(m.builtin for m in list_pets(data_dir=tmp_path / "missing"))diff --git a/tests/unit/ui/pets/test_manifest.py b/tests/unit/ui/pets/test_manifest.pynew file mode 100644index 0000000000..2b3f4e866e--- /dev/null+++ b/tests/unit/ui/pets/test_manifest.py@@ -0,0 +1,171 @@+"""The ``pet.json`` rules of the ``jarvis-pet/1`` format (docs/pets.md)."""++from __future__ import annotations++import copy++import pytest++from jarvis.ui.pets.manifest import (+ MAX_DESCRIPTION_CHARS,+ MAX_NAME_CHARS,+ AnimationSpec,+ PetManifestError,+ check_cells,+ check_sheet_size,+ parse_manifest,+)+from jarvis.ui.pets.states import PET_FORMAT, PET_STATES, STATE_FALLBACKS++USER_ID = "u0123456789abcdef"+++def _data(**overrides: object) -> dict:+ data: dict = {+ "format": PET_FORMAT,+ "id": "gigi",+ "name": "Gigi",+ "description": "A ghost.",+ "frame_size": 48,+ "sheet": "sheet.png",+ "animations": {+ "idle": {"row": 0, "frames": 4, "fps": 4, "loop": True},+ "talking": {"row": 3, "frames": 4, "fps": 10},+ "success": {"row": 4, "frames": 6, "fps": 10},+ },+ }+ data.update(overrides)+ return data+++def _animations(**changes: object) -> dict:+ animations = copy.deepcopy(_data()["animations"])+ animations["idle"].update(changes)+ return animations+++def test_valid_manifest_parses() -> None:+ manifest = parse_manifest(_data(), builtin=True)+ assert manifest.id == "gigi"+ assert manifest.name == "Gigi"+ assert manifest.frame_size == 48+ assert manifest.builtin is True+ assert manifest.animations["idle"] == AnimationSpec(row=0, frames=4, fps=4, loop=True)+++def test_loop_defaults_to_false_for_one_shots_only() -> None:+ manifest = parse_manifest(_data(), builtin=True)+ assert manifest.animations["talking"].loop is True+ assert manifest.animations["success"].loop is False+++def test_name_and_description_are_trimmed() -> None:+ manifest = parse_manifest(_data(name=" Gigi ", description=" hi "), builtin=True)+ assert (manifest.name, manifest.description) == ("Gigi", "hi")+++def test_user_id_rules() -> None:+ assert parse_manifest(_data(id=USER_ID), builtin=False).id == USER_ID+ with pytest.raises(PetManifestError):+ parse_manifest(_data(id="gigi"), builtin=False)+ # A built-in may never look like a user id (the two namespaces stay apart).+ with pytest.raises(PetManifestError):+ parse_manifest(_data(id=USER_ID), builtin=True)+++ "overrides",+ [+ {"format": "jarvis-pet/2"},+ {"id": "none"},+ {"id": "Gigi"},+ {"id": "../evil"},+ {"id": 7},+ {"name": ""},+ {"name": "x" * (MAX_NAME_CHARS + 1)},+ {"description": 5},+ {"description": "x" * (MAX_DESCRIPTION_CHARS + 1)},+ {"frame_size": 40},+ {"frame_size": True},+ {"sheet": "../sheet.png"},+ {"sheet": "sub/sheet.png"},+ {"sheet": "sheet.gif"},+ {"animations": {}},+ {"animations": {"talking": {"row": 0, "frames": 1, "fps": 4}}},+ {"animations": {"idle": {"row": 0, "frames": 1, "fps": 4}, "dancing": {}}},+ ],+)+def test_manifest_rule_rejections(overrides: dict) -> None:+ with pytest.raises(PetManifestError):+ parse_manifest(_data(**overrides), builtin=True)+++ "changes",+ [+ {"row": -1},+ {"frames": 0},+ {"frames": 9},+ {"fps": 0},+ {"fps": 13},+ {"frames": True},+ {"loop": "yes"},+ {"row": 1.5},+ ],+)+def test_animation_rule_rejections(changes: dict) -> None:+ with pytest.raises(PetManifestError):+ parse_manifest(_data(animations=_animations(**changes)), builtin=True)+++def test_not_an_object_is_rejected() -> None:+ with pytest.raises(PetManifestError):+ parse_manifest(["not", "a", "manifest"], builtin=True)+++def test_errors_are_readable_sentences() -> None:+ with pytest.raises(PetManifestError) as info:+ parse_manifest(_data(frame_size=40), builtin=True)+ assert str(info.value).endswith(".")+ assert "32" in str(info.value) and "64" in str(info.value)+++def test_spec_for_resolves_fallbacks() -> None:+ manifest = parse_manifest(_data(), builtin=True)+ assert manifest.spec_for("idle")[0] == "idle"+ assert manifest.spec_for("talking")[0] == "talking"+ # thinking -> listening -> idle (neither declared)+ assert manifest.spec_for("thinking")[0] == "idle"+ assert manifest.spec_for("sleeping")[0] == STATE_FALLBACKS["sleeping"]+ for state in PET_STATES:+ resolved, spec = manifest.spec_for(state)+ assert resolved in manifest.animations+ assert spec is manifest.animations[resolved]+++def test_spec_for_rejects_unknown_state() -> None:+ with pytest.raises(KeyError):+ parse_manifest(_data(), builtin=True).spec_for("dancing")+++def test_to_json_round_trips() -> None:+ manifest = parse_manifest(_data(), builtin=True)+ again = parse_manifest(manifest.to_json(), builtin=True)+ assert again == manifest+ assert "builtin" not in manifest.to_json()+++def test_check_cells_rejects_rows_outside_the_sheet() -> None:+ manifest = parse_manifest(_data(), builtin=True)+ check_cells(manifest, 48 * 6, 48 * 5) # rows 0..4, six columns: fits+ with pytest.raises(PetManifestError):+ check_cells(manifest, 48 * 6, 48 * 4) # success is row 4+ with pytest.raises(PetManifestError):+ check_cells(manifest, 48 * 5, 48 * 5) # success has six frames+++def test_check_sheet_size_limits() -> None:+ check_sheet_size(512, 512)+ for width, height in ((0, 10), (513, 10), (10, 513)):+ with pytest.raises(PetManifestError):+ check_sheet_size(width, height)diff --git a/tests/unit/ui/pets/test_state_machine.py b/tests/unit/ui/pets/test_state_machine.pynew file mode 100644index 0000000000..c51e997bd7--- /dev/null+++ b/tests/unit/ui/pets/test_state_machine.py@@ -0,0 +1,174 @@+"""The pet's state machine, driven by a fake clock."""++from __future__ import annotations++import pytest++from jarvis.ui.jarvisbar.modes import MODES+from jarvis.ui.pets.state_machine import MODE_STATES, PetStateMachine+from jarvis.ui.pets.states import ONE_SHOT_SECONDS, PET_STATES, SLEEP_AFTER_SECONDS+++class FakeClock:+ def __init__(self, now: float = 1000.0) -> None:+ self.now = now++ def __call__(self) -> float:+ return self.now++ def advance(self, seconds: float) -> None:+ self.now += seconds+++def clock() -> FakeClock:+ return FakeClock()+++def machine(clock: FakeClock) -> PetStateMachine:+ return PetStateMachine(clock=clock)+++def test_starts_idle(machine: PetStateMachine, clock: FakeClock) -> None:+ assert machine.state() == "idle"+ assert machine.state_started_at() == clock.now+++ ("mode", "state"),+ [+ ("idle", "idle"),+ ("listen", "listening"),+ ("dictate", "listening"),+ ("think", "thinking"),+ ("dictate_transcribing", "thinking"),+ ("speak", "talking"),+ ],+)+def test_every_mode_maps_to_a_state(machine: PetStateMachine, mode: str, state: str) -> None:+ machine.on_mode(mode)+ assert machine.state() == state+++def test_every_overlay_mode_is_handled() -> None:+ # Every mode is a state mapping or the notice one-shot; nothing is dropped.+ assert set(MODES) - set(MODE_STATES) == {"notice"}+ assert set(MODE_STATES.values()) <= set(PET_STATES)+++def test_notice_plays_the_error_one_shot(machine: PetStateMachine, clock: FakeClock) -> None:+ machine.on_mode("listen")+ machine.on_mode("notice")+ assert machine.state() == "error"+ clock.advance(ONE_SHOT_SECONDS["error"])+ assert machine.state() == "listening"+++def test_unknown_mode_and_outcome_are_ignored(machine: PetStateMachine) -> None:+ machine.on_mode("speak")+ machine.on_mode("dancing")+ machine.on_outcome("confetti")+ assert machine.state() == "talking"+++def test_state_change_restarts_the_animation_clock(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ clock.advance(5)+ machine.on_mode("think")+ assert machine.state_started_at() == clock.now+ clock.advance(1)+ machine.on_mode("think") # same state: the animation keeps its phase+ assert machine.state_started_at() == clock.now - 1++[email protected]("kind", ["success", "error"])+def test_one_shot_returns_to_the_mode_state(+ machine: PetStateMachine, clock: FakeClock, kind: str+) -> None:+ machine.on_mode("speak")+ machine.on_outcome(kind)+ assert machine.state() == kind+ assert machine.next_change_in() == pytest.approx(ONE_SHOT_SECONDS[kind])+ clock.advance(ONE_SHOT_SECONDS[kind] - 0.01)+ assert machine.state() == kind+ clock.advance(0.02)+ assert machine.state() == "talking"+++def test_mode_change_during_a_one_shot_applies_after_it(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ machine.on_outcome("success")+ machine.on_mode("listen")+ assert machine.state() == "success"+ clock.advance(ONE_SHOT_SECONDS["success"])+ assert machine.state() == "listening"+++def test_one_shot_end_is_stamped_when_it_fell_due(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ machine.on_outcome("success")+ due = clock.now + ONE_SHOT_SECONDS["success"]+ clock.advance(10) # a late poll+ assert machine.state() == "idle"+ assert machine.state_started_at() == due+++def test_repeated_outcome_restarts_its_animation(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ machine.on_outcome("error")+ clock.advance(1)+ machine.on_outcome("error")+ assert machine.state_started_at() == clock.now+++def test_falls_asleep_after_quiet_idle(machine: PetStateMachine, clock: FakeClock) -> None:+ assert machine.next_change_in() == pytest.approx(SLEEP_AFTER_SECONDS)+ clock.advance(SLEEP_AFTER_SECONDS - 1)+ assert machine.state() == "idle"+ clock.advance(1)+ assert machine.state() == "sleeping"+ assert machine.next_change_in() is None+++def test_activity_wakes_and_resets_the_countdown(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ clock.advance(SLEEP_AFTER_SECONDS + 5)+ assert machine.state() == "sleeping"+ machine.on_activity()+ assert machine.state() == "idle"+ assert machine.next_change_in() == pytest.approx(SLEEP_AFTER_SECONDS)+++def test_a_session_never_falls_asleep(machine: PetStateMachine, clock: FakeClock) -> None:+ machine.on_mode("listen")+ assert machine.next_change_in() is None+ clock.advance(SLEEP_AFTER_SECONDS * 3)+ assert machine.state() == "listening"+++def test_sleep_countdown_starts_when_the_session_ends(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ machine.on_mode("speak")+ clock.advance(SLEEP_AFTER_SECONDS * 2)+ machine.on_mode("idle")+ assert machine.state() == "idle"+ clock.advance(SLEEP_AFTER_SECONDS)+ assert machine.state() == "sleeping"+++def test_outcome_while_asleep_wakes_then_returns_to_idle(+ machine: PetStateMachine, clock: FakeClock+) -> None:+ clock.advance(SLEEP_AFTER_SECONDS)+ assert machine.state() == "sleeping"+ machine.on_outcome("success")+ assert machine.state() == "success"+ clock.advance(ONE_SHOT_SECONDS["success"])+ assert machine.state() == "idle"diff --git a/tests/unit/ui/pets/test_status_line.py b/tests/unit/ui/pets/test_status_line.pynew file mode 100644index 0000000000..4b4a856bb7--- /dev/null+++ b/tests/unit/ui/pets/test_status_line.py@@ -0,0 +1,105 @@+"""Condensing Jarvis's output into one bubble line, and the feed's dedupe/rate limit."""++from __future__ import annotations++import pytest++from jarvis.ui.pets.status_line import ELLIPSIS, StatusFeed, condense+++class FakeClock:+ def __init__(self) -> None:+ self.now = 0.0++ def __call__(self) -> float:+ return self.now+++ ("text", "expected"),+ [+ ("Hello there. This is the second sentence.", "Hello there. This is the second sentence."),+ (+ "I checked the calendar for today. Nothing else is planned.",+ "I checked the calendar for today.",+ ),+ ("**Done** — the *file* is __saved__.", "Done — the file is saved."),+ ("# Summary\nThe build passed.", "The build passed."),+ ("# Only a heading", "Only a heading"),+ # Each bullet is a sentence; a short first one borrows the next.+ ("- first item\n- second item", "first item. second item"),+ ("- the first bullet is long enough\n- second", "the first bullet is long enough"),+ ("Run `npm test` now.", "Run npm test now."),+ ("See https://example.com/docs for details.", "See for details."),+ ("[the docs](https://example.com) are updated.", "the docs are updated."),+ ("Saved to C:\\Users\\someone\\notes\\todo.md for you.", "Saved to todo.md for you."),+ ("Edited /home/someone/project/src/main.py just now.", "Edited main.py just now."),+ ('Result: {"ok": true, "count": 3} came back.', "Result: came back."),+ ],+)+def test_condense_cleans_markdown_and_noise(text: str, expected: str) -> None:+ assert condense(text) == expected+++def test_condense_drops_fenced_code() -> None:+ text = "Here is the fix:\n```python\nprint('x')\n```\nIt works now."+ assert condense(text) == "Here is the fix. It works now."+ assert "print" not in condense(text)+++def test_condense_drops_long_inline_code() -> None:+ assert condense("Try `" + "x" * 40 + "` here.") == "Try here."+++def test_condense_joins_a_very_short_first_sentence() -> None:+ text = "Okay. I will open the settings page."+ assert condense(text) == text+++def test_condense_clips_at_a_word_boundary() -> None:+ text = "This sentence is deliberately rather long so that it must be clipped somewhere sensible"+ out = condense(text, max_chars=40)+ assert len(out) <= 40+ assert out.endswith(ELLIPSIS)+ assert text.startswith(out[:-1])+ assert not out[:-1].endswith(" ")++[email protected]("text", ["", " ", "```\ncode only\n```", '{"a": 1}', None, 5])+def test_condense_returns_empty_for_nothing_readable(text: object) -> None:+ assert condense(text) == "" # type: ignore[arg-type]+++def test_feed_dedupes_and_rate_limits() -> None:+ clock = FakeClock()+ feed = StatusFeed(clock=clock, min_interval_s=0.3)+ first = ("Thinking …", "Opening the calendar.")+ assert feed.offer(*first) == first+ clock.now = 1.0+ assert feed.offer("Thinking …", "Opening the calendar.") is None # duplicate+ clock.now = 1.1+ assert feed.offer("Thinking …", "Reading events.") == ("Thinking …", "Reading events.")+ clock.now = 1.2+ assert feed.offer("Thinking …", "Counting events.") is None # too soon+ assert feed.flush() is None # still too soon+ clock.now = 1.5+ assert feed.flush() == ("Thinking …", "Counting events.")+ assert feed.flush() is None+++def test_feed_force_bypasses_interval_not_dedupe() -> None:+ clock = FakeClock()+ feed = StatusFeed(clock=clock)+ feed.offer("", "First line.")+ assert feed.offer("", "Second line.", force=True) == ("", "Second line.")+ assert feed.offer("", "Second line.", force=True) is None+++def test_feed_ignores_empty_pairs_and_resets() -> None:+ clock = FakeClock()+ feed = StatusFeed(clock=clock)+ assert feed.offer("", "") is None+ assert feed.offer("", "```\nx\n```") is None+ feed.offer("", "Same line.")+ feed.reset()+ assert feed.offer("", "Same line.") == ("", "Same line.")diff --git a/tests/unit/ui/pets/test_store.py b/tests/unit/ui/pets/test_store.pynew file mode 100644index 0000000000..f734701642--- /dev/null+++ b/tests/unit/ui/pets/test_store.py@@ -0,0 +1,181 @@+"""User-created pets: upload validation, inference, re-encoding and deletion."""++from __future__ import annotations++import io+import json+from pathlib import Path++import pytest+from PIL import Image+from PIL.PngImagePlugin import PngInfo++from jarvis.ui.pets.loader import load_pet+from jarvis.ui.pets.manifest import USER_ID_RE, PetManifestError+from jarvis.ui.pets.states import PET_FORMAT+from jarvis.ui.pets.store import PetStore++PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+++def _png(image: Image.Image, **save: object) -> bytes:+ buffer = io.BytesIO()+ image.save(buffer, format="PNG", **save)+ return buffer.getvalue()+++def _sheet(rows: list[int], size: int = 48, columns: int = 8) -> Image.Image:+ """A sheet whose row ``r`` has ``rows[r]`` filled cells from the left."""+ sheet = Image.new("RGBA", (size * columns, size * len(rows)), (0, 0, 0, 0))+ for row, filled in enumerate(rows):+ for col in range(filled):+ box = (col * size, row * size, (col + 1) * size, (row + 1) * size)+ sheet.paste((30 + col, 60, 90, 255), box)+ return sheet+++def _add(store: PetStore, sheet: bytes, **kwargs: object):+ fields: dict = {"name": "Pet", "description": ""}+ fields.update(kwargs)+ return store.add(sheet_bytes=sheet, **fields)+++def store(tmp_path: Path) -> PetStore:+ return PetStore(tmp_path / "pets")+++def test_add_infers_animations_from_the_rows(store: PetStore) -> None:+ manifest = _add(store, _png(_sheet([4, 2, 0, 3])), name=" Pixel ", description="Hi.")+ assert USER_ID_RE.match(manifest.id)+ assert manifest.name == "Pixel"+ assert manifest.frame_size == 48+ assert set(manifest.animations) == {"idle", "listening", "talking"}+ assert manifest.animations["idle"].frames == 4+ assert manifest.animations["idle"].fps == 4+ assert manifest.animations["listening"].fps == 8+ assert manifest.animations["talking"].row == 3+ # The stored pack loads through the real loader.+ folder = store.directory(manifest.id)+ assert folder is not None+ assert load_pet(folder, builtin=False).manifest == manifest+++def test_frames_stop_at_the_first_empty_cell(store: PetStore) -> None:+ sheet = _sheet([2])+ sheet.paste((1, 2, 3, 255), (48 * 3, 0, 48 * 4, 48)) # a stray cell after a gap+ assert _add(store, _png(sheet)).animations["idle"].frames == 2+++def test_add_with_manifest(store: PetStore) -> None:+ manifest_json = json.dumps(+ {+ "format": PET_FORMAT,+ "id": "ignored",+ "name": "From file",+ "description": "Named in the file.",+ "frame_size": 32,+ "sheet": "whatever.png",+ "animations": {"idle": {"row": 1, "frames": 2, "fps": 6}},+ }+ )+ sheet = _png(_sheet([1, 2], size=32))+ manifest = _add(store, sheet, name="", manifest_json=manifest_json)+ assert manifest.name == "From file"+ assert manifest.description == "Named in the file."+ assert manifest.frame_size == 32+ assert manifest.sheet == "sheet.png"+ assert manifest.animations["idle"].row == 1+ assert manifest.id != "ignored"+++def test_form_fields_win_over_the_manifest(store: PetStore) -> None:+ manifest_json = json.dumps(+ {"name": "File name", "animations": {"idle": {"row": 0, "frames": 1, "fps": 4}}}+ )+ manifest = _add(store, _png(_sheet([1])), name="Form name", manifest_json=manifest_json)+ assert manifest.name == "Form name"+++def test_upload_is_re_encoded(store: PetStore) -> None:+ info = PngInfo()+ info.add_text("Comment", "smuggled-metadata")+ upload = _png(_sheet([1]), pnginfo=info)+ assert b"smuggled-metadata" in upload+ manifest = _add(store, upload + b"trailing-junk")+ folder = store.directory(manifest.id)+ assert folder is not None+ stored = (folder / "sheet.png").read_bytes()+ assert stored.startswith(PNG_SIGNATURE)+ assert b"smuggled-metadata" not in stored+ assert b"trailing-junk" not in stored+++def test_explicit_frame_size_must_fit_the_grid(store: PetStore) -> None:+ with pytest.raises(PetManifestError, match="grid"):+ _add(store, _png(_sheet([1], size=48)), frame_size=64)+ with pytest.raises(PetManifestError):+ _add(store, _png(_sheet([1])), frame_size=40)+++ ("payload", "message"),+ [+ (b"", "empty"),+ (b"GIF89a" + b"\0" * 20, "PNG"),+ (PNG_SIGNATURE + b"garbage", "read"),+ ],+)+def test_rejects_non_png_uploads(store: PetStore, payload: bytes, message: str) -> None:+ with pytest.raises(PetManifestError, match=message):+ _add(store, payload)+++def test_rejects_oversize_uploads(store: PetStore) -> None:+ with pytest.raises(PetManifestError, match="2 MB"):+ _add(store, PNG_SIGNATURE + b"\0" * PetStore.MAX_SHEET_BYTES)+ with pytest.raises(PetManifestError, match="512"):+ _add(store, _png(Image.new("RGBA", (576, 48))))+++def test_rejects_a_bad_grid_and_an_empty_idle_row(store: PetStore) -> None:+ with pytest.raises(PetManifestError, match="grid"):+ _add(store, _png(Image.new("RGBA", (50, 50), (1, 1, 1, 255))))+ with pytest.raises(PetManifestError, match="idle"):+ _add(store, _png(_sheet([0, 2])))+++def test_rejects_bad_manifest_text(store: PetStore) -> None:+ for text in ("{not json", "[1, 2]"):+ with pytest.raises(PetManifestError):+ _add(store, _png(_sheet([1])), manifest_json=text)+++def test_rejects_a_missing_name(store: PetStore) -> None:+ with pytest.raises(PetManifestError, match="name"):+ _add(store, _png(_sheet([1])), name=" ")+++def test_list_and_delete(store: PetStore) -> None:+ first = _add(store, _png(_sheet([1])), name="B pet")+ second = _add(store, _png(_sheet([1])), name="A pet")+ assert [m.id for m in store.list()] == [second.id, first.id]+ assert store.delete(first.id) is True+ assert store.directory(first.id) is None+ assert [m.id for m in store.list()] == [second.id]+ assert store.delete(first.id) is False+ # No staging folder is left behind.+ assert sorted(p.name for p in store.root.iterdir()) == [second.id]+++def test_delete_never_leaves_the_root(store: PetStore, tmp_path: Path) -> None:+ outside = tmp_path / "keep"+ outside.mkdir()+ (outside / "file.txt").write_text("x", encoding="utf-8")+ for bad in ("..", "../keep", "gigi", "", "u0123", "u0123456789ABCDEF", None):+ assert store.delete(bad) is False # type: ignore[arg-type]+ assert (outside / "file.txt").exists()+++def test_list_of_a_missing_root_is_empty(tmp_path: Path) -> None:+ assert PetStore(tmp_path / "nothing").list() == []