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): rebuild the pet's cards in the Codex companion's look
rubenluetke10-beep5aac092907b7
diff --git a/docs/pets.md b/docs/pets.mdindex 6a831e4e3f..4177d86079 100644--- a/docs/pets.md+++ b/docs/pets.md@@ -23,7 +23,7 @@ one click.are up, and while the pointer is on the pet. With the pet "None", or with**Always show the buttons** on (My Pets → Customize, `[ui] pet_strip_always`),it always shows. From left to right:- - bell: notifications on or off for this run (see *Notifications*). Off+ - bell: done cards on or off for this run (see *Cards*). Offshows a red, struck-through bell and sends the cards on screen away; onrings the bell. Like the speaker mute it never survives a restart, so abell forgotten off cannot hide tomorrow's "your agent is done";@@ -36,17 +36,16 @@ one click.thinking or transcribing;- speaker: silence the assistant's voice for this session (TTS volume 0,mirrored from `VoiceSpeakerMuteChanged`).-- **The thinking card** under the strip: a rounded pill with a bold title- (what Jarvis is working on) and one muted detail line (the current thought- or step). It appears ONLY while Jarvis is really thinking and shows what it- thinks — never the live transcript and never the reply, which the user hears- anyway (see *The thinking card* below). It can be switched off- (`[ui] pet_bubble`).+- **The card column** under the strip (above the pet when there is no room+ below), in the Codex companion's material — a dark, slightly see-through+ surface with a hairline rim, soft corners and a soft shadow (see *Cards*):+ - the **thinking line** while Jarvis thinks: one muted line, the current+ step, with a light sweeping across it. Never the live transcript, never+ the reply. It can be switched off (`[ui] pet_bubble`);+ - **done cards** when Jarvis answered a typed chat or a job Jarvis started+ came back: a check, what was asked, the start of the answer.- **The pet "None"** (`pet_id = "none"`) shows the control strip and the- card without a figure.--- **Notification cards** under the strip (under the thinking card when one- shows; above the pet when there is no room below). See *Notifications*.+ cards without a figure.The pet stays on screen while Jarvis is idle. The global shortcut(`[trigger] hotkey_pet_toggle`, default `alt+win+p`) hides it or brings it@@ -54,49 +53,54 @@ back and to the front; hiding lasts until the next app start. The shortcut ischanged on the My Pets page (Customize); an empty value switches it off. OnWayland, global shortcuts are a no-op, as for every other shortcut.-## Notifications+## Cards++One window (`ui/orb/notice_stack.py`) holds the thinking line on top and the+done cards below it; `ui/orb/pet_cards.py` draws them. On Windows the window+carries real per-pixel alpha (`jarvis/platform/layered_window.py`,+`UpdateLayeredWindow`): the desktop shows faintly through the cards, shadows+and fades are soft. Elsewhere, or when Windows refuses a frame, the same frame+is flattened onto the colour key: opaque cards with hard edges, no shadow.-When something happens that the user waits for while looking elsewhere, the-bell swings and a card drops out from under the strip: a round icon (a check-that ticks itself for `done`, `!` for `attention`, a cross for `error`, a bell-for `info`), a bold title and one muted detail line. What becomes a card is-decided in `jarvis/ui/pets/notices.py` (titles per interface language):+Done cards are about Jarvis and nothing else (`jarvis/ui/pets/notices.py`):| Source | Card || --- | --- |-| Agentic IDE pane entry (`NotificationCenter.subscribe`) | `<agent> finished` / `needs your answer` / `exited` / `could not start` |-| `JarvisAgentBackgroundCompleted` | Background task done / failed |-| `MissionCompleted` | Mission complete / failed / timed out (a cancel stays quiet) |-| `DelegationResultReady` | `<agent> has a result` |-| `ActionApprovalRequired` | Approval needed (not when a chat answers its own card) |-| `WorkflowCompleted` | Routine finished / failed |-| `ErrorOccurred(recoverable=False)` | Something went wrong |--Cards stack (`ui/orb/notice_stack.py`): the newest in front, up to two older-ones peeking out behind it, narrower and darker; at most four are kept.-Hovering the stack fans it out into a column; leaving folds it back. A click-dismisses the card under the pointer, which slides away. Every card leaves on-its own (`done` 8 s, `error` 14 s, `attention` 20 s, `info` 6 s), never while-the pointer rests on the stack. The same card twice within 3 s refreshes-instead of stacking. Motion runs on springs at ~60 fps only while something-moves; a resting stack costs a timer every 400 ms. Cards are dropped while the-bell is off, the pet is hidden, or the look is not the pet. The strip stays in-sight while cards show.--## The thinking card--The card mirrors Jarvis's real thinking, fed by bus events in+| `JarvisChatTurnFinished` — a turn of a typed chat with Jarvis (surface `jarvis`), published by `AgentChatService` | ✓ what was asked / the start of the answer; ✕ when the turn failed (a cancel stays quiet) |+| `JarvisAgentBackgroundCompleted` | ✓ / ✕ the task as asked / its result |+| `DelegationResultReady` — a coding job Jarvis delegated | ✓ / ✕ `<agent> is done` / its report |++A coding agent the user runs on their own, a mission, a routine or an app+error gets no card; neither does a spoken turn (the answer was heard).++Done cards are always the column's width, so they stack edge to edge: the+newest in front, up to two older ones peeking out behind it, each a step+smaller and fainter and showing its surface only; at most three are kept.+Hovering fans them into a column; leaving folds them back. A click sends the+card under the pointer away. A card leaves on its own after 9 s (`error`+14 s), never while the pointer rests on the stack; the same card twice within+3 s refreshes instead of stacking. Cards drift in and fade on springs, and the+check ticks itself in. The column repaints at ~60 fps only while something+moves, at 20 fps while only the thinking line's sweep moves, and not at all at+rest. Done cards are dropped while the bell is off, the pet is hidden, or the+look is not the pet; the strip stays in sight while they show.++## The thinking line++The line mirrors Jarvis's real thinking, fed by bus events in`ui/orb/bus_bridge.py` and condensed by `jarvis/ui/pets/status_line.py`:+The surface shows ONE line: the detail when there is one, else the title.+| Source | Title | Detail ||---|---|---|| `ReasoningSummaryUpdated` — the thinking model behind GPT-Live (`jarvis/live/session.py`, streamed as cumulative snapshots a few times per second) | the newest section heading of the summary (`**Heading**`) | the last complete sentence of that section || `ActionProposed` / `ToolCallStarted` — a tool step | the current thought's heading, else the running agent task, else "Working" | the step's rationale, else the humanized tool name || `ActionExecuted` while a card is up | unchanged | "Step done" / "Step failed" |-| `JarvisAgentTaskStarted` / `JarvisAgentTaskCompleted` / `JarvisAgentBackgroundCompleted` — an agent task | the task (the user's request, condensed) | "Working …", then "Done" / "Failed" |+| `JarvisAgentTaskStarted` / `JarvisAgentTaskCompleted` — an agent task | the task (the user's request, condensed) | "Working …", then "Done" / "Failed" || `SystemStateChanged(THINKING)` with no thought after 1.5 s | "Thinking …" | empty |-When it goes away (a 1.5 s linger, then the surface fades it out):+When it goes away (a 1.5 s linger, then it fades out):- Jarvis starts talking out loud (`AudioOutFirst`), the turn ends (`IDLE`,`ERROR`, `PAUSED`), a fresh turn starts listening, or the session ends;@@ -256,14 +260,14 @@ name.| `set_pet_outcome(kind)` | Play the one-shot `success` or `error` || `set_pet_action(kind)` | `working` / `searching` for the running tool step, `None` when it ended || `set_pet_busy(busy)` | An agent task is running in the background |-| `show_status(title, detail="")` | Show or update the thinking card (already condensed) |+| `show_status(title, detail="")` | Show or update the thinking line (already condensed) || `clear_status(linger_s=1.5)` | Take the card down after `linger_s` || `wants_status_lines` (attribute) | True only for the pet: the bridge feeds the card to nothing else || `set_muted(muted)` | Mirror the microphone mute on the strip || `set_speaker_muted(muted)` | Mirror the speaker mute on the strip || `set_visible(visible)` | Hide or show the whole pet (shortcut, settings) || `toggle_visible()` | Shortcut action: hide, or show and raise |-| `push_notice(kind, title, detail)` | One notification card; rings the bell |+| `push_notice(kind, title, detail)` | One done card (`done` / `error`); rings the bell || `set_notifications_enabled(enabled)` | Switch the bell without a click (a respawned host) || `set_on_notifications_toggle(cb)` | `cb(enabled)` after the bell was clicked |@@ -289,7 +293,7 @@ Control-strip actions: `bell` (handled in the surface, reported through| `[ui] orb_style` | `jarvis_bar` | `pet` selects the pet || `[ui] pet_id` | `gigi` | Active pet (built-in id, `u…` id or `none`) || `[ui] pet_scale` | `1.0` | Size multiplier, 0.5–2.0 |-| `[ui] pet_bubble` | `true` | Show the thinking card |+| `[ui] pet_bubble` | `true` | Show the thinking line || `[ui] pet_strip_always` | `false` | Keep the control strip up even at rest || `[trigger] hotkey_pet_toggle` | `alt+win+p` | Hide / show the pet; empty disables it |diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex 7f36cdea1b..53203459f8 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -471,6 +471,8 @@ class AgentChatService:def _publish_event(self, session_id: str, event: dict[str, Any]) -> None:stored = self.store.append_event(session_id, event)+ if event.get("kind") == "turn_finished":+ self._announce_jarvis_turn(session_id, event)for q in list(self._subscribers.get(session_id, ())):try:q.put_nowait(stored)@@ -480,6 +482,46 @@ class AgentChatService:log.debug("agent chat: subscriber queue full for %s — dropping it", session_id)self.unsubscribe(session_id, q)+ def _announce_jarvis_turn(self, session_id: str, event: dict[str, Any]) -> None:+ """Publish ``JarvisChatTurnFinished`` for a finished turn of a Jarvis chat."""+ bus = self._bus()+ session = self.store.get_session(session_id)+ if bus is None or session is None or session.surface != "jarvis":+ return+ payload = event.get("payload") or {}+ status = str(payload.get("status") or "done")+ if status == "cancelled":+ return+ turn_id = str(payload.get("turn_id") or "")+ user_text = ""+ replies: list[str] = []+ for item in reversed(self.store.list_events(session_id, tail=80)):+ kind = item["kind"]+ data = item.get("payload") or {}+ if kind == "assistant_text" and (not turn_id or data.get("turn_id") == turn_id):+ replies.append(str(data.get("text") or ""))+ elif kind == "user_message":+ user_text = str(data.get("text") or "")+ break+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return # no loop, no bus delivery: the chat itself already has the turn+ from jarvis.core.events import JarvisChatTurnFinished++ loop.create_task(+ bus.publish(+ JarvisChatTurnFinished(+ session_id=session_id,+ turn_id=turn_id,+ status="error" if status == "error" else "done",+ user_text=user_text,+ reply_text=" ".join(reversed(replies)).strip(),+ source_layer="agent_chat",+ )+ )+ )+# ---------------------------------------------------------------- turnsasync def receive_message(self, session_id: str, incoming: IncomingMessage) -> dict[str, Any]:diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.pyindex ff39d3fad1..33fd035dea 100644--- a/jarvis/agentic_ide/notifications.py+++ b/jarvis/agentic_ide/notifications.py@@ -238,29 +238,9 @@ class NotificationCenter:def __init__(self, limit: int = MAX_ENTRIES) -> None:self._entries: deque[Notification] = deque(maxlen=limit)- self._listeners: list[Callable[[Notification], None]] = []-- def subscribe(self, listener: Callable[[Notification], None]) -> Callable[[], None]:- """Call ``listener`` with every entry filed from now on (the pet's bell).-- Returns the unsubscribe. A listener runs on the event loop, inside the- sweep, so it must be quick; one that raises is logged and skipped.- """- self._listeners.append(listener)-- def _unsubscribe() -> None:- if listener in self._listeners:- self._listeners.remove(listener)-- return _unsubscribedef add(self, entry: Notification) -> Notification:self._entries.append(entry)- for listener in list(self._listeners):- try:- listener(entry)- except Exception as exc: # noqa: BLE001 — a listener must not stop the sweep- logger.warning("Agentic IDE: notification listener failed: {}", exc)return entrydef list(self) -> list[Notification]:diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 94f41f0253..83e970112c 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -2101,6 +2101,25 @@ class JarvisAgentBackgroundCompleted(Event):duration_s: float = 0.0+@dataclass(frozen=True, slots=True)+class JarvisChatTurnFinished(Event):+ """A turn of a typed chat with Jarvis itself (surface ``jarvis``) ended.++ Published by ``AgentChatService`` once the turn's ``turn_finished`` is+ stored, so a surface the user is not looking at can confirm it — the+ desktop pet shows "what was asked / how Jarvis answered". Chats with other+ agents publish nothing here. A cancelled turn is not announced.+ """++ session_id: str = ""+ turn_id: str = ""+ #: ``done`` or ``error`` (the turn's own ``turn_finished`` status).+ status: str = "done"+ #: The user's message that started the turn, and Jarvis's reply.+ user_text: str = ""+ reply_text: str = ""++@dataclass(frozen=True, slots=True)class JarvisAgentAnnouncement(Event):"""Jarvis-Agent spawn start signal for UI/telemetry, without a voice ACK."""diff --git a/jarvis/platform/layered_window.py b/jarvis/platform/layered_window.pynew file mode 100644index 0000000000..0e6f583b0a--- /dev/null+++ b/jarvis/platform/layered_window.py@@ -0,0 +1,227 @@+"""Per-pixel alpha for a Tk toplevel on Windows (``UpdateLayeredWindow``).++Tk's ``-transparentcolor`` keys ONE colour out: a pixel is either fully shown+or fully gone, so soft edges and see-through controls are impossible, and a+keyed pixel does not take clicks. A layered window fed through+``UpdateLayeredWindow`` instead shows a premultiplied BGRA bitmap with real+per-pixel alpha, and every pixel whose alpha is above zero still receives the+mouse — so a control can be practically invisible (alpha 1/255) and clickable.++Windows only, behind :func:`per_pixel_alpha_supported`; every other platform+gets ``False`` from each call and keeps its own path. Once a window is fed+through ``UpdateLayeredWindow`` it must never also get+``SetLayeredWindowAttributes`` (Tk's ``-transparentcolor`` / ``-alpha``): the+two modes exclude each other.+"""++from __future__ import annotations++import logging+import sys+from typing import Any++from PIL import Image, ImageChops++log = logging.getLogger(__name__)++_GWL_EXSTYLE = -20+_WS_EX_LAYERED = 0x00080000+_ULW_ALPHA = 0x00000002+_AC_SRC_OVER = 0x00+_AC_SRC_ALPHA = 0x01+_DIB_RGB_COLORS = 0++_api: Any | None = None+++def per_pixel_alpha_supported() -> bool:+ """True where :func:`update_layered` can work (Windows)."""+ return sys.platform == "win32"+++def _load() -> Any:+ """ctypes bindings, built once. Explicit argtypes: handles are 64-bit."""+ global _api+ if _api is not None:+ return _api+ import ctypes # noqa: PLC0415 — Windows-only path+ from ctypes import wintypes # noqa: PLC0415++ class BITMAPINFOHEADER(ctypes.Structure):+ _fields_ = [+ ("biSize", wintypes.DWORD),+ ("biWidth", wintypes.LONG),+ ("biHeight", wintypes.LONG),+ ("biPlanes", wintypes.WORD),+ ("biBitCount", wintypes.WORD),+ ("biCompression", wintypes.DWORD),+ ("biSizeImage", wintypes.DWORD),+ ("biXPelsPerMeter", wintypes.LONG),+ ("biYPelsPerMeter", wintypes.LONG),+ ("biClrUsed", wintypes.DWORD),+ ("biClrImportant", wintypes.DWORD),+ ]++ class BLENDFUNCTION(ctypes.Structure):+ _fields_ = [+ ("BlendOp", ctypes.c_ubyte),+ ("BlendFlags", ctypes.c_ubyte),+ ("SourceConstantAlpha", ctypes.c_ubyte),+ ("AlphaFormat", ctypes.c_ubyte),+ ]++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ gdi32 = ctypes.WinDLL("gdi32", use_last_error=True)+ handle = ctypes.c_void_p+ user32.GetParent.argtypes = [handle]+ user32.GetParent.restype = handle+ user32.GetDC.argtypes = [handle]+ user32.GetDC.restype = handle+ user32.ReleaseDC.argtypes = [handle, handle]+ user32.ReleaseDC.restype = ctypes.c_int+ user32.GetWindowLongPtrW.argtypes = [handle, ctypes.c_int]+ user32.GetWindowLongPtrW.restype = ctypes.c_ssize_t+ user32.SetWindowLongPtrW.argtypes = [handle, ctypes.c_int, ctypes.c_ssize_t]+ user32.SetWindowLongPtrW.restype = ctypes.c_ssize_t+ user32.UpdateLayeredWindow.argtypes = [+ handle,+ handle,+ ctypes.POINTER(wintypes.POINT),+ ctypes.POINTER(wintypes.SIZE),+ handle,+ ctypes.POINTER(wintypes.POINT),+ wintypes.DWORD,+ ctypes.POINTER(BLENDFUNCTION),+ wintypes.DWORD,+ ]+ user32.UpdateLayeredWindow.restype = wintypes.BOOL+ gdi32.CreateCompatibleDC.argtypes = [handle]+ gdi32.CreateCompatibleDC.restype = handle+ gdi32.DeleteDC.argtypes = [handle]+ gdi32.DeleteDC.restype = wintypes.BOOL+ gdi32.CreateDIBSection.argtypes = [+ handle,+ ctypes.POINTER(BITMAPINFOHEADER),+ wintypes.UINT,+ ctypes.POINTER(ctypes.c_void_p),+ handle,+ wintypes.DWORD,+ ]+ gdi32.CreateDIBSection.restype = handle+ gdi32.SelectObject.argtypes = [handle, handle]+ gdi32.SelectObject.restype = handle+ gdi32.DeleteObject.argtypes = [handle]+ gdi32.DeleteObject.restype = wintypes.BOOL++ class Api:+ pass++ api = Api()+ api.ctypes = ctypes+ api.wintypes = wintypes+ api.user32 = user32+ api.gdi32 = gdi32+ api.BITMAPINFOHEADER = BITMAPINFOHEADER+ api.BLENDFUNCTION = BLENDFUNCTION+ _api = api+ return api+++def tk_toplevel_hwnd(top: Any) -> int:+ """The real top-level HWND of a Tk toplevel (``winfo_id`` is its child)."""+ if not per_pixel_alpha_supported():+ return 0+ try:+ inner = int(top.winfo_id())+ parent = _load().user32.GetParent(inner)+ return int(parent or inner)+ except Exception: # noqa: BLE001 — a missing handle degrades to "no alpha"+ log.debug("could not resolve the toplevel HWND", exc_info=True)+ return 0+++def enable_per_pixel_alpha(hwnd: int) -> bool:+ """Mark ``hwnd`` as a layered window. True on success."""+ if not per_pixel_alpha_supported() or not hwnd:+ return False+ try:+ user32 = _load().user32+ style = user32.GetWindowLongPtrW(hwnd, _GWL_EXSTYLE)+ if not style & _WS_EX_LAYERED:+ user32.SetWindowLongPtrW(hwnd, _GWL_EXSTYLE, style | _WS_EX_LAYERED)+ return True+ except Exception: # noqa: BLE001 — degrade to the colour-key path+ log.debug("could not make hwnd=%s layered", hwnd, exc_info=True)+ return False+++def premultiplied_bgra(image: Image.Image) -> bytes:+ """``image`` as top-down premultiplied BGRA bytes, the layout GDI wants."""+ rgba = image.convert("RGBA")+ r, g, b, a = rgba.split()+ return Image.merge(+ "RGBA",+ (ImageChops.multiply(b, a), ImageChops.multiply(g, a), ImageChops.multiply(r, a), a),+ ).tobytes()+++def update_layered(hwnd: int, image: Image.Image) -> bool:+ """Show ``image`` (RGBA, real alpha) as the whole content of ``hwnd``.++ Leaves the window's position alone (Tk keeps placing it) and sets its+ size to the image's. True when Windows accepted the frame.+ """+ if not per_pixel_alpha_supported() or not hwnd:+ return False+ try:+ api = _load()+ except Exception: # noqa: BLE001+ log.debug("layered-window bindings unavailable", exc_info=True)+ return False+ ctypes, wintypes = api.ctypes, api.wintypes+ width, height = image.size+ data = premultiplied_bgra(image)+ screen = api.user32.GetDC(None)+ memdc = api.gdi32.CreateCompatibleDC(screen)+ bitmap = None+ old = None+ try:+ header = api.BITMAPINFOHEADER()+ header.biSize = ctypes.sizeof(api.BITMAPINFOHEADER)+ header.biWidth = width+ header.biHeight = -height # top-down rows+ header.biPlanes = 1+ header.biBitCount = 32+ header.biCompression = 0 # BI_RGB+ bits = ctypes.c_void_p()+ bitmap = api.gdi32.CreateDIBSection(+ screen, ctypes.byref(header), _DIB_RGB_COLORS, ctypes.byref(bits), None, 0+ )+ if not bitmap or not bits.value:+ return False+ ctypes.memmove(bits, data, len(data))+ old = api.gdi32.SelectObject(memdc, bitmap)+ size = wintypes.SIZE(width, height)+ origin = wintypes.POINT(0, 0)+ blend = api.BLENDFUNCTION(_AC_SRC_OVER, 0, 255, _AC_SRC_ALPHA)+ ok = api.user32.UpdateLayeredWindow(+ hwnd,+ screen,+ None,+ ctypes.byref(size),+ memdc,+ ctypes.byref(origin),+ 0,+ ctypes.byref(blend),+ _ULW_ALPHA,+ )+ if not ok:+ log.debug("UpdateLayeredWindow refused hwnd=%s (err %s)", hwnd, ctypes.get_last_error())+ return bool(ok)+ finally:+ if old:+ api.gdi32.SelectObject(memdc, old)+ if bitmap:+ api.gdi32.DeleteObject(bitmap)+ api.gdi32.DeleteDC(memdc)+ api.user32.ReleaseDC(None, screen)diff --git a/jarvis/ui/pets/notices.py b/jarvis/ui/pets/notices.pyindex 0c8395a617..ef686c240a 100644--- a/jarvis/ui/pets/notices.py+++ b/jarvis/ui/pets/notices.py@@ -1,24 +1,20 @@-"""What the desktop pet's bell announces, and how each card is worded.--The pet shows a notification card (``OrbOverlay.push_notice``) when something-happens that the user is likely waiting for while they look elsewhere:--* a coding agent in an Agentic IDE pane finished, asks a question, exited or- could not start (``jarvis.agentic_ide.notifications`` entries),-* a background Jarvis-Agent task finished or failed,-* a mission ended (approved, failed or timed out — a cancel was the user's own- doing and is not news),-* a coding result for a Jarvis conversation is ready,-* a tool call waits for the user's approval (except approvals a chat surface- answers on its own cards — the user is already looking at those),-* a scheduled workflow (routine) finished or failed,-* an error nothing recovers from.--Every function here is pure: it turns one event into ``(kind, title, detail)``-or ``None`` (not worth a card). ``kind`` is the card's icon — ``done``,-``attention``, ``error`` or ``info``. Titles are fixed labels per interface-language; every supported locale has its own entry and none is a fallback for-another.+"""Which finished things the desktop pet confirms with a card, and how.++The pet's done cards are about Jarvis and nothing else. A card appears when:++* a typed chat with Jarvis finished a turn (``JarvisChatTurnFinished``) — the+ card is what was asked over the start of Jarvis's answer, like the Codex+ companion's confirmation;+* a task Jarvis itself started finished: a background Jarvis-Agent task+ (``JarvisAgentBackgroundCompleted``) or a coding job Jarvis delegated to an+ agent (``DelegationResultReady``).++A coding agent the user runs on their own, a mission, a routine or an error+somewhere in the app is not Jarvis answering, and gets no card. Spoken turns+get none either: the answer was heard, and echoing it reads as noise.++Every function is pure: one event in, ``(kind, title, detail)`` or ``None``+out. ``kind`` is ``done`` (a check) or ``error`` (a cross)."""from __future__ import annotations@@ -27,203 +23,97 @@ from typing import Anyfrom jarvis.ui.pets.status_line import condense-#: One card: its icon kind, bold title and muted detail line.+#: One card: its icon kind, bold title and the answer under it.Notice = tuple[str, str, str]-NOTICE_TITLE_CHARS = 60-NOTICE_DETAIL_CHARS = 110+NOTICE_TITLE_CHARS = 70+NOTICE_DETAIL_CHARS = 160NOTICE_LABELS: dict[str, dict[str, str]] = {- "agent_finished": {- "en": "{name} finished",- "de": "{name} ist fertig", # i18n-allow- "es": "{name} terminó", # i18n-allow- },- "agent_asks": {- "en": "{name} needs your answer",- "de": "{name} wartet auf dich", # i18n-allow- "es": "{name} necesita tu respuesta", # i18n-allow- },- "agent_exited": {- "en": "{name} exited",- "de": "{name} wurde beendet", # i18n-allow- "es": "{name} se cerró", # i18n-allow- },- "agent_failed": {- "en": "{name} could not start",- "de": "{name} konnte nicht starten", # i18n-allow- "es": "{name} no pudo iniciarse", # i18n-allow- },"task_done": {- "en": "Background task done",- "de": "Hintergrundaufgabe erledigt", # i18n-allow- "es": "Tarea en segundo plano lista", # i18n-allow+ "en": "Task done",+ "de": "Aufgabe erledigt", # i18n-allow+ "es": "Tarea hecha", # i18n-allow},"task_failed": {- "en": "Background task failed",- "de": "Hintergrundaufgabe fehlgeschlagen", # i18n-allow- "es": "La tarea en segundo plano falló", # i18n-allow- },- "mission_done": {- "en": "Mission complete",- "de": "Mission abgeschlossen", # i18n-allow- "es": "Misión completada", # i18n-allow- },- "mission_failed": {- "en": "Mission failed",- "de": "Mission fehlgeschlagen", # i18n-allow- "es": "La misión falló", # i18n-allow- },- "mission_timed_out": {- "en": "Mission timed out",- "de": "Mission abgelaufen", # i18n-allow- "es": "La misión agotó el tiempo", # i18n-allow+ "en": "Task failed",+ "de": "Aufgabe fehlgeschlagen", # i18n-allow+ "es": "La tarea falló", # i18n-allow},"result_ready": {- "en": "{name} has a result",- "de": "Ergebnis von {name} ist da", # i18n-allow- "es": "{name} tiene un resultado", # i18n-allow- },- "approval": {- "en": "Approval needed",- "de": "Freigabe nötig", # i18n-allow- "es": "Se necesita aprobación", # i18n-allow- },- "routine_done": {- "en": "Routine finished",- "de": "Routine erledigt", # i18n-allow- "es": "Rutina terminada", # i18n-allow- },- "routine_failed": {- "en": "Routine failed",- "de": "Routine fehlgeschlagen", # i18n-allow- "es": "La rutina falló", # i18n-allow+ "en": "{name} is done",+ "de": "{name} ist fertig", # i18n-allow+ "es": "{name} terminó", # i18n-allow},- "error": {- "en": "Something went wrong",- "de": "Etwas ist schiefgelaufen", # i18n-allow- "es": "Algo salió mal", # i18n-allow+ "result_failed": {+ "en": "{name} failed",+ "de": "{name} ist gescheitert", # i18n-allow+ "es": "{name} falló", # i18n-allow},"agent": {- "en": "Agent",- "de": "Agent", # i18n-allow- "es": "Agente", # i18n-allow+ "en": "The agent",+ "de": "Der Agent", # i18n-allow+ "es": "El agente", # i18n-allow+ },+ "no_answer": {+ "en": "Jarvis could not answer",+ "de": "Jarvis konnte nicht antworten", # i18n-allow+ "es": "Jarvis no pudo responder", # i18n-allow},}def label(key: str, language: str, **values: str) -> str:- """One title in ``language`` (English when the locale is unknown)."""+ """One label in ``language`` (English when the locale is unknown)."""labels = NOTICE_LABELS[key]text = labels.get(language, labels["en"])return text.format(**values) if values else text-def _title(text: str) -> str:- return condense(text, max_chars=NOTICE_TITLE_CHARS)-+def _title(text: object) -> str:+ return condense(str(text or ""), max_chars=NOTICE_TITLE_CHARS)-def _detail(*parts: object) -> str:- joined = " · ".join(str(p).strip() for p in parts if str(p or "").strip())- return condense(joined, max_chars=NOTICE_DETAIL_CHARS)+def _detail(text: object) -> str:+ return condense(str(text or ""), max_chars=NOTICE_DETAIL_CHARS)-def _name(value: object, language: str) -> str:- name = " ".join(str(value or "").split())- return name or label("agent", language)--def for_pane_entry(entry: Any, language: str) -> Notice | None:- """An Agentic IDE notification (``agentic_ide.notifications.Notification``)."""- kind = str(getattr(entry, "kind", "") or "")- name = _name(getattr(entry, "display_name", "") or getattr(entry, "agent", "") or "", language)- pane = str(getattr(entry, "pane", "") or "")- detail = _detail(pane, getattr(entry, "detail", ""))- if kind == "completed":- return "done", _title(label("agent_finished", language, name=name)), detail- if kind == "needs_input":- return "attention", _title(label("agent_asks", language, name=name)), detail- if kind == "failed":- return "error", _title(label("agent_failed", language, name=name)), detail- if kind == "exited":- return "info", _title(label("agent_exited", language, name=name)), detail- return None+def for_chat_turn(event: Any, language: str) -> Notice | None:+ """``JarvisChatTurnFinished``: the question over the start of the answer."""+ asked = _title(getattr(event, "user_text", ""))+ reply = _detail(getattr(event, "reply_text", ""))+ if str(getattr(event, "status", "done")) == "error":+ return "error", asked or label("no_answer", language), reply+ if not (asked or reply):+ return None+ return "done", asked or reply, reply if asked else ""def for_background_task(event: Any, language: str) -> Notice:- """``JarvisAgentBackgroundCompleted``."""- if bool(getattr(event, "success", False)):- detail = _detail(getattr(event, "summary", "") or getattr(event, "utterance", ""))- return "done", label("task_done", language), detail- detail = _detail(getattr(event, "error", "") or getattr(event, "utterance", ""))- return "error", label("task_failed", language), detail---def for_mission(event: Any, language: str) -> Notice | None:- """``MissionCompleted`` — a cancel is the user's own act and stays quiet."""- status = str(getattr(event, "status", "") or "")- summary = getattr(event, "summary_de" if language == "de" else "summary_en", "") or ""- summary = summary or getattr(event, "summary_en", "") or ""- if status == "approved":- return "done", label("mission_done", language), _detail(summary)- if status == "failed":- return (- "error",- label("mission_failed", language),- _detail(getattr(event, "reason", "") or summary),- )- if status == "timed_out":- return "error", label("mission_timed_out", language), _detail(summary)- return None---def for_delegation_result(event: Any, language: str) -> Notice | None:- """``DelegationResultReady`` — a coding result addressed to a conversation."""- name = _name(getattr(event, "agent_name", ""), language)+ """``JarvisAgentBackgroundCompleted``: what was asked over the result."""+ asked = getattr(event, "utterance", "")+ success = bool(getattr(event, "success", False))+ title = _title(asked) or label("task_done" if success else "task_failed", language)+ if success:+ return "done", title, _detail(getattr(event, "summary", ""))+ return "error", title, _detail(getattr(event, "error", "") or getattr(event, "summary", ""))+++def for_delegation_result(event: Any, language: str) -> Notice:+ """``DelegationResultReady``: a coding job Jarvis handed to an agent came back."""+ name = " ".join(str(getattr(event, "agent_name", "") or "").split()) or label("agent", language)+ text = _detail(getattr(event, "text", "") or getattr(event, "report", ""))status = str(getattr(event, "status", "") or "").lower()- text = getattr(event, "text", "") or getattr(event, "report", "")if status in ("failed", "error"):- return "error", _title(label("agent_failed", language, name=name)), _detail(text)- return "done", _title(label("result_ready", language, name=name)), _detail(text)---def for_approval(event: Any, language: str) -> Notice | None:- """``ActionApprovalRequired`` — skipped when a chat answers its own cards."""- if getattr(event, "approval_ref", None):- return None- tool = str(getattr(event, "tool_name", "") or "").split("__")[-1]- tool = tool.replace("_", " ").replace("-", " ").strip()- tool = tool[:1].upper() + tool[1:]- return (- "attention",- label("approval", language),- _detail(tool, getattr(event, "args_preview", "")),- )---def for_workflow(event: Any, language: str, name: str = "") -> Notice:- """``WorkflowCompleted`` — ``name`` is the routine's display name if known."""- if bool(getattr(event, "success", False)):- return "done", label("routine_done", language), _detail(name)- return "error", label("routine_failed", language), _detail(name, getattr(event, "error", ""))---def for_error(event: Any, language: str) -> Notice | None:- """``ErrorOccurred`` — only one nothing recovers from."""- if bool(getattr(event, "recoverable", True)):- return None- return "error", label("error", language), _detail(getattr(event, "message", ""))+ return "error", _title(label("result_failed", language, name=name)), text+ return "done", _title(label("result_ready", language, name=name)), text__all__ = ["NOTICE_LABELS","Notice",- "for_approval","for_background_task",+ "for_chat_turn","for_delegation_result",- "for_error",- "for_mission",- "for_pane_entry",- "for_workflow","label",]diff --git a/tests/unit/platform/test_layered_window.py b/tests/unit/platform/test_layered_window.pynew file mode 100644index 0000000000..3cf2b3c6c7--- /dev/null+++ b/tests/unit/platform/test_layered_window.py@@ -0,0 +1,36 @@+"""``jarvis.platform.layered_window`` — per-pixel alpha for Tk windows."""++from __future__ import annotations++import sys++import pytest+from PIL import Image++from jarvis.platform import layered_window+++def test_premultiplied_bgra_orders_and_scales_the_channels() -> None:+ img = Image.new("RGBA", (1, 1), (200, 100, 50, 128))+ b, g, r, a = layered_window.premultiplied_bgra(img)+ assert a == 128+ assert (b, g, r) == (round(50 * 128 / 255), round(100 * 128 / 255), round(200 * 128 / 255))+++def test_a_transparent_pixel_is_all_zero() -> None:+ assert layered_window.premultiplied_bgra(+ Image.new("RGBA", (2, 1), (255, 255, 255, 0))+ ) == bytes(8)++[email protected](sys.platform == "win32", reason="the no-op path is for other platforms")+def test_every_call_is_a_quiet_no_op_off_windows() -> None:+ assert layered_window.per_pixel_alpha_supported() is False+ assert layered_window.tk_toplevel_hwnd(object()) == 0+ assert layered_window.enable_per_pixel_alpha(123) is False+ assert layered_window.update_layered(123, Image.new("RGBA", (1, 1))) is False+++def test_a_missing_window_is_refused_without_raising() -> None:+ assert layered_window.enable_per_pixel_alpha(0) is False+ assert layered_window.update_layered(0, Image.new("RGBA", (1, 1))) is Falsediff --git a/tests/unit/ui/test_pet_notices.py b/tests/unit/ui/test_pet_notices.pyindex b95af68fec..41c7725db1 100644--- a/tests/unit/ui/test_pet_notices.py+++ b/tests/unit/ui/test_pet_notices.py@@ -1,32 +1,32 @@-"""The desktop pet's bell and notification cards (docs/pets.md "Notifications").--Pins, without a real window: which events become cards and how they are-worded, the stack's model and geometry (newest in front, two peeking, fanned-out on hover, mirrored upward when there is no room below), the springs that-move it, icons that never meet the colour key, the bell glyph and its swing,-the bell toggle on the overlay, the bridge's routing, the Agentic IDE hook, and-the macOS proxy / host round trip that keeps the bell across a respawn.+"""The desktop pet's card column and bell (docs/pets.md "Cards").++Pins, without a real window: which events become done cards (Jarvis only) and+how they read, the column's model and geometry (thinking line on top, newest+card in front, two peeking, fanned out on hover, mirrored upward), the springs,+the card renderer (see-through surface, soft shadow, hard edges on a colour+key), the bell glyph and toggle, the overlay's thinking-line routing, the+bridge, the chat service's announcement, and the macOS proxy / host round trip."""from __future__ import annotations+import asynciofrom types import SimpleNamespaceimport pytest-from jarvis.agentic_ide.notifications import Notification, NotificationCenter+from jarvis.agent_chat.service import AgentChatServicefrom jarvis.core import runtime_refsfrom jarvis.core.bus import EventBusfrom jarvis.core.events import (- ActionApprovalRequired,- ErrorOccurred,+ DelegationResultReady,JarvisAgentBackgroundCompleted,+ JarvisChatTurnFinished,MissionCompleted,- WorkflowCompleted,)from jarvis.ui.jarvisbar.subprocess_overlay import SubprocessMascotOverlayfrom jarvis.ui.pets import notices-from ui.orb import controls+from ui.orb import controls, pet_cardsfrom ui.orb import notice_stack as nsfrom ui.orb.bus_bridge import OrbBusBridgefrom ui.orb.overlay import OrbOverlay@@ -34,184 +34,142 @@ from ui.orb.overlay import OrbOverlayKEY = (255, 0, 255)-def _entry(kind: str, **overrides: object) -> Notification:- values: dict[str, object] = {- "id": "n1",- "kind": kind,- "workspace_id": "w1",- "workspace": "Jarvis",- "pane_key": "T2",- "pane": "Mika",- "agent": "claude",- "display_name": "Claude",- "title": "Finished and waiting at its prompt",- "detail": "Refactor the notice stack",- "created_at": 1.0,- }- values.update(overrides)- return Notification(**values) # type: ignore[arg-type]---# --- wording ---------------------------------------------------------------------- ("kind", "icon", "title"),- [- ("completed", "done", "Claude finished"),- ("needs_input", "attention", "Claude needs your answer"),- ("failed", "error", "Claude could not start"),- ("exited", "info", "Claude exited"),- ],-)-def test_a_pane_entry_names_its_agent_and_pane(kind: str, icon: str, title: str) -> None:- notice = notices.for_pane_entry(_entry(kind), "en")- assert notice == (icon, title, "Mika · Refactor the notice stack")-+# --- which events become cards -------------------------------------------------------def test_every_locale_has_its_own_titles() -> None:- for key, labels in notices.NOTICE_LABELS.items():- assert set(labels) == {"en", "de", "es"}, key- assert notices.for_pane_entry(_entry("completed"), "de")[1] == "Claude ist fertig"- # An unknown interface language reads English rather than nothing.- assert notices.for_pane_entry(_entry("completed"), "fr")[1] == "Claude finished"+def test_a_jarvis_chat_turn_is_the_question_over_the_answer() -> None:+ event = JarvisChatTurnFinished(user_text="Hi", reply_text="Hi! How can I help?")+ assert notices.for_chat_turn(event, "en") == ("done", "Hi", "Hi! How can I help?")-def test_a_pane_without_names_still_says_who() -> None:- notice = notices.for_pane_entry(_entry("completed", display_name="", agent=""), "en")- assert notice is not None and notice[1] == "Agent finished"+def test_a_failed_chat_turn_is_a_cross_and_an_empty_one_is_nothing() -> None:+ failed = JarvisChatTurnFinished(status="error", user_text="Book a table")+ assert notices.for_chat_turn(failed, "en") == ("error", "Book a table", "")+ no_text = JarvisChatTurnFinished(status="error")+ assert notices.for_chat_turn(no_text, "de") == ("error", "Jarvis konnte nicht antworten", "")+ assert notices.for_chat_turn(JarvisChatTurnFinished(), "en") is None-def test_mission_outcomes_but_not_a_cancel() -> None:- done = MissionCompleted(mission_id="m", status="approved", summary_en="Shipped the fix")- failed = MissionCompleted(mission_id="m", status="failed", reason="Tests failed")- cancelled = MissionCompleted(mission_id="m", status="cancelled")- assert notices.for_mission(done, "en") == ("done", "Mission complete", "Shipped the fix")- assert notices.for_mission(failed, "en") == ("error", "Mission failed", "Tests failed")- assert notices.for_mission(cancelled, "en") is None---def test_an_approval_a_chat_answers_itself_is_not_a_card() -> None:- plain = ActionApprovalRequired(tool_name="mcp__fs__delete_file", args_preview="a.txt")- chat = ActionApprovalRequired(tool_name="delete_file", approval_ref="agent-chat:1")- assert notices.for_approval(plain, "en") == (- "attention",- "Approval needed",- "Delete file · a.txt",- )- assert notices.for_approval(chat, "en") is None--def test_only_an_unrecoverable_error_is_a_card() -> None:- assert notices.for_error(ErrorOccurred(message="retrying", recoverable=True), "en") is None- card = notices.for_error(ErrorOccurred(message="Brain offline", recoverable=False), "en")- assert card == ("error", "Something went wrong", "Brain offline")---def test_background_task_and_routine_outcomes() -> None:- ok = JarvisAgentBackgroundCompleted(success=True, summary="Report written")+def test_jarvis_started_tasks_report_back() -> None:+ ok = JarvisAgentBackgroundCompleted(success=True, utterance="Write the report", summary="Done")bad = JarvisAgentBackgroundCompleted(success=False, error="Timed out")- assert notices.for_background_task(ok, "en") == (+ assert notices.for_background_task(ok, "en") == ("done", "Write the report", "Done")+ assert notices.for_background_task(bad, "en") == ("error", "Task failed", "Timed out")+ result = DelegationResultReady(agent_name="Codex", status="done", text="Fixed the test")+ assert notices.for_delegation_result(result, "en") == ("done",- "Background task done",- "Report written",+ "Codex is done",+ "Fixed the test",)- assert notices.for_background_task(bad, "en")[0] == "error"- assert notices.for_workflow(WorkflowCompleted(success=True), "en")[0] == "done"- assert notices.for_workflow(WorkflowCompleted(success=False, error="x"), "en")[0] == "error"-# --- model ---------------------------------------------------------------------+def test_every_locale_has_its_own_labels() -> None:+ for key, labels in notices.NOTICE_LABELS.items():+ assert set(labels) == {"en", "de", "es"}, key+ assert notices.label("task_done", "fr") == "Task done" # unknown locale: English+++# --- model and geometry ------------------------------------------------------------def test_the_newest_card_is_in_front_and_the_oldest_falls_out() -> None:- model = ns.NoticeModel(keep=3)- for i in range(4):+ model = ns.NoticeModel()+ for i in range(ns.NOTICE_KEEP + 1):model.push("done", f"T{i}", "", now=float(i * 10))assert [n.title for n in model.items] == ["T3", "T2", "T1"]-def test_a_twin_within_the_window_refreshes_instead_of_stacking() -> None:+def test_a_twin_refreshes_and_cards_expire_unless_paused() -> None:model = ns.NoticeModel()- first, _ = model.push("done", "Claude finished", "Mika", now=0.0)- again, dropped = model.push("done", "Claude finished", "Mika", now=1.0)+ first, _ = model.push("done", "Hi", "Hello", now=0.0)+ again, dropped = model.push("done", "Hi", "Hello", now=1.0)assert again is first and dropped == [] and len(model.items) == 1- model.push("done", "Claude finished", "Mika", now=1.0 + ns.NOTICE_DEDUPE_S)- assert len(model.items) == 2---def test_cards_expire_by_kind_and_a_pause_holds_them() -> None:- model = ns.NoticeModel()- model.push("done", "a", "", now=0.0)- model.push("attention", "b", "", now=0.0)- assert model.expire(ns.NOTICE_TTL_S["done"] - 0.1) == []model.pause(5.0)assert model.expire(ns.NOTICE_TTL_S["done"] + 1.0) == []- gone = model.expire(ns.NOTICE_TTL_S["done"] + 5.0)- assert [n.title for n in gone] == ["a"]- assert [n.title for n in model.items] == ["b"]---def test_an_unknown_kind_is_info() -> None:+ assert [n.title for n in model.expire(ns.NOTICE_TTL_S["done"] + 7.0)] == ["Hi"]notice, _ = ns.NoticeModel().push("party", "x", "", now=0.0)- assert notice.kind == "info"---# --- geometry ------------------------------------------------------------------+ assert notice.kind == "done"-def test_a_folded_stack_peeks_two_cards_and_hides_the_rest() -> None:- slots = ns.stack_slots(4, expanded=False, card_h=60, scale=1.0)- assert [s.depth for s in slots] == [0, 1, 2, 3]- assert slots[0].y == 0 and slots[0].inset == 0- assert slots[1].y == ns.PEEK_OFFSET and slots[1].inset == ns.PEEK_INSET- # The fourth hides exactly behind the third.- assert (slots[3].y, slots[3].inset) == (slots[2].y, slots[2].inset)- assert ns.stack_height(4, expanded=False, card_h=60, scale=1.0) == 60 + 2 * ns.PEEK_OFFSET+def test_the_thinking_line_sits_on_top_and_cards_peek_below() -> None:+ status, slots = ns.column_layout(40, [60, 60, 60, 60], expanded=False, scale=1.0)+ assert status == ns.Slot(0.0, 1.0, 1.0)+ front = slots[0]+ assert front.y == 40 + ns.CARD_GAP and front.size == 1.0 and front.opacity == 1.0+ # Each card behind is smaller and fainter, its bottom a step lower.+ assert slots[1].size < 1.0 and slots[1].opacity < 1.0+ bottoms = [s.y + 60 * s.size for s in slots[:3]]+ assert bottoms == pytest.approx([bottoms[0] + i * ns.PEEK_OFFSET for i in range(3)])+ assert slots[3].opacity == 0.0 # the fourth hides behind the third-def test_a_fanned_stack_is_a_column_and_upward_mirrors_it() -> None:- down = ns.stack_slots(3, expanded=True, card_h=60, scale=1.0)- assert [s.y for s in down] == [0, 60 + ns.CARD_GAP, 2 * (60 + ns.CARD_GAP)]- assert all(s.depth == 0 and s.inset == 0 for s in down)- up = ns.stack_slots(3, expanded=True, card_h=60, scale=1.0, upward=True)- height = ns.stack_height(3, expanded=True, card_h=60, scale=1.0)- # Upward, the newest card sits at the bottom, nearest the pet.- assert up[0].y == height - 60 and up[-1].y == 0+def test_fanned_out_cards_form_a_column() -> None:+ status, slots = ns.column_layout(None, [60, 80], expanded=True, scale=1.0)+ assert status is None+ assert [s.y for s in slots] == [0, 60 + ns.CARD_GAP]+ assert all(s.size == 1.0 and s.opacity == 1.0 for s in slots)-def test_a_spring_settles_on_its_target_with_a_small_overshoot() -> None:+def test_a_spring_settles_with_a_small_overshoot() -> None:spring = ns.Spring(0.0, 100.0)peak = 0.0for _ in range(120):spring.step(1 / 60)peak = max(peak, spring.value)- assert spring.settled- assert 100.0 <= peak < 108.0--[email protected]("kind", ns.NOTICE_KINDS)-def test_icons_are_opaque_and_end_fully_drawn(kind: str) -> None:- bg = ns.CARD_FILL- first = ns.render_icon(kind, 0, 32, bg)- last = ns.render_icon(kind, ns.ICON_FRAMES, 32, bg)- assert first.mode == last.mode == "RGB" and last.size == (32, 32)- assert KEY not in {c for _n, c in last.getcolors(32 * 32)}- # Frame 0 is still empty; the last frame carries the kind's colour.- assert first.getcolors(1) is not None- glyph, _disc = ns.ICON_COLORS[kind]- assert any(- abs(c[0] - glyph[0]) < 12 and abs(c[1] - glyph[1]) < 12 for _n, c in last.getcolors(4096)- )+ assert spring.settled and 100.0 <= peak < 108.0+++# --- the cards themselves -----------------------------------------------------------def test_the_icon_frame_follows_the_card_age() -> None:- assert ns.icon_frame(0.0) == 0- assert 0 < ns.icon_frame(ns.ICON_ANIM_S / 2) < ns.ICON_FRAMES- assert ns.icon_frame(10.0) == ns.ICON_FRAMES+def test_a_done_card_is_see_through_with_a_soft_shadow() -> None:+ card = pet_cards.render_card("done", "Hi", "Hi! How can I help?", scale=1.0, max_width=360)+ assert card.mode == "RGBA"+ x0, y0, x1, y1 = pet_cards.card_box(card, 1.0)+ middle = card.getpixel(((x0 + x1) // 2, y1 - 3))+ assert 150 < middle[3] < 255 # the desktop shows through the surface+ shadow = card.getpixel(((x0 + x1) // 2, y1 + 3))+ assert 0 < shadow[3] < 120 # a soft shadow under it, not a hard edge+ assert card.getpixel((0, 0))[3] == 0-# --- the bell on the strip -------------------------------------------------------+def test_cards_fit_their_text_and_never_outgrow_the_limit() -> None:+ short = pet_cards.render_card("status", "Thinking …", "", scale=1.0, max_width=360)+ long = pet_cards.render_card("done", "word " * 40, "word " * 80, scale=1.0, max_width=300)+ pad = 2 * pet_cards.SHADOW_PAD+ assert short.width - pad < 200+ assert long.width - pad <= 300+ assert long.height - pad < 120 # title on one line, the answer on two+++def test_text_helpers_ellipsize_and_wrap() -> None:+ font = pet_cards.font("regular", 14)+ assert pet_cards.ellipsize("x" * 400, font, 100).endswith("…")+ lines = pet_cards.wrap("word " * 60, font, 200, 2)+ assert len(lines) == 2 and lines[-1].endswith("…")+++def test_a_keyed_frame_has_hard_edges_only() -> None:+ card = pet_cards.render_card("done", "Hi", "Hello", scale=1.0, max_width=360)+ flat = pet_cards.flatten_for_key(card, KEY)+ colours = {c for _n, c in flat.getcolors(flat.width * flat.height)}+ pinkish = {c for c in colours if c != KEY and c[0] > 200 and c[2] > 200 and c[1] < 80}+ assert KEY in colours and not pinkish+++def test_the_icon_ticks_itself_and_the_sweep_moves() -> None:+ empty = pet_cards.render_icon("done", 0, 20)+ full = pet_cards.render_icon("done", pet_cards.ICON_FRAMES, 20)+ assert empty.getchannel("A").getextrema()[1] == 0+ assert full.getchannel("A").getextrema()[1] == 255+ line = pet_cards.render_card("status", "Thinking …", "", scale=1.0, max_width=360)+ a = pet_cards.shimmer(line, 4, 1.0)+ b = pet_cards.shimmer(line, 12, 1.0)+ assert a.tobytes() != b.tobytes()+ assert a.getchannel("A").tobytes() == line.getchannel("A").tobytes()+++# --- the bell ----------------------------------------------------------------------def test_the_bell_has_a_muted_look_and_a_swing() -> None:@@ -219,9 +177,7 @@ def test_the_bell_has_a_muted_look_and_a_swing() -> None:off = controls.render_pet_strip(controls.PetStripState(notify_off=True))swung = controls.render_pet_strip(controls.PetStripState(ring=2))assert on.tobytes() != off.tobytes() != swung.tobytes()- assert controls.ring_angle(0) == 0.0- assert controls.ring_angle(controls.PET_RING_PHASES) == 0.0- assert max(abs(controls.ring_angle(i)) for i in range(controls.PET_RING_PHASES)) > 8.0+ assert controls.ring_angle(0) == 0.0 == controls.ring_angle(controls.PET_RING_PHASES)class _Strip:@@ -242,39 +198,64 @@ class _Strip:pass-def _pet() -> tuple[OrbOverlay, _Strip]:+class _Column:+ def __init__(self) -> None:+ self.calls: list[tuple] = []+ self.count = 0++ def set_status(self, line: str) -> None:+ self.calls.append(("status", line))++ def clear_status(self, linger: float) -> None:+ self.calls.append(("clear", linger))++ def clear(self) -> None:+ self.calls.append(("clear_cards",))+++def _pet() -> tuple[OrbOverlay, _Strip, _Column]:pet = OrbOverlay(style="pet")- strip = _Strip()+ strip, column = _Strip(), _Column()pet._controls = strip # type: ignore[assignment]- return pet, strip+ pet._notices = column # type: ignore[assignment]+ pet._card_column = lambda: column # type: ignore[method-assign]+ pet._enqueue_ui = lambda fn: fn() # type: ignore[method-assign]+ return pet, strip, column-def test_the_bell_toggles_and_reports_its_state(monkeypatch: pytest.MonkeyPatch) -> None:+def test_the_bell_toggles_reports_and_clears(monkeypatch: pytest.MonkeyPatch) -> None:import ui.orb.overlay as overlay_modmonkeypatch.setattr(overlay_mod, "PetControlStrip", _Strip)- pet, strip = _pet()+ pet, strip, column = _pet()seen: list[bool] = []pet.set_on_notifications_toggle(seen.append)pet._on_control_action("bell")assert pet.notifications_enabled is False- assert {"notify_off": True} in strip.states+ assert {"notify_off": True} in strip.states and ("clear_cards",) in column.callspet._on_control_action("bell")- assert pet.notifications_enabled is Trueassert seen == [False, True]-def test_cards_are_dropped_while_the_bell_is_off_or_the_pet_hidden() -> None:- pet, _strip = _pet()- pet._notify_enabled = False- pet._apply_notice("done", "x", "") # no root, no bell: nothing to build- assert pet._notices is None- OrbOverlay(style="mascot").push_notice("done", "x", "") # other looks: no-op- pet.push_notice("done", "x", "") # before the window exists: safe+def test_the_thinking_line_shows_the_current_step_else_the_heading() -> None:+ pet, _strip, column = _pet()+ pet.show_status("Planning", "Search the web")+ pet.show_status("Thinking …", "")+ pet.clear_status(2.0)+ assert column.calls == [("status", "Search the web"), ("status", "Thinking …"), ("clear", 2.0)]++def test_no_thinking_line_when_the_card_is_switched_off() -> None:+ pet, _strip, column = _pet()+ pet._pet_bubble = False+ pet.show_status("Thinking …", "")+ assert column.calls == []-def test_cards_keep_the_strip_in_sight() -> None:- pet, _strip = _pet()++def test_cards_keep_the_strip_in_sight_and_calls_are_safe_early() -> None:+ pet = OrbOverlay(style="pet")+ pet.push_notice("done", "x", "") # no window yet: safe+ OrbOverlay(style="mascot").push_notice("done", "x", "") # other looks: no-oppet._pet_id = "gigi"pet._mode = "idle"assert pet._pet_strip_wanted() is False@@ -282,7 +263,7 @@ def test_cards_keep_the_strip_in_sight() -> None:assert pet._pet_strip_wanted() is True-# --- routing ---------------------------------------------------------------------+# --- routing -----------------------------------------------------------------------class _PetSurface:@@ -290,7 +271,7 @@ class _PetSurface:keeps_visible_when_idle = Truedef __init__(self) -> None:- self.notices: list[tuple[str, str, str]] = []+ self.cards: list[tuple[str, str, str]] = []def show(self, mode: str = "listen") -> None:pass@@ -299,7 +280,7 @@ class _PetSurface:passdef push_notice(self, kind: str, title: str, detail: str) -> None:- self.notices.append((kind, title, detail))+ self.cards.append((kind, title, detail))@pytest.fixture(autouse=True)@@ -307,25 +288,14 @@ def _no_live_pipeline(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(runtime_refs, "_SPEECH_PIPELINE", [])-async def test_the_bridge_turns_events_and_pane_entries_into_cards(- monkeypatch: pytest.MonkeyPatch,-) -> None:- from jarvis.agentic_ide import notifications as ide-- center = NotificationCenter()- monkeypatch.setattr(ide, "center", lambda: center)+async def test_the_bridge_confirms_jarvis_turns_only() -> None:bus = EventBus()pet = _PetSurface()- bridge = OrbBusBridge(bus=bus, orb=pet, language="en") # type: ignore[arg-type]- bridge.attach()- await bus.publish(MissionCompleted(mission_id="m", status="approved", summary_en="Done it"))- await bus.publish(MissionCompleted(mission_id="m", status="cancelled"))- await bus.publish(ErrorOccurred(message="retry", recoverable=True))- center.add(_entry("needs_input"))- assert pet.notices == [- ("done", "Mission complete", "Done it"),- ("attention", "Claude needs your answer", "Mika · Refactor the notice stack"),- ]+ OrbBusBridge(bus=bus, orb=pet, language="en").attach() # type: ignore[arg-type]+ await bus.publish(JarvisChatTurnFinished(user_text="Hi", reply_text="Hello!"))+ await bus.publish(MissionCompleted(mission_id="m", status="approved")) # not Jarvis+ await bus.publish(DelegationResultReady(agent_name="Codex", text="Done"))+ assert pet.cards == [("done", "Hi", "Hello!"), ("done", "Codex is done", "Done")]async def test_a_bar_gets_no_cards() -> None:@@ -335,24 +305,44 @@ async def test_a_bar_gets_no_cards() -> None:bus = EventBus()bar = _Bar()OrbBusBridge(bus=bus, orb=bar).attach() # type: ignore[arg-type]- await bus.publish(MissionCompleted(mission_id="m", status="failed", reason="x"))- assert bar.notices == []+ await bus.publish(JarvisChatTurnFinished(user_text="Hi", reply_text="Hello!"))+ assert bar.cards == []++class _Store:+ def __init__(self, surface: str) -> None:+ self.session = SimpleNamespace(surface=surface)-def test_a_failing_listener_does_not_stop_the_centre() -> None:- center = NotificationCenter()- seen: list[str] = []+ def get_session(self, _sid: str) -> SimpleNamespace:+ return self.session- def _boom(_entry: Notification) -> None:- raise RuntimeError("listener broke")+ def list_events(self, _sid: str, *, tail: int | None = None) -> list[dict]:+ return [+ {"kind": "user_message", "payload": {"text": "Hi"}},+ {"kind": "assistant_text", "payload": {"turn_id": "t1", "text": "Hi! How"}},+ {"kind": "assistant_text", "payload": {"turn_id": "t1", "text": "can I help?"}},+ ]- center.subscribe(_boom)- unsubscribe = center.subscribe(lambda e: seen.append(e.id))- center.add(_entry("completed"))- unsubscribe()- center.add(_entry("completed", id="n2"))- assert seen == ["n1"]- assert len(center.list()) == 2++async def test_the_chat_service_announces_finished_jarvis_turns() -> None:+ bus = EventBus()+ seen: list[JarvisChatTurnFinished] = []++ async def _record(event: JarvisChatTurnFinished) -> None:+ seen.append(event)++ bus.subscribe(JarvisChatTurnFinished, _record)+ finished = {"kind": "turn_finished", "payload": {"turn_id": "t1", "status": "done"}}+ for surface in ("jarvis", "agents"):+ stub = SimpleNamespace(_bus=lambda: bus, store=_Store(surface))+ AgentChatService._announce_jarvis_turn(stub, "s1", finished) # type: ignore[arg-type]+ cancelled = {"kind": "turn_finished", "payload": {"turn_id": "t1", "status": "cancelled"}}+ stub = SimpleNamespace(_bus=lambda: bus, store=_Store("jarvis"))+ AgentChatService._announce_jarvis_turn(stub, "s1", cancelled) # type: ignore[arg-type]+ await asyncio.sleep(0.05)+ assert [(e.user_text, e.reply_text, e.status) for e in seen] == [+ ("Hi", "Hi! How can I help?", "done")+ ]def test_the_proxy_and_host_carry_cards_and_keep_the_bell_across_a_respawn() -> None:@@ -361,7 +351,7 @@ def test_the_proxy_and_host_carry_cards_and_keep_the_bell_across_a_respawn() ->proxy = SubprocessMascotOverlay(style="pet")sent: list[dict] = []proxy._send = sent.append # type: ignore[method-assign]- proxy.push_notice("done", "Claude finished", "Mika")+ proxy.push_notice("done", "Hi", "Hello")proxy._dispatch_event({"event": "notify_toggle", "enabled": False})assert proxy.notifications_enabled is Falsesent.clear()diff --git a/tests/unit/ui/test_pet_overlay_surface.py b/tests/unit/ui/test_pet_overlay_surface.pyindex 4b7f402e9b..77a33341fc 100644--- a/tests/unit/ui/test_pet_overlay_surface.py+++ b/tests/unit/ui/test_pet_overlay_surface.py@@ -19,7 +19,7 @@ from jarvis.ui.desktop_app import DesktopAppfrom jarvis.ui.jarvisbar.null_overlay import NullOverlayfrom jarvis.ui.jarvisbar.subprocess_overlay import SubprocessMascotOverlayfrom ui.orb import controls-from ui.orb.overlay import OrbCommentBubble, OrbOverlay+from ui.orb.overlay import OrbOverlay# --- OrbOverlay (never started: no Tk root under pytest) --------------------------@@ -292,168 +292,7 @@ def test_the_macos_speaker_disc_names_its_source(live_pipeline, style: str, sourassert pipeline.sources == [source]-# --- dragging moves the status bubble without repainting it ------------------------------class _RecordingTop:- def __init__(self) -> None:- self.geometries: list[str] = []-- def geometry(self, spec: str) -> None:- self.geometries.append(spec)---def test_a_drag_only_moves_the_painted_status_bubble() -> None:- bubble = OrbCommentBubble.__new__(OrbCommentBubble) # no Tk: geometry only- top = _RecordingTop()- bubble._top = top # noqa: SLF001- bubble._screen_w = 1920 # noqa: SLF001- bubble._status_showing = True # noqa: SLF001- bubble._status_size = (240, 60) # noqa: SLF001- repaints: list[bool] = []- bubble._render_status = lambda: repaints.append(True) or True # type: ignore[method-assign]-- # (center_x, below_y, above_y, limit_bottom): room below the strip.- bubble.move_status((500, 300, 100, 1000))- # No room below: the bubble sits over the figure instead.- bubble.move_status((500, 980, 700, 1000))-- assert top.geometries == ["+380+300", "+380+640"]- assert repaints == []---# --- the status card: layout, clear and fade, forwarding -------------------------------------def _card() -> OrbCommentBubble:- bubble = OrbCommentBubble.__new__(OrbCommentBubble) # no Tk: geometry only- bubble._screen_w = 1920 # noqa: SLF001- bubble._ui_scale = 1.0 # noqa: SLF001- bubble._status_max_w = None # noqa: SLF001- bubble._status_expanded = False # noqa: SLF001- return bubble---def _chars(text: str) -> int:- return 7 * len(text)---def test_a_short_status_is_a_compact_full_pill() -> None:- bubble = _card()- width, height, title, detail, radius = bubble.card_layout(- "Thinking", "Reading the calendar", _chars, _chars, 18, 16- )- assert title == ["Thinking"] and detail == ["Reading the calendar"]- assert width < 380 # sized to its text, not to a fixed width- assert radius == height // 2 # two lines collapsed: fully rounded ends---def test_long_text_is_clipped_with_an_ellipsis_and_capped_by_the_strip() -> None:- bubble = _card()- bubble.set_status_max_width(300)- long = "word " * 80- width, _height, title, detail, _radius = bubble.card_layout(long, long, _chars, _chars, 18, 16)- assert 250 <= width <= 300 # the cap; the ellipsised line sets the rest- assert len(title) == 1 and title[0].endswith("…")- assert len(detail) == 1 and detail[0].endswith("…")---def test_a_click_expands_the_detail_to_three_lines_keeping_the_end_radius() -> None:- bubble = _card()- long = "word " * 80- collapsed = bubble.card_layout("Title", long, _chars, _chars, 18, 16)- bubble._status_expanded = True # noqa: SLF001- expanded = bubble.card_layout("Title", long, _chars, _chars, 18, 16)- assert len(expanded[3]) == 3- assert expanded[1] > collapsed[1]- assert expanded[4] == collapsed[4]---class _FakeTop:- """Just enough of a Toplevel for the clear/fade timers."""-- def __init__(self) -> None:- self.pending: dict[str, tuple[int, object]] = {}- self.alphas: list[float] = []- self.withdrawn = 0- self._next = 0-- def after(self, ms: int, fn: object) -> str:- self._next += 1- key = f"after#{self._next}"- self.pending[key] = (ms, fn)- return key-- def after_cancel(self, key: str) -> None:- self.pending.pop(key, None)-- def wm_attributes(self, name: str, value: float) -> None:- assert name == "-alpha"- self.alphas.append(value)-- def withdraw(self) -> None:- self.withdrawn += 1-- def run_next(self) -> int:- key = next(iter(self.pending))- ms, fn = self.pending.pop(key)- fn() # type: ignore[operator]- return ms---def _showing_card() -> tuple[OrbCommentBubble, _FakeTop]:- bubble = _card()- top = _FakeTop()- bubble._top = top # noqa: SLF001- bubble._canvas = object() # noqa: SLF001- bubble._status_showing = True # noqa: SLF001- bubble._status_size = (240, 52) # noqa: SLF001- bubble._status = ("Thinking", "") # noqa: SLF001- bubble._status_anchor = (500, 300, 100, 1000) # noqa: SLF001- bubble._clear_after_id = None # noqa: SLF001- bubble._fade_after_id = None # noqa: SLF001- bubble._status_clear_pending = False # noqa: SLF001- bubble._dismiss_after_id = None # noqa: SLF001- bubble._queue_after_id = None # noqa: SLF001- bubble._queued_text = None # noqa: SLF001- bubble._render_status = lambda: True # type: ignore[method-assign]- return bubble, top---def test_clear_lingers_then_fades_then_withdraws() -> None:- bubble, top = _showing_card()- bubble.clear_status(1.5)- assert top.run_next() == 1500 # the linger- while top.pending:- top.run_next() # the fade steps- fade = top.alphas[:-1]- assert fade and all(a > b for a, b in zip(fade, fade[1:], strict=False))- assert top.alphas[-1] == 1.0 # opacity restored for the next card- assert top.withdrawn == 1- assert bubble.status_showing is False---def test_a_new_status_cancels_a_pending_clear() -> None:- bubble, top = _showing_card()- bubble.clear_status(1.5)- assert top.pending- bubble._cancel_timers = lambda: None # type: ignore[method-assign]- bubble.show_status("Searching the web", "", anchor=(500, 300, 100, 1000))- assert not top.pending- assert bubble.status_showing is True---def test_clear_with_no_linger_hides_at_once() -> None:- bubble, top = _showing_card()- bubble.clear_status(0)- assert top.withdrawn == 1 and not top.pending---def test_a_repeated_clear_keeps_the_first_deadline() -> None:- bubble, top = _showing_card()- bubble.clear_status(1.5)- bubble.clear_status(1.5)- assert len(top.pending) == 1+# --- the thinking line: forwarding ------------------------------------------------def test_the_pet_surface_accepts_clear_before_the_window_exists() -> None:diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex 7764b6bfce..ba44fa61a3 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -36,7 +36,6 @@ import timefrom typing import TYPE_CHECKING, Anyfrom jarvis.core.events import (- ActionApprovalRequired,ActionExecuted,ActionProposed,AudioOutFirst,@@ -53,8 +52,8 @@ from jarvis.core.events import (JarvisAgentBackgroundCompleted,JarvisAgentTaskCompleted,JarvisAgentTaskStarted,+ JarvisChatTurnFinished,ListeningStarted,- MissionCompleted,OrbResetRequested,PetVisibilityToggleRequested,ReasoningSummaryUpdated,@@ -74,7 +73,6 @@ from jarvis.core.events import (VoiceSpeakerMuteChanged,WakeCandidateDetected,WakeWordDetected,- WorkflowCompleted,)from jarvis.dictation.outcomes import was_deliveredfrom jarvis.sessions.constants import (@@ -356,8 +354,6 @@ class OrbBusBridge:# from the running pipeline's config when needed; ``UiLanguageChanged``# overrides it live.self._language: str | None = language if language in PET_STATUS_LANGUAGES else None- #: Unsubscribe from the Agentic IDE's notification centre (the bell).- self._pane_notice_unsub: Any = None# ONE rate-limited feed for every card the pet shows, so a burst of# reasoning snapshots and tool steps cannot flood the Tk thread. A# card the feed holds back is shown by ``_status_flush_task`` once the@@ -604,14 +600,10 @@ class OrbBusBridge:self._bus.subscribe(ToolCallStarted, self._on_tool_call_started)self._bus.subscribe(JarvisAgentTaskStarted, self._on_agent_task_started)self._bus.subscribe(JarvisAgentTaskCompleted, self._on_agent_task_completed)- # The pet's bell (jarvis.ui.pets.notices): things the user waits- # for while looking elsewhere become notification cards. Coding- # panes report through the Agentic IDE's own notification centre.- self._bus.subscribe(MissionCompleted, self._on_mission_completed)+ # The pet's done cards (jarvis.ui.pets.notices): Jarvis answered a+ # typed chat, or a job Jarvis started came back. Nothing else.+ self._bus.subscribe(JarvisChatTurnFinished, self._on_chat_turn_finished)self._bus.subscribe(DelegationResultReady, self._on_delegation_result)- self._bus.subscribe(ActionApprovalRequired, self._on_approval_required)- self._bus.subscribe(WorkflowCompleted, self._on_workflow_completed)- self._subscribe_pane_notices()# Wire the orb's double-double-click gesture to a bus publish.# The orb requires two ``<Double-Button-1>`` events inside# ``MUTE_GESTURE_WINDOW_MS`` (four clicks in <600 ms) before@@ -1134,7 +1126,6 @@ class OrbBusBridge:if event.recoverable:returnself._pet_outcome("error")- self._push_notice(pet_notices.for_error(event, self._status_language()))# -- the pet's bell ---------------------------------------------------@@ -1144,37 +1135,12 @@ class OrbBusBridge:returnself._call_surface("push_notice", *notice)- def _subscribe_pane_notices(self) -> None:- """Follow the Agentic IDE's notifications (finished / asks / exited panes).-- Lazy: the module is light, but the IDE package stays off the boot path- until something asks for it (AP-26). Entries are filed on the event- loop, so the surface call below runs there like every bus handler.- """- if self._pane_notice_unsub is not None:- return- try:- from jarvis.agentic_ide import notifications as ide_notifications- except Exception: # noqa: BLE001 — a missing IDE only costs these cards- log.debug("agentic IDE notifications unavailable", exc_info=True)- return- self._pane_notice_unsub = ide_notifications.center().subscribe(self._on_pane_notice)-- def _on_pane_notice(self, entry: Any) -> None:- self._push_notice(pet_notices.for_pane_entry(entry, self._status_language()))-- async def _on_mission_completed(self, event: MissionCompleted) -> None:- self._push_notice(pet_notices.for_mission(event, self._status_language()))+ async def _on_chat_turn_finished(self, event: JarvisChatTurnFinished) -> None:+ self._push_notice(pet_notices.for_chat_turn(event, self._status_language()))async def _on_delegation_result(self, event: DelegationResultReady) -> None:self._push_notice(pet_notices.for_delegation_result(event, self._status_language()))- async def _on_approval_required(self, event: ActionApprovalRequired) -> None:- self._push_notice(pet_notices.for_approval(event, self._status_language()))-- async def _on_workflow_completed(self, event: WorkflowCompleted) -> None:- self._push_notice(pet_notices.for_workflow(event, self._status_language()))-async def _on_agent_task_started(self, event: JarvisAgentTaskStarted) -> None:"""An agent took on a task: its card stays until the task is done."""if not self._wants_card():@@ -2253,14 +2219,7 @@ class OrbBusBridge:self._pet_outcome("success")self._sync_pet_busy()self._push_notice(pet_notices.for_background_task(event, self._status_language()))- if self._wants_card() and (self._card_visible or self._agent_tasks):- title = condense(event.utterance or "", max_chars=PET_CARD_TITLE_CHARS)- self._show_card(- title or self._card_title(),- self._label("done" if event.success else "failed"),- force=True,- quiet_clear_s=PET_CARD_TASK_DONE_S,- )+ self._clear_card()if self._last_state not in ("IDLE", "ERROR", "PAUSED"):returnself._orb.show(mode="speak")diff --git a/ui/orb/notice_stack.py b/ui/orb/notice_stack.pyindex 86ba08e5b3..0d08ba116f 100644--- a/ui/orb/notice_stack.py+++ b/ui/orb/notice_stack.py@@ -1,128 +1,74 @@-"""The desktop pet's notifications: a small stack of cards under the strip.--When something the user is waiting for happens — a coding agent finished, a-pane asks a question, a background task failed — the pet's bell rings and a-card drops out from under the control strip. Several cards stack: the newest-in front, up to two older ones peeking out behind it, a little narrower and a-little darker each. Hovering the stack fans it out into a column so every card-can be read; leaving it folds it back. A click dismisses the card under the-pointer, and every card leaves on its own after a while (never while the-pointer is on the stack).--Split in two, like :mod:`ui.orb.controls`:--* **Pure model and geometry** (:class:`NoticeModel`, :func:`stack_slots`,- :class:`Spring`, :func:`render_icon`) — no Tk, fully testable.-* **The window** (:class:`PetNoticeStack`) — one frameless, colour-keyed Tk- toplevel whose canvas is redrawn from the model while something moves and- left alone while nothing does.--The window is colour-keyed like every other pet window: card shapes are Tk-canvas polygons (hard edges, no pink fringe), and the only antialiased pixels —-the icon discs — are painted onto the card's own fill colour, never onto the-key. Motion comes from springs rather than fixed tweens, so a card that is-pushed back while it is still dropping in simply changes course instead of-jumping.+"""The desktop pet's card column: what Jarvis is thinking, and what it finished.++Under the control strip hangs one quiet column (the look is+:mod:`ui.orb.pet_cards`):++* **The thinking line** at the top while Jarvis thinks — one muted line with a+ light sweeping across it. It changes in place as the thought moves on and+ fades out after Jarvis stops.+* **Done cards** below it when a Jarvis turn, or a task Jarvis started,+ finished: a check, what was asked, the start of the answer. Several stack:+ the newest in front, up to two older ones peeking out behind it, smaller+ and fainter. Hovering fans them into a column; a click sends one away; each+ leaves on its own after a while, never while the pointer rests on them.++Split like :mod:`ui.orb.controls`: a pure model and geometry+(:class:`NoticeModel`, :func:`column_layout`, :class:`Spring`), and one Tk+window (:class:`PetNoticeStack`) that composites the cards into a single+frame while something moves and leaves the screen alone while nothing does.+On Windows the frame goes through ``UpdateLayeredWindow`` with real per-pixel+alpha (see-through cards, soft shadows, true fades); elsewhere, or if Windows+refuses it, the same frame is flattened onto a colour key."""from __future__ import annotations-import functoolsimport logging-import mathimport sysimport timeimport tkinter as tk-import tkinter.font as tkfontfrom dataclasses import dataclass, fieldfrom itertools import countfrom typing import Any-from PIL import Image, ImageDraw, ImageTk+from PIL import Image, ImageTk-log = logging.getLogger("jarvis.orb")--_Rgb = tuple[int, int, int]--#: What a notice is about. ``done``: something finished. ``attention``: it-#: waits for the user (a question, an approval). ``error``: it failed.-#: ``info``: anything else worth a glance.-NOTICE_KINDS: tuple[str, ...] = ("done", "attention", "error", "info")+from jarvis.platform import layered_window+from ui.orb import pet_cards-#: Seconds a card stays before it leaves on its own. Something that waits for-#: the user stays longest; a plain "done" is news for a few seconds.-NOTICE_TTL_S: dict[str, float] = {"done": 8.0, "attention": 20.0, "error": 14.0, "info": 6.0}+log = logging.getLogger("jarvis.orb")+#: Card kinds the stack keeps (the thinking line is separate).+NOTICE_KINDS: tuple[str, ...] = ("done", "error")+#: Seconds a card stays before it leaves on its own.+NOTICE_TTL_S: dict[str, float] = {"done": 9.0, "error": 14.0}#: Cards kept at most; a newer one pushes the oldest out.-NOTICE_KEEP = 4+NOTICE_KEEP = 3#: Cards visible behind the front one while the stack is folded.NOTICE_PEEK = 2-#: The same notice again within this window refreshes the card instead of-#: stacking a twin (two events for one finished job).+#: The same card again within this window refreshes instead of stacking.NOTICE_DEDUPE_S = 3.0-#: Unscaled geometry at 100 % and ``pet_scale`` 1.0.-CARD_HEIGHT = 60-CARD_RADIUS = 20-CARD_PAD_X = 14-CARD_ICON = 32-CARD_ICON_GAP = 12+#: Unscaled geometry: the gap between cards, how far a folded card peeks out+#: and how much smaller and fainter each one behind is.CARD_GAP = 8-#: How far each card behind the front one peeks out, and how much narrower it-#: is on each side.-PEEK_OFFSET = 9-PEEK_INSET = 11-CARD_TITLE_FONT_SIZE = 10-CARD_DETAIL_FONT_SIZE = 9-CARD_FONT_FAMILY = "Segoe UI"--#: Palette — the strip's blue-black, a shade lighter so a card reads as a-#: surface above the desktop, with a hairline rim.-CARD_FILL: _Rgb = (21, 25, 32)-CARD_FILL_HOVER: _Rgb = (28, 33, 43)-CARD_BORDER: _Rgb = (46, 52, 64)-#: A card two places back sinks this far toward the desktop-dark.-CARD_FILL_DEEP: _Rgb = (12, 14, 19)-CARD_BORDER_DEEP: _Rgb = (28, 32, 40)-CARD_TITLE: _Rgb = (243, 244, 247)-CARD_DETAIL: _Rgb = (156, 161, 172)--#: Icon colours per kind: the glyph, and the disc it sits on.-ICON_COLORS: dict[str, tuple[_Rgb, _Rgb]] = {- "done": ((74, 222, 128), (20, 58, 38)),- "attention": ((251, 191, 36), (66, 50, 14)),- "error": ((248, 113, 113), (70, 26, 30)),- "info": ((126, 186, 255), (22, 42, 74)),-}--#: The icon's entrance: the disc pops in with a slight overshoot, then the-#: glyph draws itself — a check is ticked, not stamped.-ICON_ANIM_S = 0.55-ICON_FRAMES = 14--#: Spring tuning: stiff enough to feel quick, damped just under critical so a-#: card overshoots by a hair and settles.-SPRING_STIFFNESS = 340.0+PEEK_OFFSET = 10+PEEK_SHRINK = 0.05+PEEK_FADE = 0.25++SPRING_STIFFNESS = 320.0SPRING_DAMPING = 30.0FRAME_MS = 16-#: How often expiry is checked while the stack is at rest.+#: Frame interval while only the thinking line's sweep moves.+SHIMMER_FRAME_MS = 50EXPIRY_POLL_MS = 400-#: Leaving the stack folds it after this long — a pointer crossing the gap-#: between two cards must not fold it under itself.COLLAPSE_GRACE_MS = 280+#: How far a card drifts while it fades in or out.+DRIFT_PX = 10-def _lerp(a: _Rgb, b: _Rgb, t: float) -> _Rgb:- t = max(0.0, min(1.0, t))- return (- int(round(a[0] + (b[0] - a[0]) * t)),- int(round(a[1] + (b[1] - a[1]) * t)),- int(round(a[2] + (b[2] - a[2]) * t)),- )---def _hex(rgb: _Rgb) -> str:- return "#{:02x}{:02x}{:02x}".format(*rgb)+def _spx(value: float, scale: float) -> int:+ return max(1, int(round(value * max(0.25, float(scale)))))# --- model -------------------------------------------------------------------@@ -130,8 +76,6 @@ def _hex(rgb: _Rgb) -> str:@dataclassclass Notice:- """One card."""-id: intkind: strtitle: str@@ -142,25 +86,20 @@ class Notice:@dataclassclass NoticeModel:- """The cards on screen, newest first. Pure: the clock is passed in."""+ """The done cards, newest first. Pure: the clock is passed in."""keep: int = NOTICE_KEEPitems: list[Notice] = field(default_factory=list)_ids: Any = field(default_factory=lambda: count(1))def push(self, kind: str, title: str, detail: str, now: float) -> tuple[Notice, list[Notice]]:- """Add a card. Returns it and the cards it pushed out of the stack.-- A twin of a card added moments ago refreshes that card instead.- """- kind = kind if kind in NOTICE_KINDS else "info"+ """Add a card; returns it and the cards it pushed out of the stack."""+ kind = kind if kind in NOTICE_KINDS else "done"ttl = NOTICE_TTL_S[kind]for item in self.items:- if (item.kind, item.title, item.detail) == (- kind,- title,- detail,- ) and now - item.created < NOTICE_DEDUPE_S:+ if (item.kind, item.title, item.detail) == (kind, title, detail) and (+ now - item.created < NOTICE_DEDUPE_S+ ):item.expires = now + ttlreturn item, []notice = Notice(next(self._ids), kind, title, detail, now, now + ttl)@@ -176,7 +115,6 @@ class NoticeModel:return Nonedef expire(self, now: float) -> list[Notice]:- """Remove and return every card whose time is up."""gone = [item for item in self.items if item.expires <= now]if gone:self.items = [item for item in self.items if item.expires > now]@@ -184,10 +122,9 @@ class NoticeModel:def pause(self, seconds: float) -> None:"""Push every deadline back (the pointer rested on the stack)."""- if seconds <= 0:- return- for item in self.items:- item.expires += seconds+ if seconds > 0:+ for item in self.items:+ item.expires += secondsdef clear(self) -> list[Notice]:gone, self.items = self.items, []@@ -199,58 +136,55 @@ class NoticeModel:@dataclass(frozen=True)class Slot:- """Where a card wants to be: its top edge, side inset and depth (0 = front)."""+ """Where a card wants to be: its top edge, size factor and opacity."""y: float- inset: float- depth: int---def stack_slots(- count_: int, *, expanded: bool, card_h: int, scale: float, upward: bool = False-) -> list[Slot]:- """Target slots for ``count_`` cards, newest first, inside the stack window.-- Folded, the front card sits at the top and each older one peeks out below- it, narrower; cards past ``NOTICE_PEEK`` hide exactly behind the last- peeking one. Fanned out, they form a column. ``upward`` mirrors it all for- a stack that grows up from above the pet (no room below).+ size: float+ opacity: float+++def column_layout(+ status_h: int | None,+ heights: list[int],+ *,+ expanded: bool,+ scale: float,+) -> tuple[Slot | None, list[Slot]]:+ """Targets for the thinking line and the cards (newest first), top down.++ Folded, every card lines up its bottom with the front card's bottom and+ peeks out below it, a step smaller and fainter per place; cards past+ ``NOTICE_PEEK`` hide behind the last peeking one. Fanned out, they form a+ column."""- peek = PEEK_OFFSET * scale- inset = PEEK_INSET * scalegap = CARD_GAP * scale- height = stack_height(count_, expanded=expanded, card_h=card_h, scale=scale)+ cursor = 0.0+ status = None+ if status_h is not None:+ status = Slot(0.0, 1.0, 1.0)+ cursor = status_h + gapslots: list[Slot] = []- for index in range(count_):- if expanded:- y, side, depth = index * (card_h + gap), 0.0, 0- else:- level = min(index, NOTICE_PEEK)- y, side, depth = level * peek, level * inset, min(index, NOTICE_PEEK + 1)- if upward:- y = height - card_h - y- slots.append(Slot(y=y, inset=side, depth=depth))- return slots---def stack_height(count_: int, *, expanded: bool, card_h: int, scale: float) -> int:- """Height the stack takes with ``count_`` cards."""- if count_ <= 0:- return 0if expanded:- return int(round(count_ * card_h + (count_ - 1) * CARD_GAP * scale))- return int(round(card_h + min(count_ - 1, NOTICE_PEEK) * PEEK_OFFSET * scale))---def max_stack_height(card_h: int, scale: float) -> int:- """The tallest the stack can get: every kept card fanned out."""- return stack_height(NOTICE_KEEP, expanded=True, card_h=card_h, scale=scale)+ for h in heights:+ slots.append(Slot(cursor, 1.0, 1.0))+ cursor += h + gap+ return status, slots+ if not heights:+ return status, slots+ front_bottom = cursor + heights[0]+ for index, h in enumerate(heights):+ level = min(index, NOTICE_PEEK)+ size = 1.0 - PEEK_SHRINK * level+ opacity = (1.0 - PEEK_FADE * level) if index <= NOTICE_PEEK else 0.0+ bottom = front_bottom + level * PEEK_OFFSET * scale+ slots.append(Slot(bottom - h * size, size, opacity))+ return status, slotsclass Spring:- """One damped spring value. ``step`` advances it by ``dt`` seconds."""+ """One damped spring value."""- __slots__ = ("value", "velocity", "target")+ __slots__ = ("target", "value", "velocity")def __init__(self, value: float, target: float | None = None) -> None:self.value = float(value)@@ -258,8 +192,7 @@ class Spring:self.target = float(value if target is None else target)def step(self, dt: float) -> None:- # Sub-steps keep the integration stable when a frame comes in late.- steps = max(1, int(math.ceil(dt / 0.008)))+ steps = max(1, int(dt / 0.008 + 0.999))h = dt / stepsfor _ in range(steps):accel = SPRING_STIFFNESS * (self.target - self.value) - SPRING_DAMPING * self.velocity@@ -268,164 +201,84 @@ class Spring:@propertydef settled(self) -> bool:- return abs(self.target - self.value) < 0.4 and abs(self.velocity) < 4.0+ reach = max(1.0, abs(self.target))+ return abs(self.target - self.value) < 0.004 * reach and abs(self.velocity) < 0.04 * reachdef snap(self) -> None:self.value = self.targetself.velocity = 0.0-# --- icons ----------------------------------------------------------------------def _ease_out_back(t: float) -> float:- t = max(0.0, min(1.0, t))- c1 = 1.70158- c3 = c1 + 1.0- return 1.0 + c3 * (t - 1.0) ** 3 + c1 * (t - 1.0) ** 2---def icon_frame(age_s: float) -> int:- """The icon animation frame at ``age_s`` seconds after the card arrived."""- if age_s >= ICON_ANIM_S:- return ICON_FRAMES- return max(0, min(ICON_FRAMES, int(age_s / ICON_ANIM_S * ICON_FRAMES)))---def _partial(points: list[tuple[float, float]], share: float) -> list[tuple[float, float]]:- """The first ``share`` of a polyline's length."""- if share >= 1.0:- return points- lengths = [math.dist(a, b) for a, b in zip(points, points[1:], strict=False)]- want = sum(lengths) * max(0.0, share)- out = [points[0]]- for (a, b), length in zip(zip(points, points[1:], strict=False), lengths, strict=False):- if want <= 0:- break- if length <= want:- out.append(b)- want -= length- continue- f = want / length- out.append((a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f))- break- return out--[email protected]_cache(maxsize=256)-def render_icon(kind: str, frame: int, diameter: int, background: _Rgb) -> Image.Image:- """The round icon for ``kind`` at animation ``frame`` on an opaque square.-- Drawn at 4x and downscaled, on the card's own fill, so its antialiasing- never meets the colour key.- """- ss = 4- size = max(2, diameter) * ss- glyph, disc = ICON_COLORS.get(kind, ICON_COLORS["info"])- layer = Image.new("RGB", (size, size), background)- d = ImageDraw.Draw(layer)- t = frame / ICON_FRAMES- pop = _ease_out_back(min(1.0, t / 0.55))- r = size / 2.0 * max(0.0, pop)- c = size / 2.0- if r > 0.5:- d.ellipse([c - r, c - r, c + r, c + r], fill=disc)- draw = max(0.0, min(1.0, (t - 0.3) / 0.6))- width = max(1, int(round(size * 0.085)))- unit = size / 24.0-- def pt(u: float, v: float) -> tuple[float, float]:- return (c + (u - 12.0) * unit, c + (v - 12.0) * unit)-- def stroke(points: list[tuple[float, float]], share: float) -> None:- if share <= 0.0:- return- line = _partial([pt(u, v) for u, v in points], share)- if len(line) >= 2:- d.line(line, fill=glyph, width=width, joint="curve")- for x, y in (line[0], line[-1]):- d.ellipse([x - width / 2, y - width / 2, x + width / 2, y + width / 2], fill=glyph)-- if kind == "done":- stroke([(7.2, 12.4), (10.4, 15.6), (16.8, 8.6)], draw)- elif kind == "attention":- stroke([(12, 6.8), (12, 13.2)], min(1.0, draw * 1.25))- if draw >= 0.85:- dot = width * 0.62- x, y = pt(12, 17.0)- d.ellipse([x - dot, y - dot, x + dot, y + dot], fill=glyph)- elif kind == "error":- stroke([(8.2, 8.2), (15.8, 15.8)], min(1.0, draw * 2.0))- stroke([(15.8, 8.2), (8.2, 15.8)], max(0.0, draw * 2.0 - 1.0))- else:- from ui.orb.controls import _bell_outline # noqa: PLC0415 — one bell, one drawing-- for line in _bell_outline():- scaled = [(12 + (u - 12) * 0.62, 12.6 + (v - 12) * 0.62) for u, v in line]- stroke(scaled, draw)- return layer.resize((diameter, diameter), Image.Resampling.LANCZOS)---# --- the window ----------------------------------------------------------------+# --- the window --------------------------------------------------------------@dataclass-class _Card:- notice: Notice+class _Item:+ """One card on screen: its content and its moving parts."""++ key: int # notice id; 0 is the thinking line+ kind: str+ title: str+ detail: stry: Spring- inset: Spring- shade: Spring- x: Spring+ size: Spring+ opacity: Springborn: floatleaving: bool = False---def _fit(text: str, font: tkfont.Font, width: int) -> str:- """``text`` cut with an ellipsis to fit ``width`` pixels."""- if width <= 0 or not text:- return ""- if font.measure(text) <= width:- return text- lo, hi = 0, len(text)- while lo < hi:- mid = (lo + hi + 1) // 2- if font.measure(text[:mid].rstrip() + "…") <= width:- lo = mid- else:- hi = mid - 1- return text[:lo].rstrip() + "…"+ #: Where the card was last drawn (x0, y0, x1, y1) for hit tests.+ box: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)class PetNoticeStack:- """The cards' own frameless window. Every method runs on the Tk thread."""+ """The card column's own frameless window. Every method runs on the Tk thread."""- def __init__(self, parent: tk.Misc, *, scale: float = 1.0, width: int = 320) -> None:+ def __init__(self, parent: tk.Misc, *, scale: float = 1.0, width: int = 360) -> None:self._parent = parentself._scale = max(0.25, float(scale))- self._width = max(160, int(width))+ self._card_w = max(160, int(width))self._model = NoticeModel()- self._cards: dict[int, _Card] = {}- self._leaving: list[_Card] = []+ self._items: dict[int, _Item] = {}+ self._leaving: list[_Item] = []+ self._status: _Item | None = Noneself._expanded = False- self._hovered_id: int | None = None+ self._hovered: int | None = Noneself._pointer_inside = Falseself._hover_since: float | None = Noneself._upward = Falseself._anchor: tuple[int, int, int, int, int] | None = Noneself._top: tk.Toplevel | None = Noneself._canvas: tk.Canvas | None = None- self._title_font: tkfont.Font | None = None- self._detail_font: tkfont.Font | None = None- self._photos: list[ImageTk.PhotoImage] = []+ self._photo: ImageTk.PhotoImage | None = None+ self._image_id: int | None = None+ self._alpha_hwnd = 0+ self._mac_transparent = Falseself._frame_after: str | None = Noneself._expiry_after: str | None = Noneself._collapse_after: str | None = None+ self._status_clear_after: str | None = Noneself._last_tick = 0.0self._shown = False- self._mac_transparent = Falseself._build()- # -- setup --------------------------------------------------------------+ # -- setup ----------------------------------------------------------------++ @property+ def _pad(self) -> int:+ return _spx(pet_cards.SHADOW_PAD, self._scale)++ @property+ def window_size(self) -> tuple[int, int]:+ """Room for the thinking line plus every kept card fanned out."""+ s = self._scale+ tallest_card = _spx(+ 2 * pet_cards.PAD_Y + 1.45 * pet_cards.TITLE_PX + 3 + 2 * 1.45 * pet_cards.BODY_PX, s+ )+ gap = CARD_GAP * s+ height = _spx(pet_cards.STATUS_HEIGHT, s) + NOTICE_KEEP * (tallest_card + gap) + gap+ return self._card_w + 2 * self._pad, int(height) + 2 * self._pad++ def _blank(self) -> Image.Image:+ return Image.new("RGBA", self.window_size, (0, 0, 0, 0))def _build(self) -> None:from ui.orb import overlay as _ov # noqa: PLC0415 — overlay imports this module@@ -433,25 +286,38 @@ class PetNoticeStack:top = tk.Toplevel(self._parent)top.overrideredirect(True)top.wm_attributes("-topmost", True)+ width, height = self.window_sizeif sys.platform == "darwin":try:top.wm_attributes("-transparent", True)top.configure(bg="systemTransparent")self._mac_transparent = Trueexcept tk.TclError:- log.warning("macOS -transparent unsupported — notices render opaque")+ log.warning("macOS -transparent unsupported — the pet's cards render opaque")top.configure(bg=_ov.COLOR_KEY_HEX)else:- try:- top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)- except tk.TclError:- log.debug("no colour key on this window system", exc_info=True)+ if layered_window.per_pixel_alpha_supported():+ top.update_idletasks()+ hwnd = layered_window.tk_toplevel_hwnd(top)+ # The first frame goes in now: Windows refuses the very first+ # UpdateLayeredWindow on a window that was already withdrawn.+ if layered_window.enable_per_pixel_alpha(hwnd) and layered_window.update_layered(+ hwnd, self._blank()+ ):+ self._alpha_hwnd = hwnd+ if not self._alpha_hwnd:+ try:+ top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)+ except tk.TclError:+ log.debug("no colour key on this window system", exc_info=True)top.configure(bg=_ov.COLOR_KEY_HEX)_ov._hide_tk_window_from_task_switcher(top) # noqa: SLF001 — shared overlay helper_ov._exclude_tk_window_from_capture(top) # noqa: SLF001 — shared overlay helpertop.withdraw()canvas = tk.Canvas(top,+ width=width,+ height=height,bg="systemTransparent" if self._mac_transparent else _ov.COLOR_KEY_HEX,highlightthickness=0,borderwidth=0,@@ -461,77 +327,59 @@ class PetNoticeStack:top.update_idletasks()_ov.apply_macos_clear_backing()canvas.bind("<Motion>", self._on_motion)- canvas.bind("<Enter>", self._on_enter)+ canvas.bind("<Enter>", self._on_motion)canvas.bind("<Leave>", self._on_leave)canvas.bind("<ButtonRelease-1>", self._on_click)- self._title_font = tkfont.Font(- root=top, family=CARD_FONT_FAMILY, size=CARD_TITLE_FONT_SIZE, weight="bold"- )- self._detail_font = tkfont.Font(- root=top, family=CARD_FONT_FAMILY, size=CARD_DETAIL_FONT_SIZE- )self._top = topself._canvas = canvas- # -- geometry ------------------------------------------------------------- @property- def card_height(self) -> int:- return max(24, int(round(CARD_HEIGHT * self._scale)))-- @property- def window_height(self) -> int:- return max_stack_height(self.card_height, self._scale) + 2+ # -- public ---------------------------------------------------------------@propertydef count(self) -> int:+ """Done cards on screen (the thinking line is not counted)."""return len(self._model.items)@property- def showing(self) -> bool:- return self._shown+ def status_showing(self) -> bool:+ return self._status is not None++ @property+ def window(self) -> tk.Toplevel | None:+ """The column's toplevel while it is on screen (for Z-order repair)."""+ return self._top if self._shown else Nonedef set_scale(self, scale: float, width: int) -> None:- scale = max(0.25, float(scale))- width = max(160, int(width))- if (scale, width) == (self._scale, self._width):+ scale, width = max(0.25, float(scale)), max(160, int(width))+ if (scale, width) == (self._scale, self._card_w):return- self._scale, self._width = scale, width+ self._scale, self._card_w = scale, width+ if self._canvas is not None:+ w, h = self.window_size+ try:+ self._canvas.configure(width=w, height=h)+ except tk.TclError:+ log.debug("card canvas resize failed", exc_info=True)self._retarget(snap=True)self._place()- self._draw()+ self._kick()def set_anchor(self, anchor: tuple[int, int, int, int, int]) -> None:"""``(center_x, below_y, above_y, limit_bottom, screen_w)``.- The stack hangs from ``below_y`` when its fanned-out height fits above- ``limit_bottom``, else it grows upward from ``above_y``.+ The column hangs from ``below_y`` when it fits above ``limit_bottom``,+ else it grows upward from ``above_y``."""self._anchor = anchor- upward = anchor[1] + self.window_height > anchor[3]+ upward = anchor[1] + self.window_size[1] - 2 * self._pad > anchor[3]if upward != self._upward:self._upward = upwardself._retarget(snap=True)- self._draw()+ self._kick()self._place()- def _place(self) -> None:- if self._top is None or self._anchor is None:- return- center_x, below_y, above_y, _limit, screen_w = self._anchor- width, height = self._width, self.window_height- x = max(8, min(center_x - width // 2, screen_w - width - 8))- y = max(8, above_y - height) if self._upward else below_y- try:- self._top.geometry(f"{width}x{height}+{x}+{y}")- if self._canvas is not None:- self._canvas.configure(width=width, height=height)- except tk.TclError:- log.debug("notice stack placement failed", exc_info=True)-- # -- public ----------------------------------------------------------------def push(self, kind: str, title: str, detail: str) -> None:+ """A done (or failed) card."""title = " ".join(str(title or "").split())detail = " ".join(str(detail or "").split())if not title:@@ -542,83 +390,182 @@ class PetNoticeStack:notice, dropped = self._model.push(kind, title, detail, now)for gone in dropped:self._send_off(gone.id)- if notice.id not in self._cards:- card_h = self.card_height- start_y = -card_h * 0.8 if not self._upward else self.window_height + card_h * 0.2- self._cards[notice.id] = _Card(- notice=notice,- y=Spring(start_y),- inset=Spring(PEEK_INSET * self._scale * 2),- shade=Spring(0.0),- x=Spring(0.0),+ item = self._items.get(notice.id)+ if item is None:+ self._items[notice.id] = _Item(+ key=notice.id,+ kind=notice.kind,+ title=notice.title,+ detail=notice.detail,+ y=Spring(0.0),+ size=Spring(0.96),+ opacity=Spring(0.0),born=now,)+ self._retarget(fresh=notice.id)else:- self._cards[notice.id].born = now- self._retarget()+ item.born = now+ self._retarget()self._show()self._kick()+ def set_status(self, text: str) -> None:+ """Show or update the thinking line."""+ text = " ".join(str(text or "").split())+ if not text:+ self.clear_status(0.0)+ return+ self._cancel(("_status_clear_after",))+ item = self._status+ if item is None:+ item = _Item(+ key=0,+ kind="status",+ title=text,+ detail="",+ y=Spring(0.0),+ size=Spring(0.97),+ opacity=Spring(0.0),+ born=time.monotonic(),+ )+ self._status = item+ self._retarget(fresh=0)+ else:+ item.title = text+ self._retarget()+ self._show()+ self._kick()++ def clear_status(self, linger_s: float = 1.5) -> None:+ """Fade the thinking line out after ``linger_s`` seconds (at once when 0).++ A pending clear keeps its earlier deadline; a new status cancels it.+ """+ if self._status is None or self._top is None or self._status_clear_after is not None:+ return+ delay = max(0, int(float(linger_s) * 1000))+ if delay == 0:+ self._drop_status()+ return+ self._status_clear_after = self._top.after(delay, self._drop_status)+def clear(self) -> None:- """Send every card away (the bell was switched off)."""+ """Send every done card away (the bell was switched off)."""for gone in self._model.clear():self._send_off(gone.id)+ self._expanded = Falseself._retarget()self._kick()def hide(self) -> None:- """Withdraw at once (the pet was hidden); the cards are dropped."""+ """Withdraw at once (the pet was hidden); everything is dropped."""self._model.clear()- self._cards.clear()+ self._items.clear()self._leaving.clear()+ self._status = Noneself._withdraw()def destroy(self) -> None:self._cancel_all()top, self._top, self._canvas = self._top, None, None- self._photos.clear()+ self._photo = Noneif top is not None:try:top.destroy()except tk.TclError:- log.debug("notice stack destroy failed", exc_info=True)+ log.debug("card window destroy failed", exc_info=True)- # -- motion -----------------------------------------------------------------+ # -- motion ---------------------------------------------------------------++ def _drop_status(self) -> None:+ self._status_clear_after = None+ item = self._status+ if item is None:+ return+ item.leaving = True+ item.opacity.target = 0.0+ item.size.target = 0.97+ self._leaving.append(item)+ self._status = None+ self._retarget()+ self._kick()def _send_off(self, notice_id: int) -> None:- card = self._cards.pop(notice_id, None)- if card is None:+ item = self._items.pop(notice_id, None)+ if item is None:return- card.leaving = True- card.x.target = self._width + 24- card.x.velocity = max(card.x.velocity, 260.0)- self._leaving.append(card)-- def _retarget(self, *, snap: bool = False) -> None:- items = self._model.items- slots = stack_slots(- len(items),- expanded=self._expanded,- card_h=self.card_height,- scale=self._scale,- upward=self._upward,+ item.leaving = True+ item.opacity.target = 0.0+ item.size.target = item.size.value * 0.95+ self._leaving.append(item)++ def _card_image(+ self,+ item: _Item,+ *,+ hovered: bool = False,+ frame: int | None = None,+ content: bool = True,+ ) -> Image.Image:+ scale = round(self._scale, 3)+ if item.kind == "status":+ return pet_cards.render_card(+ "status", item.title, "", scale=scale, max_width=self._card_w+ )+ return pet_cards.render_card(+ item.kind,+ item.title,+ item.detail,+ scale=scale,+ max_width=self._card_w,+ hovered=hovered,+ icon_frame=pet_cards.ICON_FRAMES if frame is None else frame,+ content=content,)- for item, slot in zip(items, slots, strict=False):- card = self._cards.get(item.id)- if card is None:- continue- card.y.target = slot.y- card.inset.target = slot.inset- card.shade.target = float(min(slot.depth, NOTICE_PEEK + 1))++ def _card_height(self, item: _Item) -> int:+ return self._card_image(item).height - 2 * self._pad++ def _cards(self) -> list[_Item]:+ """The done cards on screen, newest first."""+ return [self._items[n.id] for n in self._model.items if n.id in self._items]++ def _retarget(self, *, snap: bool = False, fresh: int | None = None) -> None:+ status_h = self._card_height(self._status) if self._status is not None else None+ cards = self._cards()+ heights = [self._card_height(c) for c in cards]+ status_slot, slots = column_layout(+ status_h, heights, expanded=self._expanded, scale=self._scale+ )+ inner_h = self.window_size[1] - 2 * self._pad+ pairs: list[tuple[_Item, Slot, int]] = []+ if self._status is not None and status_slot is not None and status_h is not None:+ pairs.append((self._status, status_slot, status_h))+ pairs += list(zip(cards, slots, heights, strict=False))+ for item, slot, h in pairs:+ y = slot.y+ if self._upward:+ # Growing up from above the pet: mirror the column, newest+ # nearest the pet.+ y = inner_h - (slot.y + h * slot.size)+ item.y.target = y+ item.size.target = slot.size+ item.opacity.target = slot.opacity+ if item.key == fresh:+ # A new card starts a little off its place and drifts in+ # while it fades up.+ drift = DRIFT_PX * self._scale+ item.y.value = y + (drift if self._upward else -drift)if snap:- for spring in (card.y, card.inset, card.shade):+ for spring in (item.y, item.size, item.opacity):spring.snap()- def _kick(self) -> None:+ def _kick(self, delay: int = FRAME_MS) -> None:if self._top is None or self._frame_after is not None:return+ self._cancel(("_expiry_after",))self._last_tick = time.monotonic()- self._frame_after = self._top.after(FRAME_MS, self._tick)+ self._frame_after = self._top.after(delay, self._tick)def _tick(self) -> None:self._frame_after = None@@ -628,27 +575,36 @@ class PetNoticeStack:dt = min(0.05, max(0.001, now - self._last_tick))self._last_tick = nowmoving = False- for card in list(self._cards.values()) + self._leaving:- for spring in (card.y, card.inset, card.shade, card.x):- if not spring.settled:+ for item in [*self._all_items(), *self._leaving]:+ for spring in (item.y, item.size, item.opacity):+ if spring.settled:+ spring.snap()+ else:spring.step(dt)moving = True- else:- spring.snap()- if now - card.born < ICON_ANIM_S + 0.05:- moving = True- self._leaving = [c for c in self._leaving if c.x.value < self._width + 8]- self._draw()+ if item.kind != "status" and now - item.born < 0.6:+ moving = True # the check is still ticking itself+ self._leaving = [i for i in self._leaving if i.opacity.value > 0.02]+ self._paint(now)if moving or self._leaving:self._frame_after = self._top.after(FRAME_MS, self._tick)return- if not self._cards:+ if self._status is not None:+ # Only the sweep moves: a calmer frame rate is plenty.+ self._frame_after = self._top.after(SHIMMER_FRAME_MS, self._tick)+ if self._items:+ self._schedule_expiry()+ return+ if not self._items:self._withdraw()returnself._schedule_expiry()+ def _all_items(self) -> list[_Item]:+ return ([self._status] if self._status is not None else []) + self._cards()+def _schedule_expiry(self) -> None:- if self._top is None or self._expiry_after is not None or not self._cards:+ if self._top is None or self._expiry_after is not None or not self._items:returnself._expiry_after = self._top.after(EXPIRY_POLL_MS, self._check_expiry)@@ -667,29 +623,92 @@ class PetNoticeStack:self._send_off(notice.id)if gone:if not self._model.items:- self._set_expanded(False)+ self._expanded = Falseself._retarget()self._kick()returnself._schedule_expiry()- # -- pointer ------------------------------------------------------------+ # -- painting -------------------------------------------------------------- def _card_at(self, x: float, y: float) -> int | None:- """The front-most card under ``(x, y)``."""- card_h = self.card_height- for item in self._model.items:- card = self._cards.get(item.id)- if card is None:+ def _paint(self, now: float) -> None:+ frame = self._blank()+ pad = self._pad+ width = frame.width+ # Back to front: the deepest card first, the thinking line last.+ order = [*reversed(self._cards()), *self._leaving]+ if self._status is not None:+ order.append(self._status)+ for item in order:+ opacity = max(0.0, min(1.0, item.opacity.value))+ if opacity <= 0.01:+ item.box = (0.0, 0.0, 0.0, 0.0)continue- x0 = card.inset.value + card.x.value- x1 = self._width - card.inset.value + card.x.value- if x0 <= x <= x1 and card.y.value <= y <= card.y.value + card_h:- return item.id- return None+ if item.kind == "status":+ step = int(now / pet_cards.SHIMMER_PERIOD_S * pet_cards.SHIMMER_STEPS)+ image = pet_cards.shimmer(self._card_image(item), step, round(self._scale, 3))+ else:+ ticked = int((now - item.born) / 0.5 * pet_cards.ICON_FRAMES)+ image = self._card_image(+ item,+ hovered=item.key == self._hovered and not item.leaving,+ frame=min(pet_cards.ICON_FRAMES, ticked),+ # Behind the front card: its edge only, no text showing+ # through the see-through card in front.+ content=item.size.value > 0.985 or item.leaving,+ )+ size = max(0.5, item.size.value)+ if abs(size - 1.0) > 0.004:+ image = image.resize(+ (max(1, int(image.width * size)), max(1, int(image.height * size))),+ Image.Resampling.BILINEAR,+ )+ if opacity < 0.995:+ image = image.copy()+ image.putalpha(image.getchannel("A").point(lambda v, o=opacity: int(v * o)))+ inset = pad * size+ x = (width - image.width) // 2+ y = int(round(item.y.value + pad - inset))+ frame.alpha_composite(image, (max(0, x), max(0, y)))+ item.box = (x + inset, y + inset, x + image.width - inset, y + image.height - inset)+ self._present(frame)++ def _present(self, frame: Image.Image) -> None:+ from ui.orb import overlay as _ov # noqa: PLC0415 — overlay imports this module- def _on_enter(self, event: tk.Event) -> None:- self._on_motion(event)+ if self._alpha_hwnd:+ if layered_window.update_layered(self._alpha_hwnd, frame):+ return+ log.warning("per-pixel alpha refused; the pet's cards fall back to the colour key")+ self._alpha_hwnd = 0+ if self._top is not None:+ try:+ self._top.wm_attributes("-transparentcolor", _ov.COLOR_KEY_HEX)+ except tk.TclError:+ log.debug("colour-key fallback failed", exc_info=True)+ canvas = self._canvas+ if canvas is None:+ return+ key = (int(_ov.COLOR_KEY_RGB[0]), int(_ov.COLOR_KEY_RGB[1]), int(_ov.COLOR_KEY_RGB[2]))+ flat = pet_cards.flatten_for_key(frame, key)+ image = _ov.key_to_alpha(flat) if self._mac_transparent else flat+ try:+ self._photo = ImageTk.PhotoImage(image, master=canvas)+ if self._image_id is None:+ self._image_id = canvas.create_image(0, 0, anchor="nw", image=self._photo)+ else:+ canvas.itemconfigure(self._image_id, image=self._photo)+ except tk.TclError:+ log.debug("card frame paint failed", exc_info=True)++ # -- pointer --------------------------------------------------------------++ def _card_at(self, x: float, y: float) -> int | None:+ for item in self._cards(): # front-most first+ x0, y0, x1, y1 = item.box+ if x0 <= x <= x1 and y0 <= y <= y1 and item.opacity.value > 0.5:+ return item.key+ return Nonedef _on_motion(self, event: tk.Event) -> None:hit = self._card_at(event.x, event.y)@@ -698,28 +717,29 @@ class PetNoticeStack:self._hover_since = time.monotonic()self._pointer_inside = insideif inside:- self._cancel_collapse()- self._set_expanded(True)+ self._cancel(("_collapse_after",))+ if not self._expanded and len(self._model.items) > 1:+ self._expanded = True+ self._retarget()elif self._expanded:self._schedule_collapse()- if hit != self._hovered_id:- self._hovered_id = hit+ if hit != self._hovered:+ self._hovered = hitif self._canvas is not None:try:self._canvas.configure(cursor="hand2" if hit is not None else "")except tk.TclError:- log.debug("notice cursor change failed", exc_info=True)- self._draw()+ log.debug("card cursor change failed", exc_info=True)+ self._kick()def _on_leave(self, _event: tk.Event) -> None:if self._pointer_inside and self._hover_since is not None:self._model.pause(time.monotonic() - self._hover_since)self._pointer_inside = Falseself._hover_since = None- if self._hovered_id is not None:- self._hovered_id = None- self._draw()+ self._hovered = Noneself._schedule_collapse()+ self._kick()def _on_click(self, event: tk.Event) -> None:hit = self._card_at(event.x, event.y)@@ -727,16 +747,9 @@ class PetNoticeStack:returnself._model.dismiss(hit)self._send_off(hit)- self._hovered_id = None+ self._hovered = Noneif not self._model.items:- self._set_expanded(False)- self._retarget()- self._kick()-- def _set_expanded(self, expanded: bool) -> None:- if expanded == self._expanded:- return- self._expanded = expanded+ self._expanded = Falseself._retarget()self._kick()@@ -747,18 +760,25 @@ class PetNoticeStack:def _collapse_now(self) -> None:self._collapse_after = None- if not self._pointer_inside:- self._set_expanded(False)+ if not self._pointer_inside and self._expanded:+ self._expanded = False+ self._retarget()+ self._kick()- def _cancel_collapse(self) -> None:- if self._collapse_after is not None and self._top is not None:- try:- self._top.after_cancel(self._collapse_after)- except tk.TclError:- log.debug("collapse cancel failed", exc_info=True)- self._collapse_after = None+ # -- window ---------------------------------------------------------------- # -- painting -------------------------------------------------------------+ def _place(self) -> None:+ if self._top is None or self._anchor is None:+ return+ center_x, below_y, above_y, _limit, screen_w = self._anchor+ width, height = self.window_size+ pad = self._pad+ x = max(8 - pad, min(center_x - width // 2, screen_w - width + pad - 8))+ y = above_y - height + pad if self._upward else below_y - pad+ try:+ self._top.geometry(f"{width}x{height}+{x}+{y}")+ except tk.TclError:+ log.debug("card window placement failed", exc_info=True)def _show(self) -> None:if self._top is None or self._shown:@@ -768,7 +788,7 @@ class PetNoticeStack:self._top.deiconify()self._top.lift()except tk.TclError:- log.debug("notice stack show failed", exc_info=True)+ log.debug("card window show failed", exc_info=True)returnself._shown = True@@ -776,121 +796,30 @@ class PetNoticeStack:self._cancel_all()self._expanded = Falseself._pointer_inside = False- self._hovered_id = None- if self._canvas is not None:- try:- self._canvas.delete("all")- except tk.TclError:- log.debug("notice canvas clear failed", exc_info=True)- self._photos.clear()+ self._hovered = None+ if self._alpha_hwnd:+ # A layered window keeps its last bitmap; leave nothing behind.+ layered_window.update_layered(self._alpha_hwnd, self._blank())if self._top is not None and self._shown:try:self._top.withdraw()except tk.TclError:- log.debug("notice stack withdraw failed", exc_info=True)+ log.debug("card window withdraw failed", exc_info=True)self._shown = False- def _cancel_all(self) -> None:+ def _cancel(self, names: tuple[str, ...]) -> None:top = self._top- for attr in ("_frame_after", "_expiry_after", "_collapse_after"):+ for attr in names:after_id = getattr(self, attr)if after_id is not None and top is not None:try:top.after_cancel(after_id)except tk.TclError:- log.debug("notice timer cancel failed", exc_info=True)+ log.debug("card timer cancel failed", exc_info=True)setattr(self, attr, None)- def _draw(self) -> None:- canvas = self._canvas- if canvas is None or self._title_font is None or self._detail_font is None:- return- try:- canvas.delete("all")- except tk.TclError:- return- self._photos.clear()- order = [self._cards[i.id] for i in self._model.items if i.id in self._cards]- # Back to front: the deepest card first, leaving cards above the rest- # so a dismissed card slides out over its neighbours.- for card in reversed(order):- self._draw_card(card)- for card in self._leaving:- self._draw_card(card)-- def _draw_card(self, card: _Card) -> None:- canvas = self._canvas- assert canvas is not None and self._title_font is not None # noqa: S101- assert self._detail_font is not None # noqa: S101- scale = self._scale- card_h = self.card_height- depth = max(0.0, card.shade.value)- if depth > NOTICE_PEEK + 0.5:- return- x0 = card.inset.value + card.x.value- x1 = self._width - card.inset.value + card.x.value - 1- y0 = card.y.value- y1 = y0 + card_h - 1- hovered = card.notice.id == self._hovered_id and not card.leaving- deep = min(1.0, depth / max(1, NOTICE_PEEK))- fill = _lerp(CARD_FILL_HOVER if hovered else CARD_FILL, CARD_FILL_DEEP, deep * 0.85)- border = _lerp(CARD_BORDER, CARD_BORDER_DEEP, deep)- radius = min(card_h / 2.0, CARD_RADIUS * scale)- _rounded_rect(canvas, x0, y0, x1, y1, radius, fill=_hex(fill), outline=_hex(border))- if depth > 0.35:- return # a card behind the front one shows only its edge- icon_d = max(8, int(round(CARD_ICON * scale)))- pad_x = CARD_PAD_X * scale- icon_x = x0 + pad_x- icon_y = y0 + (card_h - icon_d) / 2.0- age = time.monotonic() - card.born- image = render_icon(card.notice.kind, icon_frame(age), icon_d, fill)- photo = ImageTk.PhotoImage(image, master=canvas)- self._photos.append(photo)- canvas.create_image(int(round(icon_x)), int(round(icon_y)), anchor="nw", image=photo)- text_x = icon_x + icon_d + CARD_ICON_GAP * scale- text_w = int(x1 - pad_x - text_x)- title_lh = int(self._title_font.metrics("linespace"))- detail_lh = int(self._detail_font.metrics("linespace"))- detail = card.notice.detail- block = title_lh + (detail_lh + 1 if detail else 0)- ty = y0 + (card_h - block) / 2.0- canvas.create_text(- text_x,- ty,- text=_fit(card.notice.title, self._title_font, text_w),- font=self._title_font,- anchor="nw",- fill=_hex(CARD_TITLE),- )- if detail:- canvas.create_text(- text_x,- ty + title_lh + 1,- text=_fit(detail, self._detail_font, text_w),- font=self._detail_font,- anchor="nw",- fill=_hex(CARD_DETAIL),- )---def _rounded_rect(- canvas: tk.Canvas, x0: float, y0: float, x1: float, y1: float, r: float, **kwargs: Any-) -> int:- """A rounded rectangle with true circular corners, as one canvas polygon.-- The corners are explicit arc points rather than Tk's ``smooth`` spline,- which pulls a corner flatter than its radius.- """- r = max(1.0, min(r, (x1 - x0) / 2.0, (y1 - y0) / 2.0))- steps = max(4, int(r / 2.0))- points: list[float] = []- for cx, cy, start in ((x1 - r, y0 + r, -90), (x1 - r, y1 - r, 0), (x0 + r, y1 - r, 90),- (x0 + r, y0 + r, 180)): # fmt: skip- for i in range(steps + 1):- a = math.radians(start + 90.0 * i / steps)- points.extend((cx + r * math.cos(a), cy + r * math.sin(a)))- return canvas.create_polygon(points, **kwargs)+ def _cancel_all(self) -> None:+ self._cancel(("_frame_after", "_expiry_after", "_collapse_after", "_status_clear_after"))__all__ = [@@ -900,9 +829,5 @@ __all__ = ["PetNoticeStack","Slot","Spring",- "icon_frame",- "max_stack_height",- "render_icon",- "stack_height",- "stack_slots",+ "column_layout",]diff --git a/ui/orb/overlay.py b/ui/orb/overlay.pyindex 33ed9b0db8..384b486c3f 100644--- a/ui/orb/overlay.py+++ b/ui/orb/overlay.py@@ -285,81 +285,11 @@ def bubble_theme_for_style(style: str) -> BubbleTheme:return MASCOT_BUBBLE_THEME-# The pet's status card (docs/pets.md): below the control strip, a one-line-# bold title over one muted detail line (three after a click), sized to its-# text up to 1.6 x the strip's width. The bridge decides when it goes: it calls-# ``clear_status`` once Jarvis stops thinking, and the card fades after a short-# linger. Pixel sizes are at 100 % and scale with the strip.-PET_CARD_PAD_X = 18-PET_CARD_PAD_Y = 10-PET_CARD_LINE_GAP = 2-PET_CARD_MIN_WIDTH = 150-#: Used until the overlay tells the card how wide the strip is.-PET_CARD_MAX_WIDTH = 380-PET_CARD_MAX_WIDTH_PER_STRIP = 1.6-PET_CARD_DETAIL_COLLAPSED_LINES = 1-PET_CARD_DETAIL_EXPANDED_LINES = 3-PET_CARD_TITLE_FONT_SIZE = 10-PET_CARD_DETAIL_FONT_SIZE = 9-#: The fade after the linger: a handful of opacity steps, then withdrawn.-PET_CARD_FADE_STEPS = 6-PET_CARD_FADE_STEP_MS = 30-#: How long a card a click expanded stays before a pending clear proceeds.-PET_CARD_READING_LINGER_S = 6.0-#: The default linger of ``clear_status``.+#: The default linger of the pet's ``clear_status`` (its thinking line).PET_STATUS_LINGER_S = 1.5PET_BUBBLE_GAP = 8#: The notification cards are this many times the strip's width.PET_NOTICE_WIDTH_PER_STRIP = 1.5-PET_BUBBLE_ELLIPSIS = "…"---def wrap_text_lines(- text: str,- measure: Callable[[str], int],- max_width: int,- max_lines: int,- ellipsis: str = PET_BUBBLE_ELLIPSIS,-) -> list[str]:- """Word-wrap ``text`` into at most ``max_lines`` lines of ``max_width`` pixels.-- ``measure`` returns a string's width in pixels (``tkfont.Font.measure`` in- the overlay, a plain character count in tests). A word wider than a whole- line is broken by characters. When the text does not fit, the last kept- line ends in ``ellipsis`` so a truncated status never reads as complete.- """- limit = max(1, int(max_lines))- width = max(1, int(max_width))- lines: list[str] = []- current = ""- for word in " ".join(str(text or "").split()).split(" "):- if not word:- continue- candidate = f"{current} {word}" if current else word- if measure(candidate) <= width:- current = candidate- continue- if current:- lines.append(current)- while len(word) > 1 and measure(word) > width:- cut = len(word) - 1- while cut > 1 and measure(word[:cut]) > width:- cut -= 1- lines.append(word[:cut])- word = word[cut:]- current = word- if len(lines) > limit:- break- if current and len(lines) <= limit:- lines.append(current)- if len(lines) <= limit:- return lines- kept = lines[:limit]- last = kept[-1]- while last and measure(last + ellipsis) > width:- last = last[:-1].rstrip()- kept[-1] = last + ellipsis- return kept# Magenta color key — Tkinter renders this color pixel-perfect transparent@@ -1302,27 +1232,6 @@ class OrbCommentBubble:self._queued_text: str | None = Noneself._queued_duration_ms: int = 0self._queue_after_id: str | None = None- # The pet's status variant (show_status): its own fonts, content,- # placement and expand state, so the comment/transcript variants the- # mascot uses stay exactly as they were.- self._status_font: tkfont.Font | None = None- self._header_font: tkfont.Font | None = None- self._status: tuple[str, str] | None = None- self._status_showing = False- self._status_expanded = False- self._status_anchor: tuple[int, int, int, int] | None = None- # (width, height) of the status bubble as last painted; a drag only- # moves a bubble of this size instead of repainting it.- self._status_size: tuple[int, int] | None = None- # A requested clear: the linger timer, then the fade steps.- self._clear_after_id: str | None = None- self._fade_after_id: str | None = None- self._status_clear_pending = False- self._status_max_w: int | None = None- self._ui_scale = 1.0- #: Called after the status card appeared, moved, resized or went away,- #: so whatever hangs below it (the notification stack) can follow.- self.on_status_change: Callable[[], None] | None = Noneself._build()def update_anchor(self, orb_x: int, orb_y: int, screen_w: int) -> None:@@ -1679,312 +1588,6 @@ class OrbCommentBubble:# -- the pet's status variant ------------------------------------------- def set_ui_scale(self, scale: float) -> None:- """Pixel sizes of the status card follow the strip's scale."""- try:- self._ui_scale = max(0.5, min(4.0, float(scale)))- except (TypeError, ValueError):- self._ui_scale = 1.0-- def set_status_max_width(self, width: int | None) -> None:- """The card's widest size (1.6 x the strip) — ``None`` for the default."""- self._status_max_w = None if width is None else max(1, int(width))-- @property- def status_showing(self) -> bool:- return self._status_showing-- def status_box(self) -> tuple[int, int, int, int] | None:- """``(x, y, width, height)`` of the status card on screen, or ``None``."""- size = self._status_size- anchor = self._status_anchor- if not self._status_showing or size is None or anchor is None:- return None- x, y = self._status_position(size[0], size[1], anchor)- return x, y, size[0], size[1]-- def _notify_status_change(self) -> None:- # getattr: tests build bubbles without __init__.- callback = getattr(self, "on_status_change", None)- if callback is None:- return- try:- callback()- except Exception: # noqa: BLE001 — a follower must not break the card- logging.getLogger("jarvis.orb").debug("status change hook failed", exc_info=True)-- @property- def window(self) -> tk.Toplevel | None:- return self._top-- def _ensure_status_fonts(self) -> bool:- if self._top is None or self._canvas is None:- return False- if self._status_font is None:- # A click expands the detail to three lines (and collapses it- # again). Bound with the first status, so the mascot's comment and- # transcript variants keep ignoring clicks as they always have.- self._canvas.bind("<ButtonRelease-1>", self._on_click)- self._status_font = tkfont.Font(- root=self._top,- family=BUBBLE_FONT_FAMILY,- size=PET_CARD_DETAIL_FONT_SIZE,- )- if self._header_font is None:- self._header_font = tkfont.Font(- root=self._top,- family=BUBBLE_FONT_FAMILY,- size=PET_CARD_TITLE_FONT_SIZE,- weight="bold",- )- return True-- def show_status(- self,- title: str,- detail: str,- *,- anchor: tuple[int, int, int, int],- ) -> None:- """Show (or update) the pet's status card and cancel a pending clear.-- ``anchor`` is ``(center_x, below_y, above_y, limit_bottom)``: the card- hangs from ``below_y`` (just under the control strip) when it fits above- ``limit_bottom``, else it sits on ``above_y`` (just over the figure) —- a pet parked on the taskbar would otherwise push its card off screen.- A title-less status shows its detail as the title.- """- if self._top is None or self._canvas is None:- return- title = " ".join(str(title or "").split())- detail = " ".join(str(detail or "").split())- if not title:- title, detail = detail, ""- if not title:- self.clear_status(0.0)- return- self._cancel_timers()- self._cancel_clear()- self._status = (title, detail)- self._status_anchor = anchor- self._render_status()-- def clear_status(self, linger_s: float = PET_STATUS_LINGER_S) -> None:- """Fade the card out after ``linger_s`` seconds (at once when 0).-- A newer :meth:`show_status` before the fade ends cancels it. Calling- it again while a clear is pending keeps the earlier deadline.- """- if self._top is None:- return- if not self._status_showing:- self._cancel_clear()- return- try:- delay = max(0.0, float(linger_s))- except (TypeError, ValueError):- delay = PET_STATUS_LINGER_S- if delay <= 0.0:- self._cancel_clear()- self.hide()- return- if self._status_clear_pending:- return- self._status_clear_pending = True- self._clear_after_id = self._top.after(int(delay * 1000), self._start_fade)-- def _start_fade(self, step: int = 0) -> None:- self._clear_after_id = None- top = self._top- if top is None or not self._status_showing:- self._status_clear_pending = False- return- if step >= PET_CARD_FADE_STEPS:- self._fade_after_id = None- self.hide()- return- try:- top.wm_attributes("-alpha", 1.0 - (step + 1) / (PET_CARD_FADE_STEPS + 1))- except tk.TclError:- # No per-window opacity here (some X11 window managers): skip- # straight to the end instead of half-fading.- self._fade_after_id = None- self.hide()- return- self._fade_after_id = top.after(PET_CARD_FADE_STEP_MS, lambda: self._start_fade(step + 1))-- def _cancel_clear(self) -> None:- """Stop a pending clear and bring the card back to full opacity."""- top = self._top- for attr in ("_clear_after_id", "_fade_after_id"):- after_id = getattr(self, attr)- if after_id is not None and top is not None:- try:- top.after_cancel(after_id)- except tk.TclError:- logging.getLogger("jarvis.orb").debug("card timer cancel failed", exc_info=True)- setattr(self, attr, None)- if self._status_clear_pending and top is not None:- try:- top.wm_attributes("-alpha", 1.0)- except tk.TclError:- logging.getLogger("jarvis.orb").debug("card opacity reset failed", exc_info=True)- self._status_clear_pending = False-- def move_status(self, anchor: tuple[int, int, int, int]) -> None:- """Follow the pet (drag, resize) without touching a pending clear.-- A drag calls this for every mouse motion, and neither the text nor the- width changes then: only the window moves. The canvas is repainted- only when nothing was painted yet.- """- self._status_anchor = anchor- if not self._status_showing:- return- size = self._status_size- if size is None or self._top is None:- self._render_status()- return- x, y = self._status_position(size[0], size[1], anchor)- try:- self._top.geometry(f"+{x}+{y}")- except tk.TclError:- logging.getLogger("jarvis.orb").debug("pet status card move failed", exc_info=True)-- def _status_position(- self, card_w: int, height: int, anchor: tuple[int, int, int, int]- ) -> tuple[int, int]:- """Top-left corner for a card of this size: under the strip when it- fits above ``limit_bottom``, else over the figure."""- center_x, below_y, above_y, limit_bottom = anchor- x = max(8, min(center_x - card_w // 2, self._screen_w - card_w - 8))- y = below_y if below_y + height <= limit_bottom else max(8, above_y - height)- return x, y-- def _on_click(self, _event: tk.Event | None = None) -> None:- if not self._status_showing:- return- self._status_expanded = not self._status_expanded- reading = self._status_clear_pending- self._cancel_clear()- self._render_status()- if reading:- # The user opened a card that was about to go: give them time.- self.clear_status(PET_CARD_READING_LINGER_S)-- def card_layout(- self,- title: str,- detail: str,- measure_title: Callable[[str], int],- measure_detail: Callable[[str], int],- title_lh: int,- detail_lh: int,- ) -> tuple[int, int, list[str], list[str], int]:- """``(width, height, title_lines, detail_lines, radius)`` of the card.-- Pure geometry (the fonts' measure functions are injected), so it is- testable without Tk. The card fits its text between the minimum width- and 1.6 x the strip; a collapsed two-line card is a full pill, an- expanded one keeps that end radius.- """- scale = self._ui_scale- pad_x = int(round(PET_CARD_PAD_X * scale))- pad_y = int(round(PET_CARD_PAD_Y * scale))- gap = int(round(PET_CARD_LINE_GAP * scale))- max_w = self._status_max_w or int(round(PET_CARD_MAX_WIDTH * scale))- max_w = max(1, min(max_w, max(160, self._screen_w - 16)))- min_w = min(max_w, int(round(PET_CARD_MIN_WIDTH * scale)))- text_max = max(40, max_w - 2 * pad_x)- title_lines = wrap_text_lines(title, measure_title, text_max, 1)- detail_limit = (- PET_CARD_DETAIL_EXPANDED_LINES- if self._status_expanded- else PET_CARD_DETAIL_COLLAPSED_LINES- )- detail_lines = (- wrap_text_lines(detail, measure_detail, text_max, detail_limit) if detail else []- )- widest = max(- [measure_title(line) for line in title_lines]- + [measure_detail(line) for line in detail_lines]- + [0]- )- width = max(min_w, min(max_w, widest + 2 * pad_x))- height = 2 * pad_y + title_lh * len(title_lines)- if detail_lines:- height += gap + detail_lh * len(detail_lines)- collapsed = 2 * pad_y + title_lh + (gap + detail_lh if detail else 0)- radius = max(4, min(height, collapsed) // 2)- return width, height, title_lines, detail_lines, radius-- def _render_status(self) -> bool:- """Paint the status card. Returns False when nothing could be drawn."""- if (- self._top is None- or self._canvas is None- or self._status is None- or self._status_anchor is None- or not self._ensure_status_fonts()- ):- return False- detail_font = self._status_font- title_font = self._header_font- assert detail_font is not None and title_font is not None # noqa: S101 — set above- title, detail = self._status- theme = self._theme- scale = self._ui_scale- pad_x = int(round(PET_CARD_PAD_X * scale))- pad_y = int(round(PET_CARD_PAD_Y * scale))- gap = int(round(PET_CARD_LINE_GAP * scale))- title_lh = max(1, int(title_font.metrics("linespace")))- detail_lh = max(1, int(detail_font.metrics("linespace")))- width, height, title_lines, detail_lines, radius = self.card_layout(- title, detail, title_font.measure, detail_font.measure, title_lh, detail_lh- )- x, y = self._status_position(width, height, self._status_anchor)- try:- self._top.wm_attributes("-alpha", 1.0)- except tk.TclError:- logging.getLogger("jarvis.orb").debug("card opacity reset failed", exc_info=True)- try:- self._top.geometry(f"{width}x{height}+{x}+{y}")- self._canvas.configure(width=width, height=height)- self._canvas.delete("all")- self._draw_rounded_rect(- 1,- 1,- width - 1,- height - 1,- radius,- fill=theme.bg,- outline=theme.border,- width=theme.border_width,- )- cursor_y = pad_y- for line in title_lines:- self._canvas.create_text(- pad_x, cursor_y, text=line, font=title_font, anchor="nw", fill=theme.header- )- cursor_y += title_lh- if detail_lines:- cursor_y += gap- for line in detail_lines:- self._canvas.create_text(- pad_x, cursor_y, text=line, font=detail_font, anchor="nw", fill=theme.text- )- cursor_y += detail_lh- self._top.deiconify()- self._top.lift()- except tk.TclError:- logging.getLogger("jarvis.orb").debug("pet status card paint failed", exc_info=True)- self._status_size = None- return False- self._status_showing = True- self._status_size = (width, height)- self._notify_status_change()- return True-def _cancel_timers(self) -> None:if self._top is None:return@@ -2000,13 +1603,6 @@ class OrbCommentBubble:self._queued_text = Nonedef hide(self) -> None:- self._cancel_clear()- was_showing = self._status_showing- self._status_showing = False- self._status_expanded = False- self._status_size = None- if was_showing:- self._notify_status_change()if self._top is None:returnif self._dismiss_after_id is not None:@@ -2984,8 +2580,6 @@ class OrbOverlay:screen_w=screen_w,theme=bubble_theme_for_style(self._style),)- self._comment_bubble.set_ui_scale(self._dpi_ratio)- self._comment_bubble.on_status_change = self._sync_notice_anchorself._ensure_controls()if self._style == "pet":self._sync_pet_strip_scale()@@ -3078,16 +2672,11 @@ class OrbOverlay:return strip_h + gapdef _sync_pet_strip_scale(self) -> None:- """Bring the strip and the status card to the current strip scale."""+ """Bring the strip and the card column to the current strip scale."""scale = self._pet_strip_scale()row = self._controlsif isinstance(row, PetControlStrip):row.set_scale(scale)- bubble = self._comment_bubble- if bubble is not None:- bubble.set_ui_scale(scale)- strip_w, _strip_h = orb_controls.pet_strip_size(scale)- bubble.set_status_max_width(int(round(strip_w * PET_CARD_MAX_WIDTH_PER_STRIP)))notices = self._noticesif notices is not None:strip_w, _strip_h = orb_controls.pet_strip_size(scale)@@ -3109,11 +2698,8 @@ class OrbOverlay:def _move_attached(self, x: int, y: int, screen_w: int) -> None:"""Bring the bubble and the control row along after the window moved."""bubble = self._comment_bubble- if bubble is not None:- if self._style == "pet":- bubble.move_status(self._status_anchor(refresh_limit=False))- else:- bubble.update_anchor(x, y, screen_w)+ if bubble is not None and self._style != "pet":+ bubble.update_anchor(x, y, screen_w)if self._controls is not None:self._controls.update_anchor(x, y)self._sync_notice_anchor(refresh_limit=False)@@ -3213,9 +2799,9 @@ class OrbOverlay:row = self._controlsif row is not None and row.visible and row.window is not None:windows.append(row.window)- bubble = self._comment_bubble- if bubble is not None and bubble.status_showing and bubble.window is not None:- windows.append(bubble.window)+ notices = self._notices+ if notices is not None and notices.window is not None:+ windows.append(notices.window)for window in windows:try:if force or is_healthy(window) is not True:@@ -3291,8 +2877,6 @@ class OrbOverlay:self._work_area_cache = Noneif self._controls is not None:self._controls.update_anchor(self._mascot_x, self._mascot_y)- if self._style == "pet" and self._comment_bubble is not None:- self._comment_bubble.move_status(self._status_anchor())self._sync_notice_anchor()self._manual_pinned = True@@ -3986,10 +3570,8 @@ class OrbOverlay:if row is not None:row.hide()self._pointer_over_orb = False- if self._style == "pet" and self._comment_bubble is not None:- # The pet's status bubble hangs off the pet; it goes with it.- self._comment_bubble.hide()if self._notices is not None:+ # The pet's cards hang off the pet; they go with it.self._notices.hide()if self._root is not None:try:@@ -4105,12 +3687,12 @@ class OrbOverlay:The pet's status bubble is not snatched away the moment a turn ends:it fades six seconds later, so the last line can still be read."""+ if self._style == "pet":+ self.clear_status(PET_STATUS_LINGER_S)+ returnbubble = self._comment_bubbleif bubble is None:return- if self._style == "pet":- self._enqueue_ui(lambda: bubble.clear_status(PET_STATUS_LINGER_S))- returnself._enqueue_ui(bubble.hide)# --- the desktop pet (docs/pets.md "Surface methods") ------------------@@ -4176,10 +3758,22 @@ class OrbOverlay:self._enqueue_ui(lambda: self._apply_notice(kind_text, title_text, detail_text))def _apply_notice(self, kind: str, title: str, detail: str) -> None:- if self._style != "pet" or not self._notify_enabled or self._root is None:+ if self._style != "pet" or not self._notify_enabled:return- if self._user_hidden or not self._window_mapped():+ notices = self._card_column()+ if notices is None:return+ notices.push(kind, title, detail)+ self._sync_controls_visibility()+ self._ring_bell()++ def _card_column(self) -> PetNoticeStack | None:+ """The pet's card column, built on first use; ``None`` when the pet+ cannot show cards right now (no window, hidden by the user)."""+ if self._style != "pet" or self._root is None:+ return None+ if self._user_hidden or not self._window_mapped():+ return Nonenotices = self._noticesif notices is None:scale = self._pet_strip_scale()@@ -4191,30 +3785,15 @@ class OrbOverlay:width=int(round(strip_w * PET_NOTICE_WIDTH_PER_STRIP)),)except tk.TclError:- logging.getLogger("jarvis.orb").debug("notice stack unavailable", exc_info=True)- return+ logging.getLogger("jarvis.orb").debug("card column unavailable", exc_info=True)+ return Noneself._notices = noticesself._sync_notice_anchor()- notices.push(kind, title, detail)- self._sync_controls_visibility()- self._ring_bell()+ return noticesdef _notice_anchor(self, *, refresh_limit: bool = True) -> tuple[int, int, int, int, int]:- """``(center_x, below_y, above_y, limit_bottom, screen_w)`` for the cards.-- Like the status card's, pushed past the status card when one shows:- the cards hang under it, or stand above it when it sits over the pet.- """+ """``(center_x, below_y, above_y, limit_bottom, screen_w)`` for the cards."""center_x, below_y, above_y, limit = self._status_anchor(refresh_limit=refresh_limit)- gap = max(1, int(round(PET_BUBBLE_GAP * self._pet_strip_scale())))- bubble = self._comment_bubble- box = bubble.status_box() if bubble is not None else None- if box is not None:- _x, y, _w, h = box- if y >= below_y - 1:- below_y = y + h + gap- else:- above_y = y - gaptry:screen_w = int(self._root.winfo_screenwidth()) if self._root is not None else 1920except tk.TclError:@@ -4281,28 +3860,33 @@ class OrbOverlay:self._kick_frame()def show_status(self, title: str = "", detail: str = "") -> None:- """Show or update the pet's status card (bold title, muted detail). Thread-safe."""+ """Show or update the pet's thinking line. Thread-safe.++ One muted line, like the Codex companion's: the current step when+ there is one (``detail``), else the heading (``title``).+ """if self._style != "pet":returnself._note_activity()- if not self._pet_bubble or self._comment_bubble is None:+ if not self._pet_bubble:return- title_text = str(title or "")- detail_text = str(detail or "")- self._enqueue_ui(lambda: self._apply_status(title_text, detail_text))+ line = " ".join(str(detail or "").split()) or " ".join(str(title or "").split())+ self._enqueue_ui(lambda: self._apply_status(line))def clear_status(self, linger_s: float = PET_STATUS_LINGER_S) -> None:- """Fade the status card out after ``linger_s`` seconds (at once when 0). Thread-safe."""+ """Fade the thinking line out after ``linger_s`` seconds (at once when 0). Thread-safe."""if self._style != "pet":return- bubble = self._comment_bubble- if bubble is None:- returntry:linger = max(0.0, float(linger_s))except (TypeError, ValueError):linger = PET_STATUS_LINGER_S- self._enqueue_ui(lambda: bubble.clear_status(linger))++ def _apply() -> None:+ if self._notices is not None:+ self._notices.clear_status(linger)++ self._enqueue_ui(_apply)def set_muted(self, muted: bool) -> None:"""Mirror Jarvis's microphone mute on the strip. Thread-safe."""@@ -4357,8 +3941,8 @@ class OrbOverlay:def _apply_pet_look(self) -> None:if self._style != "pet":return- if not self._pet_bubble and self._comment_bubble is not None:- self._comment_bubble.hide()+ if not self._pet_bubble and self._notices is not None:+ self._notices.clear_status(0.0)renderer = self._rendererif isinstance(renderer, PetRenderer):renderer.set_look(pet_scale=self._pet_scale)@@ -4396,14 +3980,17 @@ class OrbOverlay:elif row is not None:row.set_state(speaker_muted=self._speaker_muted)- def _apply_status(self, title: str, detail: str) -> None:- bubble = self._comment_bubble- if bubble is None or self._style != "pet" or not self._pet_bubble:+ def _apply_status(self, line: str) -> None:+ if not self._pet_bubble:return# No card floating over an empty desktop: it belongs to the pet.- if self._user_hidden or not self._window_mapped():+ notices = self._card_column()+ if notices is None:return- bubble.show_status(title, detail, anchor=self._status_anchor())+ if line:+ notices.set_status(line)+ else:+ notices.clear_status(0.0)def _status_anchor(self, *, refresh_limit: bool = True) -> tuple[int, int, int, int]:"""``(center_x, below_y, above_y, limit_bottom)`` for the status card."""diff --git a/ui/orb/pet_cards.py b/ui/orb/pet_cards.pynew file mode 100644index 0000000000..7b47e51800--- /dev/null+++ b/ui/orb/pet_cards.py@@ -0,0 +1,423 @@+"""The pet's cards, drawn: the thinking line and the "done" card.++Two looks, one material — the Codex companion's: a dark, slightly+see-through surface with a hairline rim, soft rounded corners and a soft+shadow.++* **status** — one muted line while Jarvis thinks ("Thinking …", "Search the+ web"). A light sweeps across the words while the line is up, so a long+ thought reads as alive without a spinner.+* **done** / **error** — a Jarvis turn or a task Jarvis started has finished:+ a small green check (red cross) and a bold title — what was asked — over+ the first line or two of the answer.++Everything is pure PIL and returns RGBA with real alpha, ready for a+per-pixel-alpha window (:mod:`jarvis.platform.layered_window`). Where only a+colour key exists, :func:`flatten_for_key` turns the same image into hard+edges on an opaque fill, so a card never grows a pink fringe.+"""++from __future__ import annotations++import functools+import math+import os+import sys+from pathlib import Path++from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont++_Rgb = tuple[int, int, int]+_Rgba = tuple[int, int, int, int]++#: What a card shows. ``status`` is the live thinking line.+CARD_KINDS: tuple[str, ...] = ("status", "done", "error")++#: Unscaled geometry (logical px at 100 % and ``pet_scale`` 1.0).+STATUS_HEIGHT = 40+PAD_X = 16+PAD_Y = 11+LINE_GAP = 3+ICON = 17+ICON_GAP = 7+RADIUS = 18+MIN_WIDTH = 120+#: Room around a card for its shadow.+SHADOW_PAD = 14+SHADOW_BLUR = 9+SHADOW_OFFSET_Y = 3+SHADOW_ALPHA = 110+#: Font sizes in px.+TITLE_PX = 14.5+BODY_PX = 14.0+STATUS_PX = 14.0+#: Lines of the answer under a done card's title.+DETAIL_LINES = 2++#: The surface: a dark grey just see-through enough that the desktop shows+#: as a shade, a hairline rim, and the text colours.+FILL: _Rgba = (34, 34, 37, 226)+RIM: _Rgba = (255, 255, 255, 30)+#: The fill a colour-keyed window uses instead (no alpha there).+FILL_SOLID: _Rgb = (30, 30, 33)+RIM_SOLID: _Rgb = (58, 58, 63)+TITLE: _Rgb = (242, 242, 245)+BODY: _Rgb = (190, 191, 198)+STATUS: _Rgb = (150, 151, 158)+#: The sweep's brightest point on the status line.+STATUS_SHINE: _Rgb = (236, 237, 242)+ICON_FILL: dict[str, _Rgb] = {"done": (34, 197, 94), "error": (239, 68, 68)}+ICON_MARK: dict[str, _Rgb] = {"done": (10, 26, 16), "error": (40, 8, 8)}+#: Hover lifts a card a shade.+HOVER_LIFT = 10++#: The icon draws itself in this many steps (the check is ticked).+ICON_FRAMES = 10+#: Sweep positions across the status line per pass.+SHIMMER_STEPS = 24+SHIMMER_PERIOD_S = 1.6++_SS = 3 # supersampling for the card silhouette+++def _px(value: float, scale: float) -> int:+ return max(1, int(round(value * max(0.25, float(scale)))))+++# --- fonts -------------------------------------------------------------------+++def _font_candidates(weight: str) -> list[Path]:+ """Font files to try, best first, on this OS."""+ out: list[Path] = []+ if sys.platform == "win32":+ root = Path(os.environ.get("WINDIR", "C:/Windows")) / "Fonts"+ names = ["seguisb.ttf", "segoeuib.ttf"] if weight == "semibold" else ["segoeui.ttf"]+ out += [root / n for n in names]+ elif sys.platform == "darwin":+ out += [Path("/System/Library/Fonts/SFNS.ttf"), Path("/System/Library/Fonts/Helvetica.ttc")]+ else:+ bold = weight == "semibold"+ for base in ("/usr/share/fonts/truetype", "/usr/share/fonts"):+ for name in (+ ("inter/Inter-SemiBold.ttf" if bold else "inter/Inter-Regular.ttf"),+ ("dejavu/DejaVuSans-Bold.ttf" if bold else "dejavu/DejaVuSans.ttf"),+ ("TTF/DejaVuSans-Bold.ttf" if bold else "TTF/DejaVuSans.ttf"),+ ("noto/NotoSans-SemiBold.ttf" if bold else "noto/NotoSans-Regular.ttf"),+ ):+ out.append(Path(base) / name)+ return out++[email protected]_cache(maxsize=32)+def font(weight: str, px: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:+ """A font of ``weight`` (``regular`` / ``semibold``) at ``px`` pixels.++ The OS's UI face where one is found; Pillow's own scalable default+ otherwise, so a bare Linux server still renders readable text.+ """+ for path in _font_candidates(weight):+ if path.is_file():+ try:+ return ImageFont.truetype(str(path), px)+ except OSError:+ continue+ try:+ return ImageFont.load_default(px)+ except TypeError: # Pillow < 10.1 has no sized default+ return ImageFont.load_default()+++def _text_w(f: ImageFont.FreeTypeFont | ImageFont.ImageFont, text: str) -> float:+ return float(f.getlength(text)) if hasattr(f, "getlength") else float(len(text) * 7)+++def _line_h(f: ImageFont.FreeTypeFont | ImageFont.ImageFont) -> int:+ try:+ ascent, descent = f.getmetrics() # type: ignore[union-attr]+ return int(ascent + descent)+ except AttributeError:+ return 14+++def ellipsize(text: str, f: ImageFont.FreeTypeFont | ImageFont.ImageFont, width: float) -> str:+ """``text`` cut with an ellipsis to fit ``width`` pixels."""+ if _text_w(f, text) <= width:+ return text+ lo, hi = 0, len(text)+ while lo < hi:+ mid = (lo + hi + 1) // 2+ if _text_w(f, text[:mid].rstrip() + "…") <= width:+ lo = mid+ else:+ hi = mid - 1+ return text[:lo].rstrip() + "…"+++def wrap(+ text: str, f: ImageFont.FreeTypeFont | ImageFont.ImageFont, width: float, max_lines: int+) -> list[str]:+ """Word-wrap ``text`` into at most ``max_lines`` lines, the last ellipsized."""+ words = text.split()+ lines: list[str] = []+ current = ""+ for index, word in enumerate(words):+ trial = f"{current} {word}".strip()+ if _text_w(f, trial) <= width or not current:+ current = trial+ continue+ lines.append(current)+ if len(lines) == max_lines:+ rest = " ".join([lines.pop(), *words[index:]])+ lines.append(ellipsize(rest, f, width))+ return lines+ current = word+ if current:+ lines.append(ellipsize(current, f, width) if len(lines) < max_lines else current)+ return lines[:max_lines]+++# --- shapes ------------------------------------------------------------------++[email protected]_cache(maxsize=64)+def _rounded_mask(width: int, height: int, radius: int) -> Image.Image:+ """An antialiased rounded-rectangle mask (drawn large, scaled down)."""+ big = Image.new("L", (width * _SS, height * _SS), 0)+ ImageDraw.Draw(big).rounded_rectangle(+ [0, 0, width * _SS - 1, height * _SS - 1], radius=radius * _SS, fill=255+ )+ return big.resize((width, height), Image.Resampling.LANCZOS)++[email protected]_cache(maxsize=64)+def _surface(width: int, height: int, radius: int, scale: float, hovered: bool) -> Image.Image:+ """Shadow, fill and rim of one card, with ``SHADOW_PAD`` around it."""+ pad = _px(SHADOW_PAD, scale)+ full = Image.new("RGBA", (width + 2 * pad, height + 2 * pad), (0, 0, 0, 0))+ mask = _rounded_mask(width, height, radius)+ shadow = Image.new("L", full.size, 0)+ shadow.paste(+ mask.point(lambda v: v * SHADOW_ALPHA // 255), (pad, pad + _px(SHADOW_OFFSET_Y, scale))+ )+ shadow = shadow.filter(ImageFilter.GaussianBlur(_px(SHADOW_BLUR, scale) / 2.0))+ full.putalpha(shadow)+ lift = HOVER_LIFT if hovered else 0+ fill = (FILL[0] + lift, FILL[1] + lift, FILL[2] + lift, FILL[3])+ body = Image.new("RGBA", (width, height), fill)+ body.putalpha(ImageChops.multiply(mask, Image.new("L", mask.size, fill[3])))+ full.alpha_composite(body, (pad, pad))+ # The rim: the silhouette minus itself shrunk by one pixel.+ inner = _rounded_mask(max(1, width - 2), max(1, height - 2), max(1, radius - 1))+ ring = mask.copy()+ hole = Image.new("L", mask.size, 0)+ hole.paste(inner, (1, 1))+ ring = ImageChops.subtract(ring, hole)+ rim = Image.new("RGBA", (width, height), RIM[:3] + (0,))+ rim.putalpha(ring.point(lambda v: v * RIM[3] // 255))+ full.alpha_composite(rim, (pad, pad))+ return full+++def _ease_out_back(t: float) -> float:+ t = max(0.0, min(1.0, t))+ c1 = 1.70158+ return 1.0 + (c1 + 1.0) * (t - 1.0) ** 3 + c1 * (t - 1.0) ** 2++[email protected]_cache(maxsize=64)+def render_icon(kind: str, frame: int, diameter: int) -> Image.Image:+ """The round check (or cross) at animation ``frame``, RGBA."""+ ss = 4+ size = max(2, diameter) * ss+ layer = Image.new("RGBA", (size, size), (0, 0, 0, 0))+ d = ImageDraw.Draw(layer)+ t = max(0, min(ICON_FRAMES, frame)) / ICON_FRAMES+ r = size / 2.0 * _ease_out_back(min(1.0, t / 0.5))+ c = size / 2.0+ fill = ICON_FILL.get(kind, ICON_FILL["done"])+ mark = ICON_MARK.get(kind, ICON_MARK["done"])+ if r > 0.5:+ d.ellipse([c - r, c - r, c + r, c + r], fill=fill + (255,))+ share = max(0.0, min(1.0, (t - 0.3) / 0.7))+ width = max(1, int(round(size * 0.12)))+ unit = size / 24.0++ def pt(u: float, v: float) -> tuple[float, float]:+ return (c + (u - 12.0) * unit, c + (v - 12.0) * unit)++ def stroke(points: list[tuple[float, float]], amount: float) -> None:+ if amount <= 0:+ return+ pts = [pt(u, v) for u, v in points]+ lengths = [math.dist(a, b) for a, b in zip(pts, pts[1:], strict=False)]+ want = sum(lengths) * amount+ line = [pts[0]]+ for (a, b), length in zip(zip(pts, pts[1:], strict=False), lengths, strict=False):+ if want >= length:+ line.append(b)+ want -= length+ continue+ f = want / length if length else 0.0+ line.append((a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f))+ break+ d.line(line, fill=mark + (255,), width=width, joint="curve")+ for x, y in (line[0], line[-1]):+ d.ellipse(+ [x - width / 2, y - width / 2, x + width / 2, y + width / 2], fill=mark + (255,)+ )++ if kind == "error":+ stroke([(8.4, 8.4), (15.6, 15.6)], min(1.0, share * 2))+ stroke([(15.6, 8.4), (8.4, 15.6)], max(0.0, share * 2 - 1))+ else:+ stroke([(7.0, 12.4), (10.6, 15.8), (17.0, 8.8)], share)+ return layer.resize((diameter, diameter), Image.Resampling.LANCZOS)+++# --- cards -------------------------------------------------------------------++[email protected]_cache(maxsize=128)+def render_card(+ kind: str,+ title: str,+ detail: str,+ *,+ scale: float = 1.0,+ max_width: int = 360,+ hovered: bool = False,+ icon_frame: int = ICON_FRAMES,+ content: bool = True,+) -> Image.Image:+ """One card as RGBA, shadow included (``SHADOW_PAD`` on every side).++ A done card is always ``max_width`` wide, so stacked cards line up edge+ to edge; the thinking line fits its text. ``content=False`` draws the+ surface alone — a card peeking out behind another must not show its+ text through the see-through card in front.++ ``status`` cards ignore ``detail`` handling of their own: the caller+ passes the one line to show as ``title``. Pure and cached — never mutate+ the result.+ """+ pad_x, pad_y = _px(PAD_X, scale), _px(PAD_Y, scale)+ max_inner = max(40, max_width - 2 * pad_x)+ if kind == "status":+ f = font("regular", _px(STATUS_PX, scale))+ text = ellipsize(" ".join(title.split()), f, max_inner)+ width = max(_px(MIN_WIDTH, scale), int(math.ceil(_text_w(f, text))) + 2 * pad_x)+ height = _px(STATUS_HEIGHT, scale)+ radius = min(height // 2, _px(RADIUS, scale))+ card = _surface(min(width, max_width), height, radius, round(scale, 3), hovered).copy()+ pad = _px(SHADOW_PAD, scale)+ ImageDraw.Draw(card).text(+ (pad + pad_x, pad + height / 2.0), text, font=f, fill=STATUS + (255,), anchor="lm"+ )+ return card+ title_font = font("semibold", _px(TITLE_PX, scale))+ body_font = font("regular", _px(BODY_PX, scale))+ icon_d = _px(ICON, scale)+ icon_gap = _px(ICON_GAP, scale)+ title_text = ellipsize(" ".join(title.split()), title_font, max_inner - icon_d - icon_gap)+ lines = wrap(" ".join(detail.split()), body_font, max_inner, DETAIL_LINES) if detail else []+ widest = max(+ [icon_d + icon_gap + _text_w(title_font, title_text)]+ + [_text_w(body_font, line) for line in lines]+ )+ _ = widest # measured for the wrap; the width itself is fixed+ width = max(_px(MIN_WIDTH, scale), max_width)+ title_h = max(_line_h(title_font), icon_d)+ body_h = _line_h(body_font)+ gap = _px(LINE_GAP, scale)+ height = 2 * pad_y + title_h + (gap + body_h * len(lines) if lines else 0)+ radius = min(height // 2, _px(RADIUS, scale))+ card = _surface(width, height, radius, round(scale, 3), hovered).copy()+ if not content:+ return card+ pad = _px(SHADOW_PAD, scale)+ x0, y0 = pad + pad_x, pad + pad_y+ icon = render_icon(kind, icon_frame, icon_d)+ card.alpha_composite(icon, (x0, int(round(y0 + (title_h - icon_d) / 2.0))))+ d = ImageDraw.Draw(card)+ d.text(+ (x0 + icon_d + icon_gap, y0 + title_h / 2.0),+ title_text,+ font=title_font,+ fill=TITLE + (255,),+ anchor="lm",+ )+ y = y0 + title_h + gap+ for line in lines:+ d.text((x0, y), line, font=body_font, fill=BODY + (255,))+ y += body_h+ return card++[email protected]_cache(maxsize=64)+def _sweep_gain(width: int, height: int, head: int, band: int) -> Image.Image:+ """The sweep's brightness across the card: a soft band centred on ``head``."""+ row = Image.new("L", (width, 1), 0)+ px = row.load()+ for x in range(width):+ d = (x - head) / max(1, band)+ px[x, 0] = int(255 * math.exp(-d * d * 2.5))+ return row.resize((width, height))+++def shimmer(card: Image.Image, step: int, scale: float) -> Image.Image:+ """A status card with the light sweep at ``step`` of ``SHIMMER_STEPS``.++ The text pixels (where the card is brighter than its fill) are re-tinted+ along a soft band moving left to right; nothing else changes.+ """+ pad = _px(SHADOW_PAD, scale)+ width, height = card.size+ band = max(8.0, (width - 2 * pad) * 0.28)+ head = -band + (width + 2 * band) * ((step % SHIMMER_STEPS) / SHIMMER_STEPS)+ gain = _sweep_gain(width, height, int(round(head)), int(round(band)))+ rgb = card.convert("RGB")+ lum = rgb.convert("L")+ text = lum.point(lambda v: 255 if v > STATUS[0] - 40 else 0)+ shine = Image.new("RGBA", card.size, STATUS_SHINE + (255,))+ sweep = ImageChops.multiply(gain, text)+ out = card.copy()+ shine.putalpha(ImageChops.multiply(sweep, card.getchannel("A")))+ out.alpha_composite(shine)+ out.putalpha(card.getchannel("A")) # the sweep tints; it never changes coverage+ return out+++def card_box(image: Image.Image, scale: float) -> tuple[int, int, int, int]:+ """The card's own rectangle inside its shadow-padded image."""+ pad = _px(SHADOW_PAD, scale)+ return pad, pad, image.width - pad, image.height - pad+++def flatten_for_key(image: Image.Image, key: _Rgb) -> Image.Image:+ """``image`` for a colour-keyed window: opaque card, keyed outside.++ Pixels at least half covered become the card over its solid fill; the+ rest become the key — a hard edge, so no blended pixel survives as a+ fringe. The shadow and the see-through are lost on purpose.+ """+ alpha = image.getchannel("A")+ solid = Image.new("RGBA", image.size, FILL_SOLID + (255,))+ solid.alpha_composite(image)+ hard = alpha.point(lambda v: 255 if v >= 200 else 0)+ out = Image.new("RGB", image.size, key)+ out.paste(solid.convert("RGB"), (0, 0), hard)+ return out+++__all__ = [+ "CARD_KINDS",+ "card_box",+ "ellipsize",+ "flatten_for_key",+ "font",+ "render_card",+ "render_icon",+ "shimmer",+ "wrap",+]