CLI for SidePulse
Python
Polish animations and add customization support (#38)
unrelatedlabse0d578fc2f86
diff --git a/LEDS_FORMAT.md b/LEDS_FORMAT.mdindex 995067b..2ad447b 100644--- a/LEDS_FORMAT.md+++ b/LEDS_FORMAT.md@@ -28,6 +28,11 @@ orTo recap, write to LEDS.LED what you want displayed.That's all you have to know.+SidePulse's host software keeps `LEDS.LED` as one fixed 512-byte record and+space-pads the unused tail. It overwrites that record in place so repeated status+updates reuse the same filesystem cluster instead of truncating and reallocating+the file. The firmware ignores the trailing whitespace.+## Initial state.The content in INIT.LED is played on power up. It can be anything supported by LEDS.LED.diff --git a/README.md b/README.mdindex f25da3c..5775f7f 100644--- a/README.md+++ b/README.md@@ -101,6 +101,25 @@ Agent status modes:| Blocked / Error | The agent cannot continue, a tool failed, or a recoverable error needs attention. | Slow amber pulse. || Completed | The agent finished successfully. | Solid green. |+Each mode can be configured independently in **Settings... → Animations**.+Every state uses the same animation library: **Idle Pulse**, **Cyan Roll**,+**Amber Pulse**, **Solid Green**, **KITT Scanner**, **KITT Scanner Red**, and+the **Ember** and **Purple** animation families, plus any named custom animation.+**Add Custom…** adds a reusable `LEDS.LED` program to that shared+library, and animation profiles save or apply all state selections together.+The built-in profiles are **Cyan** (the default), **Ember**, and **Purple**.+Built-ins live in `src/sidepulse/resources/animations/` as `.LED` files; patterns+that depend on the hardware layout have only `-2.LED` and `-8.LED` variants.+Custom programs are stored in the `animations/` folder beside `settings.json`.+An animation may set its own `brightness`, which is multiplied by the device's+brightness setting so the device setting remains the overall limit. The tab shows a+live Screen Bar-rendered preview for every state;+**Show** sends that pattern to connected agent-display devices for three+seconds, then restores live status. **Current** appears whenever individual+state selections no longer match one of the built-in or saved profiles.+Profiles can be exported as self-contained JSON—including referenced custom+animations—and imported on another SidePulse installation.+When multiple states are active, SidePulse should show the most actionablemode first: Blocked / Error, Waiting for Input, Tool Running, Long TaskProgress, Working, then Idle / Ready.@@ -484,8 +503,8 @@ it. Remove the helper with:sudo "$(command -v sidepulse)" status-bar uninstall-sleep-helper```-Open `Settings...` to edit and preview the Lid Closed and Lid Open LED-animations. Animation programs use the same `LEDS.LED` syntax as+Open **Settings... → Animations** to choose and preview the Lid Closed and Lid+Open rows alongside the agent-state animations. Animation programs use the same `LEDS.LED` syntax as`sidepulse write`; device brightness is applied automatically before writing.The app is also installed as a user LaunchAgent atdiff --git a/profiles/cyan.json b/profiles/cyan.jsonnew file mode 100644index 0000000..5deda21--- /dev/null+++ b/profiles/cyan.json@@ -0,0 +1,18 @@+{+ "animations": {+ "blocked_error": "amber-pulse",+ "completed": "cyan-complete",+ "idle_ready": "idle-pulse",+ "lid_closed": "lid-closed",+ "lid_open": "lid-open",+ "long_task_progress": "cyan-roll",+ "tool_running": "cyan-roll",+ "unknown": "idle-pulse",+ "waiting_for_input": "amber-pulse",+ "working": "cyan-roll"+ },+ "custom_animations": {},+ "format": "sidepulse-animation-profile",+ "name": "Cyan",+ "version": 1+}diff --git a/profiles/ember.json b/profiles/ember.jsonnew file mode 100644index 0000000..a7e24f5--- /dev/null+++ b/profiles/ember.json@@ -0,0 +1,18 @@+{+ "animations": {+ "blocked_error": "ember-attention",+ "completed": "ember-complete",+ "idle_ready": "ember-idle",+ "lid_closed": "lid-closed",+ "lid_open": "ember-lid-open",+ "long_task_progress": "ember-tide",+ "tool_running": "ember-tide",+ "unknown": "ember-idle",+ "waiting_for_input": "ember-attention",+ "working": "ember-tide"+ },+ "custom_animations": {},+ "format": "sidepulse-animation-profile",+ "name": "Ember",+ "version": 1+}diff --git a/profiles/purple.json b/profiles/purple.jsonnew file mode 100644index 0000000..0811b80--- /dev/null+++ b/profiles/purple.json@@ -0,0 +1,18 @@+{+ "animations": {+ "blocked_error": "purple-attention",+ "completed": "purple-complete",+ "idle_ready": "purple-idle",+ "lid_closed": "lid-closed",+ "lid_open": "purple-lid-open",+ "long_task_progress": "purple-tide",+ "tool_running": "purple-tide",+ "unknown": "purple-idle",+ "waiting_for_input": "purple-attention",+ "working": "purple-tide"+ },+ "custom_animations": {},+ "format": "sidepulse-animation-profile",+ "name": "Purple",+ "version": 1+}diff --git a/pyproject.toml b/pyproject.tomlindex ff56e56..f76a247 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -61,4 +61,4 @@ where = ["src"]include = ["sidepulse*", "agent_monitor*", "sidepulse_cli*"][tool.setuptools.package-data]-"sidepulse.resources" = ["sd_eject_guard.c", "sdled.wasm"]+"sidepulse.resources" = ["sd_eject_guard.c", "sdled.wasm", "animations/*.LED"]diff --git a/src/sidepulse/device_writer.py b/src/sidepulse/device_writer.pyindex cabb59a..b3afa79 100644--- a/src/sidepulse/device_writer.py+++ b/src/sidepulse/device_writer.py@@ -9,10 +9,12 @@ LED_FILE_NAMES = (DEFAULT_FILE_NAME,)KNOWN_LED_FILE_NAMES = frozenset(name.upper() for name in LED_FILE_NAMES)MAX_LED_BYTES = 512MAX_LED_LINES = 20+LED_RECORD_PADDING_BYTE = b" "MOUNT_ROOT = Path("/Volumes")DEVICE_NAME_HINTS = ("sidepulsepro","sidepulsedot",+ "pulsedot",)@@ -42,10 +44,45 @@ def write_led_program(return targettarget.parent.mkdir(parents=True, exist_ok=True)- target.write_text(program, encoding="utf-8")+ _write_led_record_in_place(target, program.encode("utf-8"))return target+def _write_led_record_in_place(target: Path, program: bytes) -> None:+ """Overwrite the fixed-size LED record without truncating the file first."""+ if len(program) > MAX_LED_BYTES:+ raise DeviceWriteError(+ f"LED program is {len(program)} bytes; max is {MAX_LED_BYTES}."+ )+ record = program.ljust(MAX_LED_BYTES, LED_RECORD_PADDING_BYTE)++ try:+ handle = target.open("r+b", buffering=0)+ except FileNotFoundError:+ # Creation is only a recovery path. Firmware normally provides LEDS.LED.+ handle = target.open("x+b", buffering=0)++ with handle:+ handle.seek(0)+ written = handle.write(record)+ if written != len(record):+ raise DeviceWriteError(+ f"Only wrote {written} of {len(record)} bytes to {target}."+ )++ # Repair an unexpectedly oversized file once. Normal writes stay at the+ # fixed size and therefore never release/reallocate the data cluster.+ handle.seek(0, 2)+ if handle.tell() > MAX_LED_BYTES:+ handle.truncate(MAX_LED_BYTES)+++def read_led_program(path: Path) -> str:+ """Read a fixed-size LED record as its logical, unpadded program text."""+ data = path.read_bytes().rstrip(b" \x00\xff")+ return data.decode("utf-8")++def normalize_led_text(text: str) -> str:return decode_simple_escapes(text)diff --git a/src/sidepulse/led_status.py b/src/sidepulse/led_status.pyindex dc2a619..b4a604b 100644--- a/src/sidepulse/led_status.py+++ b/src/sidepulse/led_status.py@@ -1,13 +1,17 @@from __future__ import annotations+import reimport timefrom dataclasses import dataclassfrom enum import Enum+from importlib.resources import filesfrom pathlib import Pathfrom .device_writer import (DEFAULT_FILE_NAME,DeviceWriteError,+ normalize_led_text,+ read_led_program,resolve_target_path,write_led_program,)@@ -31,12 +35,31 @@ LED_STATE_LABELS: dict[LedDisplayState, str] = {ASK_AMBER = "#FF3A00"WORKING_CYAN = "#00E5FF"+KITT_RED = "#FF1800"DONE_GREEN = "#00FF66"IDLE_DIM = "#020204"DEVICE_LED_COUNTS = {"sidepulsedot": 2,+ "pulsedot": 2,"sidepulsepro": 8,}+COUNT_SPECIFIC_ANIMATIONS = frozenset(+ {+ "idle-pulse",+ "cyan-roll",+ "kitt",+ "kitt-red",+ "ember-tide",+ "ember-idle",+ "ember-lid-open",+ "night-rider",+ "purple-idle",+ "purple-tide",+ "purple-lid-open",+ "lid-open",+ "lid-closed",+ }+)@dataclass(frozen=True)@@ -73,32 +96,112 @@ def program_for_display_state(brightness: int | float = 255,) -> str:if state == LedDisplayState.IDLE:+ return apply_brightness(builtin_animation_program("idle-pulse", led_count), brightness)+ if state == LedDisplayState.ASK:+ return apply_brightness(builtin_animation_program("amber-pulse", led_count), brightness)+ if state == LedDisplayState.DONE:+ return apply_brightness(builtin_animation_program("solid-green", led_count), brightness)+ if state == LedDisplayState.WORKING:+ return apply_brightness(builtin_animation_program("cyan-roll", led_count), brightness)+ raise ValueError(f"Unknown LED display state: {state}")+++def program_for_agent_mode(+ mode: AgentMode,+ *,+ led_count: int = 8,+ brightness: int | float = 255,+ animation_style: str = "default",+ custom_program: str = "",+) -> str:+ state = display_state_for_mode(mode)+ if animation_style == "custom":+ program = normalize_led_text(custom_program)+ if not program:+ raise DeviceWriteError("Custom agent animation is empty.")+ return apply_brightness(program, brightness)+ if animation_style == "idle-pulse":+ return program_for_display_state(+ LedDisplayState.IDLE,+ led_count=led_count,+ brightness=brightness,+ )+ if animation_style == "cyan-roll":+ return program_for_display_state(+ LedDisplayState.WORKING,+ led_count=led_count,+ brightness=brightness,+ )+ if animation_style == "amber-pulse":+ return program_for_display_state(+ LedDisplayState.ASK,+ led_count=led_count,+ brightness=brightness,+ )+ if animation_style == "solid-green":+ return program_for_display_state(+ LedDisplayState.DONE,+ led_count=led_count,+ brightness=brightness,+ )+ if animation_style == "kitt":return apply_brightness(- "\n".join(- [- "off",- f"{IDLE_DIM} 6s pulse",- "repeat",- ]- ),+ builtin_animation_program("kitt", led_count),brightness,)- if state == LedDisplayState.ASK:+ if animation_style == "kitt-red":return apply_brightness(- "\n".join(- [- "off",- f"{ASK_AMBER} 1.6s pulse",- "repeat",- ]- ),+ builtin_animation_program("kitt-red", led_count),brightness,)- if state == LedDisplayState.DONE:- return apply_brightness(DONE_GREEN, brightness)- if state == LedDisplayState.WORKING:- return apply_brightness(rolling_program(WORKING_CYAN, led_count=led_count), brightness)- raise ValueError(f"Unknown LED display state: {state}")+ if animation_style in {+ "off",+ "immediate-off",+ "cyan-complete",+ "ember-idle",+ "ember-tide",+ "ember-attention",+ "ember-complete",+ "ember-lid-open",+ "night-rider",+ "purple-idle",+ "purple-tide",+ "purple-attention",+ "purple-complete",+ "purple-lid-open",+ "lid-open",+ "lid-closed",+ }:+ return apply_brightness(+ builtin_animation_program(animation_style, led_count),+ brightness,+ )+ if animation_style != "default":+ raise DeviceWriteError(f"Unknown agent animation style: {animation_style}")+ return program_for_display_state(+ state,+ led_count=led_count,+ brightness=brightness,+ )+++def builtin_animation_file_name(animation_id: str, led_count: int = 8) -> str:+ if animation_id in COUNT_SPECIFIC_ANIMATIONS:+ count = 2 if int(led_count) == 2 else 8+ return f"{animation_id}-{count}.LED"+ return f"{animation_id}.LED"+++def builtin_animation_program(animation_id: str, led_count: int = 8) -> str:+ file_name = builtin_animation_file_name(animation_id, led_count)+ resource = files("sidepulse.resources").joinpath("animations", file_name)+ try:+ program = normalize_led_text(resource.read_text(encoding="utf-8")).strip()+ except (FileNotFoundError, OSError) as exc:+ raise DeviceWriteError(f"Built-in animation is missing: {file_name}") from exc+ if not program:+ raise DeviceWriteError(f"Built-in animation is empty: {file_name}")+ return programdef rolling_program(color: str, *, led_count: int = 8) -> str:@@ -111,13 +214,35 @@ def rolling_program(color: str, *, led_count: int = 8) -> str:segments.append(f"{active_index}:{color} {duration_ms}ms pulse {delay}ms")return "\n".join([- "off 160ms cosine",+ "off 320ms cosine","; ".join(segments),"repeat",])+def kitt_scanner_program(color: str, *, led_count: int = 8) -> str:+ """Build a compact scanner pulse that sweeps out and back."""+ count = max(2, min(8, int(led_count)))+ delay_ms = 240 if count == 2 else 85+ duration_ms = 320+ directions = (range(count), range(count - 2, -1, -1))+ scan_lines = [+ "; ".join(+ f"{index}:{color} {duration_ms}ms pulse {step * delay_ms}ms"+ for step, index in enumerate(indexes)+ )+ for indexes in directions+ ]+ return "\n".join(+ [+ "off 80ms cosine",+ *scan_lines,+ "repeat",+ ]+ )++def write_mode_to_leds(mode: AgentMode,*,@@ -125,13 +250,17 @@ def write_mode_to_leds(file_name: str = DEFAULT_FILE_NAME,dry_run: bool = False,brightness: int | float = 255,+ animation_style: str = "default",+ custom_program: str = "",) -> LedStatusWrite:target = resolve_target_path(device_path=device_path, file_name=file_name)state = display_state_for_mode(mode)- program = program_for_display_state(- state,+ program = program_for_agent_mode(+ mode,led_count=led_count_for_target(target),brightness=brightness,+ animation_style=animation_style,+ custom_program=custom_program,)written_target = write_led_program(program,@@ -171,9 +300,23 @@ def brightness_percent(value: int | float | None) -> int:def apply_brightness(program: str, brightness: int | float = 255) -> str:value = normalize_brightness(brightness)+ scaled_lines: list[str] = []+ found_brightness = False+ for line in str(program).splitlines():+ match = re.fullmatch(r"\s*brightness\s+(\d+)\s*", line, re.IGNORECASE)+ if match is None:+ scaled_lines.append(line)+ continue+ found_brightness = True+ authored = normalize_brightness(int(match.group(1)))+ scaled = round(authored * value / 255)+ scaled_lines.append(f"brightness {scaled}")+ normalized_program = "\n".join(scaled_lines)+ if found_brightness:+ return normalized_programif value >= 255:- return program- return f"brightness {value}\n{program}"+ return normalized_program+ return f"brightness {value}\n{normalized_program}"class AgentLedController:@@ -193,6 +336,8 @@ class AgentLedController:self.brightness = normalize_brightness(brightness)self.last_state: LedDisplayState | None = Noneself.last_brightness: int | None = None+ self.last_animation_signature: tuple[str, str] | None = None+ self.last_program: str | None = Noneself.last_error: str | None = Noneself.last_target: Path | None = Noneself.last_attempt_monotonic = 0.0@@ -200,15 +345,43 @@ class AgentLedController:def reset(self) -> None:self.last_state = Noneself.last_brightness = None+ self.last_animation_signature = None+ self.last_program = Noneself.last_error = Noneself.last_target = Noneself.last_attempt_monotonic = 0.0- def sync_mode(self, mode: AgentMode) -> LedStatusWrite:+ def _last_program_is_current(self) -> bool:+ if self.dry_run:+ return True+ if self.last_target is None or self.last_program is None:+ return False+ try:+ return read_led_program(self.last_target) == self.last_program+ except (OSError, UnicodeError):+ return False++ def sync_mode(+ self,+ mode: AgentMode,+ *,+ animation_style: str = "default",+ custom_program: str = "",+ ) -> LedStatusWrite:state = display_state_for_mode(mode)brightness = normalize_brightness(self.brightness)+ animation_signature = (+ animation_style,+ custom_program if animation_style == "custom" else "",+ )now = time.monotonic()- if state == self.last_state and brightness == self.last_brightness and self.last_error is None:+ if (+ state == self.last_state+ and brightness == self.last_brightness+ and animation_signature == self.last_animation_signature+ and self.last_error is None+ and self._last_program_is_current()+ ):return LedStatusWrite(state=state,target=self.last_target,@@ -218,6 +391,7 @@ class AgentLedController:if (state == self.last_stateand brightness == self.last_brightness+ and animation_signature == self.last_animation_signatureand self.last_error is not Noneand now - self.last_attempt_monotonic < self.error_retry_seconds):@@ -237,10 +411,13 @@ class AgentLedController:file_name=self.file_name,dry_run=self.dry_run,brightness=brightness,+ animation_style=animation_style,+ custom_program=custom_program,)except (DeviceWriteError, OSError) as exc:self.last_state = stateself.last_brightness = brightness+ self.last_animation_signature = animation_signatureself.last_error = str(exc)return LedStatusWrite(state=state,@@ -252,6 +429,8 @@ class AgentLedController:self.last_state = stateself.last_brightness = brightness+ self.last_animation_signature = animation_signature+ self.last_program = result.programself.last_error = Noneself.last_target = result.targetreturn resultdiff --git a/src/sidepulse/resources/animations/amber-pulse.LED b/src/sidepulse/resources/animations/amber-pulse.LEDnew file mode 100644index 0000000..a299d74--- /dev/null+++ b/src/sidepulse/resources/animations/amber-pulse.LED@@ -0,0 +1,3 @@+off+#FF3A00 1.6s pulse+repeatdiff --git a/src/sidepulse/resources/animations/cyan-complete.LED b/src/sidepulse/resources/animations/cyan-complete.LEDnew file mode 100644index 0000000..b45cffb--- /dev/null+++ b/src/sidepulse/resources/animations/cyan-complete.LED@@ -0,0 +1 @@+#00E5FF 320ms cosinediff --git a/src/sidepulse/resources/animations/cyan-roll-2.LED b/src/sidepulse/resources/animations/cyan-roll-2.LEDnew file mode 100644index 0000000..8ae9916--- /dev/null+++ b/src/sidepulse/resources/animations/cyan-roll-2.LED@@ -0,0 +1,3 @@+off 320ms cosine+0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms+repeatdiff --git a/src/sidepulse/resources/animations/cyan-roll-8.LED b/src/sidepulse/resources/animations/cyan-roll-8.LEDnew file mode 100644index 0000000..c544c9f--- /dev/null+++ b/src/sidepulse/resources/animations/cyan-roll-8.LED@@ -0,0 +1,3 @@+off 320ms cosine+0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 95ms; 2:#00E5FF 760ms pulse 190ms; 3:#00E5FF 760ms pulse 285ms; 4:#00E5FF 760ms pulse 380ms; 5:#00E5FF 760ms pulse 475ms; 6:#00E5FF 760ms pulse 570ms; 7:#00E5FF 760ms pulse 665ms+repeatdiff --git a/src/sidepulse/resources/animations/ember-attention.LED b/src/sidepulse/resources/animations/ember-attention.LEDnew file mode 100644index 0000000..2e51861--- /dev/null+++ b/src/sidepulse/resources/animations/ember-attention.LED@@ -0,0 +1,3 @@+off+#F23819 1.6s pulse+repeatdiff --git a/src/sidepulse/resources/animations/ember-complete.LED b/src/sidepulse/resources/animations/ember-complete.LEDnew file mode 100644index 0000000..10fd005--- /dev/null+++ b/src/sidepulse/resources/animations/ember-complete.LED@@ -0,0 +1 @@+#F23819 320ms cosinediff --git a/src/sidepulse/resources/animations/ember-idle-2.LED b/src/sidepulse/resources/animations/ember-idle-2.LEDnew file mode 100644index 0000000..bd094be--- /dev/null+++ b/src/sidepulse/resources/animations/ember-idle-2.LED@@ -0,0 +1,3 @@+off 2s+0:#F23819 1:#F23819 2s ease+repeatdiff --git a/src/sidepulse/resources/animations/ember-idle-8.LED b/src/sidepulse/resources/animations/ember-idle-8.LEDnew file mode 100644index 0000000..54aa5dc--- /dev/null+++ b/src/sidepulse/resources/animations/ember-idle-8.LED@@ -0,0 +1,3 @@+off 2s+3:#F23819 4:#F23819 2s ease+repeatdiff --git a/src/sidepulse/resources/animations/ember-lid-open-2.LED b/src/sidepulse/resources/animations/ember-lid-open-2.LEDnew file mode 100644index 0000000..a1c948d--- /dev/null+++ b/src/sidepulse/resources/animations/ember-lid-open-2.LED@@ -0,0 +1,4 @@+off 90ms cosine+#F23819 180ms ease+#F23819 220ms ease+off 320ms ease-outdiff --git a/src/sidepulse/resources/animations/ember-lid-open-8.LED b/src/sidepulse/resources/animations/ember-lid-open-8.LEDnew file mode 100644index 0000000..c128f06--- /dev/null+++ b/src/sidepulse/resources/animations/ember-lid-open-8.LED@@ -0,0 +1,5 @@+off 90ms cosine+3:#F23819 180ms ease; 4:#F23819 180ms ease; 2:#F23819 180ms ease 80ms; 5:#F23819 180ms ease 80ms+1:#F23819 180ms ease; 6:#F23819 180ms ease; 0:#F23819 180ms ease 80ms; 7:#F23819 180ms ease 80ms+#F23819 220ms ease+off 320ms ease-outdiff --git a/src/sidepulse/resources/animations/ember-tide-2.LED b/src/sidepulse/resources/animations/ember-tide-2.LEDnew file mode 100644index 0000000..e585978--- /dev/null+++ b/src/sidepulse/resources/animations/ember-tide-2.LED@@ -0,0 +1,3 @@+off 320ms cosine+0:#F23819 760ms pulse 0ms; 1:#F23819 760ms pulse 260ms+repeatdiff --git a/src/sidepulse/resources/animations/ember-tide-8.LED b/src/sidepulse/resources/animations/ember-tide-8.LEDnew file mode 100644index 0000000..b4659d9--- /dev/null+++ b/src/sidepulse/resources/animations/ember-tide-8.LED@@ -0,0 +1,3 @@+off 320ms cosine+0:#F23819 760ms pulse 0ms; 1:#F23819 760ms pulse 95ms; 2:#F23819 760ms pulse 190ms; 3:#F23819 760ms pulse 285ms; 4:#F23819 760ms pulse 380ms; 5:#F23819 760ms pulse 475ms; 6:#F23819 760ms pulse 570ms; 7:#F23819 760ms pulse 665ms+repeatdiff --git a/src/sidepulse/resources/animations/idle-pulse-2.LED b/src/sidepulse/resources/animations/idle-pulse-2.LEDnew file mode 100644index 0000000..6f84fac--- /dev/null+++ b/src/sidepulse/resources/animations/idle-pulse-2.LED@@ -0,0 +1,3 @@+off 2s+0:#006060 1:#006060 2s ease+repeatdiff --git a/src/sidepulse/resources/animations/idle-pulse-8.LED b/src/sidepulse/resources/animations/idle-pulse-8.LEDnew file mode 100644index 0000000..2c439fc--- /dev/null+++ b/src/sidepulse/resources/animations/idle-pulse-8.LED@@ -0,0 +1,3 @@+off 2s+3:#006060 4:#006060 2s ease+repeatdiff --git a/src/sidepulse/resources/animations/immediate-off.LED b/src/sidepulse/resources/animations/immediate-off.LEDnew file mode 100644index 0000000..cfb931e--- /dev/null+++ b/src/sidepulse/resources/animations/immediate-off.LED@@ -0,0 +1 @@+offdiff --git a/src/sidepulse/resources/animations/kitt-2.LED b/src/sidepulse/resources/animations/kitt-2.LEDnew file mode 100644index 0000000..ff8e62b--- /dev/null+++ b/src/sidepulse/resources/animations/kitt-2.LED@@ -0,0 +1,4 @@+off 80ms cosine+0:#00E5FF 320ms pulse 0ms; 1:#00E5FF 320ms pulse 240ms+0:#00E5FF 320ms pulse 0ms+repeatdiff --git a/src/sidepulse/resources/animations/kitt-8.LED b/src/sidepulse/resources/animations/kitt-8.LEDnew file mode 100644index 0000000..da44d5e--- /dev/null+++ b/src/sidepulse/resources/animations/kitt-8.LED@@ -0,0 +1,4 @@+off 80ms cosine+0:#00E5FF 320ms pulse 0ms; 1:#00E5FF 320ms pulse 85ms; 2:#00E5FF 320ms pulse 170ms; 3:#00E5FF 320ms pulse 255ms; 4:#00E5FF 320ms pulse 340ms; 5:#00E5FF 320ms pulse 425ms; 6:#00E5FF 320ms pulse 510ms; 7:#00E5FF 320ms pulse 595ms+6:#00E5FF 320ms pulse 0ms; 5:#00E5FF 320ms pulse 85ms; 4:#00E5FF 320ms pulse 170ms; 3:#00E5FF 320ms pulse 255ms; 2:#00E5FF 320ms pulse 340ms; 1:#00E5FF 320ms pulse 425ms; 0:#00E5FF 320ms pulse 510ms+repeatdiff --git a/src/sidepulse/resources/animations/kitt-red-2.LED b/src/sidepulse/resources/animations/kitt-red-2.LEDnew file mode 100644index 0000000..ff88e10--- /dev/null+++ b/src/sidepulse/resources/animations/kitt-red-2.LED@@ -0,0 +1,4 @@+off 80ms cosine+0:#FF1800 320ms pulse 0ms; 1:#FF1800 320ms pulse 240ms+0:#FF1800 320ms pulse 0ms+repeatdiff --git a/src/sidepulse/resources/animations/kitt-red-8.LED b/src/sidepulse/resources/animations/kitt-red-8.LEDnew file mode 100644index 0000000..6fea483--- /dev/null+++ b/src/sidepulse/resources/animations/kitt-red-8.LED@@ -0,0 +1,4 @@+off 80ms cosine+0:#FF1800 320ms pulse 0ms; 1:#FF1800 320ms pulse 85ms; 2:#FF1800 320ms pulse 170ms; 3:#FF1800 320ms pulse 255ms; 4:#FF1800 320ms pulse 340ms; 5:#FF1800 320ms pulse 425ms; 6:#FF1800 320ms pulse 510ms; 7:#FF1800 320ms pulse 595ms+6:#FF1800 320ms pulse 0ms; 5:#FF1800 320ms pulse 85ms; 4:#FF1800 320ms pulse 170ms; 3:#FF1800 320ms pulse 255ms; 2:#FF1800 320ms pulse 340ms; 1:#FF1800 320ms pulse 425ms; 0:#FF1800 320ms pulse 510ms+repeatdiff --git a/src/sidepulse/resources/animations/lid-closed-2.LED b/src/sidepulse/resources/animations/lid-closed-2.LEDnew file mode 100644index 0000000..00f8c89--- /dev/null+++ b/src/sidepulse/resources/animations/lid-closed-2.LED@@ -0,0 +1,2 @@+0:#000000 300ms ease; 1:#000000 300ms ease+#000000 1sdiff --git a/src/sidepulse/resources/animations/lid-closed-8.LED b/src/sidepulse/resources/animations/lid-closed-8.LEDnew file mode 100644index 0000000..2bf725b--- /dev/null+++ b/src/sidepulse/resources/animations/lid-closed-8.LED@@ -0,0 +1,5 @@+0:#000000 75ms ease; 7:#000000 75ms ease+1:#000000 75ms ease; 6:#000000 75ms ease+2:#000000 75ms ease; 5:#000000 75ms ease+3:#000000 75ms ease; 4:#000000 75ms ease+#000000 1sdiff --git a/src/sidepulse/resources/animations/lid-open-2.LED b/src/sidepulse/resources/animations/lid-open-2.LEDnew file mode 100644index 0000000..2fc650d--- /dev/null+++ b/src/sidepulse/resources/animations/lid-open-2.LED@@ -0,0 +1,4 @@+off 90ms cosine+#00E5FF 180ms ease+#00FF66 220ms ease+off 320ms ease-outdiff --git a/src/sidepulse/resources/animations/lid-open-8.LED b/src/sidepulse/resources/animations/lid-open-8.LEDnew file mode 100644index 0000000..3e72a3d--- /dev/null+++ b/src/sidepulse/resources/animations/lid-open-8.LED@@ -0,0 +1,5 @@+off 90ms cosine+3:#00E5FF 180ms ease; 4:#00E5FF 180ms ease; 2:#00E5FF 180ms ease 80ms; 5:#00E5FF 180ms ease 80ms+1:#00FFB0 180ms ease; 6:#00FFB0 180ms ease; 0:#00FF66 180ms ease 80ms; 7:#00FF66 180ms ease 80ms+#00FF66 220ms ease+off 320ms ease-outdiff --git a/src/sidepulse/resources/animations/night-rider-2.LED b/src/sidepulse/resources/animations/night-rider-2.LEDnew file mode 100644index 0000000..fb06d89--- /dev/null+++ b/src/sidepulse/resources/animations/night-rider-2.LED@@ -0,0 +1,3 @@+off+0:#FF1200 360ms pulse;1:#FF1200 360ms pulse 90ms+repeatdiff --git a/src/sidepulse/resources/animations/night-rider-8.LED b/src/sidepulse/resources/animations/night-rider-8.LEDnew file mode 100644index 0000000..a75f6d6--- /dev/null+++ b/src/sidepulse/resources/animations/night-rider-8.LED@@ -0,0 +1,4 @@+off+0:#FF1200 360ms pulse;1:#FF1200 360ms pulse 90ms;2:#FF1200 360ms pulse 180ms;3:#FF1200 360ms pulse 270ms;4:#FF1200 360ms pulse 360ms;5:#FF1200 360ms pulse 450ms;6:#FF1200 360ms pulse 540ms;7:#FF1200 360ms pulse 630ms+6:#FF1200 360ms pulse;5:#FF1200 360ms pulse 90ms;4:#FF1200 360ms pulse 180ms;3:#FF1200 360ms pulse 270ms;2:#FF1200 360ms pulse 360ms;1:#FF1200 360ms pulse 450ms+repeatdiff --git a/src/sidepulse/resources/animations/off.LED b/src/sidepulse/resources/animations/off.LEDnew file mode 100644index 0000000..19c15db--- /dev/null+++ b/src/sidepulse/resources/animations/off.LED@@ -0,0 +1 @@+off 1sdiff --git a/src/sidepulse/resources/animations/purple-attention.LED b/src/sidepulse/resources/animations/purple-attention.LEDnew file mode 100644index 0000000..8f615ec--- /dev/null+++ b/src/sidepulse/resources/animations/purple-attention.LED@@ -0,0 +1,3 @@+off+#FF00FF 1.6s pulse+repeatdiff --git a/src/sidepulse/resources/animations/purple-complete.LED b/src/sidepulse/resources/animations/purple-complete.LEDnew file mode 100644index 0000000..b1433c6--- /dev/null+++ b/src/sidepulse/resources/animations/purple-complete.LED@@ -0,0 +1 @@+#FF00FF 320ms cosinediff --git a/src/sidepulse/resources/animations/purple-idle-2.LED b/src/sidepulse/resources/animations/purple-idle-2.LEDnew file mode 100644index 0000000..ca6f643--- /dev/null+++ b/src/sidepulse/resources/animations/purple-idle-2.LED@@ -0,0 +1,3 @@+off 2s+0:#FF00FF 1:#FF00FF 2s ease+repeatdiff --git a/src/sidepulse/resources/animations/purple-idle-8.LED b/src/sidepulse/resources/animations/purple-idle-8.LEDnew file mode 100644index 0000000..bd4166a--- /dev/null+++ b/src/sidepulse/resources/animations/purple-idle-8.LED@@ -0,0 +1,3 @@+off 2s+2:#9F00FF 3:#FF00FF 4:#FF00FF 5:#9F009F 2s ease+repeatdiff --git a/src/sidepulse/resources/animations/purple-lid-open-2.LED b/src/sidepulse/resources/animations/purple-lid-open-2.LEDnew file mode 100644index 0000000..ca0fc38--- /dev/null+++ b/src/sidepulse/resources/animations/purple-lid-open-2.LED@@ -0,0 +1,4 @@+off 90ms cosine+#FF00FF 180ms ease+#FF00FF 220ms ease+off 320ms ease-outdiff --git a/src/sidepulse/resources/animations/purple-lid-open-8.LED b/src/sidepulse/resources/animations/purple-lid-open-8.LEDnew file mode 100644index 0000000..8432d1d--- /dev/null+++ b/src/sidepulse/resources/animations/purple-lid-open-8.LED@@ -0,0 +1,5 @@+off 90ms cosine+3:#FF00FF 180ms ease; 4:#FF00FF 180ms ease; 2:#FF00FF 180ms ease 80ms; 5:#FF00FF 180ms ease 80ms+1:#FF00FF 180ms ease; 6:#FF00FF 180ms ease; 0:#FF00FF 180ms ease 80ms; 7:#FF00FF 180ms ease 80ms+#FF00FF 220ms ease+off 320ms ease-outdiff --git a/src/sidepulse/resources/animations/purple-tide-2.LED b/src/sidepulse/resources/animations/purple-tide-2.LEDnew file mode 100644index 0000000..4844322--- /dev/null+++ b/src/sidepulse/resources/animations/purple-tide-2.LED@@ -0,0 +1,3 @@+off 320ms cosine+0:#FF00FF 760ms pulse 0ms; 1:#FF00FF 760ms pulse 260ms+repeatdiff --git a/src/sidepulse/resources/animations/purple-tide-8.LED b/src/sidepulse/resources/animations/purple-tide-8.LEDnew file mode 100644index 0000000..a954480--- /dev/null+++ b/src/sidepulse/resources/animations/purple-tide-8.LED@@ -0,0 +1,3 @@+off 320ms cosine+0:#FF00FF 760ms pulse 0ms; 1:#FF00FF 760ms pulse 95ms; 2:#FF00FF 760ms pulse 190ms; 3:#FF00FF 760ms pulse 285ms; 4:#FF00FF 760ms pulse 380ms; 5:#FF00FF 760ms pulse 475ms; 6:#FF00FF 760ms pulse 570ms; 7:#FF00FF 760ms pulse 665ms+repeatdiff --git a/src/sidepulse/resources/animations/solid-green.LED b/src/sidepulse/resources/animations/solid-green.LEDnew file mode 100644index 0000000..58ede71--- /dev/null+++ b/src/sidepulse/resources/animations/solid-green.LED@@ -0,0 +1 @@+#00FF66 320ms cosinediff --git a/src/sidepulse/settings.py b/src/sidepulse/settings.pyindex 52fe71c..426e89f 100644--- a/src/sidepulse/settings.py+++ b/src/sidepulse/settings.py@@ -8,6 +8,7 @@ from pathlib import Pathfrom typing import Anyfrom .battery import DEFAULT_POWER_CHANGE_PREVIEW_SECONDS+from .models import AgentModefrom .session_actions import SESSION_OPEN_CHOICES, SESSION_OPEN_TERMINAL@@ -33,6 +34,105 @@ LED_DISPLAY_AGENT = "agent"LED_DISPLAY_BATTERY = "battery"LED_DISPLAY_CUSTOM = "custom"LED_DISPLAY_CHOICES = (LED_DISPLAY_AGENT, LED_DISPLAY_BATTERY, LED_DISPLAY_CUSTOM)+AGENT_ANIMATION_DEFAULT = "default"+AGENT_ANIMATION_SLOW_OFF = "off"+AGENT_ANIMATION_IMMEDIATE_OFF = "immediate-off"+AGENT_ANIMATION_IDLE_PULSE = "idle-pulse"+AGENT_ANIMATION_CYAN_ROLL = "cyan-roll"+AGENT_ANIMATION_CYAN_COMPLETE = "cyan-complete"+AGENT_ANIMATION_AMBER_PULSE = "amber-pulse"+AGENT_ANIMATION_SOLID_GREEN = "solid-green"+AGENT_ANIMATION_KITT = "kitt"+AGENT_ANIMATION_KITT_RED = "kitt-red"+AGENT_ANIMATION_EMBER_IDLE = "ember-idle"+AGENT_ANIMATION_EMBER_TIDE = "ember-tide"+AGENT_ANIMATION_EMBER_ATTENTION = "ember-attention"+AGENT_ANIMATION_EMBER_COMPLETE = "ember-complete"+AGENT_ANIMATION_EMBER_LID_OPEN = "ember-lid-open"+AGENT_ANIMATION_PURPLE_IDLE = "purple-idle"+AGENT_ANIMATION_PURPLE_TIDE = "purple-tide"+AGENT_ANIMATION_PURPLE_ATTENTION = "purple-attention"+AGENT_ANIMATION_PURPLE_COMPLETE = "purple-complete"+AGENT_ANIMATION_PURPLE_LID_OPEN = "purple-lid-open"+AGENT_ANIMATION_NIGHT_RIDER = "night-rider"+AGENT_ANIMATION_LID_OPEN = "lid-open"+AGENT_ANIMATION_LID_CLOSED = "lid-closed"+AGENT_ANIMATION_CUSTOM = "custom"+AGENT_ANIMATION_ADD_CUSTOM = "add-custom"+AGENT_ANIMATION_CUSTOM_PREFIX = "custom:"+AGENT_ANIMATION_PROFILE_PREFIX = "profile:"+AGENT_ANIMATION_PROFILE_FORMAT = "sidepulse-animation-profile"+AGENT_ANIMATION_PROFILE_VERSION = 1+AGENT_ANIMATION_PROFILE_CYAN = "profile:cyan"+AGENT_ANIMATION_PROFILE_EMBER = "profile:ember"+AGENT_ANIMATION_PROFILE_PURPLE = "profile:purple"+AGENT_ANIMATION_BUILT_IN_PROFILE_IDS = frozenset(+ {+ AGENT_ANIMATION_PROFILE_CYAN,+ AGENT_ANIMATION_PROFILE_EMBER,+ AGENT_ANIMATION_PROFILE_PURPLE,+ }+)+AGENT_ANIMATION_BUILT_INS = (+ AGENT_ANIMATION_SLOW_OFF,+ AGENT_ANIMATION_IMMEDIATE_OFF,+ AGENT_ANIMATION_IDLE_PULSE,+ AGENT_ANIMATION_CYAN_ROLL,+ AGENT_ANIMATION_CYAN_COMPLETE,+ AGENT_ANIMATION_AMBER_PULSE,+ AGENT_ANIMATION_SOLID_GREEN,+ AGENT_ANIMATION_KITT,+ AGENT_ANIMATION_KITT_RED,+ AGENT_ANIMATION_EMBER_IDLE,+ AGENT_ANIMATION_EMBER_TIDE,+ AGENT_ANIMATION_EMBER_ATTENTION,+ AGENT_ANIMATION_EMBER_COMPLETE,+ AGENT_ANIMATION_EMBER_LID_OPEN,+ AGENT_ANIMATION_PURPLE_IDLE,+ AGENT_ANIMATION_PURPLE_TIDE,+ AGENT_ANIMATION_PURPLE_ATTENTION,+ AGENT_ANIMATION_PURPLE_COMPLETE,+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ AGENT_ANIMATION_NIGHT_RIDER,+ AGENT_ANIMATION_LID_OPEN,+ AGENT_ANIMATION_LID_CLOSED,+)+AGENT_ANIMATION_MODES = tuple(mode.value for mode in AgentMode)+AGENT_ANIMATION_WORKING_MODES = (+ AgentMode.WORKING.value,+ AgentMode.TOOL_RUNNING.value,+ AgentMode.LONG_TASK_PROGRESS.value,+)+ANIMATION_STATE_LID_OPEN = "lid_open"+ANIMATION_STATE_LID_CLOSED = "lid_closed"+ANIMATION_STATES = AGENT_ANIMATION_MODES + (+ ANIMATION_STATE_LID_OPEN,+ ANIMATION_STATE_LID_CLOSED,+)+++def default_agent_animation_id(mode: AgentMode | str) -> str:+ key = mode.value if isinstance(mode, AgentMode) else str(mode)+ if key in {+ AgentMode.WORKING.value,+ AgentMode.TOOL_RUNNING.value,+ AgentMode.LONG_TASK_PROGRESS.value,+ }:+ return AGENT_ANIMATION_CYAN_ROLL+ if key in {+ AgentMode.WAITING_FOR_INPUT.value,+ AgentMode.BLOCKED_ERROR.value,+ }:+ return AGENT_ANIMATION_AMBER_PULSE+ if key == AgentMode.COMPLETED.value:+ return AGENT_ANIMATION_CYAN_COMPLETE+ if key == ANIMATION_STATE_LID_OPEN:+ return AGENT_ANIMATION_LID_OPEN+ if key == ANIMATION_STATE_LID_CLOSED:+ return AGENT_ANIMATION_LID_CLOSED+ if key in AGENT_ANIMATION_MODES:+ return AGENT_ANIMATION_IDLE_PULSE+ raise ValueError(f"Unknown animation state: {key}")SLEEP_PREVENTION_NEVER = "never"SLEEP_PREVENTION_AGENTS = "agents"SLEEP_PREVENTION_ALWAYS = "always"@@ -54,16 +154,11 @@ LID_ANIMATION_OPEN = "open"LID_ANIMATION_CHOICES = (LID_ANIMATION_CLOSED, LID_ANIMATION_OPEN)DEFAULT_LID_CLOSED_ANIMATION_PROGRAM = "\n".join([- "off 90ms cosine",- (- "0:#FF7A00 180ms ease; 7:#FF7A00 180ms ease; "- "1:#FF7A00 180ms ease 80ms; 6:#FF7A00 180ms ease 80ms"- ),- (- "2:#FF4A00 180ms ease; 5:#FF4A00 180ms ease; "- "3:#FF3000 180ms ease 80ms; 4:#FF3000 180ms ease 80ms"- ),- "off 360ms ease-out",+ "0:#000000 75ms ease; 7:#000000 75ms ease",+ "1:#000000 75ms ease; 6:#000000 75ms ease",+ "2:#000000 75ms ease; 5:#000000 75ms ease",+ "3:#000000 75ms ease; 4:#000000 75ms ease",+ "#000000 1s",])DEFAULT_LID_OPEN_ANIMATION_PROGRAM = "\n".join(@@ -81,7 +176,7 @@ DEFAULT_LID_OPEN_ANIMATION_PROGRAM = "\n".join("off 320ms ease-out",])-DEFAULT_LID_CLOSED_ANIMATION_SECONDS = 0.9+DEFAULT_LID_CLOSED_ANIMATION_SECONDS = 1.3DEFAULT_LID_OPEN_ANIMATION_SECONDS = 1.0DEFAULT_RECENT_SESSION_RETENTION_SECONDS = 48 * 60 * 60DEFAULT_IDLE_TIMEOUT_SECONDS = 60 * 60@@ -113,6 +208,79 @@ class LedAnimationSetting:}+@dataclass(frozen=True)+class AgentAnimationSetting:+ style: str = AGENT_ANIMATION_DEFAULT+ custom_program: str = ""++ def to_dict(self) -> dict[str, str]:+ return {+ "style": self.style,+ "custom_program": self.custom_program,+ }+++@dataclass(frozen=True)+class CustomAgentAnimation:+ name: str+ program: str+ file_name: str++ def to_dict(self) -> dict[str, str]:+ return {+ "name": self.name,+ "file": self.file_name,+ }+++@dataclass(frozen=True)+class AgentAnimationProfile:+ name: str+ animations: dict[str, str]++ def to_dict(self) -> dict[str, object]:+ return {+ "name": self.name,+ "animations": dict(sorted(self.animations.items())),+ }+++def builtin_agent_animation_profiles() -> dict[str, AgentAnimationProfile]:+ cyan = {+ mode: default_agent_animation_id(mode)+ for mode in ANIMATION_STATES+ }+ ember = {+ AgentMode.IDLE_READY.value: AGENT_ANIMATION_EMBER_IDLE,+ AgentMode.WORKING.value: AGENT_ANIMATION_EMBER_TIDE,+ AgentMode.TOOL_RUNNING.value: AGENT_ANIMATION_EMBER_TIDE,+ AgentMode.WAITING_FOR_INPUT.value: AGENT_ANIMATION_EMBER_ATTENTION,+ AgentMode.LONG_TASK_PROGRESS.value: AGENT_ANIMATION_EMBER_TIDE,+ AgentMode.BLOCKED_ERROR.value: AGENT_ANIMATION_EMBER_ATTENTION,+ AgentMode.COMPLETED.value: AGENT_ANIMATION_EMBER_COMPLETE,+ AgentMode.UNKNOWN.value: AGENT_ANIMATION_EMBER_IDLE,+ ANIMATION_STATE_LID_OPEN: AGENT_ANIMATION_EMBER_LID_OPEN,+ ANIMATION_STATE_LID_CLOSED: AGENT_ANIMATION_LID_CLOSED,+ }+ purple = {+ AgentMode.IDLE_READY.value: AGENT_ANIMATION_PURPLE_IDLE,+ AgentMode.WORKING.value: AGENT_ANIMATION_PURPLE_TIDE,+ AgentMode.TOOL_RUNNING.value: AGENT_ANIMATION_PURPLE_TIDE,+ AgentMode.WAITING_FOR_INPUT.value: AGENT_ANIMATION_PURPLE_ATTENTION,+ AgentMode.LONG_TASK_PROGRESS.value: AGENT_ANIMATION_PURPLE_TIDE,+ AgentMode.BLOCKED_ERROR.value: AGENT_ANIMATION_PURPLE_ATTENTION,+ AgentMode.COMPLETED.value: AGENT_ANIMATION_PURPLE_COMPLETE,+ AgentMode.UNKNOWN.value: AGENT_ANIMATION_PURPLE_IDLE,+ ANIMATION_STATE_LID_OPEN: AGENT_ANIMATION_PURPLE_LID_OPEN,+ ANIMATION_STATE_LID_CLOSED: AGENT_ANIMATION_LID_CLOSED,+ }+ return {+ AGENT_ANIMATION_PROFILE_CYAN: AgentAnimationProfile("Cyan", cyan),+ AGENT_ANIMATION_PROFILE_EMBER: AgentAnimationProfile("Ember", ember),+ AGENT_ANIMATION_PROFILE_PURPLE: AgentAnimationProfile("Purple", purple),+ }++@dataclass(frozen=True)class DeviceDisplaySetting:device_id: str@@ -148,6 +316,11 @@ class AgentMonitorSettings:)battery_full_charge_watts: float | None = Nonebattery_show_on_power_change: bool = True+ agent_animations: dict[str, AgentAnimationSetting] = field(default_factory=dict)+ custom_agent_animations: dict[str, CustomAgentAnimation] = field(default_factory=dict)+ agent_animation_profiles: dict[str, AgentAnimationProfile] = field(+ default_factory=builtin_agent_animation_profiles+ )battery_power_change_preview_seconds: float = DEFAULT_POWER_CHANGE_PREVIEW_SECONDSsession_open_preferences: dict[str, str] = field(default_factory=dict)grok_session_open_action: str = SESSION_OPEN_TERMINAL@@ -424,6 +597,173 @@ class AgentMonitorSettings:return replace(self, lid_open_animation=animation)raise ValueError(f"Unknown lid animation: {kind}")+ def agent_animation(self, mode: AgentMode | str) -> AgentAnimationSetting:+ key = mode.value if isinstance(mode, AgentMode) else str(mode)+ if key not in ANIMATION_STATES:+ raise ValueError(f"Unknown animation state: {key}")+ selected = self.agent_animation_id(key)+ custom = self.custom_agent_animations.get(selected)+ if custom is not None:+ return AgentAnimationSetting(+ style=AGENT_ANIMATION_CUSTOM,+ custom_program=custom.program,+ )+ return AgentAnimationSetting(style=selected)++ def agent_animation_id(self, mode: AgentMode | str) -> str:+ key = mode.value if isinstance(mode, AgentMode) else str(mode)+ if key not in ANIMATION_STATES:+ raise ValueError(f"Unknown animation state: {key}")+ selected = self.agent_animations.get(key, AgentAnimationSetting()).style+ if selected == AGENT_ANIMATION_DEFAULT:+ return default_agent_animation_id(key)+ if selected in AGENT_ANIMATION_BUILT_INS:+ return selected+ if selected in self.custom_agent_animations:+ return selected+ return default_agent_animation_id(key)++ def agent_animation_choices(self) -> tuple[str, ...]:+ return AGENT_ANIMATION_BUILT_INS + tuple(+ sorted(+ self.custom_agent_animations,+ key=lambda animation_id: (+ self.custom_agent_animations[animation_id].name.casefold(),+ animation_id,+ ),+ )+ )++ def with_agent_animation(+ self,+ mode: AgentMode | str,+ style: str,+ *,+ custom_program: str | None = None,+ ) -> "AgentMonitorSettings":+ key = mode.value if isinstance(mode, AgentMode) else str(mode)+ if key not in ANIMATION_STATES:+ raise ValueError(f"Unknown animation state: {key}")+ custom_animations = dict(self.custom_agent_animations)+ selection = str(style)+ if selection == AGENT_ANIMATION_DEFAULT:+ selection = default_agent_animation_id(key)+ if selection == AGENT_ANIMATION_CUSTOM and custom_program is not None:+ animation_id = custom_agent_animation_id(+ f"Custom {key.replace('_', ' ').title()}",+ custom_animations,+ )+ custom_animations[animation_id] = CustomAgentAnimation(+ name=f"Custom {key.replace('_', ' ').title()}",+ program=str(custom_program),+ file_name=custom_agent_animation_file_name(animation_id),+ )+ selection = animation_id+ if selection not in AGENT_ANIMATION_BUILT_INS and selection not in custom_animations:+ raise ValueError(f"Unknown animation {selection!r}")+ animations = dict(self.agent_animations)+ target_modes = (+ AGENT_ANIMATION_WORKING_MODES+ if key in AGENT_ANIMATION_WORKING_MODES+ else (key,)+ )+ for target_mode in target_modes:+ animations[target_mode] = AgentAnimationSetting(style=selection)+ return replace(+ self,+ agent_animations=animations,+ custom_agent_animations=custom_animations,+ )++ def with_custom_agent_animation(+ self,+ animation_id: str,+ *,+ name: str,+ program: str,+ ) -> "AgentMonitorSettings":+ if not animation_id.startswith(AGENT_ANIMATION_CUSTOM_PREFIX):+ raise ValueError(f"Invalid custom animation id: {animation_id}")+ clean_name = str(name).strip()+ if not clean_name:+ raise ValueError("Custom animation name is required.")+ animations = dict(self.custom_agent_animations)+ animations[animation_id] = CustomAgentAnimation(+ clean_name,+ str(program),+ custom_agent_animation_file_name(animation_id),+ )+ return replace(self, custom_agent_animations=animations)++ def with_agent_animation_profile(+ self,+ profile_id: str,+ *,+ name: str,+ ) -> "AgentMonitorSettings":+ if not profile_id.startswith(AGENT_ANIMATION_PROFILE_PREFIX):+ raise ValueError(f"Invalid animation profile id: {profile_id}")+ if profile_id in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS:+ raise ValueError("Built-in animation profiles cannot be replaced.")+ clean_name = str(name).strip()+ if not clean_name:+ raise ValueError("Profile name is required.")+ profiles = dict(self.agent_animation_profiles)+ profiles[profile_id] = AgentAnimationProfile(+ name=clean_name,+ animations={+ mode: self.agent_animation_id(mode)+ for mode in ANIMATION_STATES+ },+ )+ return replace(self, agent_animation_profiles=profiles)++ def with_applied_agent_animation_profile(+ self,+ profile_id: str,+ ) -> "AgentMonitorSettings":+ profile = self.agent_animation_profiles.get(profile_id)+ if profile is None:+ raise ValueError(f"Unknown animation profile: {profile_id}")+ selections = {+ mode: AgentAnimationSetting(+ style=(+ profile.animations.get(mode, default_agent_animation_id(mode))+ if profile.animations.get(mode, default_agent_animation_id(mode))+ in self.agent_animation_choices()+ else default_agent_animation_id(mode)+ )+ )+ for mode in ANIMATION_STATES+ }+ working_selection = selections[AgentMode.WORKING.value]+ for mode in AGENT_ANIMATION_WORKING_MODES:+ selections[mode] = working_selection+ return replace(self, agent_animations=selections)++ def without_agent_animation_profile(+ self,+ profile_id: str,+ ) -> "AgentMonitorSettings":+ if profile_id in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS:+ raise ValueError("Built-in animation profiles cannot be deleted.")+ profiles = dict(self.agent_animation_profiles)+ profiles.pop(profile_id, None)+ return replace(self, agent_animation_profiles=profiles)++ def matching_agent_animation_profile_id(self) -> str | None:+ current = {+ mode: self.agent_animation_id(mode)+ for mode in ANIMATION_STATES+ }+ for profile_id, profile in sorted(self.agent_animation_profiles.items()):+ if {+ mode: profile.animations.get(mode, default_agent_animation_id(mode))+ for mode in ANIMATION_STATES+ } == current:+ return profile_id+ return None+def with_setup_screen_completed(self, completed: bool = True) -> "AgentMonitorSettings":return replace(self, setup_screen_completed=bool(completed))@@ -491,6 +831,23 @@ class AgentMonitorSettings:"history": {"timeframe_seconds": self.history_timeframe_seconds,},+ "agent_animations": {+ mode: setting.to_dict()+ for mode, setting in sorted(self.agent_animations.items())+ },+ "custom_agent_animations": {+ animation_id: animation.to_dict()+ for animation_id, animation in sorted(+ self.custom_agent_animations.items()+ )+ },+ "agent_animation_profiles": {+ profile_id: profile.to_dict()+ for profile_id, profile in sorted(+ self.agent_animation_profiles.items()+ )+ if profile_id not in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS+ },"setup_screen_completed": self.setup_screen_completed,}@@ -509,6 +866,10 @@ def default_settings_path(home: Path | None = None) -> Path:return default_config_dir(home) / "settings.json"+def default_animation_dir(home: Path | None = None) -> Path:+ return default_config_dir(home) / "animations"++def load_settings(path: Path | None = None) -> AgentMonitorSettings:target = (path or default_settings_path()).expanduser()if not target.exists():@@ -559,6 +920,29 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:SESSION_OPEN_TERMINAL,)session_open_preferences.pop("grok", None)+ custom_agent_animations = _custom_agent_animation_settings(+ data.get("custom_agent_animations"),+ animation_dir=target.parent / "animations",+ )+ agent_animations, custom_agent_animations = _agent_animation_settings(+ data.get("agent_animations"),+ custom_agent_animations,+ )+ saved_agent_animation_profiles = _agent_animation_profile_settings(+ data.get("agent_animation_profiles"),+ custom_agent_animations,+ )+ agent_animation_profiles = builtin_agent_animation_profiles()+ agent_animation_profiles.update(+ {+ profile_id: profile+ for profile_id, profile in saved_agent_animation_profiles.items()+ if (+ profile_id not in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS+ and profile_id != "profile:default"+ )+ }+ )return AgentMonitorSettings(codex_transcripts_enabled=_bool_setting(transcript.get("codex"), False),claude_transcripts_enabled=_bool_setting(transcript.get("claude"), False),@@ -591,6 +975,9 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:battery.get("power_change_preview_seconds"),DEFAULT_POWER_CHANGE_PREVIEW_SECONDS,),+ agent_animations=agent_animations,+ custom_agent_animations=custom_agent_animations,+ agent_animation_profiles=agent_animation_profiles,session_open_preferences=session_open_preferences,grok_session_open_action=grok_session_open_action,session_terminal_app=normalize_terminal_app(terminal.get("app")),@@ -631,6 +1018,19 @@ def save_settings() -> Path:target = (path or default_settings_path()).expanduser()target.parent.mkdir(parents=True, exist_ok=True)+ if settings.custom_agent_animations:+ animation_dir = target.parent / "animations"+ animation_dir.mkdir(parents=True, exist_ok=True)+ for animation_id, animation in settings.custom_agent_animations.items():+ file_name = animation.file_name or custom_agent_animation_file_name(+ animation_id+ )+ animation_path = animation_dir / file_name+ if not animation_path.exists():+ animation_path.write_text(+ normalize_animation_file_program(animation.program) + "\n",+ encoding="utf-8",+ )target.write_text(json.dumps(settings.to_dict(), indent=2, sort_keys=True) + "\n")return target@@ -647,6 +1047,281 @@ def _led_display_setting(value: object, default: str) -> str:return default+def agent_animation_style_choices(_mode: AgentMode | str | None = None) -> tuple[str, ...]:+ """Return the shared built-in catalog used by every agent state."""+ return AGENT_ANIMATION_BUILT_INS+++def custom_agent_animation_id(+ name: str,+ existing: object = (),+) -> str:+ keys = existing.keys() if isinstance(existing, dict) else existing+ used = {str(item) for item in keys}+ slug = re.sub(r"[^a-z0-9]+", "-", str(name).strip().casefold()).strip("-")+ base = f"{AGENT_ANIMATION_CUSTOM_PREFIX}{slug or 'animation'}"+ candidate = base+ suffix = 2+ while candidate in used:+ candidate = f"{base}-{suffix}"+ suffix += 1+ return candidate+++def custom_agent_animation_file_name(animation_id: str) -> str:+ stem = str(animation_id).removeprefix(AGENT_ANIMATION_CUSTOM_PREFIX)+ safe = re.sub(r"[^a-z0-9_-]+", "-", stem.casefold()).strip("-")+ return f"{safe or 'animation'}.LED"+++def normalize_animation_file_program(program: str) -> str:+ return str(program).replace("\r\n", "\n").replace("\r", "\n").strip()+++def agent_animation_profile_id(+ name: str,+ existing: object = (),+) -> str:+ keys = existing.keys() if isinstance(existing, dict) else existing+ used = {str(item) for item in keys}+ slug = re.sub(r"[^a-z0-9]+", "-", str(name).strip().casefold()).strip("-")+ base = f"{AGENT_ANIMATION_PROFILE_PREFIX}{slug or 'profile'}"+ candidate = base+ suffix = 2+ while candidate in used:+ candidate = f"{base}-{suffix}"+ suffix += 1+ return candidate+++def agent_animation_profile_document(+ settings: AgentMonitorSettings,+ profile_id: str | None = None,+) -> dict[str, object]:+ if profile_id is None:+ name = "Current"+ selections = {+ mode: settings.agent_animation_id(mode)+ for mode in ANIMATION_STATES+ }+ else:+ profile = settings.agent_animation_profiles.get(profile_id)+ if profile is None:+ raise ValueError(f"Unknown animation profile: {profile_id}")+ name = profile.name+ selections = {+ mode: profile.animations.get(mode, default_agent_animation_id(mode))+ for mode in ANIMATION_STATES+ }++ referenced_custom_ids = {+ animation_id+ for animation_id in selections.values()+ if animation_id.startswith(AGENT_ANIMATION_CUSTOM_PREFIX)+ }+ custom = {}+ for animation_id in sorted(referenced_custom_ids):+ animation = settings.custom_agent_animations.get(animation_id)+ if animation is None:+ raise ValueError(+ f"Profile references missing custom animation: {animation_id}"+ )+ custom[animation_id] = {+ "name": animation.name,+ "program": animation.program,+ }+ return {+ "format": AGENT_ANIMATION_PROFILE_FORMAT,+ "version": AGENT_ANIMATION_PROFILE_VERSION,+ "name": name,+ "animations": selections,+ "custom_animations": custom,+ }+++def with_imported_agent_animation_profile(+ settings: AgentMonitorSettings,+ document: object,+) -> tuple[AgentMonitorSettings, str]:+ if not isinstance(document, dict):+ raise ValueError("Animation profile JSON must contain an object.")+ if document.get("format") != AGENT_ANIMATION_PROFILE_FORMAT:+ raise ValueError("This is not a SidePulse animation profile.")+ if document.get("version") != AGENT_ANIMATION_PROFILE_VERSION:+ raise ValueError("Unsupported animation profile version.")+ name = document.get("name")+ animations = document.get("animations")+ raw_custom = document.get("custom_animations", {})+ if not isinstance(name, str) or not name.strip():+ raise ValueError("Animation profile name is required.")+ if not isinstance(animations, dict):+ raise ValueError("Animation profile selections are missing.")+ animation_keys = set(animations)+ if (+ not set(AGENT_ANIMATION_MODES).issubset(animation_keys)+ or not animation_keys.issubset(ANIMATION_STATES)+ ):+ raise ValueError("Animation profile must include every agent state.")+ if not isinstance(raw_custom, dict):+ raise ValueError("Custom animations must be a JSON object.")++ imported_custom = _custom_agent_animation_settings(raw_custom)+ if set(imported_custom) != set(raw_custom):+ raise ValueError("A custom animation entry is invalid.")+ updated_custom = dict(settings.custom_agent_animations)+ remapped_ids: dict[str, str] = {}+ for incoming_id, animation in imported_custom.items():+ existing = updated_custom.get(incoming_id)+ if existing is None or existing == animation:+ target_id = incoming_id+ else:+ target_id = custom_agent_animation_id(animation.name, updated_custom)+ updated_custom[target_id] = CustomAgentAnimation(+ animation.name,+ animation.program,+ custom_agent_animation_file_name(target_id),+ )+ remapped_ids[incoming_id] = target_id++ choices = set(AGENT_ANIMATION_BUILT_INS) | set(imported_custom)+ selections: dict[str, str] = {}+ for mode in ANIMATION_STATES:+ animation_id = animations.get(mode, default_agent_animation_id(mode))+ if not isinstance(animation_id, str) or animation_id not in choices:+ raise ValueError(f"Unknown animation for {mode}: {animation_id}")+ selections[mode] = remapped_ids.get(animation_id, animation_id)+ working_selection = selections[AgentMode.WORKING.value]+ for mode in AGENT_ANIMATION_WORKING_MODES:+ selections[mode] = working_selection++ profile_id = agent_animation_profile_id(+ name,+ settings.agent_animation_profiles,+ )+ profiles = dict(settings.agent_animation_profiles)+ profiles[profile_id] = AgentAnimationProfile(name.strip(), selections)+ updated = replace(+ settings,+ custom_agent_animations=updated_custom,+ agent_animation_profiles=profiles,+ )+ return updated.with_applied_agent_animation_profile(profile_id), profile_id+++def _custom_agent_animation_settings(+ value: object,+ *,+ animation_dir: Path | None = None,+) -> dict[str, CustomAgentAnimation]:+ if not isinstance(value, dict):+ return {}+ result: dict[str, CustomAgentAnimation] = {}+ for animation_id, raw in value.items():+ if (+ not isinstance(animation_id, str)+ or not animation_id.startswith(AGENT_ANIMATION_CUSTOM_PREFIX)+ or not isinstance(raw, dict)+ ):+ continue+ name = raw.get("name")+ file_name = raw.get("file")+ if (+ not isinstance(file_name, str)+ or Path(file_name).name != file_name+ or Path(file_name).suffix.upper() != ".LED"+ ):+ file_name = custom_agent_animation_file_name(animation_id)+ program = None+ if animation_dir is not None:+ try:+ program = (animation_dir / file_name).read_text(encoding="utf-8")+ except OSError:+ pass+ if program is None:+ program = raw.get("program")+ if isinstance(name, str) and name.strip() and isinstance(program, str):+ result[animation_id] = CustomAgentAnimation(+ name.strip(),+ normalize_animation_file_program(program),+ file_name,+ )+ return result+++def _agent_animation_settings(+ value: object,+ custom_animations: dict[str, CustomAgentAnimation],+) -> tuple[dict[str, AgentAnimationSetting], dict[str, CustomAgentAnimation]]:+ if not isinstance(value, dict):+ return {}, custom_animations+ result: dict[str, AgentAnimationSetting] = {}+ custom = dict(custom_animations)+ for mode, raw in value.items():+ if mode not in ANIMATION_STATES or not isinstance(raw, dict):+ continue+ selection = raw.get("style")+ if selection == AGENT_ANIMATION_CUSTOM:+ program = raw.get("custom_program")+ if isinstance(program, str) and program.strip():+ name = f"Custom {mode.replace('_', ' ').title()}"+ selection = custom_agent_animation_id(name, custom)+ custom[selection] = CustomAgentAnimation(+ name,+ program,+ custom_agent_animation_file_name(selection),+ )+ if selection == AGENT_ANIMATION_DEFAULT:+ selection = default_agent_animation_id(mode)+ if selection not in AGENT_ANIMATION_BUILT_INS and selection not in custom:+ selection = default_agent_animation_id(mode)+ result[mode] = AgentAnimationSetting(style=str(selection))+ working_selection = next(+ (result[mode] for mode in AGENT_ANIMATION_WORKING_MODES if mode in result),+ None,+ )+ if working_selection is not None:+ for mode in AGENT_ANIMATION_WORKING_MODES:+ result[mode] = working_selection+ return result, custom+++def _agent_animation_profile_settings(+ value: object,+ custom_animations: dict[str, CustomAgentAnimation],+) -> dict[str, AgentAnimationProfile]:+ if not isinstance(value, dict):+ return {}+ choices = set(AGENT_ANIMATION_BUILT_INS) | set(custom_animations)+ result: dict[str, AgentAnimationProfile] = {}+ for profile_id, raw in value.items():+ if (+ not isinstance(profile_id, str)+ or not profile_id.startswith(AGENT_ANIMATION_PROFILE_PREFIX)+ or not isinstance(raw, dict)+ ):+ continue+ name = raw.get("name")+ animations = raw.get("animations")+ if not isinstance(name, str) or not name.strip() or not isinstance(animations, dict):+ continue+ selections = {+ mode: (+ str(animations.get(mode))+ if animations.get(mode) in choices+ else default_agent_animation_id(mode)+ )+ for mode in ANIMATION_STATES+ }+ working_selection = selections[AgentMode.WORKING.value]+ for mode in AGENT_ANIMATION_WORKING_MODES:+ selections[mode] = working_selection+ result[profile_id] = AgentAnimationProfile(+ name=name.strip(),+ animations=selections,+ )+ return result++def normalize_terminal_app(value: object) -> str:if isinstance(value, str) and value in TERMINAL_APP_CHOICES:return valuediff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.pyindex eb3853b..c789b32 100644--- a/src/sidepulse/status_bar.py+++ b/src/sidepulse/status_bar.py@@ -22,12 +22,14 @@ try:NSButtonTypeSwitch,NSColor,NSCompositingOperationSourceOver,+ NSEventTrackingRunLoopMode,NSFont,NSFontAttributeName,NSForegroundColorAttributeName,NSImage,NSMenu,NSMenuItem,+ NSEventModifierFlagCommand,NSOffState,NSOnState,NSOpenPanel,@@ -41,6 +43,8 @@ try:NSTextField,NSTextView,NSView,+ NSViewHeightSizable,+ NSViewWidthSizable,NSWorkspace,NSWindow,NSWindowStyleMaskClosable,@@ -48,7 +52,7 @@ try:NSWindowStyleMaskTitled,NSVariableStatusItemLength,)- from Foundation import NSObject, NSString, NSTimer, NSURL+ from Foundation import NSRunLoop, NSRunLoopCommonModes, NSObject, NSString, NSTimer, NSURLexcept ImportError as exc: # pragma: no cover - only exercised on non-macOS setups.raise SystemExit(f"The status-bar app requires PyObjC/AppKit ({exc}):\n"@@ -105,11 +109,16 @@ from .led_status import (brightness_percent,normalize_brightness,normalized_device_name,- program_for_display_state,+ program_for_agent_mode,write_mode_to_leds,- display_state_for_mode,)-from .virtual_device import VIRTUAL_DEVICE_ID, VIRTUAL_DEVICE_NAME, VirtualStatusDevice+from .virtual_device import (+ FRAME_INTERVAL,+ VIRTUAL_DEVICE_ID,+ VIRTUAL_DEVICE_NAME,+ VirtualLedView,+ VirtualStatusDevice,+)from .lid_sleep import (LID_POLL_SECONDS,ClosedLidAwakeController,@@ -119,7 +128,7 @@ from .lid_sleep import (sleep_helper_install_command,sleep_helper_installed,)-from .models import AgentMode, AgentStatus, provider_label+from .models import AgentMode, AgentStatus, MODE_LABELS, provider_labelfrom .providers import (ProviderConfig,detect_claude_config,@@ -144,6 +153,34 @@ from .session_actions import (session_open_target,)from .settings import (+ ANIMATION_STATE_LID_CLOSED,+ ANIMATION_STATE_LID_OPEN,+ ANIMATION_STATES,+ AGENT_ANIMATION_ADD_CUSTOM,+ AGENT_ANIMATION_AMBER_PULSE,+ AGENT_ANIMATION_CYAN_COMPLETE,+ AGENT_ANIMATION_CYAN_ROLL,+ AGENT_ANIMATION_EMBER_ATTENTION,+ AGENT_ANIMATION_EMBER_COMPLETE,+ AGENT_ANIMATION_EMBER_IDLE,+ AGENT_ANIMATION_EMBER_LID_OPEN,+ AGENT_ANIMATION_EMBER_TIDE,+ AGENT_ANIMATION_IDLE_PULSE,+ AGENT_ANIMATION_KITT,+ AGENT_ANIMATION_KITT_RED,+ AGENT_ANIMATION_LID_CLOSED,+ AGENT_ANIMATION_LID_OPEN,+ AGENT_ANIMATION_MODES,+ AGENT_ANIMATION_NIGHT_RIDER,+ AGENT_ANIMATION_IMMEDIATE_OFF,+ AGENT_ANIMATION_SLOW_OFF,+ AGENT_ANIMATION_PURPLE_ATTENTION,+ AGENT_ANIMATION_PURPLE_COMPLETE,+ AGENT_ANIMATION_PURPLE_IDLE,+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ AGENT_ANIMATION_PURPLE_TIDE,+ AGENT_ANIMATION_SOLID_GREEN,+ AGENT_ANIMATION_BUILT_IN_PROFILE_IDS,DEFAULT_IDLE_TIMEOUT_SECONDS,DEFAULT_HISTORY_TIMEFRAME_SECONDS,DEFAULT_RECENT_SESSION_RETENTION_SECONDS,@@ -172,13 +209,18 @@ from .settings import (TERMINAL_APP_CHOICES,TERMINAL_APP_WARP,TERMINAL_APP_WEZTERM,+ AgentMonitorSettings,LedAnimationSetting,+ agent_animation_profile_document,+ agent_animation_profile_id,+ custom_agent_animation_id,default_settings_path,default_lid_animation,load_settings,normalize_terminal_app,normalize_animation_duration,save_settings,+ with_imported_agent_animation_profile,)from .status_bar_launch import install_launch_agent, launch_agent_installed@@ -202,6 +244,75 @@ class StatusBarDevice:reason: str = ""+class AnimationProgramTextView(NSTextView):+ """NSTextView with reliable edit shortcuts in an accessory application."""++ def performKeyEquivalent_(self, event):+ if int(event.modifierFlags()) & int(NSEventModifierFlagCommand):+ key = str(event.charactersIgnoringModifiers() or "").casefold()+ action = {+ "x": self.cut_,+ "c": self.copy_,+ "v": self.paste_,+ "a": self.selectAll_,+ }.get(key)+ if action is not None:+ action(None)+ return True+ return objc.super(AnimationProgramTextView, self).performKeyEquivalent_(event)+++class AgentAnimationMenuItemView(NSView):+ """Interactive menu row with a Screen Bar-rendered animation preview."""++ def initWithFrame_(self, frame):+ self = objc.super(AgentAnimationMenuItemView, self).initWithFrame_(frame)+ if self is not None:+ self.popup = None+ self.mode = None+ self.animation_id = None+ self.label = add_label(self, "", 10, 7, 106, 20)+ self.animation_preview = VirtualLedView.alloc().initWithFrame_(+ ((122, 2), (72, 28))+ )+ self.animation_preview.setCompactPreview_(True)+ self.addSubview_(self.animation_preview)+ return self++ def configurePopup_mode_animation_label_program_(+ self,+ popup,+ mode,+ animation_id,+ label,+ program,+ ):+ self.popup = popup+ self.mode = str(mode)+ self.animation_id = str(animation_id)+ self.label.setStringValue_(str(label))+ self.animation_preview.setProgram_(str(program))++ def mouseDown_(self, _event):+ popup = self.popup+ if popup is None:+ return+ for index in range(popup.numberOfItems()):+ item = popup.itemAtIndex_(index)+ payload = item.representedObject()+ if (+ isinstance(payload, dict)+ and payload.get("mode") == self.mode+ and payload.get("animation_id") == self.animation_id+ ):+ popup.selectItemAtIndex_(index)+ break+ target = popup.target()+ if target is not None:+ target.setAgentAnimationStyle_(popup)+ popup.menu().cancelTracking()++@dataclass(frozen=True)class TerminalAppSpec:key: str@@ -223,26 +334,55 @@ STATE_IDLE = StatusBarState("Idle", "circle", 4)STATE_WORKING = StatusBarState("Working", "arrow.triangle.2.circlepath", 2)STATE_DONE = StatusBarState("Done", "checkmark.circle", 3)STATE_ASK = StatusBarState("Ask", "questionmark.circle", 1)-STATUS_BAR_DEVICE_PRIORITY = ("sidepulsepro", "sidepulsedot")+STATUS_BAR_DEVICE_PRIORITY = ("sidepulsepro", "sidepulsedot", "pulsedot")STATUS_BAR_KEEPALIVE_VOLUME_NAMES = ("SidePulsePro","SidePulseDot",+ "PulseDot",)STATUS_BAR_REFRESH_SECONDS = 15.0STATUS_BAR_DEVICE_POLL_SECONDS = 2.0STATUS_BAR_SESSION_HISTORY_LIMIT = 10SCREEN_BAR_FEATURE_ENABLED = TrueSTATUS_BAR_MAX_LINES_PER_SOURCE = 500+SETTINGS_WINDOW_WIDTH = 680+SETTINGS_WINDOW_HEIGHT = 560+SETTINGS_ANIMATIONS_WINDOW_WIDTH = 720+SETTINGS_ANIMATIONS_WINDOW_HEIGHT = 500+SETTINGS_TAB_Y = 44+SETTINGS_TAB_TOP_MARGIN = 20STATUS_BAR_HISTORY_CHART_RECORD_LIMIT = 2400STATUS_BAR_HISTORY_CHART_RECORD_LIMIT_PADDING = 300STATUS_BAR_HISTORY_CHART_RECORD_LIMIT_MULTIPLIER = 3.0MAC_SLEEP_POLL_SECONDS = 60.0SYSTEM_POLL_ERROR_BACKOFF_SECONDS = 30.0LID_ANIMATION_RESTORE_FUDGE_SECONDS = 0.15+AGENT_ANIMATION_DEVICE_PREVIEW_SECONDS = 3.0+AGENT_ANIMATION_EDITOR_DEVICE_PREVIEW_SECONDS = 10.0+AGENT_ANIMATION_PROFILE_CUSTOM = ""LID_ANIMATION_LABELS = {LID_ANIMATION_CLOSED: "Lid Closed",LID_ANIMATION_OPEN: "Lid Open",}+ANIMATION_STATE_LABELS = {+ **{mode.value: MODE_LABELS[mode] for mode in AgentMode},+ ANIMATION_STATE_LID_OPEN: "Lid Open",+ ANIMATION_STATE_LID_CLOSED: "Lid Closed",+}+ANIMATION_UI_STATES = tuple(+ state+ for state in ANIMATION_STATES+ if state+ not in {+ AgentMode.TOOL_RUNNING.value,+ AgentMode.LONG_TASK_PROGRESS.value,+ }+)+ANIMATION_STATE_LABELS[AgentMode.WORKING.value] = "Working / Tool / Long Task"+LID_KIND_BY_ANIMATION_STATE = {+ ANIMATION_STATE_LID_OPEN: LID_ANIMATION_OPEN,+ ANIMATION_STATE_LID_CLOSED: LID_ANIMATION_CLOSED,+}SLEEP_PREVENTION_LABELS = {SLEEP_PREVENTION_NEVER: "Never",SLEEP_PREVENTION_AGENTS: "When Agents Work",@@ -311,6 +451,36 @@ def awake_policy_should_hold(policy: str, *, agents_active: bool) -> bool:return False+def lid_closed_led_state_should_hold(+ *,+ lid_closed: bool | None,+ sleep_prevention_policy: str,+ agents_active: bool | None,+ battery_safeguard_active: bool = False,+) -> bool:+ """Keep the shutdown frame while the closed Mac is allowed to sleep."""+ if lid_closed is not True or agents_active is None:+ return False+ sleep_prevention_requested = awake_policy_should_hold(+ sleep_prevention_policy,+ agents_active=agents_active,+ ) and not battery_safeguard_active+ return not sleep_prevention_requested+++def lid_close_animation_should_run(+ *,+ sleep_prevention_policy: str,+ agents_active: bool | None,+) -> bool:+ """Run the physical close animation only when the Mac may go to sleep."""+ if sleep_prevention_policy == SLEEP_PREVENTION_ALWAYS:+ return False+ if sleep_prevention_policy == SLEEP_PREVENTION_AGENTS:+ return agents_active is False+ return True++def sleep_prevention_battery_safeguard(snapshot: BatterySnapshot | None,threshold_percent: float,@@ -351,7 +521,21 @@ class StatusBarController(NSObject):self.timer = Noneself.lid_timer = Noneself.device_timer = None+ self.agent_animation_preview_timer = Noneself.settings_window = None+ self.agent_animation_editor_window = None+ self.agent_animation_editor_mode = None+ self.agent_animation_editor_existing_id = None+ self.agent_animation_editor_name = None+ self.agent_animation_editor_program = None+ self.agent_animation_editor_preview = None+ self.agent_animation_editor_preview_status = None+ self.agent_animation_profile_editor_window = None+ self.agent_animation_profile_editor_name = None+ self.selected_agent_animation_profile_id = (+ self.settings.matching_agent_animation_profile_id()+ or AGENT_ANIMATION_PROFILE_CUSTOM+ )self.setup_window = Noneself.settings_fields = {}self.settings_buttons = {}@@ -400,6 +584,7 @@ class StatusBarController(NSObject):self.lid_poll_backoff_until_monotonic = 0.0self.pending_lid_closed = Noneself.pending_lid_error = None+ self.lid_closed_led_hold_active = Falseself.led_animation_until_monotonic = 0.0self.led_animation_token = 0self.virtual_status_device = VirtualStatusDevice.alloc().init()@@ -407,6 +592,7 @@ class StatusBarController(NSObject):def applicationDidFinishLaunching_(self, _notification):NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)+ install_standard_edit_menu()log_status_bar("launching status item")self.start_event_server()@@ -701,6 +887,81 @@ class StatusBarController(NSObject):def setBatteryPowerPreviewFromCheckbox_(self, sender):self.set_battery_power_preview(sender.state() == NSOnState)+ @objc.IBAction+ def setAgentAnimationStyle_(self, sender):+ item = sender.selectedItem()+ payload = item.representedObject() if item is not None else None+ if not isinstance(payload, dict):+ return+ mode = payload.get("mode")+ animation_id = payload.get("animation_id")+ if animation_id == AGENT_ANIMATION_ADD_CUSTOM:+ self.show_agent_animation_editor(mode)+ return+ self.set_agent_animation_style(mode, animation_id)++ @objc.IBAction+ def addCustomAgentAnimation_(self, _sender):+ self.show_agent_animation_editor(None)++ @objc.IBAction+ def editAgentAnimation_(self, sender):+ self.show_agent_animation_editor(+ sender.representedObject(),+ edit_selected=True,+ )++ @objc.IBAction+ def applyAgentAnimationProfile_(self, sender):+ item = sender.selectedItem()+ profile_id = item.representedObject() if item is not None else None+ self.apply_agent_animation_profile(+ str(profile_id) if profile_id is not None else None+ )++ @objc.IBAction+ def showAgentAnimationProfileEditor_(self, _sender):+ self.show_agent_animation_profile_editor()++ @objc.IBAction+ def saveAgentAnimationProfile_(self, _sender):+ self.save_agent_animation_profile()++ @objc.IBAction+ def cancelAgentAnimationProfile_(self, _sender):+ if self.agent_animation_profile_editor_window is not None:+ self.agent_animation_profile_editor_window.orderOut_(None)++ @objc.IBAction+ def deleteAgentAnimationProfile_(self, _sender):+ self.delete_matching_agent_animation_profile()++ @objc.IBAction+ def exportAgentAnimationProfile_(self, _sender):+ self.export_agent_animation_profile()++ @objc.IBAction+ def importAgentAnimationProfile_(self, _sender):+ self.import_agent_animation_profile()++ @objc.IBAction+ def showAgentAnimationOnDevice_(self, sender):+ self.show_agent_animation_on_device(sender.representedObject())++ @objc.IBAction+ def showAgentAnimationEditorOnDevice_(self, _sender):+ self.show_agent_animation_editor_on_device()++ @objc.IBAction+ def saveAgentAnimationCustom_(self, _sender):+ self.save_custom_agent_animation()++ @objc.IBAction+ def cancelAgentAnimationCustom_(self, _sender):+ if self.agent_animation_editor_window is not None:+ self.agent_animation_editor_window.orderOut_(None)+ self.refresh_settings_window()+@objc.IBActiondef saveAgentListTiming_(self, _sender):self.save_agent_list_timing_from_fields()@@ -766,6 +1027,7 @@ class StatusBarController(NSObject):NSApp.terminate_(self)def applicationWillTerminate_(self, _notification):+ self.stop_agent_animation_preview_timer()self.stop_event_server()self.closed_lid_awake.release()self.keep_awake.release()@@ -842,8 +1104,96 @@ class StatusBarController(NSObject):self.settings_window = build_settings_window(self)self.refresh_settings_window()self.settings_window.makeKeyAndOrderFront_(None)+ self.start_agent_animation_preview_timer()NSApp.activateIgnoringOtherApps_(True)+ def tabView_didSelectTabViewItem_(self, tab_view, tab_item) -> None:+ window = self.settings_window or tab_view.window()+ if window is None:+ return+ identifier = str(tab_item.identifier())+ height = (+ SETTINGS_ANIMATIONS_WINDOW_HEIGHT+ if identifier == "animations"+ else SETTINGS_WINDOW_HEIGHT+ )+ width = (+ SETTINGS_ANIMATIONS_WINDOW_WIDTH+ if identifier == "animations"+ else SETTINGS_WINDOW_WIDTH+ )+ current_width = float(window.contentView().frame().size.width)+ current_height = float(window.contentView().frame().size.height)+ if abs(current_width - width) < 0.5 and abs(current_height - height) < 0.5:+ return+ window.setContentSize_((width, height))+ tab_view.setFrame_(+ (+ (20, SETTINGS_TAB_Y),+ (+ width - 40,+ height - SETTINGS_TAB_Y - SETTINGS_TAB_TOP_MARGIN,+ ),+ )+ )+ message = self.settings_fields.get("message")+ if message is not None:+ message.setFrameSize_((width - 48, 22))+ window.center()+ def start_agent_animation_preview_timer(self) -> None:+ if self.agent_animation_preview_timer is not None:+ return+ self.agent_animation_preview_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(+ FRAME_INTERVAL,+ self,+ "redrawAgentAnimationPreviews:",+ None,+ True,+ )+ run_loop = NSRunLoop.mainRunLoop()+ run_loop.addTimer_forMode_(+ self.agent_animation_preview_timer,+ NSRunLoopCommonModes,+ )+ run_loop.addTimer_forMode_(+ self.agent_animation_preview_timer,+ NSEventTrackingRunLoopMode,+ )++ def stop_agent_animation_preview_timer(self) -> None:+ if self.agent_animation_preview_timer is not None:+ self.agent_animation_preview_timer.invalidate()+ self.agent_animation_preview_timer = None++ @objc.IBAction+ def redrawAgentAnimationPreviews_(self, _sender):+ settings_visible = (+ self.settings_window is not None and self.settings_window.isVisible()+ )+ editor_visible = (+ self.agent_animation_editor_window is not None+ and self.agent_animation_editor_window.isVisible()+ )+ if not settings_visible and not editor_visible:+ self.stop_agent_animation_preview_timer()+ return+ if settings_visible:+ for mode_value in ANIMATION_UI_STATES:+ preview = self.settings_fields.get(+ f"agent_animation_preview_{mode_value}"+ )+ if preview is not None:+ preview.setNeedsDisplay_(True)+ popup = self.settings_fields.get(f"agent_animation_{mode_value}")+ if popup is not None:+ for index in range(popup.numberOfItems()):+ menu_view = popup.itemAtIndex_(index).view()+ menu_preview = getattr(menu_view, "animation_preview", None)+ if menu_preview is not None:+ menu_preview.setNeedsDisplay_(True)+ if editor_visible and self.agent_animation_editor_preview is not None:+ self.agent_animation_editor_preview.setNeedsDisplay_(True)+def show_setup_window_if_needed(self) -> None:if should_show_setup_window(self.settings):self.show_setup_window()@@ -1014,6 +1364,35 @@ class StatusBarController(NSObject):self.settings_buttons.get("battery_power_preview"),self.settings.battery_show_on_power_change,)+ for mode_value in ANIMATION_UI_STATES:+ popup = self.settings_fields.get(f"agent_animation_{mode_value}")+ if popup is not None:+ refresh_agent_animation_popup(+ popup,+ mode_value,+ self.settings,+ self.settings.agent_animation_id(mode_value),+ )+ preview = self.settings_fields.get(+ f"agent_animation_preview_{mode_value}"+ )+ if preview is not None:+ preview.setProgram_(animation_state_program(self.settings, mode_value))+ profile_popup = self.settings_fields.get("agent_animation_profile")+ if profile_popup is not None:+ refresh_agent_animation_profile_popup(+ profile_popup,+ self.settings,+ self.selected_agent_animation_profile_id,+ )+ delete_profile = self.settings_buttons.get("delete_agent_animation_profile")+ if delete_profile is not None:+ delete_profile.setEnabled_(+ self.selected_agent_animation_profile_id+ in self.settings.agent_animation_profiles+ and self.selected_agent_animation_profile_id+ not in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS+ )for provider in ("codex", "claude", "grok"):popup = self.settings_fields.get(f"{provider}_session_opener")if popup is not None:@@ -1567,6 +1946,424 @@ class StatusBarController(NSObject):self.refresh_settings_window()self.refresh_(None)+ def set_agent_animation_style(+ self,+ mode_value: str | None,+ animation_id: str | None,+ ) -> None:+ try:+ state = str(mode_value)+ if state not in ANIMATION_STATES:+ raise ValueError(f"Unknown animation state: {state}")+ if animation_id is None:+ return+ self.settings = self.settings.with_agent_animation(+ state,+ str(animation_id),+ )+ save_settings(self.settings)+ except Exception as exc:+ self.set_settings_message(f"Could not save animation: {exc}")+ self.settings = load_settings()+ self.refresh_settings_window()+ return++ self.reset_led_controllers_for_display_change()+ self.selected_agent_animation_profile_id = AGENT_ANIMATION_PROFILE_CUSTOM+ self.set_settings_message(+ f"{ANIMATION_STATE_LABELS[state]} animation: "+ f"{agent_animation_label(self.settings, str(animation_id))}."+ )+ self.refresh_settings_window()+ self.refresh_(None)++ def apply_agent_animation_profile(self, profile_id: str | None) -> None:+ if not profile_id or profile_id == AGENT_ANIMATION_PROFILE_CUSTOM:+ self.selected_agent_animation_profile_id = AGENT_ANIMATION_PROFILE_CUSTOM+ self.refresh_settings_window()+ return+ try:+ profile = self.settings.agent_animation_profiles.get(profile_id)+ if profile is None:+ raise ValueError(f"Unknown animation profile: {profile_id}")+ self.settings = self.settings.with_applied_agent_animation_profile(+ profile_id+ )+ label = profile.name+ save_settings(self.settings)+ except Exception as exc:+ self.set_settings_message(f"Could not apply animation profile: {exc}")+ self.settings = load_settings()+ self.refresh_settings_window()+ return++ self.reset_led_controllers_for_display_change()+ self.selected_agent_animation_profile_id = profile_id+ self.set_settings_message(f"Animation profile applied: {label}.")+ self.refresh_settings_window()+ self.refresh_(None)++ def show_agent_animation_profile_editor(self) -> None:+ if self.agent_animation_profile_editor_window is None:+ self.agent_animation_profile_editor_window = (+ build_agent_animation_profile_editor_window(self)+ )+ set_field_value(self.agent_animation_profile_editor_name, "")+ self.agent_animation_profile_editor_window.makeKeyAndOrderFront_(None)+ NSApp.activateIgnoringOtherApps_(True)++ def save_agent_animation_profile(self) -> None:+ name = text_control_value(self.agent_animation_profile_editor_name).strip()+ if not name:+ self.set_settings_message("Enter a profile name.")+ return+ try:+ profile_id = agent_animation_profile_id(+ name,+ self.settings.agent_animation_profiles,+ )+ self.settings = self.settings.with_agent_animation_profile(+ profile_id,+ name=name,+ )+ save_settings(self.settings)+ except Exception as exc:+ self.set_settings_message(f"Could not save animation profile: {exc}")+ return++ self.agent_animation_profile_editor_window.orderOut_(None)+ self.selected_agent_animation_profile_id = profile_id+ self.set_settings_message(f"Animation profile saved: {name}.")+ self.refresh_settings_window()++ def delete_matching_agent_animation_profile(self) -> None:+ profile_id = self.selected_agent_animation_profile_id+ if profile_id not in self.settings.agent_animation_profiles:+ self.set_settings_message("Choose a saved profile before deleting it.")+ return+ if profile_id in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS:+ self.set_settings_message("Built-in animation profiles cannot be deleted.")+ return+ name = self.settings.agent_animation_profiles[profile_id].name+ try:+ self.settings = self.settings.without_agent_animation_profile(profile_id)+ save_settings(self.settings)+ except Exception as exc:+ self.set_settings_message(f"Could not delete animation profile: {exc}")+ return+ self.selected_agent_animation_profile_id = AGENT_ANIMATION_PROFILE_CUSTOM+ self.set_settings_message(f"Animation profile deleted: {name}.")+ self.refresh_settings_window()++ def export_agent_animation_profile(self) -> None:+ profile_id = self.selected_agent_animation_profile_id or None+ if profile_id is not None and profile_id not in self.settings.agent_animation_profiles:+ profile_id = None+ try:+ document = agent_animation_profile_document(self.settings, profile_id)+ except Exception as exc:+ self.set_settings_message(f"Could not prepare animation profile: {exc}")+ return+ path = choose_animation_profile_export_path(str(document["name"]))+ if path is None:+ return+ try:+ path.write_text(+ json.dumps(document, indent=2, sort_keys=True) + "\n",+ encoding="utf-8",+ )+ except Exception as exc:+ self.set_settings_message(f"Could not export animation profile: {exc}")+ return+ self.set_settings_message(f"Animation profile exported: {path.name}.")++ def import_agent_animation_profile(self) -> None:+ path = choose_animation_profile_import_path()+ if path is None:+ return+ try:+ document = json.loads(path.read_text(encoding="utf-8"))+ raw_custom = document.get("custom_animations", {})+ if isinstance(raw_custom, dict):+ for raw in raw_custom.values():+ if isinstance(raw, dict) and isinstance(raw.get("program"), str):+ validate_agent_animation_program(raw["program"])+ self.settings, profile_id = with_imported_agent_animation_profile(+ self.settings,+ document,+ )+ save_settings(self.settings)+ except Exception as exc:+ self.set_settings_message(f"Could not import animation profile: {exc}")+ return++ self.selected_agent_animation_profile_id = profile_id+ self.reset_led_controllers_for_display_change()+ profile = self.settings.agent_animation_profiles[profile_id]+ self.set_settings_message(f"Animation profile imported: {profile.name}.")+ self.refresh_settings_window()+ self.refresh_(None)++ def show_agent_animation_on_device(self, mode_value: str | None) -> None:+ if not self.leds_enabled:+ self.set_settings_message("Connect LEDs before showing an animation.")+ return+ try:+ state = str(mode_value)+ if state not in ANIMATION_STATES:+ raise ValueError(f"Unknown animation state: {state}")+ animation = self.settings.agent_animation(state)+ except Exception as exc:+ self.set_settings_message(f"Could not show animation: {exc}")+ return++ lid_kind = LID_KIND_BY_ANIMATION_STATE.get(state)+ if lid_kind is not None:+ self.play_lid_animation(lid_kind)+ self.set_settings_message(+ f"Showing {ANIMATION_STATE_LABELS[state]} on device."+ )+ return++ mode = AgentMode(state)++ devices = [+ device+ for device in self.status_bar_devices()+ if (+ device.connected+ and device.device_id != VIRTUAL_DEVICE_ID+ and device.display != LED_DISPLAY_CUSTOM+ )+ ]+ if not devices:+ self.set_settings_message("No connected agent-display device to show it on.")+ return++ self.led_animation_token += 1+ token = self.led_animation_token+ self.led_animation_until_monotonic = (+ time.monotonic() + AGENT_ANIMATION_DEVICE_PREVIEW_SECONDS+ )+ self.set_settings_message(+ f"Showing {MODE_LABELS[mode]} on device for "+ f"{AGENT_ANIMATION_DEVICE_PREVIEW_SECONDS:g} seconds."+ )+ thread = threading.Thread(+ target=self.show_agent_animation_on_device_worker,+ args=(mode, animation.style, animation.custom_program, devices, token),+ daemon=True,+ )+ thread.start()++ def show_agent_animation_on_device_worker(+ self,+ mode: AgentMode,+ animation_style: str,+ custom_program: str,+ devices: list[StatusBarDevice],+ token: int,+ ) -> None:+ for device in devices:+ try:+ result = write_mode_to_leds(+ mode,+ device_path=device.target,+ brightness=device.brightness,+ animation_style=animation_style,+ custom_program=custom_program,+ )+ log_status_bar(+ f"animation device preview={MODE_LABELS[mode]} "+ f"device={device.name} target={result.target}"+ )+ except Exception as exc:+ log_status_bar(+ f"animation device preview error {MODE_LABELS[mode]} "+ f"device={device.name}: {exc}"+ )+ time.sleep(AGENT_ANIMATION_DEVICE_PREVIEW_SECONDS)+ self.performSelectorOnMainThread_withObject_waitUntilDone_(+ "restoreLedDisplay:",+ str(token),+ False,+ )++ def show_agent_animation_editor(+ self,+ mode_value: str | None,+ *,+ edit_selected: bool = False,+ ) -> None:+ state = None+ if mode_value is not None:+ state = str(mode_value)+ if state not in ANIMATION_STATES:+ self.set_settings_message(f"Unknown animation state: {mode_value}")+ self.refresh_settings_window()+ return+ if self.agent_animation_editor_window is None:+ self.agent_animation_editor_window = build_agent_animation_editor_window(self)+ self.agent_animation_editor_mode = state+ self.agent_animation_editor_existing_id = None+ program = (+ animation_state_program(self.settings, state)+ if state is not None+ else program_for_agent_mode(AgentMode.WORKING, led_count=8)+ )+ title = "Add Custom Animation"+ name = ""+ if edit_selected and state is not None:+ animation_id = self.settings.agent_animation_id(state)+ custom = self.settings.custom_agent_animations.get(animation_id)+ if custom is not None:+ self.agent_animation_editor_existing_id = animation_id+ title = "Edit Custom Animation"+ name = custom.name+ program = custom.program+ else:+ title = "Clone Built-in Animation"+ name = f"{agent_animation_label(self.settings, animation_id)} Copy"+ self.agent_animation_editor_window.setTitle_(title)+ set_field_value(self.agent_animation_editor_name, name)+ set_text_control_value(self.agent_animation_editor_program, program)+ self.refresh_agent_animation_editor_preview()+ self.agent_animation_editor_window.makeKeyAndOrderFront_(None)+ self.start_agent_animation_preview_timer()+ NSApp.activateIgnoringOtherApps_(True)++ def textDidChange_(self, notification) -> None:+ if notification.object() is self.agent_animation_editor_program:+ self.refresh_agent_animation_editor_preview()++ def refresh_agent_animation_editor_preview(self) -> None:+ preview = self.agent_animation_editor_preview+ status = self.agent_animation_editor_preview_status+ if preview is None:+ return+ program = normalize_led_text(+ text_control_value(self.agent_animation_editor_program)+ )+ try:+ validate_agent_animation_program(program)+ preview.setProgram_(program)+ if preview.wasm_error:+ raise ValueError(preview.wasm_error)+ except Exception as exc:+ preview.setProgram_("off")+ if status is not None:+ status.setStringValue_(str(exc))+ status.setTextColor_(NSColor.systemRedColor())+ return+ if status is not None:+ status.setStringValue_("Updates as you type")+ status.setTextColor_(NSColor.secondaryLabelColor())++ def show_agent_animation_editor_on_device(self) -> None:+ status = self.agent_animation_editor_preview_status+ try:+ if not self.leds_enabled:+ raise ValueError("Connect LEDs before showing this animation.")+ program = normalize_led_text(+ text_control_value(self.agent_animation_editor_program)+ )+ validate_agent_animation_program(program)+ devices = [+ device+ for device in self.status_bar_devices()+ if (+ device.connected+ and device.device_id != VIRTUAL_DEVICE_ID+ and device.display != LED_DISPLAY_CUSTOM+ )+ ]+ if not devices:+ raise ValueError("No connected physical LED device found.")+ except Exception as exc:+ if status is not None:+ status.setStringValue_(str(exc))+ status.setTextColor_(NSColor.systemRedColor())+ return++ self.led_animation_token += 1+ token = self.led_animation_token+ self.led_animation_until_monotonic = (+ time.monotonic() + AGENT_ANIMATION_EDITOR_DEVICE_PREVIEW_SECONDS+ )+ if status is not None:+ status.setStringValue_(+ f"Showing for {AGENT_ANIMATION_EDITOR_DEVICE_PREVIEW_SECONDS:g} seconds"+ )+ status.setTextColor_(NSColor.secondaryLabelColor())+ thread = threading.Thread(+ target=self.show_animation_program_on_device_worker,+ args=(program, devices, token),+ daemon=True,+ )+ thread.start()++ def show_animation_program_on_device_worker(+ self,+ program: str,+ devices: list[StatusBarDevice],+ token: int,+ ) -> None:+ for device in devices:+ try:+ scaled_program = apply_brightness(program, device.brightness)+ target = write_led_program(+ scaled_program,+ device_path=device.target,+ )+ log_status_bar(+ f"custom animation preview device={device.name} target={target}"+ )+ except Exception as exc:+ log_status_bar(+ f"custom animation preview error {device.name}: {exc}"+ )+ time.sleep(AGENT_ANIMATION_EDITOR_DEVICE_PREVIEW_SECONDS)+ self.performSelectorOnMainThread_withObject_waitUntilDone_(+ "restoreLedDisplay:",+ str(token),+ False,+ )++ def save_custom_agent_animation(self) -> None:+ mode = self.agent_animation_editor_mode+ existing_id = self.agent_animation_editor_existing_id+ name = text_control_value(self.agent_animation_editor_name).strip()+ program = normalize_led_text(+ text_control_value(self.agent_animation_editor_program)+ )+ try:+ if not name:+ raise ValueError("Animation name is required.")+ validate_agent_animation_program(program)+ animation_id = existing_id or custom_agent_animation_id(+ name, self.settings.custom_agent_animations+ )+ self.settings = self.settings.with_custom_agent_animation(+ animation_id,+ name=name,+ program=program,+ )+ if mode is not None:+ self.settings = self.settings.with_agent_animation(mode, animation_id)+ save_settings(self.settings)+ except Exception as exc:+ self.set_settings_message(f"Could not add custom animation: {exc}")+ return++ self.agent_animation_editor_window.orderOut_(None)+ if mode is not None:+ self.selected_agent_animation_profile_id = AGENT_ANIMATION_PROFILE_CUSTOM+ self.reset_led_controllers_for_display_change()+ action = "updated" if existing_id is not None else "added"+ self.set_settings_message(f"Custom animation {action}: {name}.")+ self.refresh_settings_window()+ self.refresh_(None)+def read_battery_snapshot(self) -> BatterySnapshot | None:try:snapshot = read_battery_snapshot(@@ -1851,6 +2648,12 @@ class StatusBarController(NSObject):self.sync_virtual_status_device(mode, battery_snapshot)+ if self.lid_closed_led_hold_active:+ if self.should_hold_lid_closed_led_state():+ return+ self.lid_closed_led_hold_active = False+ log_status_bar("lid_led_state=restoring reason=sleep_conditions_changed")+if time.monotonic() < self.led_animation_until_monotonic:return@@ -1896,13 +2699,19 @@ class StatusBarController(NSObject):))else:- self.virtual_status_device.set_program(- program_for_display_state(- display_state_for_mode(mode),+ animation = self.settings.agent_animation(mode)+ try:+ program = program_for_agent_mode(+ mode,led_count=8,brightness=device.brightness,+ animation_style=animation.style,+ custom_program=animation.custom_program,)- )+ except DeviceWriteError as exc:+ log_status_bar(f"virtual animation error {MODE_LABELS[mode]}: {exc}")+ return+ self.virtual_status_device.set_program(program)def sync_leds_worker(self,@@ -1957,7 +2766,12 @@ class StatusBarController(NSObject):f"{format_watts(battery_snapshot.adapter_power)}")else:- result = self.agent_controller_for_device(device).sync_mode(mode)+ animation = self.settings.agent_animation(mode)+ result = self.agent_controller_for_device(device).sync_mode(+ mode,+ animation_style=animation.style,+ custom_program=animation.custom_program,+ )label = f"{device.name} {result.label}"if result.error:@@ -1983,7 +2797,24 @@ class StatusBarController(NSObject):) -> None:if not self.leds_enabled:return- animation = animation or self.settings.lid_animation(kind)+ if animation is None:+ state = (+ ANIMATION_STATE_LID_CLOSED+ if kind == LID_ANIMATION_CLOSED+ else ANIMATION_STATE_LID_OPEN+ )+ current = self.settings.lid_animation(kind)+ animation_id = self.settings.agent_animation_id(state)+ duration_seconds = current.duration_seconds+ if animation_id in {+ AGENT_ANIMATION_LID_CLOSED,+ AGENT_ANIMATION_LID_OPEN,+ }:+ duration_seconds = default_lid_animation(kind).duration_seconds+ animation = LedAnimationSetting(+ program=animation_state_program(self.settings, state),+ duration_seconds=duration_seconds,+ )try:validate_lid_animation(animation)except DeviceWriteError as exc:@@ -2012,6 +2843,26 @@ class StatusBarController(NSObject):)thread.start()+ def should_hold_lid_closed_led_state(self) -> bool:+ agents_active = None+ if self.last_snapshot is not None:+ agents_active = self.last_snapshot.aggregate.active_count > 0+ return lid_closed_led_state_should_hold(+ lid_closed=self.last_lid_closed,+ sleep_prevention_policy=self.settings.sleep_prevention_policy,+ agents_active=agents_active,+ battery_safeguard_active=self.battery_sleep_safeguard_active,+ )++ def should_run_lid_close_animation(self) -> bool:+ agents_active = None+ if self.last_snapshot is not None:+ agents_active = self.last_snapshot.aggregate.active_count > 0+ return lid_close_animation_should_run(+ sleep_prevention_policy=self.settings.sleep_prevention_policy,+ agents_active=agents_active,+ )+def play_lid_animation_worker(self,kind: str,@@ -2182,6 +3033,18 @@ class StatusBarController(NSObject):self.last_lid_closed = closedkind = LID_ANIMATION_CLOSED if closed else LID_ANIMATION_OPENlog_status_bar(f"lid_state={'closed' if closed else 'open'}")+ if closed:+ if not self.should_run_lid_close_animation():+ self.lid_closed_led_hold_active = False+ log_status_bar(+ "animation=Lid Closed skipped reason=sleep_prevention_active"+ )+ return+ self.lid_closed_led_hold_active = self.should_hold_lid_closed_led_state()+ if self.lid_closed_led_hold_active:+ log_status_bar("lid_led_state=held reason=sleep_allowed")+ else:+ self.lid_closed_led_hold_active = Falseself.play_lid_animation(kind)@objc.IBAction@@ -2578,6 +3441,40 @@ def choose_debug_export_path(format_name: str) -> Path | None:return Path(str(url.path()))+def choose_animation_profile_export_path(profile_name: str) -> Path | None:+ safe_name = "-".join(str(profile_name).strip().lower().split()) or "current"+ safe_name = "".join(+ char for char in safe_name if char.isalnum() or char in {"-", "_"}+ )+ panel = NSSavePanel.savePanel()+ panel.setTitle_("Export SidePulse Animation Profile")+ panel.setNameFieldStringValue_(f"sidepulse-{safe_name}-profile.json")+ if hasattr(panel, "setAllowedFileTypes_"):+ panel.setAllowedFileTypes_(["json"])+ if panel.runModal() != 1:+ return None+ url = panel.URL()+ if url is None:+ return None+ return Path(str(url.path()))+++def choose_animation_profile_import_path() -> Path | None:+ panel = NSOpenPanel.openPanel()+ panel.setTitle_("Import SidePulse Animation Profile")+ panel.setCanChooseFiles_(True)+ panel.setCanChooseDirectories_(False)+ panel.setAllowsMultipleSelection_(False)+ if hasattr(panel, "setAllowedFileTypes_"):+ panel.setAllowedFileTypes_(["json"])+ if panel.runModal() != 1:+ return None+ url = panel.URL()+ if url is None:+ return None+ return Path(str(url.path()))++def choose_terminal_app() -> Path | None:panel = NSOpenPanel.openPanel()panel.setTitle_("Choose Terminal App")@@ -3216,8 +4113,8 @@ def rect_parts(rect) -> tuple[float, float, float, float]:def build_settings_window(target: StatusBarController) -> NSWindow:- width = 680- height = 560+ width = SETTINGS_WINDOW_WIDTH+ height = SETTINGS_WINDOW_HEIGHTstyle = (NSWindowStyleMaskTitled| NSWindowStyleMaskClosable@@ -3235,20 +4132,23 @@ def build_settings_window(target: StatusBarController) -> NSWindow:content = window.contentView()tab_width = width - 40- tab_height = height - 84- tab_view = NSTabView.alloc().initWithFrame_(((20, 54), (tab_width, tab_height)))+ tab_height = height - SETTINGS_TAB_Y - SETTINGS_TAB_TOP_MARGIN+ tab_view = NSTabView.alloc().initWithFrame_(+ ((20, SETTINGS_TAB_Y), (tab_width, tab_height))+ )+ tab_view.setDelegate_(target)agents_tab = add_settings_tab(tab_view, "agents", "Agents", tab_width, tab_height)devices_tab = add_settings_tab(tab_view,"devices",- "Devices & LEDs",+ "Devices",tab_width,tab_height,)- sleep_tab = add_settings_tab(+ animations_tab = add_settings_tab(tab_view,- "lid",- "Lid & Sleep",+ "animations",+ "Animations",tab_width,tab_height,)@@ -3275,6 +4175,8 @@ def build_settings_window(target: StatusBarController) -> NSWindow:)content.addSubview_(tab_view)+ agent_animations_tab = animations_tab+add_label(agents_tab, "Agent Hooks", 24, 398, 200, 24)add_label(agents_tab, "Codex", 32, 360, 80, 22)codex_status = add_label(agents_tab, "", 130, 360, 240, 22)@@ -3350,21 +4252,124 @@ def build_settings_window(target: StatusBarController) -> NSWindow:"setBatteryPowerPreviewFromCheckbox:",)- add_label(sleep_tab, "Lid Closed", 24, 398, 120, 22)- add_label(sleep_tab, "Duration", 516, 398, 70, 22)- closed_duration = add_editable_field(sleep_tab, "", 588, 396, 48, 24)- closed_program = add_text_view(sleep_tab, "", 24, 276, 612, 110)- add_button(sleep_tab, "Preview", 24, 236, 90, 28, target, "previewLidClosedAnimation:")- add_button(sleep_tab, "Reset", 124, 236, 90, 28, target, "resetLidClosedAnimation:")-- add_separator(sleep_tab, 24, 210, tab_width - 48)- add_label(sleep_tab, "Lid Open", 24, 176, 120, 22)- add_label(sleep_tab, "Duration", 516, 176, 70, 22)- open_duration = add_editable_field(sleep_tab, "", 588, 174, 48, 24)- open_program = add_text_view(sleep_tab, "", 24, 54, 612, 110)- add_button(sleep_tab, "Preview", 24, 14, 90, 28, target, "previewLidOpenAnimation:")- add_button(sleep_tab, "Reset", 124, 14, 90, 28, target, "resetLidOpenAnimation:")- add_button(sleep_tab, "Save Animations", 490, 14, 146, 28, target, "saveLidAnimations:")+ add_label(agent_animations_tab, "Profile", 32, 360, 56, 24)+ animation_profile = add_agent_animation_profile_popup(+ agent_animations_tab,+ 88,+ 360,+ target,+ )+ add_button(+ agent_animations_tab,+ "Save Profile…",+ 288,+ 359,+ 112,+ 28,+ target,+ "showAgentAnimationProfileEditor:",+ )+ delete_animation_profile = add_button(+ agent_animations_tab,+ "Delete",+ 408,+ 359,+ 82,+ 28,+ target,+ "deleteAgentAnimationProfile:",+ )+ selected_profile_id = getattr(+ target,+ "selected_agent_animation_profile_id",+ AGENT_ANIMATION_PROFILE_CUSTOM,+ )+ target_settings = getattr(target, "settings", AgentMonitorSettings())+ delete_animation_profile.setEnabled_(+ selected_profile_id in target_settings.agent_animation_profiles+ and selected_profile_id not in AGENT_ANIMATION_BUILT_IN_PROFILE_IDS+ )+ add_button(+ agent_animations_tab,+ "Export JSON",+ 32,+ 321,+ 110,+ 28,+ target,+ "exportAgentAnimationProfile:",+ )+ add_button(+ agent_animations_tab,+ "Import JSON",+ 150,+ 321,+ 110,+ 28,+ target,+ "importAgentAnimationProfile:",+ )+ add_button(+ agent_animations_tab,+ "Add Custom…",+ 492,+ 321,+ 138,+ 28,+ target,+ "addCustomAgentAnimation:",+ )+ add_label(agent_animations_tab, "State", 24, 287, 178, 24)+ add_label(agent_animations_tab, "Animation", 210, 287, 190, 24)+ add_label(agent_animations_tab, "Live Preview", 410, 287, 90, 24)+ add_label(agent_animations_tab, "Actions", 510, 287, 126, 24)+ animation_popups = {}+ animation_previews = {}+ for index, mode_value in enumerate(ANIMATION_UI_STATES):+ row_y = 253 - index * 28+ add_label(+ agent_animations_tab,+ ANIMATION_STATE_LABELS[mode_value],+ 24,+ row_y + 2,+ 178,+ 22,+ )+ animation_popups[mode_value] = add_agent_animation_popup(+ agent_animations_tab,+ mode_value,+ 210,+ row_y,+ target,+ )+ preview = VirtualLedView.alloc().initWithFrame_(+ ((410, row_y - 1), (90, 28))+ )+ preview.setCompactPreview_(True)+ agent_animations_tab.addSubview_(preview)+ animation_previews[mode_value] = preview+ show_button = add_button(+ agent_animations_tab,+ "Show",+ 510,+ row_y - 1,+ 58,+ 28,+ target,+ "showAgentAnimationOnDevice:",+ )+ show_button.setRepresentedObject_(mode_value)+ edit_button = add_button(+ agent_animations_tab,+ "Edit",+ 574,+ row_y - 1,+ 62,+ 28,+ target,+ "editAgentAnimation:",+ )+ edit_button.setRepresentedObject_(mode_value)add_label(behavior_tab, "Agent List", 24, 398, 240, 24)add_label(behavior_tab, "Keep last 10 sessions for", 32, 356, 180, 22)@@ -3404,7 +4409,7 @@ def build_settings_window(target: StatusBarController) -> NSWindow:add_label(diagnostics_tab, "Settings File", 24, 246, 240, 24)settings_path = add_label(diagnostics_tab, "", 32, 208, 588, 22)- message = add_label(content, "", 24, 22, width - 48, 22)+ message = add_label(content, "", 24, 12, width - 48, 22)target.settings_fields = {"codex_hook_status": codex_status,@@ -3416,28 +4421,214 @@ def build_settings_window(target: StatusBarController) -> NSWindow:"grok_session_opener": grok_opener,"session_terminal": terminal_popup,"custom_terminal_path": custom_terminal_path,- "closed_animation_program": closed_program,- "closed_animation_duration": closed_duration,- "open_animation_program": open_program,- "open_animation_duration": open_duration,"recent_session_retention_hours": retention_hours,"idle_timeout_minutes": idle_minutes,"sleep_prevention_min_battery_percent": min_battery_percent,"status_history_timeframe": history_timeframe,"status_history_status": history_status,"status_history_chart": history_chart,+ "agent_animation_profile": animation_profile,"message": message,"settings_path": settings_path,+ **{+ f"agent_animation_{mode}": popup+ for mode, popup in animation_popups.items()+ },+ **{+ f"agent_animation_preview_{mode}": preview+ for mode, preview in animation_previews.items()+ },}target.settings_buttons = {"codex_transcripts": codex_transcripts,"claude_transcripts": claude_transcripts,"battery_leds": battery_leds,"battery_power_preview": battery_power_preview,+ "delete_agent_animation_profile": delete_animation_profile,}return window+def build_agent_animation_editor_window(target: StatusBarController) -> NSWindow:+ install_standard_edit_menu()+ width = 640+ height = 400+ style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable+ window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(+ ((0, 0), (width, height)),+ style,+ NSBackingStoreBuffered,+ False,+ )+ window.setTitle_("Custom Agent Animation")+ window.setReleasedWhenClosed_(False)+ window.center()+ content = window.contentView()+ add_label(content, "Name", 20, 354, 70, 24)+ target.agent_animation_editor_name = add_editable_field(+ content,+ "",+ 90,+ 352,+ 530,+ 24,+ )+ add_label(+ content,+ "Enter a LEDS.LED program (maximum 512 bytes and 20 lines).",+ 20,+ 316,+ 600,+ 24,+ )+ add_label(content, "Live Preview", 20, 274, 90, 24)+ target.agent_animation_editor_preview = VirtualLedView.alloc().initWithFrame_(+ ((116, 272), (220, 28))+ )+ target.agent_animation_editor_preview.setCompactPreview_(True)+ content.addSubview_(target.agent_animation_editor_preview)+ target.agent_animation_editor_preview_status = add_label(+ content,+ "Updates as you type",+ 350,+ 274,+ 270,+ 24,+ )+ target.agent_animation_editor_preview_status.setTextColor_(+ NSColor.secondaryLabelColor()+ )+ target.agent_animation_editor_program = add_text_view(+ content,+ "",+ 20,+ 70,+ 600,+ 190,+ )+ target.agent_animation_editor_program.setDelegate_(target)+ add_button(+ content,+ "Show on Device",+ 20,+ 22,+ 150,+ 30,+ target,+ "showAgentAnimationEditorOnDevice:",+ )+ add_button(+ content,+ "Cancel",+ 420,+ 22,+ 90,+ 30,+ target,+ "cancelAgentAnimationCustom:",+ )+ add_button(+ content,+ "Save",+ 520,+ 22,+ 100,+ 30,+ target,+ "saveAgentAnimationCustom:",+ )+ return window+++STANDARD_EDIT_MENU_ITEMS = (+ ("Cut", "cut:", "x"),+ ("Copy", "copy:", "c"),+ ("Paste", "paste:", "v"),+ ("Select All", "selectAll:", "a"),+)+++def install_standard_edit_menu(app=None) -> NSMenu | None:+ """Install first-responder text shortcuts for the accessory application."""+ application = app or NSApp+ if application is None:+ return None+ main_menu = application.mainMenu()+ if main_menu is None:+ main_menu = NSMenu.alloc().initWithTitle_("Main Menu")+ application.setMainMenu_(main_menu)++ for index in range(main_menu.numberOfItems()):+ existing = main_menu.itemAtIndex_(index).submenu()+ if existing is not None and str(existing.title()) == "Edit":+ return existing++ edit_menu = NSMenu.alloc().initWithTitle_("Edit")+ edit_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Edit",+ None,+ "",+ )+ edit_item.setSubmenu_(edit_menu)+ main_menu.addItem_(edit_item)+ for title, action, key in STANDARD_EDIT_MENU_ITEMS:+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ title,+ action,+ key,+ )+ edit_menu.addItem_(item)+ return edit_menu+++def build_agent_animation_profile_editor_window(+ target: StatusBarController,+) -> NSWindow:+ width = 420+ height = 150+ style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable+ window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(+ ((0, 0), (width, height)),+ style,+ NSBackingStoreBuffered,+ False,+ )+ window.setTitle_("Save Animation Profile")+ window.setReleasedWhenClosed_(False)+ window.center()+ content = window.contentView()+ add_label(content, "Profile Name", 20, 98, 100, 24)+ target.agent_animation_profile_editor_name = add_editable_field(+ content,+ "",+ 122,+ 96,+ 278,+ 24,+ )+ add_button(+ content,+ "Cancel",+ 220,+ 30,+ 82,+ 30,+ target,+ "cancelAgentAnimationProfile:",+ )+ add_button(+ content,+ "Save",+ 312,+ 30,+ 88,+ 30,+ target,+ "saveAgentAnimationProfile:",+ )+ return window++def add_settings_tab(tab_view, identifier: str, title: str, width: int, height: int):item = NSTabViewItem.alloc().initWithIdentifier_(identifier)item.setLabel_(title)@@ -3498,6 +4689,167 @@ def add_checkbox(return checkbox+def add_agent_animation_popup(parent, state: str, x: int, y: int, target):+ popup = NSPopUpButton.alloc().initWithFrame_pullsDown_(+ ((x, y), (190, 26)), False+ )+ popup.setTarget_(target)+ popup.setAction_("setAgentAnimationStyle:")+ refresh_agent_animation_popup(+ popup,+ state,+ getattr(target, "settings", AgentMonitorSettings()),+ getattr(target, "settings", AgentMonitorSettings()).agent_animation_id(state),+ )+ parent.addSubview_(popup)+ return popup+++def agent_animation_label(settings: AgentMonitorSettings, animation_id: str) -> str:+ built_in = {+ AGENT_ANIMATION_SLOW_OFF: "Slow Off",+ AGENT_ANIMATION_IMMEDIATE_OFF: "Immediate Off",+ AGENT_ANIMATION_IDLE_PULSE: "Idle Pulse",+ AGENT_ANIMATION_CYAN_ROLL: "Cyan Roll",+ AGENT_ANIMATION_CYAN_COMPLETE: "Cyan Complete",+ AGENT_ANIMATION_AMBER_PULSE: "Amber Pulse",+ AGENT_ANIMATION_SOLID_GREEN: "Solid Green",+ AGENT_ANIMATION_KITT: "KITT Scanner",+ AGENT_ANIMATION_KITT_RED: "KITT Scanner Red",+ AGENT_ANIMATION_EMBER_IDLE: "Ember Idle",+ AGENT_ANIMATION_EMBER_TIDE: "Ember Tide",+ AGENT_ANIMATION_EMBER_ATTENTION: "Ember Attention",+ AGENT_ANIMATION_EMBER_COMPLETE: "Ember Complete",+ AGENT_ANIMATION_EMBER_LID_OPEN: "Ember Lid Open",+ AGENT_ANIMATION_PURPLE_IDLE: "Purple Idle",+ AGENT_ANIMATION_PURPLE_TIDE: "Purple Tide",+ AGENT_ANIMATION_PURPLE_ATTENTION: "Purple Attention",+ AGENT_ANIMATION_PURPLE_COMPLETE: "Purple Complete",+ AGENT_ANIMATION_PURPLE_LID_OPEN: "Purple Lid Open",+ AGENT_ANIMATION_NIGHT_RIDER: "Night Rider",+ AGENT_ANIMATION_LID_OPEN: "Lid Open Sweep",+ AGENT_ANIMATION_LID_CLOSED: "Lid Closed Sweep",+ }.get(animation_id)+ if built_in is not None:+ return built_in+ custom = settings.custom_agent_animations.get(animation_id)+ return custom.name if custom is not None else "Default"+++def refresh_agent_animation_popup(+ popup,+ state: str,+ settings: AgentMonitorSettings,+ selected_animation_id: str,+) -> None:+ popup.removeAllItems()+ for animation_id in settings.agent_animation_choices():+ label = agent_animation_label(settings, animation_id)+ popup.addItemWithTitle_(label)+ item = popup.lastItem()+ item.setRepresentedObject_(+ {"mode": state, "animation_id": animation_id}+ )+ menu_view = AgentAnimationMenuItemView.alloc().initWithFrame_(+ ((0, 0), (204, 32))+ )+ menu_view.configurePopup_mode_animation_label_program_(+ popup,+ state,+ animation_id,+ label,+ agent_animation_catalog_program(settings, state, animation_id),+ )+ item.setView_(menu_view)+ popup.menu().addItem_(NSMenuItem.separatorItem())+ popup.addItemWithTitle_("Add Custom…")+ popup.lastItem().setRepresentedObject_(+ {"mode": state, "animation_id": AGENT_ANIMATION_ADD_CUSTOM}+ )+ for index in range(popup.numberOfItems()):+ payload = popup.itemAtIndex_(index).representedObject()+ if (+ isinstance(payload, dict)+ and payload.get("animation_id") == selected_animation_id+ ):+ popup.selectItemAtIndex_(index)+ return+ popup.selectItemAtIndex_(0)+++def agent_animation_catalog_program(+ settings: AgentMonitorSettings,+ state: str,+ animation_id: str,+) -> str:+ selected = settings.with_agent_animation(state, animation_id)+ animation = selected.agent_animation(state)+ mode = AgentMode(state) if state in AGENT_ANIMATION_MODES else AgentMode.IDLE_READY+ return program_for_agent_mode(+ mode,+ led_count=8,+ animation_style=animation.style,+ custom_program=animation.custom_program,+ )+++def animation_state_program(+ settings: AgentMonitorSettings,+ state: str,+ *,+ led_count: int = 8,+) -> str:+ animation = settings.agent_animation(state)+ mode = AgentMode(state) if state in AGENT_ANIMATION_MODES else AgentMode.IDLE_READY+ return program_for_agent_mode(+ mode,+ led_count=led_count,+ animation_style=animation.style,+ custom_program=animation.custom_program,+ )+++def add_agent_animation_profile_popup(parent, x: int, y: int, target):+ popup = NSPopUpButton.alloc().initWithFrame_pullsDown_(+ ((x, y), (190, 26)), False+ )+ popup.setTarget_(target)+ popup.setAction_("applyAgentAnimationProfile:")+ refresh_agent_animation_profile_popup(+ popup,+ getattr(target, "settings", AgentMonitorSettings()),+ getattr(target, "selected_agent_animation_profile_id", ""),+ )+ parent.addSubview_(popup)+ return popup+++def refresh_agent_animation_profile_popup(+ popup,+ settings: AgentMonitorSettings,+ selected_profile_id: str = AGENT_ANIMATION_PROFILE_CUSTOM,+) -> None:+ popup.removeAllItems()+ popup.addItemWithTitle_("Current")+ popup.lastItem().setRepresentedObject_(AGENT_ANIMATION_PROFILE_CUSTOM)+ for profile_id, profile in sorted(+ settings.agent_animation_profiles.items(),+ key=lambda item: (item[1].name.casefold(), item[0]),+ ):+ popup.addItemWithTitle_(profile.name)+ popup.lastItem().setRepresentedObject_(profile_id)++ selected = (+ selected_profile_id+ if selected_profile_id in settings.agent_animation_profiles+ else AGENT_ANIMATION_PROFILE_CUSTOM+ )+ for index in range(popup.numberOfItems()):+ if str(popup.itemAtIndex_(index).representedObject()) == selected:+ popup.selectItemAtIndex_(index)+ return++def add_provider_opener_popup(parent, provider: str, x: int, y: int, target):popup = NSPopUpButton.alloc().initWithFrame_pullsDown_(((x, y), (180, 26)), False@@ -3717,7 +5069,9 @@ def add_text_view(parent, text: str, x: int, y: int, width: int, height: int):scroll = NSScrollView.alloc().initWithFrame_(((x, y), (width, height)))scroll.setHasVerticalScroller_(True)scroll.setHasHorizontalScroller_(False)- text_view = NSTextView.alloc().initWithFrame_(((0, 0), (width, height)))+ text_view = AnimationProgramTextView.alloc().initWithFrame_(+ ((0, 0), (width, height))+ )text_view.setString_(text)text_view.setVerticallyResizable_(True)text_view.setHorizontallyResizable_(False)@@ -3817,6 +5171,12 @@ def validate_lid_animation(animation: LedAnimationSetting) -> None:normalize_animation_duration(animation.duration_seconds)+def validate_agent_animation_program(program: str) -> None:+ normalized = normalize_led_text(program)+ validate_led_text(normalized)+ validate_led_text(apply_brightness(normalized, 1))++def program_for_lid_animation(animation: LedAnimationSetting,*,@@ -3885,7 +5245,7 @@ def device_mount_key(root: Path) -> str:def device_display_name(name: str) -> str:normalized = normalized_device_name(name)- if "sidepulsedot" in normalized:+ if "sidepulsedot" in normalized or "pulsedot" in normalized:return "SidePulse Dot"if "sidepulsepro" in normalized:return "SidePulse Pro"diff --git a/src/sidepulse/virtual_device.py b/src/sidepulse/virtual_device.pyindex d58d132..ea21d44 100644--- a/src/sidepulse/virtual_device.py+++ b/src/sidepulse/virtual_device.py@@ -1,6 +1,7 @@from __future__ import annotationsimport math+import reimport timeimport objc@@ -223,6 +224,21 @@ def current_cg_context():return None+def compact_preview_program(program: str) -> str:+ """Loop one-shot programs in compact previews without changing the source."""+ source = str(program)+ if any(line.strip().casefold() == "repeat" for line in source.splitlines()):+ return source+ colors = re.findall(r"#[0-9a-fA-F]{6}", source)+ if len(colors) >= 2 and all(color.casefold() == "#000000" for color in colors):+ # A shutdown transition depends on the physical LEDs' current pixels.+ # Seed compact previews with the working cyan so the outside-in fade is+ # visible without adding a color command to the real device program.+ source = f"#00E5FF\n{source}"+ stripped = source.rstrip()+ return f"{stripped}\nrepeat" if stripped else "repeat"++class VirtualLedView(NSView):def initWithFrame_(self, frame):self = objc.super(VirtualLedView, self).initWithFrame_(frame)@@ -232,15 +248,28 @@ class VirtualLedView(NSView):self.started_at = time.monotonic()self.fixed_colors = Noneself.current_program = None+ self.rendered_program = Noneself.wasm_controller = Noneself.wasm_error = Noneself.has_notch = True+ self.compact_preview = Falsereturn selfdef setHasNotch_(self, has_notch):self.has_notch = bool(has_notch)self.setNeedsDisplay_(True)+ def setCompactPreview_(self, compact_preview):+ compact_preview = bool(compact_preview)+ if compact_preview != self.compact_preview and self.current_program is not None:+ current_program = self.current_program+ self.current_program = None+ self.compact_preview = compact_preview+ self.setProgram_(current_program)+ return+ self.compact_preview = compact_preview+ self.setNeedsDisplay_(True)+def setState_brightness_(self, state, brightness):if state != self.state:self.started_at = time.monotonic()@@ -256,21 +285,33 @@ class VirtualLedView(NSView):)def setProgram_(self, program):- if program == self.current_program:+ source_program = str(program)+ rendered_program = (+ compact_preview_program(source_program)+ if self.compact_preview+ else source_program+ )+ if (+ source_program == self.current_program+ and rendered_program == self.rendered_program+ ):self.setNeedsDisplay_(True)return- self.current_program = str(program)+ self.current_program = source_program+ self.rendered_program = rendered_programself.fixed_colors = Noneself.started_at = time.monotonic()if self._ensure_wasm_controller():try:- self.wasm_controller.parse(self.current_program, monotonic_ms())+ self.wasm_controller.parse(self.rendered_program, monotonic_ms())+ self.wasm_error = Noneexcept Exception as exc:self.wasm_error = str(exc)self.setNeedsDisplay_(True)def setBatteryPercent_brightness_(self, percent, brightness):self.current_program = None+ self.rendered_program = Nonescale = normalize_brightness(brightness) / 255.0filled = max(0.0, min(8.0, float(percent) * 8.0 / 100.0))colors = []@@ -323,6 +364,65 @@ class VirtualLedView(NSView):colors = self._colors_for_draw()width = self.bounds().size.widthheight = self.bounds().size.height++ if self.compact_preview:+ pill_height = min(12.0, max(4.0, height - 4.0))+ pill_y = (height - pill_height) / 2.0+ pill_rect = ((0.0, pill_y), (width, pill_height))+ pill = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(+ pill_rect,+ pill_height / 2.0,+ pill_height / 2.0,+ )+ NSColor.colorWithCalibratedRed_green_blue_alpha_(+ 0.006, 0.007, 0.010, 0.94+ ).set()+ pill.fill()++ NSGraphicsContext.saveGraphicsState()+ pill.addClip()+ cg_context = current_cg_context()+ led_width = width / LED_COUNT+ column_x = 0.0+ while column_x < width:+ column_width = min(BLEND_COLUMN_WIDTH, width - column_x)+ sample_x = column_x + column_width / 2.0+ red, green, blue, alpha = blended_led_color_at_x(+ colors,+ sample_x,+ led_width,+ )+ fill_rect_with_cg(+ cg_context,+ ((column_x, pill_y), (column_width, pill_height)),+ tone_mapped_led_color(+ red,+ green,+ blue,+ alpha,+ boost=LED_CORE_BOOST,+ alpha_scale=0.88,+ ),+ )+ fill_rect_with_cg(+ cg_context,+ (+ (column_x, pill_y + pill_height * 0.38),+ (column_width, pill_height * 0.24),+ ),+ tone_mapped_led_color(+ red,+ green,+ blue,+ alpha,+ boost=LED_HOTLINE_BOOST,+ alpha_scale=0.54,+ ),+ )+ column_x += column_width+ NSGraphicsContext.restoreGraphicsState()+ return+body = notch_bar_path(((0.0, 0.0), (width, height)))# A MacBook gets the black camera-housing continuation. On a notchlessdiff --git a/tests/test_environment.py b/tests/test_environment.pyindex 80f8256..8ef29b3 100644--- a/tests/test_environment.py+++ b/tests/test_environment.py@@ -298,6 +298,7 @@ class CleanInstallTests(unittest.TestCase):for p in (REPO_ROOT / "src/sidepulse/resources").rglob("*")if p.is_file()and p.suffix != ".py"+ and not p.name.startswith(".")and "__pycache__" not in p.parts}self.assertTrue(source_resources, "expected packaged resource files")diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.pyindex 424b910..b555a97 100644--- a/tests/test_sidepulse.py+++ b/tests/test_sidepulse.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonimport osimport plistlib+import reimport subprocessimport sysimport tempfile@@ -44,6 +45,7 @@ from sidepulse.device_writer import (DeviceWriteError,discover_devices,normalize_led_text,+ read_led_program,validate_led_text,write_led_program,)@@ -63,8 +65,12 @@ from sidepulse.keep_awake import KeepAwakeController, status_file_for_targetfrom sidepulse.led_status import (AgentLedController,LedDisplayState,+ apply_brightness,+ builtin_animation_file_name,+ builtin_animation_program,display_state_for_mode,led_count_for_target,+ program_for_agent_mode,program_for_display_state,write_mode_to_leds,)@@ -115,6 +121,37 @@ from sidepulse.session_actions import (session_vscode_link,)from sidepulse.settings import (+ ANIMATION_STATE_LID_CLOSED,+ ANIMATION_STATE_LID_OPEN,+ ANIMATION_STATES,+ AGENT_ANIMATION_AMBER_PULSE,+ AGENT_ANIMATION_CYAN_COMPLETE,+ AGENT_ANIMATION_CYAN_ROLL,+ AGENT_ANIMATION_CUSTOM,+ AGENT_ANIMATION_DEFAULT,+ AGENT_ANIMATION_EMBER_ATTENTION,+ AGENT_ANIMATION_EMBER_COMPLETE,+ AGENT_ANIMATION_EMBER_IDLE,+ AGENT_ANIMATION_EMBER_LID_OPEN,+ AGENT_ANIMATION_EMBER_TIDE,+ AGENT_ANIMATION_IDLE_PULSE,+ AGENT_ANIMATION_KITT,+ AGENT_ANIMATION_KITT_RED,+ AGENT_ANIMATION_LID_CLOSED,+ AGENT_ANIMATION_LID_OPEN,+ AGENT_ANIMATION_NIGHT_RIDER,+ AGENT_ANIMATION_IMMEDIATE_OFF,+ AGENT_ANIMATION_SLOW_OFF,+ AGENT_ANIMATION_PROFILE_CYAN,+ AGENT_ANIMATION_PROFILE_EMBER,+ AGENT_ANIMATION_PROFILE_PURPLE,+ AGENT_ANIMATION_PURPLE_ATTENTION,+ AGENT_ANIMATION_PURPLE_COMPLETE,+ AGENT_ANIMATION_PURPLE_IDLE,+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ AGENT_ANIMATION_PURPLE_TIDE,+ AGENT_ANIMATION_SOLID_GREEN,+ AGENT_ANIMATION_WORKING_MODES,CLOSED_LID_AWAKE_AGENTS,CLOSED_LID_AWAKE_ALWAYS,CLOSED_LID_AWAKE_NEVER,@@ -139,11 +176,17 @@ from sidepulse.settings import (TERMINAL_APP_WEZTERM,AgentMonitorSettings,DeviceDisplaySetting,+ agent_animation_profile_document,+ agent_animation_profile_id,+ builtin_agent_animation_profiles,+ custom_agent_animation_id,+ default_agent_animation_id,default_config_dir,default_lid_animation,default_settings_path,load_settings,save_settings,+ with_imported_agent_animation_profile,)from sidepulse.status_bar_launch import (LAUNCH_AGENT_LABEL,@@ -832,6 +875,29 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(virtual_device.FRAME_RATE, 60.0)self.assertAlmostEqual(virtual_device.FRAME_INTERVAL, 1.0 / 60.0)+ def test_compact_preview_loops_one_shot_program_without_changing_loops(self) -> None:+ try:+ from sidepulse import virtual_device+ except (ImportError, SystemExit) as exc:+ self.skipTest(str(exc))++ one_shot = "off 90ms\n#00E5FF 180ms ease\noff 320ms"+ self.assertEqual(+ virtual_device.compact_preview_program(one_shot),+ f"{one_shot}\nrepeat",+ )+ looping = "#00E5FF 180ms ease\nrepeat"+ self.assertEqual(virtual_device.compact_preview_program(looping), looping)++ shutdown = (+ "0:#000000 75ms ease; 7:#000000 75ms ease\n"+ "1:#000000 75ms ease; 6:#000000 75ms ease"+ )+ shutdown_preview = virtual_device.compact_preview_program(shutdown)+ self.assertTrue(shutdown_preview.startswith("#00E5FF\n"))+ self.assertTrue(shutdown_preview.endswith("\nrepeat"))+ self.assertNotIn("#00E5FF", shutdown)+def test_led_wasm_controller_uses_packaged_firmware_engine(self) -> None:try:from sidepulse.led_wasm import LedWasmUnavailableError, SdLedWasmController@@ -864,6 +930,44 @@ class AgentMonitorTests(unittest.TestCase):self.assertTrue(result.ok)self.assertEqual(controller.step(0), [(255, 0, 0), (0, 255, 0)])+ def test_core_animation_programs_transition_from_current_pixels(self) -> None:+ try:+ from sidepulse.led_wasm import LedWasmUnavailableError, SdLedWasmController+ except ImportError as exc:+ self.skipTest(str(exc))++ try:+ controller = SdLedWasmController(led_count=8)+ except LedWasmUnavailableError as exc:+ self.skipTest(str(exc))++ controller.parse(builtin_animation_program("cyan-roll", 8), 0)+ working_pixels = controller.step(700)+ controller.parse(builtin_animation_program("solid-green", 8), 700)+ self.assertEqual(controller.step(700), working_pixels)+ transition_pixels = controller.step(860)+ self.assertNotEqual(transition_pixels, working_pixels)+ self.assertNotEqual(transition_pixels, [(0, 255, 102)] * 8)+ self.assertEqual(controller.step(1020), [(0, 255, 102)] * 8)++ controller.parse(builtin_animation_program("lid-closed", 8), 1020)+ green = (0, 255, 102)+ black = (0, 0, 0)+ self.assertEqual(controller.step(1020), [green] * 8)+ self.assertEqual(+ controller.step(1095),+ [black, green, green, green, green, green, green, black],+ )+ self.assertEqual(+ controller.step(1170),+ [black, black, green, green, green, green, black, black],+ )+ self.assertEqual(+ controller.step(1245),+ [black, black, black, green, green, black, black, black],+ )+ self.assertEqual(controller.step(1320), [black] * 8)+def test_virtual_screen_bar_led_blend_spans_three_leds(self) -> None:try:from sidepulse import virtual_device@@ -1748,6 +1852,63 @@ class AgentMonitorTests(unittest.TestCase):]self.assertEqual(len(tab_views), 1)self.assertEqual(tab_views[0].numberOfTabViewItems(), 6)+ animations_tab = next(+ tab_views[0].tabViewItemAtIndex_(index)+ for index in range(tab_views[0].numberOfTabViewItems())+ if str(tab_views[0].tabViewItemAtIndex_(index).identifier()) == "animations"+ )+ agent_animations = animations_tab.view()+ self.assertFalse(+ any(+ hasattr(view, "numberOfTabViewItems")+ for view in agent_animations.subviews()+ )+ )+ previews = [+ view+ for view in agent_animations.subviews()+ if isinstance(view, status_bar.VirtualLedView)+ ]+ self.assertEqual(len(previews), len(status_bar.ANIMATION_UI_STATES))+ show_buttons = [+ view+ for view in agent_animations.subviews()+ if hasattr(view, "title") and str(view.title()) == "Show"+ ]+ self.assertEqual(len(show_buttons), len(status_bar.ANIMATION_UI_STATES))+ self.assertEqual(+ {str(button.representedObject()) for button in show_buttons},+ set(status_bar.ANIMATION_UI_STATES),+ )+ edit_buttons = [+ view+ for view in agent_animations.subviews()+ if hasattr(view, "title") and str(view.title()) == "Edit"+ ]+ self.assertEqual(len(edit_buttons), len(status_bar.ANIMATION_UI_STATES))+ self.assertEqual(+ {str(button.representedObject()) for button in edit_buttons},+ set(status_bar.ANIMATION_UI_STATES),+ )+ labels = {+ str(view.stringValue())+ for view in agent_animations.subviews()+ if hasattr(view, "stringValue")+ }+ self.assertIn("Lid Open", labels)+ self.assertIn("Lid Closed", labels)+ self.assertIn("Working / Tool / Long Task", labels)+ self.assertNotIn("Tool Running", labels)+ self.assertNotIn("Long Task Progress", labels)+ self.assertNotIn("agent_animation_tool_running", target.settings_fields)+ self.assertNotIn("agent_animation_long_task_progress", target.settings_fields)+ self.assertNotIn(+ "lid",+ {+ str(tab_views[0].tabViewItemAtIndex_(index).identifier())+ for index in range(tab_views[0].numberOfTabViewItems())+ },+ )self.assertIn("debug_log_status", target.settings_fields)self.assertIn("status_history_status", target.settings_fields)self.assertIn("status_history_chart", target.settings_fields)@@ -1757,12 +1918,107 @@ class AgentMonitorTests(unittest.TestCase):self.assertIn("idle_timeout_minutes", target.settings_fields)self.assertIn("sleep_prevention_min_battery_percent", target.settings_fields)self.assertIn("status_history_timeframe", target.settings_fields)- self.assertIn("closed_animation_program", target.settings_fields)- self.assertIn("closed_animation_duration", target.settings_fields)- self.assertIn("open_animation_program", target.settings_fields)- self.assertIn("open_animation_duration", target.settings_fields)+ self.assertIn("agent_animation_lid_closed", target.settings_fields)+ self.assertIn("agent_animation_lid_open", target.settings_fields)+ for mode in status_bar.ANIMATION_UI_STATES:+ self.assertIn(f"agent_animation_{mode}", target.settings_fields)+ self.assertIn(+ f"agent_animation_preview_{mode}", target.settings_fields+ )self.assertNotIn("closed_lid_system_override", target.settings_buttons)+ def test_status_bar_validates_custom_agent_animation_program(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ status_bar.validate_agent_animation_program("off\n#FF0000 pulse\nrepeat")+ with self.assertRaises(DeviceWriteError):+ status_bar.validate_agent_animation_program("x" * 513)++ def test_animation_preview_timer_runs_while_menu_tracks_input(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ timer = object()+ modes = []+ run_loop = SimpleNamespace(+ addTimer_forMode_=lambda added_timer, mode: modes.append(+ (added_timer, mode)+ )+ )+ fake = SimpleNamespace(agent_animation_preview_timer=None)+ with (+ patch(+ "sidepulse.status_bar.NSTimer",+ SimpleNamespace(+ timerWithTimeInterval_target_selector_userInfo_repeats_=(+ lambda *args: timer+ )+ ),+ ),+ patch(+ "sidepulse.status_bar.NSRunLoop",+ SimpleNamespace(mainRunLoop=lambda: run_loop),+ ),+ ):+ status_bar.StatusBarController.start_agent_animation_preview_timer(fake)++ self.assertEqual(fake.agent_animation_preview_timer, timer)+ self.assertEqual(+ modes,+ [+ (timer, status_bar.NSRunLoopCommonModes),+ (timer, status_bar.NSEventTrackingRunLoopMode),+ ],+ )++ def test_status_bar_show_agent_animation_on_device_writes_and_restores(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "SidePulsePro"+ root.mkdir()+ device = status_bar.StatusBarDevice(+ device_id=str(root),+ name="SidePulse Pro",+ root=root,+ target=root / "LEDS.LED",+ connected=True,+ display="agent",+ )+ restore_calls = []+ fake = SimpleNamespace(+ performSelectorOnMainThread_withObject_waitUntilDone_=(+ lambda selector, value, wait: restore_calls.append(+ (selector, value, wait)+ )+ )+ )++ with patch("sidepulse.status_bar.time.sleep"):+ status_bar.StatusBarController.show_agent_animation_on_device_worker(+ fake,+ AgentMode.WORKING,+ AGENT_ANIMATION_KITT,+ "",+ [device],+ 17,+ )++ program = read_led_program(root / "LEDS.LED")+ self.assertIn("7:#00E5FF 320ms pulse 595ms", program)+ self.assertEqual(+ restore_calls,+ [("restoreLedDisplay:", "17", False)],+ )+def test_status_history_status_text_is_compact(self) -> None:try:from sidepulse import status_bar@@ -3339,6 +3595,13 @@ class AgentMonitorTests(unittest.TestCase):changed=False,backup_path=None,)+ cursor_result = SimpleNamespace(+ provider="cursor",+ config_path=Path("/tmp/cursor-hooks.json"),+ log_path=Path("/tmp/cursor.jsonl"),+ changed=True,+ backup_path=None,+ )grok_result = SimpleNamespace(provider="grok",config_path=Path("/tmp/grok-hook.json"),@@ -3365,6 +3628,11 @@ class AgentMonitorTests(unittest.TestCase):with (patch.object(cli_module, "install_codex_hooks", return_value=codex_result) as codex,patch.object(cli_module, "install_claude_hooks", return_value=claude_result) as claude,+ patch.object(+ cli_module,+ "install_cursor_hooks",+ return_value=cursor_result,+ ) as cursor,patch.object(cli_module, "install_grok_hooks", return_value=grok_result) as grok,patch("sidepulse.sd_eject_guard_launch.install_sd_eject_guard",@@ -3380,6 +3648,7 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(result, 0)codex.assert_called_once()claude.assert_called_once()+ cursor.assert_called_once()grok.assert_called_once()guard.assert_called_once_with(scope="auto", dry_run=False)launch.assert_called_once_with(start=True)@@ -3430,7 +3699,26 @@ class AgentMonitorTests(unittest.TestCase):)self.assertEqual(target, device / "LEDS.LED")- self.assertEqual(target.read_text(), "off\n#FF00FF pulse")+ self.assertEqual(read_led_program(target), "off\n#FF00FF pulse")+ self.assertEqual(target.stat().st_size, 512)++ def test_sidepulse_write_reuses_fixed_record_and_clears_old_tail(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ device = Path(tmp) / "SidePulsePro"+ device.mkdir()+ target = device / "LEDS.LED"+ target.write_bytes(b"old")++ write_led_program("off\n#FF00FF pulse", device_path=device)+ first_inode = target.stat().st_ino+ write_led_program("off", device_path=device)++ data = target.read_bytes()+ self.assertEqual(target.stat().st_ino, first_inode)+ self.assertEqual(len(data), 512)+ self.assertEqual(data[:3], b"off")+ self.assertEqual(data[3:], b" " * 509)+ self.assertEqual(read_led_program(target), "off")def test_sidepulse_write_uses_leds_led_even_when_old_file_exists(self) -> None:with tempfile.TemporaryDirectory() as tmp:@@ -3444,7 +3732,7 @@ class AgentMonitorTests(unittest.TestCase):)self.assertEqual(target, device / "LEDS.LED")- self.assertEqual(target.read_text(), "off\n#FF00FF pulse")+ self.assertEqual(read_led_program(target), "off\n#FF00FF pulse")self.assertEqual((device / "LEDS.TXT").read_text(), "off")def test_sidepulse_write_discovers_sidepulse_dot_volume(self) -> None:@@ -3520,7 +3808,7 @@ class AgentMonitorTests(unittest.TestCase):)self.assertEqual(result, 0)- self.assertEqual((device / "LEDS.LED").read_text(), "off\n#FF00FF pulse")+ self.assertEqual(read_led_program(device / "LEDS.LED"), "off\n#FF00FF pulse")def test_led_status_maps_agent_modes_to_programs(self) -> None:self.assertEqual(@@ -3542,14 +3830,17 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(program_for_display_state(LedDisplayState.IDLE),- "off\n#020204 6s pulse\nrepeat",+ "off 2s\n3:#006060 4:#006060 2s ease\nrepeat",+ )+ self.assertEqual(+ program_for_display_state(LedDisplayState.DONE),+ "#00FF66 320ms cosine",)- self.assertEqual(program_for_display_state(LedDisplayState.DONE), "#00FF66")self.assertIn("#FF3A00 1.6s pulse", program_for_display_state(LedDisplayState.ASK))self.assertEqual(program_for_display_state(LedDisplayState.WORKING, led_count=2).splitlines(),[- "off 160ms cosine",+ "off 320ms cosine","0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms","repeat",],@@ -3558,9 +3849,275 @@ class AgentMonitorTests(unittest.TestCase):len(program_for_display_state(LedDisplayState.WORKING, led_count=8).splitlines()),3,)+ kitt_program = program_for_agent_mode(+ AgentMode.WORKING,+ led_count=8,+ brightness=128,+ animation_style=AGENT_ANIMATION_KITT,+ )+ validate_led_text(kitt_program)+ self.assertLessEqual(len(kitt_program.encode("utf-8")), 512)+ self.assertIn("7:#00E5FF 320ms pulse 595ms", kitt_program)+ self.assertIn("6:#00E5FF 320ms pulse 0ms", kitt_program)+ red_kitt_program = program_for_agent_mode(+ AgentMode.WORKING,+ led_count=8,+ animation_style=AGENT_ANIMATION_KITT_RED,+ )+ validate_led_text(red_kitt_program)+ self.assertIn("7:#FF1800 320ms pulse 595ms", red_kitt_program)+ for mode in AgentMode:+ with self.subTest(kitt_mode=mode.value):+ validate_led_text(+ program_for_agent_mode(+ mode,+ animation_style=AGENT_ANIMATION_KITT,+ )+ )+ custom_program = program_for_agent_mode(+ AgentMode.COMPLETED,+ brightness=64,+ animation_style=AGENT_ANIMATION_CUSTOM,+ custom_program="off\\n#FF0000 pulse\\nrepeat",+ )+ self.assertEqual(+ custom_program,+ "brightness 64\noff\n#FF0000 pulse\nrepeat",+ )self.assertEqual(program_for_display_state(LedDisplayState.DONE, brightness=128),- "brightness 128\n#00FF66",+ "brightness 128\n#00FF66 320ms cosine",+ )++ def test_builtin_animation_programs_are_loaded_from_led_files(self) -> None:+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_SLOW_OFF, 2),+ "off 1s",+ )+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_SLOW_OFF, 8),+ "off 1s",+ )+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_IMMEDIATE_OFF, 2),+ "off",+ )+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_IMMEDIATE_OFF, 8),+ "off",+ )+ self.assertEqual(builtin_animation_file_name("idle-pulse", 2), "idle-pulse-2.LED")+ self.assertEqual(builtin_animation_file_name("idle-pulse", 8), "idle-pulse-8.LED")+ self.assertEqual(+ builtin_animation_program("idle-pulse", 8),+ "off 2s\n3:#006060 4:#006060 2s ease\nrepeat",+ )+ self.assertEqual(+ builtin_animation_program("idle-pulse", 2),+ "off 2s\n0:#006060 1:#006060 2s ease\nrepeat",+ )+ self.assertEqual(builtin_animation_file_name("cyan-roll", 2), "cyan-roll-2.LED")+ self.assertEqual(builtin_animation_file_name("cyan-roll", 8), "cyan-roll-8.LED")+ self.assertEqual(builtin_animation_file_name("cyan-roll", 5), "cyan-roll-8.LED")+ self.assertIn("1:#00E5FF", builtin_animation_program("cyan-roll", 2))+ self.assertNotIn("2:#00E5FF", builtin_animation_program("cyan-roll", 2))+ self.assertIn("7:#FF1800", builtin_animation_program("kitt-red", 8))+ self.assertEqual(+ builtin_animation_file_name("ember-tide", 2),+ "ember-tide-2.LED",+ )+ self.assertIn(+ "1:#F23819 760ms pulse 260ms",+ builtin_animation_program("ember-tide", 2),+ )+ self.assertIn(+ "7:#F23819 760ms pulse 665ms",+ builtin_animation_program("ember-tide", 8),+ )+ self.assertIn(+ "7:#FF1200 360ms pulse 630ms",+ builtin_animation_program("night-rider", 8),+ )+ self.assertEqual(+ builtin_animation_file_name(AGENT_ANIMATION_PURPLE_IDLE, 2),+ "purple-idle-2.LED",+ )+ self.assertIn(+ "2:#9F00FF 3:#FF00FF 4:#FF00FF 5:#9F009F 2s ease",+ builtin_animation_program(AGENT_ANIMATION_PURPLE_IDLE, 8),+ )+ self.assertIn(+ "1:#FF00FF 760ms pulse 260ms",+ builtin_animation_program(AGENT_ANIMATION_PURPLE_TIDE, 2),+ )+ self.assertIn(+ "#FF00FF 1.6s pulse",+ builtin_animation_program(AGENT_ANIMATION_PURPLE_ATTENTION, 8),+ )+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_PURPLE_COMPLETE, 8),+ "#FF00FF 320ms cosine",+ )+ self.assertIn(+ "#FF00FF 220ms ease",+ builtin_animation_program(AGENT_ANIMATION_PURPLE_LID_OPEN, 8),+ )++ def test_color_profiles_use_the_exact_cyan_animation_shapes(self) -> None:+ def without_colors(program: str) -> str:+ return re.sub(r"#[0-9A-Fa-f]{6}", "#COLOR", program)++ for led_count in (2, 8):+ cyan_idle_shape = without_colors(+ builtin_animation_program(AGENT_ANIMATION_IDLE_PULSE, led_count)+ )+ self.assertEqual(+ without_colors(+ builtin_animation_program(AGENT_ANIMATION_EMBER_IDLE, led_count)+ ),+ cyan_idle_shape,+ )+ if led_count == 2:+ self.assertEqual(+ without_colors(+ builtin_animation_program(+ AGENT_ANIMATION_PURPLE_IDLE,+ led_count,+ )+ ),+ cyan_idle_shape,+ )++ corresponding_animations = (+ (+ AGENT_ANIMATION_CYAN_ROLL,+ AGENT_ANIMATION_EMBER_TIDE,+ AGENT_ANIMATION_PURPLE_TIDE,+ ),+ (+ AGENT_ANIMATION_AMBER_PULSE,+ AGENT_ANIMATION_EMBER_ATTENTION,+ AGENT_ANIMATION_PURPLE_ATTENTION,+ ),+ (+ AGENT_ANIMATION_CYAN_COMPLETE,+ AGENT_ANIMATION_EMBER_COMPLETE,+ AGENT_ANIMATION_PURPLE_COMPLETE,+ ),+ (+ AGENT_ANIMATION_LID_OPEN,+ AGENT_ANIMATION_EMBER_LID_OPEN,+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ ),+ )+ for led_count in (2, 8):+ for cyan_id, ember_id, purple_id in corresponding_animations:+ cyan_shape = without_colors(+ builtin_animation_program(cyan_id, led_count)+ )+ with self.subTest(profile="Ember", animation=cyan_id, leds=led_count):+ self.assertEqual(+ without_colors(+ builtin_animation_program(ember_id, led_count)+ ),+ cyan_shape,+ )+ with self.subTest(profile="Purple", animation=cyan_id, leds=led_count):+ self.assertEqual(+ without_colors(+ builtin_animation_program(purple_id, led_count)+ ),+ cyan_shape,+ )++ def test_purple_profile_uses_ff00ff_for_every_colored_animation(self) -> None:+ purple_animations = (+ AGENT_ANIMATION_PURPLE_TIDE,+ AGENT_ANIMATION_PURPLE_ATTENTION,+ AGENT_ANIMATION_PURPLE_COMPLETE,+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ )+ for led_count in (2, 8):+ for animation_id in purple_animations:+ with self.subTest(animation=animation_id, leds=led_count):+ self.assertEqual(+ set(+ re.findall(+ r"#[0-9A-Fa-f]{6}",+ builtin_animation_program(animation_id, led_count),+ )+ ),+ {"#FF00FF"},+ )+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_PURPLE_IDLE, 2),+ "off 2s\n0:#FF00FF 1:#FF00FF 2s ease\nrepeat",+ )+ self.assertEqual(+ builtin_animation_program(AGENT_ANIMATION_PURPLE_IDLE, 8),+ "off 2s\n"+ "2:#9F00FF 3:#FF00FF 4:#FF00FF 5:#9F009F 2s ease\n"+ "repeat",+ )++ def test_ember_profile_uses_f23819_for_every_colored_animation(self) -> None:+ ember_animations = (+ AGENT_ANIMATION_EMBER_IDLE,+ AGENT_ANIMATION_EMBER_TIDE,+ AGENT_ANIMATION_EMBER_ATTENTION,+ AGENT_ANIMATION_EMBER_COMPLETE,+ AGENT_ANIMATION_EMBER_LID_OPEN,+ )+ for led_count in (2, 8):+ for animation_id in ember_animations:+ with self.subTest(animation=animation_id, leds=led_count):+ self.assertEqual(+ set(+ re.findall(+ r"#[0-9A-Fa-f]{6}",+ builtin_animation_program(animation_id, led_count),+ )+ ),+ {"#F23819"},+ )++ def test_core_state_transitions_and_lid_close_outside_in_program(self) -> None:+ completed = builtin_animation_program("solid-green", 8)+ working = builtin_animation_program("cyan-roll", 8)+ lid_closed = builtin_animation_program("lid-closed", 8)++ self.assertEqual(completed, "#00FF66 320ms cosine")+ self.assertTrue(working.startswith("off 320ms cosine\n"))+ self.assertEqual(+ lid_closed.splitlines(),+ [+ "0:#000000 75ms ease; 7:#000000 75ms ease",+ "1:#000000 75ms ease; 6:#000000 75ms ease",+ "2:#000000 75ms ease; 5:#000000 75ms ease",+ "3:#000000 75ms ease; 4:#000000 75ms ease",+ "#000000 1s",+ ],+ )+ self.assertEqual(+ builtin_animation_program("lid-closed", 2),+ "0:#000000 300ms ease; 1:#000000 300ms ease\n#000000 1s",+ )+ self.assertEqual(+ default_lid_animation(LID_ANIMATION_CLOSED).duration_seconds,+ 1.3,+ )++ def test_device_brightness_multiplies_authored_file_brightness(self) -> None:+ self.assertEqual(+ apply_brightness("brightness 128\n#FF0000", 128),+ "brightness 64\n#FF0000",+ )+ self.assertEqual(+ apply_brightness(+ "brightness 200\n#FF0000\nbrightness 100\n#00FF00",+ 64,+ ),+ "brightness 50\n#FF0000\nbrightness 25\n#00FF00",)def test_write_mode_to_leds_uses_device_specific_program(self) -> None:@@ -3573,8 +4130,8 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(result.state, LedDisplayState.WORKING)self.assertEqual(result.target, device / "LEDS.LED")self.assertEqual(- (device / "LEDS.LED").read_text(),- "off 160ms cosine\n"+ read_led_program(device / "LEDS.LED"),+ "off 320ms cosine\n""0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms\n""repeat",)@@ -3582,16 +4139,20 @@ class AgentMonitorTests(unittest.TestCase):write_mode_to_leds(AgentMode.IDLE_READY, device_path=device)self.assertEqual(- (device / "LEDS.LED").read_text(),- "off\n#020204 6s pulse\nrepeat",+ read_led_program(device / "LEDS.LED"),+ "off 2s\n0:#006060 1:#006060 2s ease\nrepeat",)write_mode_to_leds(AgentMode.COMPLETED, device_path=device, brightness=64)- self.assertEqual((device / "LEDS.LED").read_text(), "brightness 64\n#00FF66")+ self.assertEqual(+ read_led_program(device / "LEDS.LED"),+ "brightness 64\n#00FF66 320ms cosine",+ )def test_led_count_uses_product_name(self) -> None:self.assertEqual(led_count_for_target(Path("/Volumes/SidePulseDot/LEDS.LED")), 2)+ self.assertEqual(led_count_for_target(Path("/Volumes/PulseDot/LEDS.LED")), 2)self.assertEqual(led_count_for_target(Path("/Volumes/SidePulsePro/LEDS.LED")), 8)def test_sidepulse_working_program_uses_eight_leds(self) -> None:@@ -3601,9 +4162,9 @@ class AgentMonitorTests(unittest.TestCase):write_mode_to_leds(AgentMode.WORKING, device_path=device)- lines = (device / "LEDS.LED").read_text().splitlines()+ lines = read_led_program(device / "LEDS.LED").splitlines()self.assertEqual(len(lines), 3)- self.assertEqual(lines[0], "off 160ms cosine")+ self.assertEqual(lines[0], "off 320ms cosine")self.assertIn("0:#00E5FF 760ms pulse 0ms", lines[1])self.assertIn("5:#00E5FF 760ms pulse 475ms", lines[1])self.assertIn("7:#00E5FF 760ms pulse 665ms", lines[1])@@ -3622,7 +4183,58 @@ class AgentMonitorTests(unittest.TestCase):self.assertTrue(first.changed)self.assertFalse(second.changed)self.assertTrue(third.changed)- self.assertIn("#FF3A00 1.6s pulse", (device / "LEDS.LED").read_text())+ self.assertIn("#FF3A00 1.6s pulse", read_led_program(device / "LEDS.LED"))++ def test_agent_led_controller_repairs_externally_changed_program(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ device = Path(tmp) / "SidePulsePro"+ device.mkdir()+ controller = AgentLedController(device_path=device, brightness=211)++ first = controller.sync_mode(+ AgentMode.WORKING,+ animation_style=AGENT_ANIMATION_PURPLE_TIDE,+ )+ target = device / "LEDS.LED"+ target.write_text("off 2s\n3:#006060 4:#006060 2s ease\nrepeat")++ repaired = controller.sync_mode(+ AgentMode.WORKING,+ animation_style=AGENT_ANIMATION_PURPLE_TIDE,+ )++ self.assertTrue(repaired.changed)+ self.assertEqual(read_led_program(target), first.program)++ def test_agent_led_controller_tracks_mode_and_animation_choice(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ device = Path(tmp) / "SidePulsePro"+ device.mkdir()+ controller = AgentLedController(device_path=device)++ default = controller.sync_mode(AgentMode.WORKING)+ same_default = controller.sync_mode(AgentMode.TOOL_RUNNING)+ kitt = controller.sync_mode(+ AgentMode.WORKING,+ animation_style=AGENT_ANIMATION_KITT,+ )+ custom_tool = controller.sync_mode(+ AgentMode.TOOL_RUNNING,+ animation_style=AGENT_ANIMATION_CUSTOM,+ custom_program="#123456",+ )+ unchanged = controller.sync_mode(+ AgentMode.TOOL_RUNNING,+ animation_style=AGENT_ANIMATION_CUSTOM,+ custom_program="#123456",+ )++ self.assertTrue(default.changed)+ self.assertFalse(same_default.changed)+ self.assertTrue(kitt.changed)+ self.assertTrue(custom_tool.changed)+ self.assertFalse(unchanged.changed)+ self.assertEqual(read_led_program(device / "LEDS.LED"), "#123456")def test_battery_parser_uses_adapter_watts_and_raw_capacity(self) -> None:payload = plistlib.dumps(@@ -3858,6 +4470,209 @@ class AgentMonitorTests(unittest.TestCase):closed_lid_awake_should_hold(CLOSED_LID_AWAKE_ALWAYS, agents_active=False))+ def test_lid_close_holds_final_led_state_only_when_sleep_is_allowed(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ self.assertTrue(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=True,+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=False,+ )+ )+ self.assertFalse(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=True,+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=True,+ )+ )+ self.assertFalse(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=False,+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=False,+ )+ )+ self.assertFalse(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=True,+ sleep_prevention_policy=SLEEP_PREVENTION_ALWAYS,+ agents_active=False,+ )+ )+ self.assertTrue(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=True,+ sleep_prevention_policy=SLEEP_PREVENTION_ALWAYS,+ agents_active=False,+ battery_safeguard_active=True,+ )+ )+ self.assertTrue(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=True,+ sleep_prevention_policy=SLEEP_PREVENTION_NEVER,+ agents_active=True,+ )+ )+ self.assertFalse(+ status_bar.lid_closed_led_state_should_hold(+ lid_closed=True,+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=None,+ )+ )++ def test_lid_close_animation_runs_only_when_sleep_prevention_is_inactive(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ self.assertFalse(+ status_bar.lid_close_animation_should_run(+ sleep_prevention_policy=SLEEP_PREVENTION_ALWAYS,+ agents_active=False,+ )+ )+ self.assertFalse(+ status_bar.lid_close_animation_should_run(+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=True,+ )+ )+ self.assertFalse(+ status_bar.lid_close_animation_should_run(+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=None,+ )+ )+ self.assertTrue(+ status_bar.lid_close_animation_should_run(+ sleep_prevention_policy=SLEEP_PREVENTION_AGENTS,+ agents_active=False,+ )+ )+ self.assertTrue(+ status_bar.lid_close_animation_should_run(+ sleep_prevention_policy=SLEEP_PREVENTION_NEVER,+ agents_active=True,+ )+ )++ def test_lid_poll_enables_hold_on_close_and_clears_it_on_open(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ animations = []+ controller = status_bar.StatusBarController.alloc().init()+ controller.lid_poll_in_flight = True+ controller.pending_lid_error = None+ controller.pending_lid_closed = True+ controller.last_lid_error = None+ controller.lid_poll_backoff_until_monotonic = 0.0+ controller.last_lid_closed = False+ controller.lid_closed_led_hold_active = False++ with (+ patch("sidepulse.status_bar.log_status_bar"),+ patch.object(+ status_bar.StatusBarController,+ "should_run_lid_close_animation",+ return_value=True,+ ),+ patch.object(+ status_bar.StatusBarController,+ "should_hold_lid_closed_led_state",+ return_value=True,+ ),+ patch.object(+ status_bar.StatusBarController,+ "play_lid_animation",+ side_effect=lambda kind: animations.append(kind),+ ),+ ):+ controller.handleLidPollResult_(None)+ self.assertTrue(controller.lid_closed_led_hold_active)+ self.assertEqual(animations, [LID_ANIMATION_CLOSED])++ controller.pending_lid_closed = False+ controller.handleLidPollResult_(None)++ self.assertFalse(controller.lid_closed_led_hold_active)+ self.assertEqual(animations, [LID_ANIMATION_CLOSED, LID_ANIMATION_OPEN])++ def test_lid_poll_skips_close_animation_while_sleep_prevention_is_active(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ controller = status_bar.StatusBarController.alloc().init()+ controller.lid_poll_in_flight = True+ controller.pending_lid_error = None+ controller.pending_lid_closed = True+ controller.last_lid_error = None+ controller.lid_poll_backoff_until_monotonic = 0.0+ controller.last_lid_closed = False+ controller.lid_closed_led_hold_active = True++ with (+ patch("sidepulse.status_bar.log_status_bar"),+ patch.object(+ status_bar.StatusBarController,+ "should_run_lid_close_animation",+ return_value=False,+ ),+ patch.object(+ status_bar.StatusBarController,+ "play_lid_animation",+ ) as play_lid_animation,+ ):+ controller.handleLidPollResult_(None)++ self.assertTrue(controller.last_lid_closed)+ self.assertFalse(controller.lid_closed_led_hold_active)+ play_lid_animation.assert_not_called()++ def test_lid_close_hold_suppresses_refresh_until_conditions_change(self) -> None:+ try:+ from sidepulse import status_bar+ except SystemExit as exc:+ self.skipTest(str(exc))++ controller = status_bar.StatusBarController.alloc().init()+ controller.leds_enabled = True+ controller.lid_closed_led_hold_active = True+ controller.led_animation_until_monotonic = 0.0+ controller.led_sync_in_flight = False++ with (+ patch.object(controller, "sync_virtual_status_device"),+ patch.object(+ status_bar.StatusBarController,+ "should_hold_lid_closed_led_state",+ side_effect=[True, False],+ ),+ patch("sidepulse.status_bar.threading.Thread") as thread,+ patch("sidepulse.status_bar.log_status_bar"),+ ):+ controller.sync_leds(AgentMode.IDLE_READY, None, "agent")+ thread.assert_not_called()+ self.assertTrue(controller.lid_closed_led_hold_active)++ controller.sync_leds(AgentMode.WORKING, None, "agent")+ thread.assert_called_once()+ thread.return_value.start.assert_called_once()++ self.assertFalse(controller.lid_closed_led_hold_active)+def test_status_bar_sleep_prevention_never_releases_all_sleep_prevention(self) -> None:try:from sidepulse import status_bar@@ -4320,6 +5135,308 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(loaded.recent_session_retention_seconds, 36 * 60 * 60)self.assertEqual(loaded.idle_timeout_seconds, 15 * 60)+ def test_settings_round_trip_agent_animations(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ settings_path = Path(tmp) / "settings.json"+ settings = AgentMonitorSettings()+ settings = settings.with_agent_animation(+ AgentMode.WORKING,+ AGENT_ANIMATION_KITT,+ )+ settings = settings.with_agent_animation(+ AgentMode.BLOCKED_ERROR,+ AGENT_ANIMATION_CUSTOM,+ custom_program="off\n#FF0000 pulse\nrepeat",+ )++ save_settings(settings, settings_path)+ loaded = load_settings(settings_path)++ saved_json = json.loads(settings_path.read_text())+ custom_metadata = next(+ iter(saved_json["custom_agent_animations"].values())+ )+ self.assertNotIn("program", custom_metadata)+ custom_path = settings_path.parent / "animations" / custom_metadata["file"]+ self.assertEqual(+ custom_path.read_text(),+ "off\n#FF0000 pulse\nrepeat\n",+ )++ self.assertEqual(+ loaded.agent_animation(AgentMode.WORKING).style,+ AGENT_ANIMATION_KITT,+ )+ self.assertEqual(+ loaded.agent_animation(AgentMode.BLOCKED_ERROR).custom_program,+ "off\n#FF0000 pulse\nrepeat",+ )+ self.assertEqual(+ loaded.agent_animation(AgentMode.COMPLETED).style,+ AGENT_ANIMATION_CYAN_COMPLETE,+ )++ custom_path.write_text("brightness 128\n#123456\n")+ reloaded = load_settings(settings_path)+ self.assertEqual(+ reloaded.agent_animation(AgentMode.BLOCKED_ERROR).custom_program,+ "brightness 128\n#123456",+ )++ def test_agent_animation_catalog_is_shared_by_every_state(self) -> None:+ settings = AgentMonitorSettings()+ animation_id = custom_agent_animation_id(+ "Purple Sweep",+ settings.custom_agent_animations,+ )+ settings = settings.with_custom_agent_animation(+ animation_id,+ name="Purple Sweep",+ program="off\n#AA44FF 700ms pulse\nrepeat",+ )++ expected = (+ AGENT_ANIMATION_SLOW_OFF,+ AGENT_ANIMATION_IMMEDIATE_OFF,+ AGENT_ANIMATION_IDLE_PULSE,+ AGENT_ANIMATION_CYAN_ROLL,+ AGENT_ANIMATION_CYAN_COMPLETE,+ AGENT_ANIMATION_AMBER_PULSE,+ AGENT_ANIMATION_SOLID_GREEN,+ AGENT_ANIMATION_KITT,+ AGENT_ANIMATION_KITT_RED,+ AGENT_ANIMATION_EMBER_IDLE,+ AGENT_ANIMATION_EMBER_TIDE,+ AGENT_ANIMATION_EMBER_ATTENTION,+ AGENT_ANIMATION_EMBER_COMPLETE,+ AGENT_ANIMATION_EMBER_LID_OPEN,+ AGENT_ANIMATION_PURPLE_IDLE,+ AGENT_ANIMATION_PURPLE_TIDE,+ AGENT_ANIMATION_PURPLE_ATTENTION,+ AGENT_ANIMATION_PURPLE_COMPLETE,+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ AGENT_ANIMATION_NIGHT_RIDER,+ AGENT_ANIMATION_LID_OPEN,+ AGENT_ANIMATION_LID_CLOSED,+ animation_id,+ )+ self.assertEqual(settings.agent_animation_choices(), expected)+ for mode in ANIMATION_STATES:+ with self.subTest(mode=mode):+ selected = settings.with_agent_animation(mode, animation_id)+ self.assertEqual(selected.agent_animation_id(mode), animation_id)+ self.assertEqual(+ selected.agent_animation(mode).custom_program,+ "off\n#AA44FF 700ms pulse\nrepeat",+ )++ def test_working_tool_and_long_task_share_one_animation_setting(self) -> None:+ settings = AgentMonitorSettings().with_agent_animation(+ AgentMode.TOOL_RUNNING,+ AGENT_ANIMATION_KITT,+ )++ self.assertEqual(+ {+ settings.agent_animation_id(mode)+ for mode in AGENT_ANIMATION_WORKING_MODES+ },+ {AGENT_ANIMATION_KITT},+ )++ def test_animation_profile_round_trip_includes_every_state(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ settings_path = Path(tmp) / "settings.json"+ settings = AgentMonitorSettings()+ custom_id = custom_agent_animation_id(+ "Purple Sweep",+ settings.custom_agent_animations,+ )+ settings = settings.with_custom_agent_animation(+ custom_id,+ name="Purple Sweep",+ program="#AA44FF 700ms pulse\nrepeat",+ )+ for index, mode in enumerate(AgentMode):+ selection = custom_id if index % 2 else AGENT_ANIMATION_KITT+ settings = settings.with_agent_animation(mode, selection)+ profile_id = agent_animation_profile_id(+ "Focus",+ settings.agent_animation_profiles,+ )+ settings = settings.with_agent_animation_profile(+ profile_id,+ name="Focus",+ )+ save_settings(settings, settings_path)++ loaded = load_settings(settings_path)+ profile = loaded.agent_animation_profiles[profile_id]+ self.assertEqual(set(profile.animations), set(ANIMATION_STATES))+ reset = loaded+ for mode in AgentMode:+ reset = reset.with_agent_animation(mode, AGENT_ANIMATION_DEFAULT)+ applied = reset.with_applied_agent_animation_profile(profile_id)+ self.assertEqual(+ [applied.agent_animation_id(mode) for mode in AgentMode],+ [loaded.agent_animation_id(mode) for mode in AgentMode],+ )++ def test_cyan_is_the_default_builtin_profile(self) -> None:+ settings = AgentMonitorSettings()++ self.assertEqual(+ settings.matching_agent_animation_profile_id(),+ AGENT_ANIMATION_PROFILE_CYAN,+ )+ self.assertEqual(+ [settings.agent_animation_id(mode) for mode in ANIMATION_STATES],+ [default_agent_animation_id(mode) for mode in ANIMATION_STATES],+ )++ purple = settings.with_applied_agent_animation_profile(+ AGENT_ANIMATION_PROFILE_PURPLE+ )+ self.assertEqual(+ purple.matching_agent_animation_profile_id(),+ AGENT_ANIMATION_PROFILE_PURPLE,+ )+ self.assertEqual(+ purple.agent_animation_id(AgentMode.WORKING),+ AGENT_ANIMATION_PURPLE_TIDE,+ )+ self.assertEqual(+ purple.agent_animation_id(ANIMATION_STATE_LID_OPEN),+ AGENT_ANIMATION_PURPLE_LID_OPEN,+ )+ self.assertEqual(+ purple.agent_animation_id(ANIMATION_STATE_LID_CLOSED),+ AGENT_ANIMATION_LID_CLOSED,+ )++ def test_shipped_profile_json_matches_builtin_profiles(self) -> None:+ profiles = builtin_agent_animation_profiles()+ expected = {+ "cyan": AGENT_ANIMATION_PROFILE_CYAN,+ "ember": AGENT_ANIMATION_PROFILE_EMBER,+ "purple": AGENT_ANIMATION_PROFILE_PURPLE,+ }+ for file_stem, profile_id in expected.items():+ with self.subTest(profile=file_stem):+ document = json.loads(+ (+ Path(__file__).parent.parent+ / "profiles"+ / f"{file_stem}.json"+ ).read_text()+ )+ profile = profiles[profile_id]+ self.assertEqual(document["name"], profile.name)+ self.assertEqual(document["animations"], profile.animations)+ self.assertEqual(set(profile.animations), set(ANIMATION_STATES))++ def test_builtin_profiles_keep_saved_animation_selections(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ settings_path = Path(tmp) / "settings.json"+ settings_path.write_text(+ json.dumps(+ {+ "agent_animations": {+ AgentMode.IDLE_READY.value: {+ "style": AGENT_ANIMATION_KITT,+ "custom_program": "",+ }+ },+ "agent_animation_profiles": {+ "profile:default": {+ "name": "Default",+ "animations": {+ mode: default_agent_animation_id(mode)+ for mode in ANIMATION_STATES+ },+ }+ },+ }+ )+ )++ loaded = load_settings(settings_path)++ self.assertEqual(+ loaded.agent_animation_id(AgentMode.IDLE_READY),+ AGENT_ANIMATION_KITT,+ )+ self.assertEqual(+ set(loaded.agent_animation_profiles),+ {+ AGENT_ANIMATION_PROFILE_CYAN,+ AGENT_ANIMATION_PROFILE_EMBER,+ AGENT_ANIMATION_PROFILE_PURPLE,+ },+ )++ def test_animation_profile_json_is_self_contained_and_importable(self) -> None:+ settings = AgentMonitorSettings()+ custom_id = custom_agent_animation_id(+ "Purple Sweep",+ settings.custom_agent_animations,+ )+ settings = settings.with_custom_agent_animation(+ custom_id,+ name="Purple Sweep",+ program="#AA44FF 700ms pulse\nrepeat",+ )+ for mode in AgentMode:+ settings = settings.with_agent_animation(mode, custom_id)++ document = agent_animation_profile_document(settings)++ self.assertEqual(document["format"], "sidepulse-animation-profile")+ self.assertEqual(document["version"], 1)+ self.assertEqual(document["name"], "Current")+ self.assertEqual(+ set(document["animations"]),+ set(ANIMATION_STATES),+ )+ self.assertEqual(+ document["custom_animations"][custom_id]["program"],+ "#AA44FF 700ms pulse\nrepeat",+ )++ imported, profile_id = with_imported_agent_animation_profile(+ AgentMonitorSettings(),+ json.loads(json.dumps(document)),+ )+ self.assertIn(profile_id, imported.agent_animation_profiles)+ for mode in AgentMode:+ self.assertEqual(imported.agent_animation_id(mode), custom_id)+ self.assertEqual(+ imported.agent_animation(mode).custom_program,+ "#AA44FF 700ms pulse\nrepeat",+ )++ def test_animation_profile_json_requires_all_agent_states(self) -> None:+ document = agent_animation_profile_document(AgentMonitorSettings())+ del document["animations"][AgentMode.UNKNOWN.value]++ with self.assertRaisesRegex(ValueError, "every agent state"):+ with_imported_agent_animation_profile(+ AgentMonitorSettings(),+ document,+ )++ def test_settings_do_not_migrate_pr_kitt_toggle(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ settings_path = Path(tmp) / "settings.json"+ settings_path.write_text(json.dumps({"kitt_mode_enabled": True}))++ loaded = load_settings(settings_path)++ self.assertEqual(+ loaded.agent_animation(AgentMode.WORKING).style,+ AGENT_ANIMATION_CYAN_ROLL,+ )+def test_settings_migrates_missing_agent_list_timing_to_defaults(self) -> None:with tempfile.TemporaryDirectory() as tmp:settings_path = Path(tmp) / "settings.json"diff --git a/tests/test_status_bar_ui.py b/tests/test_status_bar_ui.pyindex 0e7a19f..bf9b15c 100644--- a/tests/test_status_bar_ui.py+++ b/tests/test_status_bar_ui.py@@ -57,8 +57,13 @@ def tearDownModule():from AppKit import ( # noqa: E402NSApplication,NSControl,+ NSEvent,+ NSEventModifierFlagCommand,+ NSEventTypeKeyDown,NSImage,NSMenu,+ NSPasteboard,+ NSPasteboardTypeString,NSView,NSWindow,)@@ -210,6 +215,8 @@ class SelectorWiringTests(StatusBarTestCase):unresolved = []for path in sources:for selector in sorted(self.selector_literals(path)):+ if selector in {item[1] for item in sb.STANDARD_EDIT_MENU_ITEMS}:+ continueif not any(c.instancesRespondToSelector_(selector) for c in classes):unresolved.append(f"{path.relative_to(REPO_ROOT)}: {selector}")self.assertEqual(@@ -361,13 +368,261 @@ class WindowBuildTests(StatusBarTestCase):window = sb.build_settings_window(self.controller)self.assertIsNotNone(window)self.assertTrue(window.title())+ self.assertEqual(window.contentView().frame().size.height, 560)self.assert_controls_are_wired(window)+ def test_settings_window_resizes_for_compact_animations_tab(self):+ window = sb.build_settings_window(self.controller)+ self.controller.settings_window = window+ tab_view = next(+ view+ for view in window.contentView().subviews()+ if hasattr(view, "numberOfTabViewItems")+ )+ items = {+ str(tab_view.tabViewItemAtIndex_(index).identifier()):+ tab_view.tabViewItemAtIndex_(index)+ for index in range(tab_view.numberOfTabViewItems())+ }++ tab_view.selectTabViewItem_(items["animations"])+ self.assertEqual(+ window.contentView().frame().size.height,+ sb.SETTINGS_ANIMATIONS_WINDOW_HEIGHT,+ )+ self.assertEqual(+ window.contentView().frame().size.width,+ sb.SETTINGS_ANIMATIONS_WINDOW_WIDTH,+ )+ agent_animations = items["animations"].view()+ profile_label = next(+ view+ for view in agent_animations.subviews()+ if hasattr(view, "stringValue") and str(view.stringValue()) == "Profile"+ )+ profile_popup = self.controller.settings_fields["agent_animation_profile"]+ self.assertEqual(+ profile_label.frame().origin.y,+ profile_popup.frame().origin.y,+ )+ for view in agent_animations.subviews():+ frame = view.frame()+ self.assertGreaterEqual(frame.origin.x, 0)+ self.assertGreaterEqual(frame.origin.y, 0)+ self.assertLessEqual(+ frame.origin.x + frame.size.width,+ agent_animations.frame().size.width,+ )+ self.assertLessEqual(+ frame.origin.y + frame.size.height,+ agent_animations.frame().size.height,+ )++ tab_view.selectTabViewItem_(items["agents"])+ self.assertEqual(+ window.contentView().frame().size.height,+ sb.SETTINGS_WINDOW_HEIGHT,+ )+ self.assertEqual(+ window.contentView().frame().size.width,+ sb.SETTINGS_WINDOW_WIDTH,+ )+def test_setup_window_builds(self):window = sb.build_setup_window(self.controller)self.assertIsNotNone(window)self.assert_controls_are_wired(window)+ def test_custom_agent_animation_editor_builds(self):+ window = sb.build_agent_animation_editor_window(self.controller)+ self.assertIsNotNone(window)+ self.assertTrue(window.title())+ self.assertIsNotNone(self.controller.agent_animation_editor_name)+ self.assertIsNotNone(self.controller.agent_animation_editor_program)+ self.assertIsInstance(+ self.controller.agent_animation_editor_preview,+ vd.VirtualLedView,+ )+ self.assertTrue(self.controller.agent_animation_editor_preview.compact_preview)+ self.assertIs(+ self.controller.agent_animation_editor_program.delegate(),+ self.controller,+ )+ self.assertIn(+ "Show on Device",+ {+ str(view.title())+ for view in window.contentView().subviews()+ if hasattr(view, "title")+ },+ )+ self.assert_controls_are_wired(window)++ def test_custom_animation_editor_installs_native_edit_shortcuts(self):+ window = sb.build_agent_animation_editor_window(self.controller)+ edit_menu = sb.install_standard_edit_menu(self.app)+ self.assertIsNotNone(edit_menu)+ shortcuts = {+ str(edit_menu.itemAtIndex_(index).action()): str(+ edit_menu.itemAtIndex_(index).keyEquivalent()+ )+ for index in range(edit_menu.numberOfItems())+ }+ self.assertEqual(+ shortcuts,+ {+ "cut:": "x",+ "copy:": "c",+ "paste:": "v",+ "selectAll:": "a",+ },+ )+ count = self.app.mainMenu().numberOfItems()+ self.assertIs(sb.install_standard_edit_menu(self.app), edit_menu)+ self.assertEqual(self.app.mainMenu().numberOfItems(), count)+ self.assertIsNotNone(window)++ def test_custom_animation_editor_command_c_copies_selected_program(self):+ window = sb.build_agent_animation_editor_window(self.controller)+ program = self.controller.agent_animation_editor_program+ program.setString_("off 2s\ncopy me")+ program.setSelectedRange_((0, 6))+ window.makeFirstResponder_(program)+ pasteboard = NSPasteboard.generalPasteboard()+ pasteboard.clearContents()+ event = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(+ NSEventTypeKeyDown,+ (0, 0),+ NSEventModifierFlagCommand,+ 0.0,+ window.windowNumber(),+ None,+ "c",+ "c",+ False,+ 8,+ )++ self.assertTrue(program.performKeyEquivalent_(event))+ self.assertEqual(+ pasteboard.stringForType_(NSPasteboardTypeString),+ "off 2s",+ )++ def test_custom_agent_animation_editor_preview_updates_and_reports_errors(self):+ sb.build_agent_animation_editor_window(self.controller)+ sb.set_text_control_value(+ self.controller.agent_animation_editor_program,+ "#FF0000 1s pulse\nrepeat",+ )+ self.controller.refresh_agent_animation_editor_preview()+ preview = self.controller.agent_animation_editor_preview+ self.assertEqual(preview.current_program, "#FF0000 1s pulse\nrepeat")+ self.assertIsNone(preview.wasm_error)+ self.assertEqual(+ str(self.controller.agent_animation_editor_preview_status.stringValue()),+ "Updates as you type",+ )++ sb.set_text_control_value(self.controller.agent_animation_editor_program, "")+ self.controller.refresh_agent_animation_editor_preview()+ self.assertEqual(preview.current_program, "off")+ self.assertNotEqual(+ str(self.controller.agent_animation_editor_preview_status.stringValue()),+ "Updates as you type",+ )++ def test_edit_animation_clones_builtins_and_edits_custom_in_place(self):+ original_settings = self.controller.settings+ try:+ self.controller.settings = original_settings.with_agent_animation(+ AgentMode.WORKING,+ sb.AGENT_ANIMATION_KITT_RED,+ )+ self.controller.show_agent_animation_editor(+ AgentMode.WORKING.value,+ edit_selected=True,+ )+ self.assertEqual(+ str(self.controller.agent_animation_editor_window.title()),+ "Clone Built-in Animation",+ )+ self.assertIsNone(self.controller.agent_animation_editor_existing_id)+ self.assertEqual(+ str(self.controller.agent_animation_editor_name.stringValue()),+ "KITT Scanner Red Copy",+ )++ custom_id = "custom:purple-sweep"+ self.controller.settings = (+ original_settings.with_custom_agent_animation(+ custom_id,+ name="Purple Sweep",+ program="#AA44FF 700ms pulse\nrepeat",+ ).with_agent_animation(AgentMode.WORKING, custom_id)+ )+ self.controller.show_agent_animation_editor(+ AgentMode.WORKING.value,+ edit_selected=True,+ )+ self.assertEqual(+ str(self.controller.agent_animation_editor_window.title()),+ "Edit Custom Animation",+ )+ self.assertEqual(+ self.controller.agent_animation_editor_existing_id,+ custom_id,+ )+ self.assertEqual(+ sb.text_control_value(self.controller.agent_animation_editor_program),+ "#AA44FF 700ms pulse\nrepeat",+ )+ finally:+ if self.controller.agent_animation_editor_window is not None:+ self.controller.agent_animation_editor_window.orderOut_(None)+ self.controller.settings = original_settings++ def test_custom_editor_device_preview_applies_device_brightness(self):+ device = sb.StatusBarDevice(+ device_id="sidepulse",+ name="SidePulse",+ root=Path("/Volumes/SidePulse"),+ target=Path("/Volumes/SidePulse/LEDS.LED"),+ connected=True,+ display=sb.LED_DISPLAY_AGENT,+ brightness=128,+ reason="test",+ )+ program = "brightness 200\n#FF0000 1s pulse\nrepeat"+ with (+ patch.object(sb, "write_led_program") as write_program,+ patch.object(sb.time, "sleep") as sleep,+ patch.object(+ self.controller,+ "performSelectorOnMainThread_withObject_waitUntilDone_",+ ),+ ):+ self.controller.show_animation_program_on_device_worker(+ program,+ [device],+ 12,+ )++ write_program.assert_called_once_with(+ sb.apply_brightness(program, 128),+ device_path=device.target,+ )+ sleep.assert_called_once_with(+ sb.AGENT_ANIMATION_EDITOR_DEVICE_PREVIEW_SECONDS+ )+ self.assertEqual(sb.AGENT_ANIMATION_EDITOR_DEVICE_PREVIEW_SECONDS, 10.0)++ def test_agent_animation_profile_editor_builds(self):+ window = sb.build_agent_animation_profile_editor_window(self.controller)+ self.assertIsNotNone(window)+ self.assertIsNotNone(self.controller.agent_animation_profile_editor_name)+ self.assert_controls_are_wired(window)+def test_settings_window_registers_its_fields(self):"""The controller reads values back out of this dict when saving."""self.controller.settings_fields = {}@@ -376,11 +631,176 @@ class WindowBuildTests(StatusBarTestCase):self.controller.settings_fields,"settings window built no addressable fields; saving would be a no-op",)+ for mode in sb.ANIMATION_UI_STATES:+ preview = self.controller.settings_fields[+ f"agent_animation_preview_{mode}"+ ]+ self.assertIsInstance(preview, vd.VirtualLedView)+ profile_popup = self.controller.settings_fields["agent_animation_profile"]+ self.assertEqual(str(profile_popup.titleOfSelectedItem()), "Cyan")+ self.assertEqual(+ [+ str(profile_popup.itemAtIndex_(index).title())+ for index in range(profile_popup.numberOfItems())+ ],+ ["Current", "Cyan", "Ember", "Purple"],+ )+ self.assertFalse(+ self.controller.settings_buttons[+ "delete_agent_animation_profile"+ ].isEnabled()+ )++ def test_settings_window_has_profile_json_controls(self):+ window = sb.build_settings_window(self.controller)+ tab_view = next(+ view+ for view in window.contentView().subviews()+ if hasattr(view, "numberOfTabViewItems")+ )+ animations = next(+ tab_view.tabViewItemAtIndex_(index).view()+ for index in range(tab_view.numberOfTabViewItems())+ if str(tab_view.tabViewItemAtIndex_(index).identifier()) == "animations"+ )+ titles = {+ str(view.title())+ for view in walk_views(animations)+ if hasattr(view, "title")+ }+ self.assertIn("Export JSON", titles)+ self.assertIn("Import JSON", titles)++ def test_settings_animation_previews_use_wasm_programs(self):+ window = sb.build_settings_window(self.controller)+ self.controller.settings_window = window+ self.controller.refresh_settings_window()++ for mode in sb.ANIMATION_UI_STATES:+ with self.subTest(mode=mode):+ preview = self.controller.settings_fields[+ f"agent_animation_preview_{mode}"+ ]+ self.assertTrue(preview.compact_preview)+ self.assertIsNotNone(preview.current_program)+ self.assertIsNotNone(preview.wasm_controller)+ self.assertIsNone(preview.wasm_error)++ for state in (sb.ANIMATION_STATE_LID_OPEN, sb.ANIMATION_STATE_LID_CLOSED):+ preview = self.controller.settings_fields[+ f"agent_animation_preview_{state}"+ ]+ self.assertNotIn("repeat", preview.current_program)+ self.assertEqual(preview.rendered_program.splitlines()[-1], "repeat")++ lid_closed_preview = self.controller.settings_fields[+ f"agent_animation_preview_{sb.ANIMATION_STATE_LID_CLOSED}"+ ]+ self.assertTrue(lid_closed_preview.current_program.startswith("0:#000000"))+ self.assertTrue(lid_closed_preview.rendered_program.startswith("#00E5FF\n"))++ def test_every_state_popup_uses_the_same_animation_catalog(self):+ original_settings = self.controller.settings+ try:+ animation_id = "custom:purple-sweep"+ self.controller.settings = original_settings.with_custom_agent_animation(+ animation_id,+ name="Purple Sweep",+ program="#AA44FF 700ms pulse\nrepeat",+ )+ sb.build_settings_window(self.controller)+ catalogs = []+ for mode in sb.ANIMATION_UI_STATES:+ popup = self.controller.settings_fields[+ f"agent_animation_{mode}"+ ]+ catalogs.append(+ [+ item.representedObject()["animation_id"]+ for item in (+ popup.itemAtIndex_(index)+ for index in range(popup.numberOfItems())+ )+ if isinstance(item.representedObject(), dict)+ ]+ )+ self.assertTrue(catalogs)+ self.assertTrue(all(catalog == catalogs[0] for catalog in catalogs))+ self.assertIn("kitt", catalogs[0])+ self.assertIn(animation_id, catalogs[0])+ self.assertEqual(catalogs[0][-1], "add-custom")+ working_popup = self.controller.settings_fields[+ f"agent_animation_{AgentMode.WORKING.value}"+ ]+ self.assertEqual(+ [+ str(working_popup.itemAtIndex_(index).title())+ for index in range(working_popup.numberOfItems())+ if isinstance(+ working_popup.itemAtIndex_(index).representedObject(),+ dict,+ )+ ],+ [+ "Slow Off",+ "Immediate Off",+ "Idle Pulse",+ "Cyan Roll",+ "Cyan Complete",+ "Amber Pulse",+ "Solid Green",+ "KITT Scanner",+ "KITT Scanner Red",+ "Ember Idle",+ "Ember Tide",+ "Ember Attention",+ "Ember Complete",+ "Ember Lid Open",+ "Purple Idle",+ "Purple Tide",+ "Purple Attention",+ "Purple Complete",+ "Purple Lid Open",+ "Night Rider",+ "Lid Open Sweep",+ "Lid Closed Sweep",+ "Purple Sweep",+ "Add Custom…",+ ],+ )+ animated_rows = [+ working_popup.itemAtIndex_(index).view()+ for index in range(working_popup.numberOfItems())+ if isinstance(+ working_popup.itemAtIndex_(index).representedObject(),+ dict,+ )+ and working_popup.itemAtIndex_(index).representedObject()[+ "animation_id"+ ]+ != "add-custom"+ ]+ self.assertTrue(animated_rows)+ for row in animated_rows:+ self.assertIsInstance(row, sb.AgentAnimationMenuItemView)+ self.assertIsNotNone(row.animation_preview.wasm_controller)+ self.assertIsNone(row.animation_preview.wasm_error)+ finally:+ self.controller.settings = original_settingsdef test_settings_window_is_not_visible(self):window = sb.build_settings_window(self.controller)self.assertFalse(window.isVisible(), "building a window must not show it")+ def test_show_settings_window_brings_it_forward_and_starts_previews(self):+ self.controller.show_settings_window()+ try:+ self.assertTrue(self.controller.settings_window.isVisible())+ self.assertIsNotNone(self.controller.agent_animation_preview_timer)+ finally:+ self.controller.stop_agent_animation_preview_timer()+ self.controller.settings_window.orderOut_(None)+class IconTests(StatusBarTestCase):"""Icon builders return real images rather than None."""