Skip to content

CLI for SidePulse

Python

Add SidePulse agent status bar controls

Peter Kuhardfa72ee57fa3
diff --git a/README.md b/README.md
index 7daf115..ab889ff 100644
--- a/README.md
+++ b/README.md
@@ -9,9 +9,7 @@ PulseDot is the tiny two-LED USB-C version.
They can display the status of an AI agent, battery level, or other system
signals.
-The device mounts as a flash drive. Control the LEDs by writing to `LEDS.LED`
-on current firmware. Older PulseDot firmware exposes the same control as
-`LEDS.TXT`, and the CLI keeps that fallback.
+The device mounts as a flash drive. Control the LEDs by writing to `LEDS.LED`.
The LED control DSL is described in [`LEDS_FORMAT.txt`](LEDS_FORMAT.txt).
@@ -22,14 +20,12 @@ sidepulse write "off\n#ff3a00 1.6s pulse\nrepeat"
```
The CLI auto-detects mounted devices under `/Volumes` by looking for a
-SidePulse/PulseDot-style volume name, an existing `LEDS.LED`, or a legacy
-`LEDS.TXT`. If more than one device is possible, pass the mounted folder or
-file explicitly:
+SidePulse/PulseDot-style volume name or an existing `LEDS.LED`. If more than
+one device is possible, pass the mounted folder or file explicitly:
```sh
sidepulse write "off\n#ff3a00 1.6s pulse\nrepeat" --device /Volumes/SidePulse
sidepulse write "off" --device /Volumes/SidePulse/LEDS.LED
-sidepulse write "off" --device /Volumes/PulseDot/LEDS.TXT
```
The writer decodes simple escapes such as `\n`, then enforces the controller's
@@ -128,8 +124,7 @@ small `latest.json` restart snapshot plus provider JSONL debug logs. It does
not rescan historical logs or transcripts on every refresh.
The package can also mirror the aggregate state to a mounted SidePulse or
-PulseDot by writing the current LED program to `LEDS.LED`, with `LEDS.TXT`
-fallback for legacy firmware.
+PulseDot by writing the current LED program to `LEDS.LED`.
The monitor currently supports:
@@ -169,6 +164,44 @@ To use the macOS status-bar app, install its Cocoa extra:
python3 -m pip install -e ".[status-bar]"
```
+Set up this Mac explicitly after package install:
+
+```sh
+sidepulse setup
+```
+
+`sidepulse setup` installs or refreshes Codex and Claude hooks, installs the SD
+eject guard, writes the status-bar LaunchAgent, starts both helpers
+immediately, and enables them at login. This is intentionally an explicit
+command instead of a `pip install` side effect. To set up only one provider, use
+`sidepulse setup codex` or `sidepulse setup claude`. To skip the status-bar app
+but still install hooks and the SD eject guard, use `sidepulse setup
+--no-status-bar`.
+
+The SD eject guard keeps the built-in SD reader attached after macOS hibernate
+or lock-screen mount refusals. By default setup installs it system-wide when
+already running with system permissions, otherwise as a per-user LaunchAgent:
+
+```sh
+sidepulse setup --sd-eject-guard-scope auto
+sidepulse setup --sd-eject-guard-scope user
+sidepulse setup --sd-eject-guard-scope system --no-status-bar
+```
+
+The system scope requires the command to already have system install
+permissions.
+
+Manage the SD eject guard directly:
+
+```sh
+sidepulse sdejectguard start
+sidepulse sdejectguard stop
+sidepulse sdejectguard logs
+sidepulse sdejectguard start -it
+```
+
+`start -it` runs the guard in the current terminal for interactive debugging.
+
On Homebrew Python, use the user-site install form:
```sh
@@ -287,15 +320,16 @@ sidepulse agent-monitor uninstall claude
Install and start the macOS status-bar app:
```sh
-sidepulse agent-monitor status-bar
+sidepulse status-bar
+sidepulse status-bar start
```
-This writes `~/Library/LaunchAgents/com.sidepulse.agentstatus.plist`, starts the
+This writes `~/Library/LaunchAgents/io.sidepulse.agentstatus.plist`, starts the
menu-bar app immediately, enables it at login, and mirrors the same aggregate
state to the LEDs. For debugging, run it in the foreground:
```sh
-sidepulse agent-monitor status-bar --foreground
+sidepulse status-bar start --foreground
```
The status-bar item shows one of four collapsed states:
@@ -307,12 +341,10 @@ The status-bar item shows one of four collapsed states:
| Done | The most recent active agent completed successfully. |
| Ask | An agent needs input, permission, or attention. |
-Click the status-bar item to expand the recent session list. Each session row
-has two actions:
-
-- `Deep Link` opens the provider app. Codex uses `codex://threads/<session-id>`.
-- `Resume` opens Terminal in the session working directory and runs the
- provider CLI resume command.
+Click the status-bar item to expand the recent session list. Click a session
+row to open that agent using the remembered choice for that provider. Use the
+session's Open Options row to choose and remember another opener, such as the
+provider app, Terminal resume, or Claude Code in VS Code.
The dropdown also includes a checked `Connect to Device` item. A checkmark means
the status-bar app is actively connected to a mounted SidePulse/PulseDot target.
@@ -331,22 +363,47 @@ checkboxes control the file-based CLI/debug fallback; the status-bar app gets
live updates from the local hook event socket. Settings are stored at
`${XDG_CONFIG_HOME:-~/.config}/sidepulse/agent-monitor/settings.json`.
-The checked `Keep Awake` item controls a macOS `caffeinate -dimsu` assertion.
-When enabled, the status-bar app keeps the Mac awake while agents are Working /
-Tool Running / Progressing. Done and Ask states keep the Mac awake for a
-five-minute grace period, then release the assertion so normal sleep can resume.
-While keep-awake is enabled and a device is connected, the app also touches a
-`keepalive` file on each SidePulse/PulseDot volume at least once per minute to
-keep the device volume active. Closed-lid sleep is still subject to macOS
-clamshell rules.
+The `Keep Awake With Lid Closed` menu section controls the stronger sleep
+prevention policy:
+
+| Choice | Behavior |
+| --- | --- |
+| Never | Do not use the closed-lid sleep override. |
+| When Agents Work | Keep the Mac awake while agents are Working / Tool Running / Progressing, plus the existing five-minute Ask / Done / Error grace period. |
+| Always | Keep the closed-lid sleep override active while the status-bar app is running. |
+
+The status-bar app still keeps the SidePulse/PulseDot volume active by touching
+a `keepalive` file on each connected device at least once per minute. The
+closed-lid policy uses `caffeinate` by default, so it does not ask for
+administrator permission in the background. For Macs that need the stronger
+system sleep-disable setting, explicitly enable `Strong Sleep Override...` in
+the menu or `Strong sleep override (requires helper)` in Settings, then run the
+one-time setup command:
+
+```sh
+sudo "$(command -v sidepulse)" status-bar install-sleep-helper
+```
+
+The helper is a narrow sudoers rule for exactly
+`/usr/bin/pmset -a disablesleep 0|1`, so the status-bar app can toggle it
+silently with non-interactive `sudo`. SidePulse only restores the setting if
+SidePulse changed it. Remove the helper with:
+
+```sh
+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
+`sidepulse write`; device brightness is applied automatically before writing.
The app is also installed as a user LaunchAgent at
-`~/Library/LaunchAgents/com.sidepulse.agentstatus.plist`.
+`~/Library/LaunchAgents/io.sidepulse.agentstatus.plist`.
Stop and remove the LaunchAgent:
```sh
-sidepulse agent-monitor status-bar --uninstall
+sidepulse status-bar stop
```
Use it from another Python app:
diff --git a/examples/audio_monitor.py b/examples/audio_monitor.py
index 02755d5..aea7ce4 100644
--- a/examples/audio_monitor.py
+++ b/examples/audio_monitor.py
@@ -17,11 +17,10 @@ if REPO_SRC.exists():
from agent_monitor.device_writer import ( # noqa: E402
DEFAULT_FILE_NAME,
DeviceWriteError,
- LEGACY_FILE_NAMES,
validate_led_text,
write_led_program,
)
-from agent_monitor.led_status import led_count_for_target # noqa: E402
+from agent_monitor.led_status import apply_brightness, led_count_for_target # noqa: E402
DEFAULT_FPS = 25.0
@@ -83,18 +82,20 @@ def build_led_program(
peak = max(idle, clamp(max_brightness))
fill = level * count
duration = max(0, int(transition_ms))
+ global_brightness = int(round(peak * 255))
segments: list[str] = []
for index in range(count):
segment_level = clamp(fill - index)
- brightness = idle + ((peak - idle) * segment_level)
+ absolute_brightness = idle + ((peak - idle) * segment_level)
+ brightness = absolute_brightness / peak if peak > 0 else 0.0
color = rgb_hex(scale_rgb(green_to_red_rgb(index, count), brightness))
token = f"{index}:{color}"
if duration:
token += f" {duration}ms cosine"
segments.append(token)
- program = "; ".join(segments)
+ program = apply_brightness("; ".join(segments), global_brightness)
validate_led_text(program)
return program
@@ -381,10 +382,7 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument(
"--file-name",
default=DEFAULT_FILE_NAME,
- help=(
- f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}; "
- f"legacy devices may use {', '.join(LEGACY_FILE_NAMES)}."
- ),
+ help=f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}.",
)
parser.add_argument("--led-count", type=int, help="LED count. Defaults to device name, then 8.")
parser.add_argument("--fps", type=float, default=DEFAULT_FPS, help="LED update rate.")
diff --git a/mac_menu_test.py b/mac_menu_test.py
deleted file mode 100644
index ffedccb..0000000
--- a/mac_menu_test.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/env python3
-"""Tiny native macOS status-bar UI smoke test.
-
-If needed:
- python3 -m pip install pyobjc-framework-Cocoa
-"""
-
-try:
- import objc
- from AppKit import (
- NSApp,
- NSApplication,
- NSApplicationActivationPolicyAccessory,
- NSButton,
- NSFont,
- NSMakeRect,
- NSMinYEdge,
- NSPopover,
- NSPopoverBehaviorTransient,
- NSPopUpButton,
- NSStatusBar,
- NSTextField,
- NSVariableStatusItemLength,
- NSView,
- NSViewController,
- )
- from Foundation import NSObject
-except ImportError as exc:
- raise SystemExit(
- "This status-bar test requires PyObjC:\n"
- " python3 -m pip install pyobjc-framework-Cocoa"
- ) from exc
-
-
-class PopoverController(NSViewController):
- def init(self):
- self = objc.super(PopoverController, self).init()
- if self is None:
- return None
-
- self.status_label = None
- return self
-
- def loadView(self):
- view = NSView.alloc().initWithFrame_(NSMakeRect(0, 0, 200, 200))
-
- title = NSTextField.labelWithString_("Status Bar UI")
- title.setFrame_(NSMakeRect(16, 162, 168, 24))
- title.setFont_(NSFont.boldSystemFontOfSize_(14))
- view.addSubview_(title)
-
- dropdown = NSPopUpButton.alloc().initWithFrame_pullsDown_(
- NSMakeRect(16, 120, 168, 28), False
- )
- dropdown.addItemsWithTitles_(["One", "Two", "Three"])
- dropdown.setTarget_(self)
- dropdown.setAction_("dropdownChanged:")
- view.addSubview_(dropdown)
-
- button_one = NSButton.alloc().initWithFrame_(NSMakeRect(16, 82, 168, 30))
- button_one.setTitle_("Button 1")
- button_one.setTarget_(self)
- button_one.setAction_("buttonOneClicked:")
- view.addSubview_(button_one)
-
- button_two = NSButton.alloc().initWithFrame_(NSMakeRect(16, 46, 168, 30))
- button_two.setTitle_("Button 2")
- button_two.setTarget_(self)
- button_two.setAction_("buttonTwoClicked:")
- view.addSubview_(button_two)
-
- self.status_label = NSTextField.labelWithString_("Pick an action")
- self.status_label.setFrame_(NSMakeRect(16, 14, 168, 20))
- view.addSubview_(self.status_label)
-
- self.setView_(view)
-
- @objc.IBAction
- def dropdownChanged_(self, sender):
- self.status_label.setStringValue_(f"Selected {sender.titleOfSelectedItem()}")
-
- @objc.IBAction
- def buttonOneClicked_(self, _sender):
- self.status_label.setStringValue_("Button 1 clicked")
-
- @objc.IBAction
- def buttonTwoClicked_(self, _sender):
- self.status_label.setStringValue_("Button 2 clicked")
-
-
-class AppDelegate(NSObject):
- def applicationDidFinishLaunching_(self, _notification):
- NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)
-
- self.popover_controller = PopoverController.alloc().init()
- self.popover = NSPopover.alloc().init()
- self.popover.setBehavior_(NSPopoverBehaviorTransient)
- self.popover.setContentViewController_(self.popover_controller)
-
- self.status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(
- NSVariableStatusItemLength
- )
- status_button = self.status_item.button()
- status_button.setTitle_("UI")
- status_button.setTarget_(self)
- status_button.setAction_("togglePopover:")
-
- @objc.IBAction
- def togglePopover_(self, sender):
- if self.popover.isShown():
- self.popover.performClose_(sender)
- return
-
- self.popover.showRelativeToRect_ofView_preferredEdge_(
- sender.bounds(), sender, NSMinYEdge
- )
- NSApp.activateIgnoringOtherApps_(True)
-
-
-def main() -> None:
- app = NSApplication.sharedApplication()
- delegate = AppDelegate.alloc().init()
- app.setDelegate_(delegate)
- app.run()
-
-
-if __name__ == "__main__":
- main()
diff --git a/pyproject.toml b/pyproject.toml
index 5b871ef..806b05c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -20,3 +20,6 @@ agent-status-bar = "agent_monitor.status_bar:main"
[tool.setuptools.packages.find]
where = ["src"]
+
+[tool.setuptools.package-data]
+"agent_monitor.resources" = ["sd_eject_guard.c"]
diff --git a/src/agent_monitor/__init__.py b/src/agent_monitor/__init__.py
index 32ceb0a..fa63c1e 100644
--- a/src/agent_monitor/__init__.py
+++ b/src/agent_monitor/__init__.py
@@ -20,6 +20,16 @@ from .led_status import (
program_for_display_state,
write_mode_to_leds,
)
+from .lid_sleep import (
+ ClosedLidAwakeController,
+ install_sleep_helper,
+ read_lid_closed,
+ read_sleep_disabled,
+ run_sudo_pmset_disablesleep,
+ sleep_helper_install_command,
+ sleep_helper_installed,
+ uninstall_sleep_helper,
+)
from .models import AgentMode, AgentStatus, AggregateStatus, HookEvent
__all__ = [
@@ -36,11 +46,19 @@ __all__ = [
"LedDisplayState",
"MonitorSnapshot",
"SourceSpec",
+ "ClosedLidAwakeController",
"default_event_socket_path",
"default_latest_state_path",
"display_state_for_mode",
"program_for_battery",
"read_battery_snapshot",
+ "read_lid_closed",
+ "read_sleep_disabled",
+ "install_sleep_helper",
+ "run_sudo_pmset_disablesleep",
+ "sleep_helper_install_command",
+ "sleep_helper_installed",
+ "uninstall_sleep_helper",
"send_hook_event",
"program_for_display_state",
"write_mode_to_leds",
diff --git a/src/agent_monitor/battery.py b/src/agent_monitor/battery.py
index f918c90..6c822bd 100644
--- a/src/agent_monitor/battery.py
+++ b/src/agent_monitor/battery.py
@@ -18,6 +18,7 @@ from .device_writer import (
write_led_program,
)
from .led_status import led_count_for_target
+from .led_status import apply_brightness, normalize_brightness
BATTERY_LOW_RED = "#FF2600"
@@ -285,6 +286,7 @@ def program_for_battery(
led_count: int = 8,
full_charge_watts: float | None = None,
transition_ms: int = 360,
+ brightness: int | float = 255,
) -> str:
count = max(1, min(8, int(led_count)))
percent = max(0, min(100, int(snapshot.percent)))
@@ -295,13 +297,19 @@ def program_for_battery(
if not snapshot.is_plugged or snapshot.is_charged:
color = battery_color(percent)
if snapshot.is_charged or percent >= 100:
- return ";".join(
- battery_segment(index, BATTERY_HIGH_GREEN, transition)
- for index in range(count)
+ return apply_brightness(
+ ";".join(
+ battery_segment(index, BATTERY_HIGH_GREEN, transition)
+ for index in range(count)
+ ),
+ brightness,
)
- return ";".join(
- battery_segment(index, battery_fill_color(index, fill, color), transition)
- for index in range(count)
+ return apply_brightness(
+ ";".join(
+ battery_segment(index, battery_fill_color(index, fill, color), transition)
+ for index in range(count)
+ ),
+ brightness,
)
color = BATTERY_CHARGING_MINT
@@ -322,7 +330,7 @@ def program_for_battery(
f"{pulse_index}:{color} {pulse_ms}ms pulse",
]
)
- return "\n".join(lines)
+ return apply_brightness("\n".join(lines), brightness)
@dataclass(frozen=True)
@@ -373,12 +381,14 @@ def write_battery_to_leds(
file_name: str = DEFAULT_FILE_NAME,
dry_run: bool = False,
full_charge_watts: float | None = None,
+ brightness: int | float = 255,
) -> BatteryLedWrite:
target = resolve_target_path(device_path=device_path, file_name=file_name)
program = program_for_battery(
snapshot,
led_count=led_count_for_target(target),
full_charge_watts=full_charge_watts,
+ brightness=brightness,
)
written_target = write_led_program(
program,
@@ -401,11 +411,13 @@ class BatteryLedController:
file_name: str = DEFAULT_FILE_NAME,
dry_run: bool = False,
error_retry_seconds: float = 10.0,
+ brightness: int | float = 255,
) -> None:
self.device_path = device_path
self.file_name = file_name
self.dry_run = dry_run
self.error_retry_seconds = error_retry_seconds
+ self.brightness = normalize_brightness(brightness)
self.last_program: str | None = None
self.last_error: str | None = None
self.last_target: Path | None = None
@@ -423,7 +435,11 @@ class BatteryLedController:
now = time.monotonic()
try:
target = resolve_target_path(device_path=self.device_path, file_name=self.file_name)
- program = program_for_battery(snapshot, led_count=led_count_for_target(target))
+ program = program_for_battery(
+ snapshot,
+ led_count=led_count_for_target(target),
+ brightness=self.brightness,
+ )
except (DeviceWriteError, OSError) as exc:
self.last_error = str(exc)
return BatteryLedWrite(
diff --git a/src/agent_monitor/cli.py b/src/agent_monitor/cli.py
index 3546a06..2180bf7 100644
--- a/src/agent_monitor/cli.py
+++ b/src/agent_monitor/cli.py
@@ -4,6 +4,7 @@ import argparse
import json
import os
import shutil
+import subprocess
import sys
import time
from pathlib import Path
@@ -16,7 +17,7 @@ from .battery import (
render_battery_snapshot,
)
from .collector import AgentMonitor, SourceSpec, default_sources
-from .device_writer import DEFAULT_FILE_NAME, DeviceWriteError, LEGACY_FILE_NAMES, write_led_program
+from .device_writer import DEFAULT_FILE_NAME, DeviceWriteError, write_led_program
from .hook import hook_log_main
from .install import (
install_claude_hooks,
@@ -25,6 +26,12 @@ from .install import (
uninstall_codex_hooks,
)
from .led_status import AgentLedController, LedStatusWrite
+from .lid_sleep import (
+ install_sleep_helper,
+ sleep_helper_install_command,
+ sleep_helper_installed,
+ uninstall_sleep_helper,
+)
from .models import AgentStatus
from .providers import (
detect_claude_config,
@@ -70,6 +77,34 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:
"agent-monitor",
help="Install hooks and show live AI agent statuses.",
)
+ setup = subparsers.add_parser(
+ "setup",
+ help="Install agent hooks and start the macOS status-bar app.",
+ )
+ setup.add_argument(
+ "provider",
+ choices=("all", "codex", "claude"),
+ nargs="?",
+ default="all",
+ help="Agent hooks to install. Default: all.",
+ )
+ setup.add_argument("--log-dir", type=Path, help="Directory for provider JSONL files.")
+ setup.add_argument("--codex-log", type=Path, help="Codex JSONL log path.")
+ setup.add_argument("--claude-log", type=Path, help="Claude JSONL log path.")
+ setup.add_argument("--dry-run", action="store_true", help="Show what would change.")
+ setup.add_argument(
+ "--sd-eject-guard-scope",
+ choices=("auto", "system", "user"),
+ default="auto",
+ help="Install the SD eject guard as a system service when possible, or as a user agent.",
+ )
+ setup.add_argument(
+ "--no-status-bar",
+ action="store_true",
+ help="Do not install or start the status-bar app.",
+ )
+ setup.set_defaults(func=cmd_sidepulse_setup)
+
write = subparsers.add_parser(
"write",
help=f"Write an LED program to {DEFAULT_FILE_NAME} on a mounted SidePulse or PulseDot device.",
@@ -83,18 +118,87 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:
write.add_argument(
"--file-name",
default=DEFAULT_FILE_NAME,
- help=(
- f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}; "
- f"auto-detect falls back to {', '.join(LEGACY_FILE_NAMES)} when present."
- ),
+ help=f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}.",
)
write.add_argument("--dry-run", action="store_true", help="Show the target without writing.")
write.set_defaults(func=cmd_sidepulse_write)
+ add_sidepulse_status_bar_parser(subparsers)
+ add_sidepulse_sdejectguard_parser(subparsers)
add_sidepulse_battery_parser(subparsers)
return parser
+def add_sidepulse_status_bar_parser(subparsers: argparse._SubParsersAction) -> None:
+ status_bar = subparsers.add_parser(
+ "status-bar",
+ help="Start or stop the macOS SidePulse menu-bar app.",
+ )
+ status_bar.add_argument(
+ "status_bar_command",
+ choices=(
+ "start",
+ "stop",
+ "install-sleep-helper",
+ "uninstall-sleep-helper",
+ "sleep-helper-status",
+ ),
+ nargs="?",
+ default="start",
+ help="Start/stop the menu-bar app, or manage the closed-lid sleep helper. Default: start.",
+ )
+ status_bar.add_argument(
+ "--foreground",
+ action="store_true",
+ help="Run the menu-bar app in the foreground instead of installing a LaunchAgent.",
+ )
+ status_bar.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Show sleep-helper changes without writing them.",
+ )
+ status_bar.set_defaults(func=cmd_sidepulse_status_bar)
+
+
+def add_sidepulse_sdejectguard_parser(subparsers: argparse._SubParsersAction) -> None:
+ guard = subparsers.add_parser(
+ "sdejectguard",
+ help="Start, stop, or inspect the macOS SD eject guard.",
+ )
+ guard_subparsers = guard.add_subparsers(dest="sdejectguard_command", required=True)
+
+ start = guard_subparsers.add_parser("start", help="Install and start the SD eject guard.")
+ add_sdejectguard_scope_arg(start)
+ start.add_argument("--dry-run", action="store_true", help="Show what would change.")
+ start.add_argument(
+ "-it",
+ "--interactive",
+ action="store_true",
+ help="Run the guard in this terminal instead of launchd.",
+ )
+ start.set_defaults(func=cmd_sidepulse_sdejectguard_start)
+
+ stop = guard_subparsers.add_parser("stop", help="Stop the SD eject guard.")
+ add_sdejectguard_scope_arg(stop)
+ stop.add_argument("--dry-run", action="store_true", help="Show what would stop.")
+ stop.set_defaults(func=cmd_sidepulse_sdejectguard_stop)
+
+ logs = guard_subparsers.add_parser("logs", help="Show SD eject guard logs.")
+ add_sdejectguard_scope_arg(logs)
+ logs.add_argument("--lines", type=int, default=80, help="Lines to show per log file.")
+ logs.add_argument("-f", "--follow", action="store_true", help="Follow existing log files.")
+ logs.set_defaults(func=cmd_sidepulse_sdejectguard_logs)
+
+
+def add_sdejectguard_scope_arg(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--scope",
+ choices=("auto", "system", "user"),
+ default="auto",
+ help="Use system scope when possible, or target one scope explicitly.",
+ )
+
+
def add_sidepulse_battery_parser(subparsers: argparse._SubParsersAction) -> None:
battery = subparsers.add_parser(
"battery",
@@ -120,10 +224,7 @@ def add_sidepulse_battery_parser(subparsers: argparse._SubParsersAction) -> None
leds.add_argument(
"--file-name",
default=DEFAULT_FILE_NAME,
- help=(
- f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}; "
- f"auto-detect falls back to {', '.join(LEGACY_FILE_NAMES)} when present."
- ),
+ help=f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}.",
)
leds.add_argument("--dry-run", action="store_true", help="Show writes without touching the device.")
leds.add_argument("--once", action="store_true", help="Write the current battery state once and exit.")
@@ -251,6 +352,187 @@ def cmd_sidepulse_battery_configure(args: argparse.Namespace) -> int:
return 0
+def cmd_sidepulse_status_bar(args: argparse.Namespace) -> int:
+ if args.status_bar_command == "install-sleep-helper":
+ return cmd_sidepulse_sleep_helper_install(args)
+ if args.status_bar_command == "uninstall-sleep-helper":
+ return cmd_sidepulse_sleep_helper_uninstall(args)
+ if args.status_bar_command == "sleep-helper-status":
+ return cmd_sidepulse_sleep_helper_status(args)
+
+ args.uninstall = args.status_bar_command == "stop"
+ args.no_start = False
+ if args.uninstall:
+ args.foreground = False
+ return cmd_status_bar(args)
+
+
+def cmd_sidepulse_sleep_helper_install(args: argparse.Namespace) -> int:
+ try:
+ result = install_sleep_helper(dry_run=args.dry_run)
+ except (PermissionError, OSError, subprocess.CalledProcessError, ValueError) as exc:
+ print(f"sleep-helper: {exc}", file=sys.stderr)
+ return 1
+
+ action = "would install" if result.dry_run and result.changed else "installed"
+ if not result.changed:
+ action = "already installed"
+ print(f"sleep-helper: {action}")
+ print(f" user: {result.user}")
+ print(f" sudoers: {result.path}")
+ return 0
+
+
+def cmd_sidepulse_sleep_helper_uninstall(args: argparse.Namespace) -> int:
+ try:
+ result = uninstall_sleep_helper(dry_run=args.dry_run)
+ except (PermissionError, OSError) as exc:
+ print(f"sleep-helper: {exc}", file=sys.stderr)
+ return 1
+
+ action = "would remove" if result.dry_run and result.changed else "removed"
+ if not result.changed:
+ action = "not installed"
+ print(f"sleep-helper: {action}")
+ print(f" sudoers: {result.path}")
+ return 0
+
+
+def cmd_sidepulse_sleep_helper_status(_args: argparse.Namespace) -> int:
+ installed = sleep_helper_installed()
+ print(f"sleep-helper: {'installed' if installed else 'not installed'}")
+ if not installed:
+ print(f" install: {sleep_helper_install_command()}")
+ return 0
+
+
+def cmd_sidepulse_sdejectguard_start(args: argparse.Namespace) -> int:
+ from .sd_eject_guard_launch import (
+ SdEjectGuardInstallError,
+ install_sd_eject_guard,
+ run_sd_eject_guard_interactive,
+ )
+
+ try:
+ if args.interactive:
+ if args.dry_run:
+ print(f"sd-eject-guard: would run interactively ({args.scope})")
+ return 0
+ return run_sd_eject_guard_interactive(scope=args.scope)
+
+ result = install_sd_eject_guard(scope=args.scope, dry_run=args.dry_run)
+ except (SdEjectGuardInstallError, OSError, subprocess.CalledProcessError) as exc:
+ print(f"sd-eject-guard: {exc}", file=sys.stderr)
+ return 1
+
+ print_sd_eject_guard_result(result)
+ return 0
+
+
+def cmd_sidepulse_sdejectguard_stop(args: argparse.Namespace) -> int:
+ from .sd_eject_guard_launch import SdEjectGuardInstallError, stop_sd_eject_guard
+
+ try:
+ results = stop_sd_eject_guard(scope=args.scope, dry_run=args.dry_run)
+ except (SdEjectGuardInstallError, OSError, subprocess.CalledProcessError) as exc:
+ print(f"sd-eject-guard: {exc}", file=sys.stderr)
+ return 1
+
+ for result in results:
+ if result.skipped:
+ action = f"skipped ({result.skipped})"
+ elif result.stopped:
+ action = "would stop" if args.dry_run else "stopped"
+ else:
+ action = "not installed"
+ print(f"sd-eject-guard: {action} ({result.scope})")
+ print(f" plist: {result.plist_path}")
+ return 0
+
+
+def cmd_sidepulse_sdejectguard_logs(args: argparse.Namespace) -> int:
+ from .sd_eject_guard_launch import log_paths_for_requested_scope, read_log_tail
+
+ try:
+ paths = log_paths_for_requested_scope(args.scope)
+ except Exception as exc:
+ print(f"sd-eject-guard logs: {exc}", file=sys.stderr)
+ return 1
+
+ existing_paths = [path for path in paths if path.exists()]
+ if args.follow:
+ if not existing_paths:
+ for path in paths:
+ print(f"{path}: missing")
+ return 1
+ try:
+ return subprocess.run(
+ ["tail", "-n", str(args.lines), "-f", *(str(path) for path in existing_paths)],
+ check=False,
+ ).returncode
+ except KeyboardInterrupt:
+ return 130
+
+ for path in paths:
+ print(f"==> {path} <==")
+ if not path.exists():
+ print("(missing)")
+ continue
+ text = read_log_tail(path, args.lines)
+ print(text if text else "(empty)")
+ return 0
+
+
+def cmd_sidepulse_setup(args: argparse.Namespace) -> int:
+ results = install_hook_results(args)
+ print_install_results(results, dry_run=args.dry_run)
+
+ from .sd_eject_guard_launch import SdEjectGuardInstallError, install_sd_eject_guard
+
+ try:
+ guard_result = install_sd_eject_guard(
+ scope=args.sd_eject_guard_scope,
+ dry_run=args.dry_run,
+ )
+ except (SdEjectGuardInstallError, OSError, subprocess.CalledProcessError) as exc:
+ print(f"sd-eject-guard: {exc}", file=sys.stderr)
+ return 1
+ print_sd_eject_guard_result(guard_result)
+
+ if args.no_status_bar:
+ return 0
+
+ if args.dry_run:
+ print("status-bar: would install and start")
+ return 0
+
+ from .status_bar_launch import install_launch_agent
+
+ result = install_launch_agent(start=True)
+ action = "installed" if result.changed else "already installed"
+ if result.started:
+ action += " and started"
+ print(f"status-bar: {action}")
+ print(f" plist: {result.plist_path}")
+ return 0
+
+
+def print_sd_eject_guard_result(result) -> None:
+ if result.dry_run:
+ action = "would install and start" if result.changed else "would start (already configured)"
+ else:
+ action = "installed" if result.changed else "already installed"
+ if result.started:
+ action += " and started"
+ print(f"sd-eject-guard: {action} ({result.scope})")
+ print(f" plist: {result.plist_path}")
+ print(f" binary: {result.binary_path}")
+ if result.cleanup_removed:
+ print(f" removed other scope: {result.cleanup_removed}")
+ if result.cleanup_skipped:
+ print(f" cleanup skipped: {result.cleanup_skipped}")
+
+
def build_parser(prog: str = "agent-monitor") -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog=prog,
@@ -280,10 +562,7 @@ def build_parser(prog: str = "agent-monitor") -> argparse.ArgumentParser:
leds.add_argument(
"--file-name",
default=DEFAULT_FILE_NAME,
- help=(
- f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}; "
- f"auto-detect falls back to {', '.join(LEGACY_FILE_NAMES)} when present."
- ),
+ help=f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}.",
)
leds.add_argument("--dry-run", action="store_true", help="Show writes without touching the device.")
leds.add_argument("--once", action="store_true", help="Write the current status once and exit.")
@@ -467,7 +746,17 @@ def cmd_status_bar(args: argparse.Namespace) -> int:
def cmd_install(args: argparse.Namespace) -> int:
- providers = ("codex", "claude") if args.provider == "all" else (args.provider,)
+ results = install_hook_results(args)
+ print_install_results(results, dry_run=args.dry_run)
+ return 0
+
+
+def selected_hook_providers(provider: str) -> tuple[str, ...]:
+ return ("codex", "claude") if provider == "all" else (provider,)
+
+
+def install_hook_results(args: argparse.Namespace):
+ providers = selected_hook_providers(args.provider)
results = []
for provider in providers:
log_path = install_log_path(provider, args)
@@ -475,9 +764,12 @@ def cmd_install(args: argparse.Namespace) -> int:
results.append(install_codex_hooks(log_path=log_path, dry_run=args.dry_run))
else:
results.append(install_claude_hooks(log_path=log_path, dry_run=args.dry_run))
+ return results
+
+def print_install_results(results, *, dry_run: bool) -> None:
for result in results:
- action = "would update" if args.dry_run and result.changed else "updated"
+ action = "would update" if dry_run and result.changed else "updated"
if not result.changed:
action = "already configured"
print(f"{result.provider}: {action}")
@@ -485,7 +777,6 @@ def cmd_install(args: argparse.Namespace) -> int:
print(f" log: {result.log_path}")
if result.backup_path:
print(f" backup: {result.backup_path}")
- return 0
def cmd_uninstall(args: argparse.Namespace) -> int:
@@ -538,11 +829,12 @@ def monitor_from_args(args: argparse.Namespace) -> AgentMonitor:
def install_log_path(provider: str, args: argparse.Namespace) -> Path:
- explicit = args.codex_log if provider == "codex" else args.claude_log
+ explicit = getattr(args, "codex_log", None) if provider == "codex" else getattr(args, "claude_log", None)
if explicit:
return explicit.expanduser()
- if args.log_dir:
- return args.log_dir.expanduser() / f"{provider}.jsonl"
+ log_dir = getattr(args, "log_dir", None)
+ if log_dir:
+ return log_dir.expanduser() / f"{provider}.jsonl"
return default_log_path(provider)
diff --git a/src/agent_monitor/device_writer.py b/src/agent_monitor/device_writer.py
index d6424f5..3f6a753 100644
--- a/src/agent_monitor/device_writer.py
+++ b/src/agent_monitor/device_writer.py
@@ -5,8 +5,7 @@ from pathlib import Path
from typing import Iterable
DEFAULT_FILE_NAME = "LEDS.LED"
-LEGACY_FILE_NAMES = ("LEDS.TXT",)
-LED_FILE_NAMES = (DEFAULT_FILE_NAME, *LEGACY_FILE_NAMES)
+LED_FILE_NAMES = (DEFAULT_FILE_NAME,)
KNOWN_LED_FILE_NAMES = frozenset(name.upper() for name in LED_FILE_NAMES)
MAX_LED_BYTES = 512
MAX_LED_LINES = 20
@@ -124,10 +123,6 @@ def resolve_target_path(
def target_from_device_path(path: Path, file_name: str) -> Path:
if path.name.upper() in KNOWN_LED_FILE_NAMES:
return path
- if file_name == DEFAULT_FILE_NAME:
- existing = existing_led_file(path)
- if existing is not None:
- return existing
return path / file_name
@@ -150,15 +145,6 @@ def discover_devices(
candidates.append(DeviceCandidate(volume, target, "name matches device"))
return candidates
-
-def existing_led_file(volume: Path) -> Path | None:
- for name in LED_FILE_NAMES:
- target = volume / name
- if path_exists(target):
- return target
- return None
-
-
def iter_mounts(mount_root: Path) -> Iterable[Path]:
try:
children = list(mount_root.iterdir())
diff --git a/src/agent_monitor/install.py b/src/agent_monitor/install.py
index c85e9a9..5c9b763 100644
--- a/src/agent_monitor/install.py
+++ b/src/agent_monitor/install.py
@@ -364,7 +364,6 @@ def codex_cli_path() -> Path | None:
Path(env_path).expanduser() if env_path else None,
Path("/Applications/ChatGPT.app/Contents/Resources/codex"),
Path("/Applications/Codex.app/Contents/Resources/codex"),
- Path("/Applications/ChatGPT.app/Contents/Resources/codex"),
Path(shutil.which("codex")).expanduser() if shutil.which("codex") else None,
]
for candidate in candidates:
diff --git a/src/agent_monitor/keep_awake.py b/src/agent_monitor/keep_awake.py
index 9b2662e..db99dc1 100644
--- a/src/agent_monitor/keep_awake.py
+++ b/src/agent_monitor/keep_awake.py
@@ -41,6 +41,7 @@ class KeepAwakeController:
self.watch_current_process = watch_current_process
self.process = None
self.last_mode: AgentMode | None = None
+ self.holding_requested = False
self.grace_until_monotonic: float | None = None
self.last_error: str | None = None
self.last_status_read_monotonic_by_path: dict[Path, float] = {}
@@ -53,6 +54,7 @@ class KeepAwakeController:
self.enabled = enabled
if not enabled:
self.release()
+ self.holding_requested = False
self.grace_until_monotonic = None
self.last_status_error = None
self.last_status_read_monotonic_by_path.clear()
@@ -61,6 +63,7 @@ class KeepAwakeController:
def update(self, mode: AgentMode, *, now: float | None = None) -> bool:
current = time.monotonic() if now is None else now
should_hold = self.should_hold_for_mode(mode, current)
+ self.holding_requested = should_hold
self.last_mode = mode
if not self.enabled or not should_hold:
diff --git a/src/agent_monitor/led_status.py b/src/agent_monitor/led_status.py
index d6fe273..f3c23e4 100644
--- a/src/agent_monitor/led_status.py
+++ b/src/agent_monitor/led_status.py
@@ -72,27 +72,34 @@ def program_for_display_state(
state: LedDisplayState,
*,
led_count: int = 8,
+ brightness: int | float = 255,
) -> str:
if state == LedDisplayState.IDLE:
- return "\n".join(
- [
- "off",
- f"{IDLE_DIM} 6s pulse",
- "repeat",
- ]
+ return apply_brightness(
+ "\n".join(
+ [
+ "off",
+ f"{IDLE_DIM} 6s pulse",
+ "repeat",
+ ]
+ ),
+ brightness,
)
if state == LedDisplayState.ASK:
- return "\n".join(
- [
- "off",
- f"{ASK_AMBER} 1.6s pulse",
- "repeat",
- ]
+ return apply_brightness(
+ "\n".join(
+ [
+ "off",
+ f"{ASK_AMBER} 1.6s pulse",
+ "repeat",
+ ]
+ ),
+ brightness,
)
if state == LedDisplayState.DONE:
- return DONE_GREEN
+ return apply_brightness(DONE_GREEN, brightness)
if state == LedDisplayState.WORKING:
- return rolling_program(WORKING_CYAN, led_count=led_count)
+ return apply_brightness(rolling_program(WORKING_CYAN, led_count=led_count), brightness)
raise ValueError(f"Unknown LED display state: {state}")
@@ -119,12 +126,14 @@ def write_mode_to_leds(
device_path: Path | None = None,
file_name: str = DEFAULT_FILE_NAME,
dry_run: bool = False,
+ brightness: int | float = 255,
) -> 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,
led_count=led_count_for_target(target),
+ brightness=brightness,
)
written_target = write_led_program(
program,
@@ -152,6 +161,23 @@ def normalized_device_name(name: str) -> str:
return "".join(char for char in name.lower() if char.isalnum())
+def normalize_brightness(value: int | float | None) -> int:
+ if value is None:
+ return 255
+ return max(0, min(255, int(round(float(value)))))
+
+
+def brightness_percent(value: int | float | None) -> int:
+ return round(normalize_brightness(value) / 255 * 100)
+
+
+def apply_brightness(program: str, brightness: int | float = 255) -> str:
+ value = normalize_brightness(brightness)
+ if value >= 255:
+ return program
+ return f"brightness {value}\n{program}"
+
+
class AgentLedController:
def __init__(
self,
@@ -160,26 +186,31 @@ class AgentLedController:
file_name: str = DEFAULT_FILE_NAME,
dry_run: bool = False,
error_retry_seconds: float = 10.0,
+ brightness: int | float = 255,
) -> None:
self.device_path = device_path
self.file_name = file_name
self.dry_run = dry_run
self.error_retry_seconds = error_retry_seconds
+ self.brightness = normalize_brightness(brightness)
self.last_state: LedDisplayState | None = None
+ self.last_brightness: int | None = None
self.last_error: str | None = None
self.last_target: Path | None = None
self.last_attempt_monotonic = 0.0
def reset(self) -> None:
self.last_state = None
+ self.last_brightness = None
self.last_error = None
self.last_target = None
self.last_attempt_monotonic = 0.0
def sync_mode(self, mode: AgentMode) -> LedStatusWrite:
state = display_state_for_mode(mode)
+ brightness = normalize_brightness(self.brightness)
now = time.monotonic()
- if state == self.last_state and self.last_error is None:
+ if state == self.last_state and brightness == self.last_brightness and self.last_error is None:
return LedStatusWrite(
state=state,
target=self.last_target,
@@ -188,6 +219,7 @@ class AgentLedController:
)
if (
state == self.last_state
+ and brightness == self.last_brightness
and self.last_error is not None
and now - self.last_attempt_monotonic < self.error_retry_seconds
):
@@ -206,9 +238,11 @@ class AgentLedController:
device_path=self.device_path,
file_name=self.file_name,
dry_run=self.dry_run,
+ brightness=brightness,
)
except (DeviceWriteError, OSError) as exc:
self.last_state = state
+ self.last_brightness = brightness
self.last_error = str(exc)
return LedStatusWrite(
state=state,
@@ -219,6 +253,7 @@ class AgentLedController:
)
self.last_state = state
+ self.last_brightness = brightness
self.last_error = None
self.last_target = result.target
return result
diff --git a/src/agent_monitor/lid_sleep.py b/src/agent_monitor/lid_sleep.py
new file mode 100644
index 0000000..f37f769
--- /dev/null
+++ b/src/agent_monitor/lid_sleep.py
@@ -0,0 +1,382 @@
+from __future__ import annotations
+
+import getpass
+import os
+import re
+import shlex
+import shutil
+import subprocess
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Callable, Sequence
+
+from .settings import (
+ CLOSED_LID_AWAKE_AGENTS,
+ CLOSED_LID_AWAKE_ALWAYS,
+ CLOSED_LID_AWAKE_NEVER,
+)
+
+
+CAFFEINATE_CLOSED_LID_COMMAND = ("/usr/bin/caffeinate", "-dimsu")
+IOREG_CLAMSHELL_COMMAND = ("/usr/sbin/ioreg", "-r", "-k", "AppleClamshellState", "-d", "4")
+IOREG_SLEEP_DISABLED_COMMAND = ("/usr/sbin/ioreg", "-r", "-k", "SleepDisabled", "-d", "4")
+SUDO_PMSET_DISABLE_SLEEP_COMMAND = (
+ "/usr/bin/sudo",
+ "-n",
+ "/usr/bin/pmset",
+ "-a",
+ "disablesleep",
+)
+SLEEP_HELPER_SUDOERS_PATH = Path("/etc/sudoers.d/sidepulse-disablesleep")
+LID_POLL_SECONDS = 1.0
+
+
+CommandRunner = Callable[..., subprocess.CompletedProcess]
+
+
+@dataclass(frozen=True)
+class SleepHelperInstallResult:
+ path: Path
+ user: str
+ changed: bool
+ installed: bool
+ dry_run: bool = False
+
+
+class SleepHelperRequiredError(RuntimeError):
+ pass
+
+
+def closed_lid_awake_should_hold(policy: str, *, agents_active: bool) -> bool:
+ if policy == CLOSED_LID_AWAKE_ALWAYS:
+ return True
+ if policy == CLOSED_LID_AWAKE_AGENTS:
+ return agents_active
+ return False
+
+
+def read_lid_closed(
+ *,
+ runner: CommandRunner = subprocess.run,
+ command: Sequence[str] = IOREG_CLAMSHELL_COMMAND,
+) -> bool | None:
+ result = runner(
+ list(command),
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=2,
+ )
+ return parse_bool_ioreg_property(result.stdout, "AppleClamshellState")
+
+
+def read_sleep_disabled(
+ *,
+ runner: CommandRunner = subprocess.run,
+ command: Sequence[str] = IOREG_SLEEP_DISABLED_COMMAND,
+) -> bool | None:
+ result = runner(
+ list(command),
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=2,
+ )
+ return parse_bool_ioreg_property(result.stdout, "SleepDisabled")
+
+
+def parse_bool_ioreg_property(text: str | bytes, property_name: str) -> bool | None:
+ if isinstance(text, bytes):
+ text = text.decode("utf-8", errors="replace")
+ pattern = rf'"{re.escape(property_name)}"\s*=\s*(Yes|No|true|false|1|0)'
+ match = re.search(pattern, text, flags=re.IGNORECASE)
+ if match is None:
+ return None
+ value = match.group(1).lower()
+ if value in {"yes", "true", "1"}:
+ return True
+ if value in {"no", "false", "0"}:
+ return False
+ return None
+
+
+def run_sudo_pmset_disablesleep(
+ enabled: bool,
+ *,
+ runner: CommandRunner = subprocess.run,
+) -> None:
+ value = "1" if enabled else "0"
+ command = [*SUDO_PMSET_DISABLE_SLEEP_COMMAND, value]
+ result = runner(
+ command,
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.returncode == 0:
+ return
+
+ detail = (result.stderr or result.stdout or "").strip()
+ if detail:
+ detail = f" ({detail.splitlines()[0]})"
+ raise SleepHelperRequiredError(
+ "Strong Sleep Override needs one-time setup: "
+ f"{sleep_helper_install_command()}"
+ f"{detail}"
+ )
+
+
+def run_privileged_pmset_disablesleep(
+ enabled: bool,
+ *,
+ runner: CommandRunner = subprocess.run,
+) -> None:
+ """Compatibility wrapper for the old name.
+
+ Runtime sleep control is intentionally non-interactive. Any admin prompt
+ belongs to an explicit helper installation step, never a background refresh.
+ """
+ run_sudo_pmset_disablesleep(enabled, runner=runner)
+
+
+def sleep_helper_sudoers_rule(user: str) -> str:
+ if not re.fullmatch(r"[A-Za-z0-9._-]+", user):
+ raise ValueError(f"invalid sudoers user: {user!r}")
+ return (
+ f"{user} ALL=(root) NOPASSWD: "
+ "/usr/bin/pmset -a disablesleep 0, "
+ "/usr/bin/pmset -a disablesleep 1\n"
+ )
+
+
+def sleep_helper_target_user() -> str:
+ for value in (os.environ.get("SUDO_USER"), os.environ.get("USER")):
+ if value:
+ return value
+ try:
+ return os.getlogin()
+ except OSError:
+ return getpass.getuser()
+
+
+def sleep_helper_installed(path: Path = SLEEP_HELPER_SUDOERS_PATH) -> bool:
+ return path.exists()
+
+
+def sleep_helper_install_command(executable: str = "sidepulse") -> str:
+ resolved = shutil.which(executable) or executable
+ return f"sudo {shlex.quote(resolved)} status-bar install-sleep-helper"
+
+
+def install_sleep_helper(
+ *,
+ user: str | None = None,
+ path: Path = SLEEP_HELPER_SUDOERS_PATH,
+ dry_run: bool = False,
+ runner: CommandRunner = subprocess.run,
+) -> SleepHelperInstallResult:
+ target_user = user or sleep_helper_target_user()
+ rule = sleep_helper_sudoers_rule(target_user)
+ try:
+ current = path.read_text(encoding="utf-8") if path.exists() else None
+ except OSError:
+ current = None
+ changed = current != rule
+
+ if dry_run:
+ return SleepHelperInstallResult(
+ path=path,
+ user=target_user,
+ changed=changed,
+ installed=not changed,
+ dry_run=True,
+ )
+
+ require_root_for_sleep_helper()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_path = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ try:
+ tmp_path.write_text(rule, encoding="utf-8")
+ os.chown(tmp_path, 0, 0)
+ os.chmod(tmp_path, 0o440)
+ runner(
+ ["/usr/sbin/visudo", "-cf", str(tmp_path)],
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if changed:
+ tmp_path.replace(path)
+ else:
+ tmp_path.unlink()
+ except Exception:
+ try:
+ tmp_path.unlink()
+ except FileNotFoundError:
+ pass
+ raise
+
+ return SleepHelperInstallResult(
+ path=path,
+ user=target_user,
+ changed=changed,
+ installed=True,
+ )
+
+
+def uninstall_sleep_helper(
+ *,
+ path: Path = SLEEP_HELPER_SUDOERS_PATH,
+ dry_run: bool = False,
+) -> SleepHelperInstallResult:
+ target_user = sleep_helper_target_user()
+ changed = path.exists()
+ if dry_run:
+ return SleepHelperInstallResult(
+ path=path,
+ user=target_user,
+ changed=changed,
+ installed=changed,
+ dry_run=True,
+ )
+
+ require_root_for_sleep_helper()
+ if changed:
+ path.unlink()
+ return SleepHelperInstallResult(
+ path=path,
+ user=target_user,
+ changed=changed,
+ installed=False,
+ )
+
+
+def require_root_for_sleep_helper() -> None:
+ if hasattr(os, "geteuid") and os.geteuid() != 0:
+ raise PermissionError(f"run once with sudo: {sleep_helper_install_command()}")
+
+
+class ClosedLidAwakeController:
+ def __init__(
+ self,
+ *,
+ command: Sequence[str] = CAFFEINATE_CLOSED_LID_COMMAND,
+ process_factory: Callable[..., object] | None = None,
+ sleep_disabled_reader: Callable[[], bool | None] = read_sleep_disabled,
+ sleep_disabled_setter: Callable[[bool], None] = run_sudo_pmset_disablesleep,
+ watch_current_process: bool = True,
+ use_system_disable: bool = False,
+ ) -> None:
+ self.command = tuple(command)
+ self.process_factory = process_factory or subprocess.Popen
+ self.sleep_disabled_reader = sleep_disabled_reader
+ self.sleep_disabled_setter = sleep_disabled_setter
+ self.watch_current_process = watch_current_process
+ self.use_system_disable = use_system_disable
+ self.process = None
+ self.changed_system_disable = False
+ self.system_disable_attempted = False
+ self.last_error: str | None = None
+ self.last_policy = CLOSED_LID_AWAKE_NEVER
+ self.last_requested = False
+
+ def set_use_system_disable(self, enabled: bool) -> None:
+ enabled = bool(enabled)
+ if self.use_system_disable == enabled:
+ return
+ self.use_system_disable = enabled
+ self.system_disable_attempted = False
+ if not enabled:
+ self.release_system_disable()
+
+ def update(self, policy: str, *, agents_active: bool) -> bool:
+ should_hold = closed_lid_awake_should_hold(policy, agents_active=agents_active)
+ if policy != self.last_policy:
+ self.system_disable_attempted = False
+ self.last_policy = policy
+ self.last_requested = should_hold
+ if should_hold:
+ self.ensure_awake()
+ else:
+ self.release()
+ return self.active()
+
+ def ensure_awake(self) -> None:
+ errors: list[str] = []
+ if (
+ self.use_system_disable
+ and not self.changed_system_disable
+ and not self.system_disable_attempted
+ ):
+ self.system_disable_attempted = True
+ try:
+ already_disabled = self.sleep_disabled_reader()
+ if already_disabled is False:
+ self.sleep_disabled_setter(True)
+ self.changed_system_disable = True
+ elif already_disabled is None:
+ self.sleep_disabled_setter(True)
+ self.changed_system_disable = True
+ except Exception as exc:
+ errors.append(f"disablesleep: {exc}")
+
+ if not self.process_running():
+ try:
+ self.process = self.process_factory(
+ self.caffeinate_command(),
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ except Exception as exc:
+ self.process = None
+ errors.append(f"caffeinate: {exc}")
+
+ self.last_error = "; ".join(errors) if errors else None
+
+ def release(self) -> None:
+ process = self.process
+ self.process = None
+ errors: list[str] = []
+ if process is not None:
+ try:
+ if process.poll() is None:
+ process.terminate()
+ process.wait(timeout=1)
+ except Exception:
+ try:
+ process.kill()
+ except Exception as exc:
+ errors.append(f"caffeinate: {exc}")
+
+ self.release_system_disable(errors=errors)
+
+ self.last_error = "; ".join(errors) if errors else None
+
+ def release_system_disable(self, *, errors: list[str] | None = None) -> None:
+ active_errors = errors if errors is not None else []
+ if self.changed_system_disable:
+ try:
+ self.sleep_disabled_setter(False)
+ self.changed_system_disable = False
+ self.system_disable_attempted = False
+ except Exception as exc:
+ active_errors.append(f"disablesleep: {exc}")
+ else:
+ self.system_disable_attempted = False
+
+ if errors is None:
+ self.last_error = "; ".join(active_errors) if active_errors else None
+
+ def active(self) -> bool:
+ return self.process_running() or self.changed_system_disable
+
+ def process_running(self) -> bool:
+ return self.process is not None and self.process.poll() is None
+
+ def caffeinate_command(self) -> list[str]:
+ command = list(self.command)
+ if self.watch_current_process:
+ command.extend(["-w", str(os.getpid())])
+ return command
diff --git a/src/agent_monitor/resources/__init__.py b/src/agent_monitor/resources/__init__.py
new file mode 100644
index 0000000..e0611b7
--- /dev/null
+++ b/src/agent_monitor/resources/__init__.py
@@ -0,0 +1 @@
+"""Packaged resources for SidePulse helper installers."""
diff --git a/src/agent_monitor/resources/sd_eject_guard.c b/src/agent_monitor/resources/sd_eject_guard.c
new file mode 100644
index 0000000..46ca028
--- /dev/null
+++ b/src/agent_monitor/resources/sd_eject_guard.c
@@ -0,0 +1,127 @@
+// sd_eject_guard - veto software ejects of cards in the built-in SD reader.
+//
+// macOS loginwindow dissents the mount and ejects any disk that appears
+// while the screen is locked (e.g. the SD slot re-enumerating after a
+// hibernate wake). The eject goes through the same DiskArbitration approval
+// mechanism, so a registered client can dissent it right back. This tool does
+// that, then retries the mount every few seconds; the retries are dissented
+// while locked and succeed after unlock.
+//
+// Build: clang -o sd_eject_guard sd_eject_guard.c \
+// -framework DiskArbitration -framework CoreFoundation
+// Run: ./sd_eject_guard [-n] (leave running; Ctrl-C to stop)
+// -n / --no-mount: only veto ejects; don't retry mounting.
+
+#include <CoreFoundation/CoreFoundation.h>
+#include <DiskArbitration/DiskArbitration.h>
+#include <stdio.h>
+#include <string.h>
+
+#define MOUNT_RETRY_SECONDS 5.0
+
+static DASessionRef g_session;
+static bool g_no_mount = false;
+
+static void log_msg(const char *fmt, CFStringRef s) {
+ char buf[256] = "?";
+ if (s) CFStringGetCString(s, buf, sizeof(buf), kCFStringEncodingUTF8);
+ printf(fmt, buf);
+ fflush(stdout);
+}
+
+static bool is_builtin_sd(DADiskRef disk) {
+ CFDictionaryRef desc = DADiskCopyDescription(disk);
+ if (!desc) return false;
+ CFStringRef proto = CFDictionaryGetValue(desc, kDADiskDescriptionDeviceProtocolKey);
+ CFStringRef model = CFDictionaryGetValue(desc, kDADiskDescriptionDeviceModelKey);
+ bool match =
+ (proto && CFStringFind(proto, CFSTR("Secure Digital"), 0).location != kCFNotFound) ||
+ (model && CFStringFind(model, CFSTR("SDXC"), 0).location != kCFNotFound);
+ CFRelease(desc);
+ return match;
+}
+
+static bool is_mounted(DADiskRef disk) {
+ CFDictionaryRef desc = DADiskCopyDescription(disk);
+ if (!desc) return false;
+ bool mounted = CFDictionaryGetValue(desc, kDADiskDescriptionVolumePathKey) != NULL;
+ CFRelease(desc);
+ return mounted;
+}
+
+static void mount_done(DADiskRef disk, DADissenterRef dissenter, void *ctx);
+
+static void retry_mount(CFRunLoopTimerRef timer, void *info) {
+ DADiskRef disk = (DADiskRef)info;
+ if (is_mounted(disk)) {
+ printf("mounted; stopping retries for %s\n", DADiskGetBSDName(disk));
+ fflush(stdout);
+ CFRunLoopTimerInvalidate(timer);
+ CFRelease(disk);
+ return;
+ }
+ DADiskMount(disk, NULL, kDADiskMountOptionDefault, mount_done, NULL);
+}
+
+static void mount_done(DADiskRef disk, DADissenterRef dissenter, void *ctx) {
+ if (dissenter)
+ printf("mount of %s dissented (0x%x), will retry\n",
+ DADiskGetBSDName(disk), DADissenterGetStatus(dissenter));
+ else
+ printf("mount of %s succeeded\n", DADiskGetBSDName(disk));
+ fflush(stdout);
+}
+
+static void start_mount_retries(DADiskRef disk) {
+ CFRetain(disk);
+ CFRunLoopTimerContext tctx = { 0, (void *)disk, NULL, NULL, NULL };
+ CFRunLoopTimerRef timer = CFRunLoopTimerCreate(
+ kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + MOUNT_RETRY_SECONDS,
+ MOUNT_RETRY_SECONDS, 0, 0, retry_mount, &tctx);
+ CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
+ CFRelease(timer);
+}
+
+static DADissenterRef eject_approval(DADiskRef disk, void *ctx) {
+ if (!is_builtin_sd(disk))
+ return NULL; // not ours, allow
+ CFDictionaryRef desc = DADiskCopyDescription(disk);
+ CFStringRef vol = desc ? CFDictionaryGetValue(desc, kDADiskDescriptionVolumeNameKey) : NULL;
+ printf("vetoing eject of %s", DADiskGetBSDName(disk));
+ log_msg(" (volume: %s)\n", vol);
+ if (desc) CFRelease(desc);
+ if (!g_no_mount)
+ start_mount_retries(disk);
+ return DADissenterCreate(kCFAllocatorDefault, kDAReturnNotPermitted,
+ CFSTR("sd_eject_guard: keeping SD card attached"));
+}
+
+static void disk_appeared(DADiskRef disk, void *ctx) {
+ if (!is_builtin_sd(disk)) return;
+ printf("SD disk appeared: %s\n", DADiskGetBSDName(disk));
+ fflush(stdout);
+}
+
+int main(int argc, char **argv) {
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--no-mount")) {
+ g_no_mount = true;
+ } else {
+ fprintf(stderr, "usage: %s [-n | --no-mount]\n", argv[0]);
+ return 2;
+ }
+ }
+ g_session = DASessionCreate(kCFAllocatorDefault);
+ if (!g_session) {
+ fprintf(stderr, "DASessionCreate failed\n");
+ return 1;
+ }
+ DARegisterDiskEjectApprovalCallback(g_session, NULL, eject_approval, NULL);
+ DARegisterDiskAppearedCallback(g_session, NULL, disk_appeared, NULL);
+ DASessionScheduleWithRunLoop(g_session, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
+ printf("sd_eject_guard: watching for ejects of the built-in SD reader%s...\n",
+ g_no_mount ? " (mount retries disabled)" : "");
+ fflush(stdout);
+ CFRunLoopRun();
+ return 0;
+}
diff --git a/src/agent_monitor/sd_eject_guard_launch.py b/src/agent_monitor/sd_eject_guard_launch.py
new file mode 100644
index 0000000..4f51548
--- /dev/null
+++ b/src/agent_monitor/sd_eject_guard_launch.py
@@ -0,0 +1,441 @@
+from __future__ import annotations
+
+import os
+import plistlib
+import subprocess
+from dataclasses import dataclass
+from importlib.resources import as_file, files
+from pathlib import Path
+from typing import Any, Literal
+
+from .providers import default_state_dir
+
+SD_EJECT_GUARD_LABEL = "io.sidepulse.sdejectguard"
+SD_EJECT_GUARD_FILENAME = f"{SD_EJECT_GUARD_LABEL}.plist"
+SD_EJECT_GUARD_BINARY_NAME = "sd_eject_guard"
+SD_EJECT_GUARD_SCOPES = ("auto", "system", "user")
+
+SdEjectGuardScope = Literal["auto", "system", "user"]
+ResolvedSdEjectGuardScope = Literal["system", "user"]
+
+
+class SdEjectGuardInstallError(RuntimeError):
+ pass
+
+
+@dataclass(frozen=True)
+class SdEjectGuardPaths:
+ scope: ResolvedSdEjectGuardScope
+ plist_path: Path
+ binary_path: Path
+ stdout_path: Path
+ stderr_path: Path
+
+
+@dataclass(frozen=True)
+class SdEjectGuardResult:
+ label: str
+ scope: ResolvedSdEjectGuardScope
+ plist_path: Path
+ binary_path: Path
+ changed: bool
+ compiled: bool = False
+ started: bool = False
+ dry_run: bool = False
+ cleanup_removed: Path | None = None
+ cleanup_skipped: str | None = None
+
+
+@dataclass(frozen=True)
+class SdEjectGuardStopResult:
+ label: str
+ scope: ResolvedSdEjectGuardScope
+ plist_path: Path
+ stopped: bool
+ skipped: str | None = None
+
+
+def install_sd_eject_guard(
+ *,
+ scope: SdEjectGuardScope = "auto",
+ dry_run: bool = False,
+ start: bool = True,
+ source_path: Path | None = None,
+ user_paths: SdEjectGuardPaths | None = None,
+ system_paths: SdEjectGuardPaths | None = None,
+) -> SdEjectGuardResult:
+ resolved_scope = resolve_sd_eject_guard_scope(scope)
+ if scope == "system" and not dry_run and not can_install_system_scope():
+ raise SdEjectGuardInstallError(
+ "system SD eject guard install requires root privileges; "
+ "rerun with sudo or use --sd-eject-guard-scope user"
+ )
+
+ paths = paths_for_scope(resolved_scope, user_paths=user_paths, system_paths=system_paths)
+ plist = build_sd_eject_guard_plist(paths)
+ data = plistlib.dumps(plist, sort_keys=False)
+ existing = paths.plist_path.read_bytes() if paths.plist_path.exists() else None
+ plist_changed = existing != data
+ compiled = False
+ cleanup_removed = None
+ cleanup_skipped = None
+
+ source = source_path or packaged_sd_eject_guard_source()
+ source_context = as_file(source) if not isinstance(source, Path) else _path_context(source)
+ with source_context as resolved_source:
+ needs_compile = binary_needs_compile(paths.binary_path, resolved_source)
+ if not dry_run:
+ paths.binary_path.parent.mkdir(parents=True, exist_ok=True)
+ paths.plist_path.parent.mkdir(parents=True, exist_ok=True)
+ paths.stdout_path.parent.mkdir(parents=True, exist_ok=True)
+ paths.stderr_path.parent.mkdir(parents=True, exist_ok=True)
+
+ if needs_compile:
+ compile_sd_eject_guard(resolved_source, paths.binary_path)
+ compiled = True
+
+ paths.binary_path.chmod(0o755)
+ if resolved_scope == "system":
+ apply_system_ownership(paths.binary_path)
+
+ if plist_changed:
+ paths.plist_path.write_bytes(data)
+ paths.plist_path.chmod(0o644)
+ if resolved_scope == "system":
+ apply_system_ownership(paths.plist_path)
+
+ cleanup = cleanup_other_scope(
+ resolved_scope,
+ user_paths=user_paths,
+ system_paths=system_paths,
+ )
+ cleanup_removed = cleanup.removed
+ cleanup_skipped = cleanup.skipped
+
+ if start:
+ restart_sd_eject_guard(paths.plist_path, resolved_scope)
+
+ return SdEjectGuardResult(
+ label=SD_EJECT_GUARD_LABEL,
+ scope=resolved_scope,
+ plist_path=paths.plist_path,
+ binary_path=paths.binary_path,
+ changed=plist_changed or compiled or cleanup_removed is not None or (dry_run and needs_compile),
+ compiled=compiled,
+ started=start and not dry_run,
+ dry_run=dry_run,
+ cleanup_removed=cleanup_removed,
+ cleanup_skipped=cleanup_skipped,
+ )
+
+
+def ensure_sd_eject_guard_binary(
+ *,
+ scope: SdEjectGuardScope = "auto",
+ source_path: Path | None = None,
+ user_paths: SdEjectGuardPaths | None = None,
+ system_paths: SdEjectGuardPaths | None = None,
+) -> SdEjectGuardPaths:
+ resolved_scope = resolve_sd_eject_guard_scope(scope)
+ if resolved_scope == "system" and not can_install_system_scope():
+ raise SdEjectGuardInstallError(
+ "system SD eject guard run requires root privileges; "
+ "rerun with sudo or use --scope user"
+ )
+
+ paths = paths_for_scope(resolved_scope, user_paths=user_paths, system_paths=system_paths)
+ source = source_path or packaged_sd_eject_guard_source()
+ source_context = as_file(source) if not isinstance(source, Path) else _path_context(source)
+ with source_context as resolved_source:
+ paths.binary_path.parent.mkdir(parents=True, exist_ok=True)
+ if binary_needs_compile(paths.binary_path, resolved_source):
+ compile_sd_eject_guard(resolved_source, paths.binary_path)
+ paths.binary_path.chmod(0o755)
+ if resolved_scope == "system":
+ apply_system_ownership(paths.binary_path)
+ return paths
+
+
+def run_sd_eject_guard_interactive(
+ *,
+ scope: SdEjectGuardScope = "auto",
+ source_path: Path | None = None,
+ user_paths: SdEjectGuardPaths | None = None,
+ system_paths: SdEjectGuardPaths | None = None,
+) -> int:
+ paths = ensure_sd_eject_guard_binary(
+ scope=scope,
+ source_path=source_path,
+ user_paths=user_paths,
+ system_paths=system_paths,
+ )
+ try:
+ return subprocess.run([str(paths.binary_path)], check=False).returncode
+ except KeyboardInterrupt:
+ return 130
+
+
+def stop_sd_eject_guard(
+ *,
+ scope: SdEjectGuardScope = "auto",
+ user_paths: SdEjectGuardPaths | None = None,
+ system_paths: SdEjectGuardPaths | None = None,
+ dry_run: bool = False,
+) -> tuple[SdEjectGuardStopResult, ...]:
+ scopes: tuple[ResolvedSdEjectGuardScope, ...]
+ if scope == "auto":
+ scopes = ("user", "system")
+ elif scope in ("user", "system"):
+ scopes = (scope,)
+ else:
+ raise SdEjectGuardInstallError(f"unknown SD eject guard scope: {scope}")
+
+ results: list[SdEjectGuardStopResult] = []
+ for resolved_scope in scopes:
+ paths = paths_for_scope(resolved_scope, user_paths=user_paths, system_paths=system_paths)
+ if not paths.plist_path.exists():
+ results.append(
+ SdEjectGuardStopResult(
+ label=SD_EJECT_GUARD_LABEL,
+ scope=resolved_scope,
+ plist_path=paths.plist_path,
+ stopped=False,
+ )
+ )
+ continue
+
+ if resolved_scope == "system" and not can_install_system_scope():
+ message = f"missing permissions to stop {paths.plist_path}"
+ if scope == "system":
+ raise SdEjectGuardInstallError(message)
+ results.append(
+ SdEjectGuardStopResult(
+ label=SD_EJECT_GUARD_LABEL,
+ scope=resolved_scope,
+ plist_path=paths.plist_path,
+ stopped=False,
+ skipped=message,
+ )
+ )
+ continue
+
+ if not dry_run:
+ bootout_sd_eject_guard(paths.plist_path, resolved_scope)
+ results.append(
+ SdEjectGuardStopResult(
+ label=SD_EJECT_GUARD_LABEL,
+ scope=resolved_scope,
+ plist_path=paths.plist_path,
+ stopped=True,
+ )
+ )
+ return tuple(results)
+
+
+def resolve_sd_eject_guard_scope(scope: SdEjectGuardScope) -> ResolvedSdEjectGuardScope:
+ if scope == "auto":
+ return "system" if can_install_system_scope() else "user"
+ if scope in ("system", "user"):
+ return scope
+ raise SdEjectGuardInstallError(f"unknown SD eject guard scope: {scope}")
+
+
+def can_install_system_scope() -> bool:
+ return os.geteuid() == 0
+
+
+def paths_for_scope(
+ scope: ResolvedSdEjectGuardScope,
+ *,
+ user_paths: SdEjectGuardPaths | None = None,
+ system_paths: SdEjectGuardPaths | None = None,
+) -> SdEjectGuardPaths:
+ if scope == "system":
+ return system_paths or system_sd_eject_guard_paths()
+ return user_paths or user_sd_eject_guard_paths()
+
+
+def user_sd_eject_guard_paths(home: Path | None = None) -> SdEjectGuardPaths:
+ base = home or Path.home()
+ data_dir = default_user_data_dir(home) / "sidepulse" / "sd-eject-guard"
+ state_dir = default_state_dir(home)
+ return SdEjectGuardPaths(
+ scope="user",
+ plist_path=base / "Library" / "LaunchAgents" / SD_EJECT_GUARD_FILENAME,
+ binary_path=data_dir / SD_EJECT_GUARD_BINARY_NAME,
+ stdout_path=state_dir / "sd-eject-guard.out.log",
+ stderr_path=state_dir / "sd-eject-guard.err.log",
+ )
+
+
+def system_sd_eject_guard_paths() -> SdEjectGuardPaths:
+ return SdEjectGuardPaths(
+ scope="system",
+ plist_path=Path("/Library/LaunchDaemons") / SD_EJECT_GUARD_FILENAME,
+ binary_path=Path("/Library/Application Support/SidePulse/sd-eject-guard")
+ / SD_EJECT_GUARD_BINARY_NAME,
+ stdout_path=Path("/Library/Logs/SidePulse/sd-eject-guard.out.log"),
+ stderr_path=Path("/Library/Logs/SidePulse/sd-eject-guard.err.log"),
+ )
+
+
+def default_user_data_dir(home: Path | None = None) -> Path:
+ if home is None:
+ xdg_data_home = os.environ.get("XDG_DATA_HOME")
+ if xdg_data_home:
+ return Path(xdg_data_home).expanduser()
+ base = home or Path.home()
+ return base / ".local" / "share"
+
+
+def build_sd_eject_guard_plist(paths: SdEjectGuardPaths) -> dict[str, Any]:
+ return {
+ "Label": SD_EJECT_GUARD_LABEL,
+ "ProgramArguments": [str(paths.binary_path)],
+ "RunAtLoad": True,
+ "KeepAlive": True,
+ "StandardOutPath": str(paths.stdout_path),
+ "StandardErrorPath": str(paths.stderr_path),
+ "WorkingDirectory": "/",
+ }
+
+
+def log_paths_for_scope(scope: ResolvedSdEjectGuardScope) -> tuple[Path, Path]:
+ paths = paths_for_scope(scope)
+ return paths.stdout_path, paths.stderr_path
+
+
+def log_paths_for_requested_scope(scope: SdEjectGuardScope = "auto") -> tuple[Path, ...]:
+ if scope == "auto":
+ scopes: tuple[ResolvedSdEjectGuardScope, ...] = ("user", "system")
+ elif scope in ("user", "system"):
+ scopes = (scope,)
+ else:
+ raise SdEjectGuardInstallError(f"unknown SD eject guard scope: {scope}")
+
+ paths: list[Path] = []
+ seen: set[Path] = set()
+ for resolved_scope in scopes:
+ for path in log_paths_for_scope(resolved_scope):
+ if path in seen:
+ continue
+ seen.add(path)
+ paths.append(path)
+ return tuple(paths)
+
+
+def read_log_tail(path: Path, line_count: int = 80) -> str:
+ if line_count <= 0:
+ return ""
+ try:
+ lines = path.read_text(errors="replace").splitlines()
+ except FileNotFoundError:
+ return ""
+ except OSError as exc:
+ return f"(unreadable: {exc})"
+ return "\n".join(lines[-line_count:])
+
+
+def packaged_sd_eject_guard_source():
+ return files("agent_monitor.resources").joinpath("sd_eject_guard.c")
+
+
+def binary_needs_compile(binary_path: Path, source_path: Path) -> bool:
+ if not binary_path.exists():
+ return True
+ try:
+ return binary_path.stat().st_mtime < source_path.stat().st_mtime
+ except OSError:
+ return True
+
+
+def compile_sd_eject_guard(source_path: Path, binary_path: Path) -> None:
+ tmp_binary = binary_path.with_name(f"{binary_path.name}.tmp")
+ subprocess.run(
+ [
+ "clang",
+ "-O2",
+ "-o",
+ str(tmp_binary),
+ str(source_path),
+ "-framework",
+ "DiskArbitration",
+ "-framework",
+ "CoreFoundation",
+ ],
+ check=True,
+ )
+ tmp_binary.chmod(0o755)
+ tmp_binary.replace(binary_path)
+
+
+def restart_sd_eject_guard(
+ plist_path: Path,
+ scope: ResolvedSdEjectGuardScope,
+) -> None:
+ domain = launch_domain(scope)
+ bootout_sd_eject_guard(plist_path, scope)
+ subprocess.run(["launchctl", "bootstrap", domain, str(plist_path)], check=True)
+ subprocess.run(
+ ["launchctl", "kickstart", "-k", f"{domain}/{SD_EJECT_GUARD_LABEL}"],
+ check=False,
+ )
+
+
+def bootout_sd_eject_guard(
+ plist_path: Path,
+ scope: ResolvedSdEjectGuardScope,
+) -> None:
+ subprocess.run(
+ ["launchctl", "bootout", launch_domain(scope), str(plist_path)],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ check=False,
+ )
+
+
+def launch_domain(scope: ResolvedSdEjectGuardScope) -> str:
+ if scope == "system":
+ return "system"
+ return f"gui/{os.getuid()}"
+
+
+@dataclass(frozen=True)
+class CleanupResult:
+ removed: Path | None = None
+ skipped: str | None = None
+
+
+def cleanup_other_scope(
+ installed_scope: ResolvedSdEjectGuardScope,
+ *,
+ user_paths: SdEjectGuardPaths | None = None,
+ system_paths: SdEjectGuardPaths | None = None,
+) -> CleanupResult:
+ other_scope: ResolvedSdEjectGuardScope = "user" if installed_scope == "system" else "system"
+ paths = paths_for_scope(other_scope, user_paths=user_paths, system_paths=system_paths)
+ if not paths.plist_path.exists():
+ return CleanupResult()
+ if other_scope == "system" and not can_install_system_scope():
+ return CleanupResult(
+ skipped=f"missing permissions to remove {paths.plist_path}",
+ )
+
+ bootout_sd_eject_guard(paths.plist_path, other_scope)
+ paths.plist_path.unlink()
+ return CleanupResult(removed=paths.plist_path)
+
+
+def apply_system_ownership(path: Path) -> None:
+ os.chown(path, 0, 0)
+
+
+class _path_context:
+ def __init__(self, path: Path) -> None:
+ self.path = path
+
+ def __enter__(self) -> Path:
+ return self.path
+
+ def __exit__(self, *_exc: object) -> None:
+ return None
diff --git a/src/agent_monitor/session_actions.py b/src/agent_monitor/session_actions.py
index 99949aa..48b5a84 100644
--- a/src/agent_monitor/session_actions.py
+++ b/src/agent_monitor/session_actions.py
@@ -2,10 +2,15 @@ from __future__ import annotations
import shlex
from pathlib import Path
-from urllib.parse import quote
+from urllib.parse import quote, urlencode
from .models import AgentStatus
+SESSION_OPEN_APP = "app"
+SESSION_OPEN_TERMINAL = "terminal"
+SESSION_OPEN_VSCODE = "vscode"
+SESSION_OPEN_CHOICES = (SESSION_OPEN_APP, SESSION_OPEN_TERMINAL, SESSION_OPEN_VSCODE)
+
def session_deep_link(status: AgentStatus) -> str | None:
provider = status.provider.lower()
@@ -18,6 +23,15 @@ def session_deep_link(status: AgentStatus) -> str | None:
return None
+def session_vscode_link(status: AgentStatus) -> str | None:
+ if status.provider.lower() != "claude" or not status.session_id:
+ return None
+ return "vscode://anthropic.claude-code/open?" + urlencode(
+ {"session": status.session_id},
+ quote_via=quote,
+ )
+
+
def session_resume_command(status: AgentStatus) -> str | None:
if not status.session_id:
return None
@@ -31,3 +45,43 @@ def session_resume_command(status: AgentStatus) -> str | None:
if provider == "claude":
return f"cd {cwd} && claude --resume {session_id}"
return None
+
+
+def default_session_open_action(status: AgentStatus) -> str:
+ if status.provider.lower() == "claude" and session_vscode_link(status):
+ return SESSION_OPEN_VSCODE
+ if session_deep_link(status):
+ return SESSION_OPEN_APP
+ return SESSION_OPEN_TERMINAL
+
+
+def session_open_target(status: AgentStatus, action: str) -> tuple[str, str] | None:
+ if action == SESSION_OPEN_APP:
+ url = session_deep_link(status)
+ return ("url", url) if url else None
+ if action == SESSION_OPEN_VSCODE:
+ url = session_vscode_link(status)
+ return ("url", url) if url else None
+ if action == SESSION_OPEN_TERMINAL:
+ command = session_resume_command(status)
+ return ("terminal", command) if command else None
+ return None
+
+
+def available_session_open_actions(status: AgentStatus) -> tuple[str, ...]:
+ return tuple(action for action in SESSION_OPEN_CHOICES if session_open_target(status, action))
+
+
+def session_open_action_label(status: AgentStatus, action: str) -> str:
+ provider = status.provider.lower()
+ if action == SESSION_OPEN_APP:
+ if provider == "codex":
+ return "Open in Codex"
+ if provider == "claude":
+ return "Open Claude App"
+ return "Open App"
+ if action == SESSION_OPEN_VSCODE:
+ return "Open in VS Code"
+ if action == SESSION_OPEN_TERMINAL:
+ return "Resume in Terminal"
+ return action
diff --git a/src/agent_monitor/settings.py b/src/agent_monitor/settings.py
index 3ef2a4e..cd76d9a 100644
--- a/src/agent_monitor/settings.py
+++ b/src/agent_monitor/settings.py
@@ -2,16 +2,71 @@ from __future__ import annotations
import json
import os
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
from .battery import DEFAULT_POWER_CHANGE_PREVIEW_SECONDS
+from .session_actions import SESSION_OPEN_CHOICES
LED_DISPLAY_AGENT = "agent"
LED_DISPLAY_BATTERY = "battery"
LED_DISPLAY_CHOICES = (LED_DISPLAY_AGENT, LED_DISPLAY_BATTERY)
+CLOSED_LID_AWAKE_NEVER = "never"
+CLOSED_LID_AWAKE_AGENTS = "agents"
+CLOSED_LID_AWAKE_ALWAYS = "always"
+CLOSED_LID_AWAKE_CHOICES = (
+ CLOSED_LID_AWAKE_NEVER,
+ CLOSED_LID_AWAKE_AGENTS,
+ CLOSED_LID_AWAKE_ALWAYS,
+)
+LID_ANIMATION_CLOSED = "closed"
+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",
+ ]
+)
+DEFAULT_LID_OPEN_ANIMATION_PROGRAM = "\n".join(
+ [
+ "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-out",
+ ]
+)
+DEFAULT_LID_CLOSED_ANIMATION_SECONDS = 0.9
+DEFAULT_LID_OPEN_ANIMATION_SECONDS = 1.0
+
+
+@dataclass(frozen=True)
+class LedAnimationSetting:
+ program: str
+ duration_seconds: float
+
+ def to_dict(self) -> dict[str, object]:
+ return {
+ "program": self.program,
+ "duration_seconds": self.duration_seconds,
+ }
@dataclass(frozen=True)
@@ -20,13 +75,15 @@ class DeviceDisplaySetting:
name: str
path: str
led_display: str = LED_DISPLAY_AGENT
+ brightness: int = 255
- def to_dict(self) -> dict[str, str]:
+ def to_dict(self) -> dict[str, object]:
return {
"id": self.device_id,
"name": self.name,
"path": self.path,
"led_display": self.led_display,
+ "brightness": self.brightness,
}
@@ -36,9 +93,18 @@ class AgentMonitorSettings:
claude_transcripts_enabled: bool = False
led_display: str = LED_DISPLAY_AGENT
devices: tuple[DeviceDisplaySetting, ...] = ()
+ closed_lid_awake_policy: str = CLOSED_LID_AWAKE_NEVER
+ closed_lid_system_override_enabled: bool = False
+ lid_closed_animation: LedAnimationSetting = field(
+ default_factory=lambda: default_lid_animation(LID_ANIMATION_CLOSED)
+ )
+ lid_open_animation: LedAnimationSetting = field(
+ default_factory=lambda: default_lid_animation(LID_ANIMATION_OPEN)
+ )
battery_full_charge_watts: float | None = None
battery_show_on_power_change: bool = True
battery_power_change_preview_seconds: float = DEFAULT_POWER_CHANGE_PREVIEW_SECONDS
+ session_open_preferences: dict[str, str] = field(default_factory=dict)
def transcript_enabled(self, provider: str) -> bool:
if provider == "codex":
@@ -65,6 +131,12 @@ class AgentMonitorSettings:
return device.led_display
return self.led_display
+ def brightness_for_device(self, device_id: str) -> int:
+ for device in self.devices:
+ if device.device_id == device_id:
+ return normalize_brightness(device.brightness)
+ return 255
+
def with_device_display(
self,
device_id: str,
@@ -86,6 +158,7 @@ class AgentMonitorSettings:
name=name or device.name,
path=path or device.path,
led_display=display,
+ brightness=device.brightness,
)
)
updated = True
@@ -98,6 +171,44 @@ class AgentMonitorSettings:
name=name or device_id,
path=path or device_id,
led_display=display,
+ brightness=self.brightness_for_device(device_id),
+ )
+ )
+ return replace(self, devices=tuple(devices))
+
+ def with_device_brightness(
+ self,
+ device_id: str,
+ brightness: int | float,
+ *,
+ name: str | None = None,
+ path: str | None = None,
+ ) -> "AgentMonitorSettings":
+ value = normalize_brightness(brightness)
+ devices: list[DeviceDisplaySetting] = []
+ updated = False
+ for device in self.devices:
+ if device.device_id == device_id:
+ devices.append(
+ DeviceDisplaySetting(
+ device_id=device.device_id,
+ name=name or device.name,
+ path=path or device.path,
+ led_display=device.led_display,
+ brightness=value,
+ )
+ )
+ updated = True
+ else:
+ devices.append(device)
+ if not updated:
+ devices.append(
+ DeviceDisplaySetting(
+ device_id=device_id,
+ name=name or device_id,
+ path=path or device_id,
+ led_display=self.display_for_device(device_id),
+ brightness=value,
)
)
return replace(self, devices=tuple(devices))
@@ -116,6 +227,26 @@ class AgentMonitorSettings:
path=path,
)
+ def without_device(self, device_id: str) -> "AgentMonitorSettings":
+ devices = tuple(device for device in self.devices if device.device_id != device_id)
+ if devices == self.devices:
+ return self
+ return replace(self, devices=devices)
+
+ def session_open_action(self, provider: str) -> str | None:
+ action = self.session_open_preferences.get(provider.lower())
+ if action in SESSION_OPEN_CHOICES:
+ return action
+ return None
+
+ def with_session_open_action(self, provider: str, action: str) -> "AgentMonitorSettings":
+ if action not in SESSION_OPEN_CHOICES:
+ raise ValueError(f"Unknown session open action: {action}")
+ key = provider.lower()
+ preferences = dict(self.session_open_preferences)
+ preferences[key] = action
+ return replace(self, session_open_preferences=preferences)
+
def with_battery_full_charge_watts(self, watts: float | None) -> "AgentMonitorSettings":
if watts is not None and watts <= 0:
watts = None
@@ -138,10 +269,46 @@ class AgentMonitorSettings:
battery_power_change_preview_seconds=preview_seconds,
)
+ def lid_animation(self, kind: str) -> LedAnimationSetting:
+ if kind == LID_ANIMATION_CLOSED:
+ return self.lid_closed_animation
+ if kind == LID_ANIMATION_OPEN:
+ return self.lid_open_animation
+ raise ValueError(f"Unknown lid animation: {kind}")
+
+ def with_closed_lid_awake_policy(self, policy: str) -> "AgentMonitorSettings":
+ if policy not in CLOSED_LID_AWAKE_CHOICES:
+ raise ValueError(f"Unknown closed-lid awake policy: {policy}")
+ return replace(self, closed_lid_awake_policy=policy)
+
+ def with_closed_lid_system_override(self, enabled: bool) -> "AgentMonitorSettings":
+ return replace(self, closed_lid_system_override_enabled=bool(enabled))
+
+ def with_lid_animation(
+ self,
+ kind: str,
+ *,
+ program: str,
+ duration_seconds: float,
+ ) -> "AgentMonitorSettings":
+ animation = LedAnimationSetting(
+ program=program,
+ duration_seconds=normalize_animation_duration(duration_seconds),
+ )
+ if kind == LID_ANIMATION_CLOSED:
+ return replace(self, lid_closed_animation=animation)
+ if kind == LID_ANIMATION_OPEN:
+ return replace(self, lid_open_animation=animation)
+ raise ValueError(f"Unknown lid animation: {kind}")
+
def to_dict(self) -> dict[str, Any]:
return {
"led_display": self.led_display,
"devices": [device.to_dict() for device in self.devices],
+ "closed_lid_awake_policy": self.closed_lid_awake_policy,
+ "closed_lid_system_override_enabled": self.closed_lid_system_override_enabled,
+ "lid_closed_animation": self.lid_closed_animation.to_dict(),
+ "lid_open_animation": self.lid_open_animation.to_dict(),
"transcript_monitoring": {
"codex": self.codex_transcripts_enabled,
"claude": self.claude_transcripts_enabled,
@@ -151,6 +318,7 @@ class AgentMonitorSettings:
"show_on_power_change": self.battery_show_on_power_change,
"power_change_preview_seconds": self.battery_power_change_preview_seconds,
},
+ "session_open_preferences": dict(sorted(self.session_open_preferences.items())),
}
@@ -195,6 +363,21 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:
claude_transcripts_enabled=_bool_setting(transcript.get("claude"), False),
led_display=led_display,
devices=_device_display_settings(data.get("devices"), led_display),
+ closed_lid_awake_policy=_closed_lid_awake_policy(
+ data.get("closed_lid_awake_policy"),
+ ),
+ closed_lid_system_override_enabled=_bool_setting(
+ data.get("closed_lid_system_override_enabled"),
+ False,
+ ),
+ lid_closed_animation=_lid_animation_setting(
+ data.get("lid_closed_animation"),
+ default_lid_animation(LID_ANIMATION_CLOSED),
+ ),
+ lid_open_animation=_lid_animation_setting(
+ data.get("lid_open_animation"),
+ default_lid_animation(LID_ANIMATION_OPEN),
+ ),
battery_full_charge_watts=_optional_float_setting(
battery.get("full_charge_watts"),
),
@@ -206,6 +389,7 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:
battery.get("power_change_preview_seconds"),
DEFAULT_POWER_CHANGE_PREVIEW_SECONDS,
),
+ session_open_preferences=_session_open_preferences(data.get("session_open_preferences")),
)
@@ -231,6 +415,12 @@ def _led_display_setting(value: object, default: str) -> str:
return default
+def _closed_lid_awake_policy(value: object) -> str:
+ if isinstance(value, str) and value in CLOSED_LID_AWAKE_CHOICES:
+ return value
+ return CLOSED_LID_AWAKE_NEVER
+
+
def _device_display_settings(value: object, default_display: str) -> tuple[DeviceDisplaySetting, ...]:
if not isinstance(value, list):
return ()
@@ -252,18 +442,33 @@ def _device_display_settings(value: object, default_display: str) -> tuple[Devic
if not isinstance(name, str) or not name:
name = Path(path).name or device_id
display = _led_display_setting(item.get("led_display"), default_display)
+ brightness = normalize_brightness(item.get("brightness"))
devices.append(
DeviceDisplaySetting(
device_id=device_id,
name=name,
path=path,
led_display=display,
+ brightness=brightness,
)
)
seen.add(device_id)
return tuple(devices)
+def _session_open_preferences(value: object) -> dict[str, str]:
+ if not isinstance(value, dict):
+ return {}
+ result: dict[str, str] = {}
+ for provider, action in value.items():
+ if not isinstance(provider, str) or not isinstance(action, str):
+ continue
+ if action not in SESSION_OPEN_CHOICES:
+ continue
+ result[provider.lower()] = action
+ return result
+
+
def _optional_float_setting(value: object) -> float | None:
if value is None:
return None
@@ -276,3 +481,49 @@ def _float_setting(value: object, default: float) -> float:
if isinstance(value, (int, float)):
return float(value)
return default
+
+
+def normalize_brightness(value: object) -> int:
+ if value is None:
+ return 255
+ if isinstance(value, (int, float)):
+ return max(0, min(255, int(round(float(value)))))
+ return 255
+
+
+def default_lid_animation(kind: str) -> LedAnimationSetting:
+ if kind == LID_ANIMATION_CLOSED:
+ return LedAnimationSetting(
+ program=DEFAULT_LID_CLOSED_ANIMATION_PROGRAM,
+ duration_seconds=DEFAULT_LID_CLOSED_ANIMATION_SECONDS,
+ )
+ if kind == LID_ANIMATION_OPEN:
+ return LedAnimationSetting(
+ program=DEFAULT_LID_OPEN_ANIMATION_PROGRAM,
+ duration_seconds=DEFAULT_LID_OPEN_ANIMATION_SECONDS,
+ )
+ raise ValueError(f"Unknown lid animation: {kind}")
+
+
+def normalize_animation_duration(value: object) -> float:
+ if not isinstance(value, (int, float)):
+ return 1.0
+ return max(0.1, min(10.0, float(value)))
+
+
+def _lid_animation_setting(
+ value: object,
+ default: LedAnimationSetting,
+) -> LedAnimationSetting:
+ if not isinstance(value, dict):
+ return default
+ program = value.get("program")
+ if not isinstance(program, str) or not program.strip():
+ program = default.program
+ duration = value.get("duration_seconds")
+ if not isinstance(duration, (int, float)):
+ duration = default.duration_seconds
+ return LedAnimationSetting(
+ program=program,
+ duration_seconds=normalize_animation_duration(duration),
+ )
diff --git a/src/agent_monitor/status_bar.py b/src/agent_monitor/status_bar.py
index f1545b7..2dba06c 100644
--- a/src/agent_monitor/status_bar.py
+++ b/src/agent_monitor/status_bar.py
@@ -18,13 +18,18 @@ try:
NSBezelStyleRounded,
NSButton,
NSButtonTypeSwitch,
+ NSFont,
NSImage,
NSMenu,
NSMenuItem,
NSOffState,
NSOnState,
+ NSScrollView,
+ NSSlider,
NSStatusBar,
NSTextField,
+ NSTextView,
+ NSView,
NSWorkspace,
NSWindow,
NSWindowStyleMaskClosable,
@@ -42,7 +47,6 @@ except ImportError as exc: # pragma: no cover - only exercised on non-macOS set
from .battery import (
BatteryLedController,
BatterySnapshot,
- battery_state_label,
format_watts,
read_battery_snapshot,
)
@@ -51,9 +55,13 @@ from .device_writer import (
DEFAULT_FILE_NAME,
MOUNT_ROOT,
DeviceCandidate,
+ DeviceWriteError,
discover_devices,
+ normalize_led_text,
path_exists,
target_from_device_path,
+ validate_led_text,
+ write_led_program,
)
from .keep_awake import KEEPALIVE_FILE_NAME, KeepAwakeController
from .ipc import HookEventServer, default_event_socket_path, default_latest_state_path
@@ -63,7 +71,21 @@ from .install import (
uninstall_claude_hooks,
uninstall_codex_hooks,
)
-from .led_status import AgentLedController, normalized_device_name, write_mode_to_leds
+from .led_status import (
+ AgentLedController,
+ apply_brightness,
+ brightness_percent,
+ normalize_brightness,
+ normalized_device_name,
+ write_mode_to_leds,
+)
+from .lid_sleep import (
+ LID_POLL_SECONDS,
+ ClosedLidAwakeController,
+ read_lid_closed,
+ sleep_helper_install_command,
+ sleep_helper_installed,
+)
from .models import AgentMode, AgentStatus
from .providers import (
ProviderConfig,
@@ -72,12 +94,26 @@ from .providers import (
detect_log_path,
parse_log_line,
)
-from .session_actions import session_deep_link, session_resume_command
+from .session_actions import (
+ available_session_open_actions,
+ default_session_open_action,
+ session_open_action_label,
+ session_open_target,
+)
from .settings import (
+ CLOSED_LID_AWAKE_AGENTS,
+ CLOSED_LID_AWAKE_ALWAYS,
+ CLOSED_LID_AWAKE_CHOICES,
+ CLOSED_LID_AWAKE_NEVER,
LED_DISPLAY_AGENT,
LED_DISPLAY_BATTERY,
+ LID_ANIMATION_CLOSED,
+ LID_ANIMATION_OPEN,
+ LedAnimationSetting,
default_settings_path,
+ default_lid_animation,
load_settings,
+ normalize_animation_duration,
save_settings,
)
@@ -97,6 +133,7 @@ class StatusBarDevice:
target: Path
connected: bool
display: str
+ brightness: int = 255
reason: str = ""
@@ -109,6 +146,16 @@ STATUS_BAR_KEEPALIVE_VOLUME_NAMES = ("SidePulse", "PulseDot")
STATUS_BAR_REFRESH_SECONDS = 15.0
STATUS_BAR_MAX_LINES_PER_SOURCE = 500
STATUS_BAR_STARTUP_REPLAY_LINES = 200
+LID_ANIMATION_RESTORE_FUDGE_SECONDS = 0.15
+LID_ANIMATION_LABELS = {
+ LID_ANIMATION_CLOSED: "Lid Closed",
+ LID_ANIMATION_OPEN: "Lid Open",
+}
+CLOSED_LID_AWAKE_LABELS = {
+ CLOSED_LID_AWAKE_NEVER: "Never",
+ CLOSED_LID_AWAKE_AGENTS: "When Agents Work",
+ CLOSED_LID_AWAKE_ALWAYS: "Always",
+}
def state_for_mode(mode: AgentMode) -> StatusBarState:
@@ -160,6 +207,7 @@ class StatusBarController(NSObject):
self.event_server = None
self.status_item = None
self.timer = None
+ self.lid_timer = None
self.settings_window = None
self.settings_fields = {}
self.settings_buttons = {}
@@ -180,9 +228,17 @@ class StatusBarController(NSObject):
self.last_led_error = None
self.last_led_display_kind = LED_DISPLAY_AGENT
self.keep_awake = KeepAwakeController()
+ self.closed_lid_awake = ClosedLidAwakeController(
+ use_system_disable=self.settings.closed_lid_system_override_enabled,
+ )
self.last_keep_awake_error = None
+ self.last_closed_lid_awake_error = None
self.last_status_read_error = None
self.event_refresh_pending = False
+ self.last_lid_closed = None
+ self.last_lid_error = None
+ self.led_animation_until_monotonic = 0.0
+ self.led_animation_token = 0
return self
def applicationDidFinishLaunching_(self, _notification):
@@ -208,6 +264,13 @@ class StatusBarController(NSObject):
None,
True,
)
+ self.lid_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
+ LID_POLL_SECONDS,
+ self,
+ "pollLid:",
+ None,
+ True,
+ )
@objc.IBAction
def refresh_(self, _sender):
@@ -242,9 +305,7 @@ class StatusBarController(NSObject):
url = sender.representedObject()
if not url:
return
- ns_url = NSURL.URLWithString_(str(url))
- if ns_url is not None:
- NSWorkspace.sharedWorkspace().openURL_(ns_url)
+ open_url(str(url))
@objc.IBAction
def resumeSession_(self, sender):
@@ -252,6 +313,17 @@ class StatusBarController(NSObject):
if command:
open_terminal_command(str(command))
+ @objc.IBAction
+ def openSession_(self, sender):
+ self.open_session(sender.representedObject(), None, remember=False)
+
+ @objc.IBAction
+ def openSessionWithAction_(self, sender):
+ payload = sender.representedObject()
+ if not isinstance(payload, dict):
+ return
+ self.open_session(payload.get("status"), payload.get("action"), remember=True)
+
@objc.IBAction
def toggleDeviceConnection_(self, _sender):
if self.device_connected():
@@ -266,6 +338,18 @@ class StatusBarController(NSObject):
log_status_bar(f"keep_awake={'on' if self.keep_awake.enabled else 'off'}")
self.refresh_(None)
+ @objc.IBAction
+ def setClosedLidAwakePolicy_(self, sender):
+ self.set_closed_lid_awake_policy(sender.representedObject())
+
+ @objc.IBAction
+ def toggleClosedLidSystemOverride_(self, sender):
+ if hasattr(sender, "state"):
+ enabled = sender.state() != NSOnState
+ else:
+ enabled = not self.settings.closed_lid_system_override_enabled
+ self.set_closed_lid_system_override(enabled)
+
@objc.IBAction
def openSettings_(self, _sender):
self.show_settings_window()
@@ -310,6 +394,10 @@ class StatusBarController(NSObject):
def setBatteryPowerPreviewFromCheckbox_(self, sender):
self.set_battery_power_preview(sender.state() == NSOnState)
+ @objc.IBAction
+ def setClosedLidSystemOverrideFromCheckbox_(self, sender):
+ self.set_closed_lid_system_override(sender.state() == NSOnState)
+
@objc.IBAction
def setDeviceDisplayAgent_(self, sender):
self.set_device_display(sender.representedObject(), LED_DISPLAY_AGENT)
@@ -318,13 +406,50 @@ class StatusBarController(NSObject):
def setDeviceDisplayBattery_(self, sender):
self.set_device_display(sender.representedObject(), LED_DISPLAY_BATTERY)
+ @objc.IBAction
+ def setDeviceBrightness_(self, sender):
+ device_id = sender.identifier()
+ if device_id is None:
+ return
+ self.set_device_brightness(str(device_id), sender.doubleValue())
+
+ @objc.IBAction
+ def saveLidAnimations_(self, _sender):
+ self.save_lid_animations_from_fields()
+
+ @objc.IBAction
+ def previewLidClosedAnimation_(self, _sender):
+ animation = self.lid_animation_from_fields(LID_ANIMATION_CLOSED)
+ if animation is not None:
+ self.play_lid_animation(LID_ANIMATION_CLOSED, animation=animation)
+
+ @objc.IBAction
+ def previewLidOpenAnimation_(self, _sender):
+ animation = self.lid_animation_from_fields(LID_ANIMATION_OPEN)
+ if animation is not None:
+ self.play_lid_animation(LID_ANIMATION_OPEN, animation=animation)
+
+ @objc.IBAction
+ def resetLidClosedAnimation_(self, _sender):
+ self.reset_lid_animation(LID_ANIMATION_CLOSED)
+
+ @objc.IBAction
+ def resetLidOpenAnimation_(self, _sender):
+ self.reset_lid_animation(LID_ANIMATION_OPEN)
+
+ @objc.IBAction
+ def removeRememberedDevice_(self, sender):
+ self.remove_remembered_device(sender.representedObject())
+
@objc.IBAction
def quit_(self, _sender):
+ self.closed_lid_awake.release()
self.keep_awake.release()
NSApp.terminate_(self)
def applicationWillTerminate_(self, _notification):
self.stop_event_server()
+ self.closed_lid_awake.release()
self.keep_awake.release()
def set_status(self, state: StatusBarState) -> None:
@@ -440,6 +565,28 @@ class StatusBarController(NSObject):
self.settings_buttons.get("battery_power_preview"),
self.settings.battery_show_on_power_change,
)
+ set_checkbox_state(
+ self.settings_buttons.get("closed_lid_system_override"),
+ self.settings.closed_lid_system_override_enabled,
+ )
+ closed = self.settings.lid_closed_animation
+ opened = self.settings.lid_open_animation
+ set_text_control_value(
+ self.settings_fields.get("closed_animation_program"),
+ closed.program,
+ )
+ set_text_control_value(
+ self.settings_fields.get("closed_animation_duration"),
+ f"{closed.duration_seconds:g}",
+ )
+ set_text_control_value(
+ self.settings_fields.get("open_animation_program"),
+ opened.program,
+ )
+ set_text_control_value(
+ self.settings_fields.get("open_animation_duration"),
+ f"{opened.duration_seconds:g}",
+ )
def set_settings_message(self, message: str) -> None:
set_field_value(self.settings_fields.get("message"), message)
@@ -532,6 +679,213 @@ class StatusBarController(NSObject):
self.refresh_settings_window()
self.refresh_(None)
+ def set_device_brightness(self, device_id: str | None, brightness: int | float) -> None:
+ if not device_id:
+ return
+ device = next(
+ (
+ entry
+ for entry in self.status_bar_devices(remember=False)
+ if entry.device_id == str(device_id)
+ ),
+ None,
+ )
+ value = normalize_brightness(brightness)
+ try:
+ self.settings = self.settings.with_device_brightness(
+ str(device_id),
+ value,
+ name=device.name if device else None,
+ path=str(device.root) if device else None,
+ )
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not save brightness: {exc}")
+ self.settings = load_settings()
+ return
+
+ self.reset_led_controllers_for_device(str(device_id))
+ self.set_settings_message(
+ f"{device.name if device else device_id}: brightness {brightness_percent(value)}%."
+ )
+ self.refresh_settings_window()
+ if self.last_snapshot is not None:
+ self.sync_leds(
+ self.last_snapshot.aggregate.mode,
+ self.last_battery_snapshot,
+ self.active_led_display_kind(self.last_battery_snapshot),
+ )
+
+ def set_closed_lid_awake_policy(self, policy: str | None) -> None:
+ if policy not in CLOSED_LID_AWAKE_CHOICES:
+ return
+ try:
+ self.settings = self.settings.with_closed_lid_awake_policy(str(policy))
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not save lid sleep setting: {exc}")
+ self.settings = load_settings()
+ return
+
+ self.set_settings_message(
+ f"Closed-lid awake: {CLOSED_LID_AWAKE_LABELS[self.settings.closed_lid_awake_policy]}."
+ )
+ self.sync_closed_lid_awake()
+ self.refresh_settings_window()
+ self.refresh_(None)
+
+ def set_closed_lid_system_override(self, enabled: bool) -> None:
+ try:
+ self.settings = self.settings.with_closed_lid_system_override(enabled)
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not save sleep override setting: {exc}")
+ self.settings = load_settings()
+ self.refresh_settings_window()
+ return
+
+ self.closed_lid_awake.set_use_system_disable(
+ self.settings.closed_lid_system_override_enabled
+ )
+ if self.settings.closed_lid_system_override_enabled and not sleep_helper_installed():
+ self.set_settings_message(
+ "Strong sleep override needs setup: "
+ + sleep_helper_install_command()
+ )
+ else:
+ label = "enabled" if self.settings.closed_lid_system_override_enabled else "disabled"
+ self.set_settings_message(f"Strong sleep override {label}.")
+ self.sync_closed_lid_awake()
+ self.refresh_settings_window()
+ self.refresh_(None)
+
+ def lid_animation_from_fields(self, kind: str) -> LedAnimationSetting | None:
+ program_field = self.settings_fields.get(f"{kind}_animation_program")
+ duration_field = self.settings_fields.get(f"{kind}_animation_duration")
+ current = self.settings.lid_animation(kind)
+ program = text_control_value(program_field) or current.program
+ duration_text = text_control_value(duration_field)
+ try:
+ duration = float(duration_text) if duration_text else current.duration_seconds
+ except ValueError:
+ self.set_settings_message(f"{LID_ANIMATION_LABELS[kind]} duration is not a number.")
+ return None
+
+ animation = LedAnimationSetting(
+ program=normalize_led_text(program),
+ duration_seconds=normalize_animation_duration(duration),
+ )
+ try:
+ validate_lid_animation(animation)
+ except DeviceWriteError as exc:
+ self.set_settings_message(f"{LID_ANIMATION_LABELS[kind]} animation invalid: {exc}")
+ return None
+ return animation
+
+ def save_lid_animations_from_fields(self) -> None:
+ closed = self.lid_animation_from_fields(LID_ANIMATION_CLOSED)
+ if closed is None:
+ return
+ opened = self.lid_animation_from_fields(LID_ANIMATION_OPEN)
+ if opened is None:
+ return
+ try:
+ self.settings = self.settings.with_lid_animation(
+ LID_ANIMATION_CLOSED,
+ program=closed.program,
+ duration_seconds=closed.duration_seconds,
+ )
+ self.settings = self.settings.with_lid_animation(
+ LID_ANIMATION_OPEN,
+ program=opened.program,
+ duration_seconds=opened.duration_seconds,
+ )
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not save lid animations: {exc}")
+ self.settings = load_settings()
+ self.refresh_settings_window()
+ return
+
+ self.set_settings_message("Lid animations saved.")
+ self.refresh_settings_window()
+
+ def reset_lid_animation(self, kind: str) -> None:
+ animation = default_lid_animation(kind)
+ try:
+ self.settings = self.settings.with_lid_animation(
+ kind,
+ program=animation.program,
+ duration_seconds=animation.duration_seconds,
+ )
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not reset {LID_ANIMATION_LABELS[kind]}: {exc}")
+ self.settings = load_settings()
+ self.refresh_settings_window()
+ return
+
+ self.set_settings_message(f"{LID_ANIMATION_LABELS[kind]} reset.")
+ self.refresh_settings_window()
+
+ def remove_remembered_device(self, device_id: str | None) -> None:
+ if not device_id:
+ return
+ device = next(
+ (
+ entry
+ for entry in self.status_bar_devices(remember=False)
+ if entry.device_id == str(device_id)
+ ),
+ None,
+ )
+ try:
+ self.settings = self.settings.without_device(str(device_id))
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not remove device: {exc}")
+ self.settings = load_settings()
+ return
+
+ self.reset_led_controllers_for_device(str(device_id))
+ self.set_settings_message(f"{device.name if device else device_id}: removed.")
+ self.refresh_settings_window()
+ self.refresh_(None)
+
+ def open_session(self, status: AgentStatus | object, action: str | None, *, remember: bool) -> None:
+ if not isinstance(status, AgentStatus):
+ return
+ provider = status.provider.lower()
+ requested_action = (
+ action
+ or self.settings.session_open_action(provider)
+ or default_session_open_action(status)
+ )
+ target = session_open_target(status, requested_action)
+ if target is None:
+ requested_action = default_session_open_action(status)
+ target = session_open_target(status, requested_action)
+ if target is None:
+ self.set_settings_message(f"No open action available for {status.display_name}.")
+ return
+
+ kind, value = target
+ if kind == "url":
+ open_url(value)
+ elif kind == "terminal":
+ open_terminal_command(value)
+ else:
+ self.set_settings_message(f"Unknown open action for {status.display_name}.")
+ return
+
+ if remember:
+ try:
+ self.settings = self.settings.with_session_open_action(provider, requested_action)
+ save_settings(self.settings)
+ except Exception as exc:
+ self.set_settings_message(f"Could not save open preference: {exc}")
+ self.settings = load_settings()
+
def set_battery_power_preview(self, enabled: bool) -> None:
try:
self.settings = self.settings.with_battery_power_change_preview(enabled=enabled)
@@ -612,6 +966,7 @@ class StatusBarController(NSObject):
controller = AgentLedController(device_path=device.target)
self.agent_led_controllers_by_device[device.device_id] = controller
controller.device_path = device.target
+ controller.brightness = device.brightness
return controller
def battery_controller_for_device(self, device: StatusBarDevice) -> BatteryLedController:
@@ -620,6 +975,7 @@ class StatusBarController(NSObject):
controller = BatteryLedController(device_path=device.target)
self.battery_led_controllers_by_device[device.device_id] = controller
controller.device_path = device.target
+ controller.brightness = device.brightness
return controller
def status_bar_devices(self, *, remember: bool = True) -> list[StatusBarDevice]:
@@ -640,6 +996,7 @@ class StatusBarController(NSObject):
target=candidate.target,
connected=True,
display=self.settings.display_for_device(device_id),
+ brightness=self.settings.brightness_for_device(device_id),
reason=candidate.reason,
)
@@ -654,6 +1011,7 @@ class StatusBarController(NSObject):
target=target_from_device_path(root, DEFAULT_FILE_NAME),
connected=False,
display=device.led_display,
+ brightness=device.brightness,
reason="previously connected",
)
@@ -703,6 +1061,9 @@ class StatusBarController(NSObject):
if not self.leds_enabled:
return
+ if time.monotonic() < self.led_animation_until_monotonic:
+ return
+
if self.led_sync_in_flight:
return
self.led_sync_in_flight = True
@@ -775,6 +1136,63 @@ class StatusBarController(NSObject):
self.device_errors.update(active_errors)
self.last_led_error = next(iter(self.device_errors.values()), None)
+ def play_lid_animation(
+ self,
+ kind: str,
+ *,
+ animation: LedAnimationSetting | None = None,
+ ) -> None:
+ if not self.leds_enabled:
+ return
+ animation = animation or self.settings.lid_animation(kind)
+ try:
+ validate_lid_animation(animation)
+ except DeviceWriteError as exc:
+ self.set_settings_message(f"{LID_ANIMATION_LABELS[kind]} animation invalid: {exc}")
+ return
+
+ devices = [device for device in self.status_bar_devices() if device.connected]
+ if not devices:
+ return
+
+ self.led_animation_token += 1
+ token = self.led_animation_token
+ duration = animation.duration_seconds + LID_ANIMATION_RESTORE_FUDGE_SECONDS
+ self.led_animation_until_monotonic = time.monotonic() + duration
+ thread = threading.Thread(
+ target=self.play_lid_animation_worker,
+ args=(kind, animation, devices, token),
+ daemon=True,
+ )
+ thread.start()
+
+ def play_lid_animation_worker(
+ self,
+ kind: str,
+ animation: LedAnimationSetting,
+ devices: list[StatusBarDevice],
+ token: int,
+ ) -> None:
+ label = LID_ANIMATION_LABELS[kind]
+ for device in devices:
+ try:
+ program = program_for_lid_animation(animation, brightness=device.brightness)
+ target = write_led_program(program, device_path=device.target)
+ log_status_bar(f"animation={label} device={device.name} target={target}")
+ except Exception as exc:
+ log_status_bar(f"animation error {label} {device.name}: {exc}")
+
+ time.sleep(animation.duration_seconds + LID_ANIMATION_RESTORE_FUDGE_SECONDS)
+ self.performSelectorOnMainThread_withObject_waitUntilDone_(
+ "restoreLedDisplay:",
+ str(token),
+ False,
+ )
+
+ @objc.IBAction
+ def restoreLedDisplay_(self, token_value):
+ restore_led_display(self, token_value)
+
def connect_device(self) -> None:
self.leds_enabled = True
self.status_bar_devices()
@@ -859,6 +1277,31 @@ class StatusBarController(NSObject):
self.led_controller.device_path = target
self.battery_led_controller.device_path = target
+ @objc.IBAction
+ def pollLid_(self, _sender):
+ try:
+ closed = read_lid_closed()
+ except Exception as exc:
+ error = str(exc)
+ if error != self.last_lid_error:
+ self.last_lid_error = error
+ log_status_bar(f"lid_state error: {error}")
+ return
+
+ if closed is None:
+ return
+ self.last_lid_error = None
+ if self.last_lid_closed is None:
+ self.last_lid_closed = closed
+ return
+ if closed == self.last_lid_closed:
+ return
+
+ self.last_lid_closed = closed
+ kind = LID_ANIMATION_CLOSED if closed else LID_ANIMATION_OPEN
+ log_status_bar(f"lid_state={'closed' if closed else 'open'}")
+ self.play_lid_animation(kind)
+
def sync_keep_awake(self, mode: AgentMode) -> None:
was_running = self.keep_awake.process_running()
self.keep_awake.update(mode)
@@ -870,6 +1313,8 @@ class StatusBarController(NSObject):
if self.last_keep_awake_error:
log_status_bar(f"keep_awake error: {self.last_keep_awake_error}")
+ self.sync_closed_lid_awake()
+
if not self.leds_enabled:
return
read_any = False
@@ -883,6 +1328,28 @@ class StatusBarController(NSObject):
if self.last_status_read_error:
log_status_bar(f"sd_keepalive error: {self.last_status_read_error}")
+ def sync_closed_lid_awake(self) -> None:
+ was_active = self.closed_lid_awake.active()
+ self.closed_lid_awake.set_use_system_disable(
+ self.settings.closed_lid_system_override_enabled
+ )
+ self.closed_lid_awake.update(
+ self.settings.closed_lid_awake_policy,
+ agents_active=self.keep_awake.holding_requested,
+ )
+ is_active = self.closed_lid_awake.active()
+ if was_active != is_active:
+ log_status_bar(
+ f"closed_lid_awake={'active' if is_active else 'released'} "
+ f"policy={self.settings.closed_lid_awake_policy}"
+ )
+ if self.closed_lid_awake.last_error != self.last_closed_lid_awake_error:
+ self.last_closed_lid_awake_error = self.closed_lid_awake.last_error
+ if self.last_closed_lid_awake_error:
+ log_status_bar(
+ f"closed_lid_awake error: {self.last_closed_lid_awake_error}"
+ )
+
def status_keepalive_targets(self) -> list[Path]:
targets = self.current_led_targets()
if targets:
@@ -898,143 +1365,41 @@ class StatusBarController(NSObject):
def build_menu(snapshot, state: StatusBarState, target: StatusBarController) -> NSMenu:
menu = NSMenu.alloc().init()
- title = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- f"Agent Status: {state.label}",
- None,
- "",
- )
- title.setEnabled_(False)
- menu.addItem_(title)
-
- updated = snapshot.collected_at.astimezone().strftime("%H:%M:%S")
- counts = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- f"{snapshot.aggregate.active_count} active, {snapshot.aggregate.stale_count} stale - {updated}",
- None,
- "",
- )
- counts.setEnabled_(False)
- menu.addItem_(counts)
+ menu.addItem_(disabled_menu_item("SidePulse"))
menu.addItem_(NSMenuItem.separatorItem())
- devices_title = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Devices",
- None,
- "",
- )
- devices_title.setEnabled_(False)
- menu.addItem_(devices_title)
-
- device_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "LED Output",
- "toggleDeviceConnection:",
- "",
- )
- device_item.setTarget_(target)
- device_item.setState_(1 if target.device_connected() else 0)
- menu.addItem_(device_item)
-
- detail = device_connection_detail(target)
- if detail:
- detail_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- detail,
- None,
- "",
- )
- detail_item.setEnabled_(False)
- menu.addItem_(detail_item)
-
+ menu.addItem_(disabled_menu_item("Devices"))
devices = target.status_bar_devices()
if devices:
- connected_devices = [device for device in devices if device.connected]
- previous_devices = [device for device in devices if not device.connected]
- if connected_devices:
- menu.addItem_(disabled_menu_item("Connected"))
- for device in connected_devices:
- menu.addItem_(build_device_menu_item(device, target))
- if previous_devices:
- menu.addItem_(disabled_menu_item("Previously Connected"))
- for device in previous_devices:
+ for device in devices:
menu.addItem_(build_device_menu_item(device, target))
else:
- no_devices = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "No SidePulse or PulseDot devices seen",
- None,
- "",
- )
- no_devices.setEnabled_(False)
- menu.addItem_(no_devices)
+ menu.addItem_(disabled_menu_item("No devices"))
menu.addItem_(NSMenuItem.separatorItem())
-
- keep_awake_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Keep Awake",
- "toggleKeepAwake:",
- "",
- )
- keep_awake_item.setTarget_(target)
- keep_awake_item.setState_(1 if target.keep_awake.enabled else 0)
- menu.addItem_(keep_awake_item)
-
- keep_awake_detail_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- target.keep_awake.detail(),
- None,
- "",
+ menu.addItem_(disabled_menu_item("Keep Awake With Lid Closed"))
+ for policy in CLOSED_LID_AWAKE_CHOICES:
+ menu.addItem_(build_closed_lid_awake_policy_item(policy, target))
+ menu.addItem_(build_closed_lid_system_override_item(target))
+ helper_title = (
+ "Sleep Helper Installed"
+ if sleep_helper_installed()
+ else "Sleep Helper Missing"
)
- keep_awake_detail_item.setEnabled_(False)
- menu.addItem_(keep_awake_detail_item)
-
- battery_preview_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Show Battery on Plug/Unplug",
- "toggleBatteryPowerPreview:",
- "",
- )
- battery_preview_item.setTarget_(target)
- battery_preview_item.setState_(1 if target.settings.battery_show_on_power_change else 0)
- menu.addItem_(battery_preview_item)
-
- battery_detail = battery_status_detail(target)
- if battery_detail:
- battery_detail_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- battery_detail,
- None,
- "",
- )
- battery_detail_item.setEnabled_(False)
- menu.addItem_(battery_detail_item)
+ menu.addItem_(disabled_menu_item(helper_title))
+ if target.closed_lid_awake.last_error:
+ menu.addItem_(disabled_menu_item(f"Sleep warning: {target.closed_lid_awake.last_error}"))
menu.addItem_(NSMenuItem.separatorItem())
+ menu.addItem_(disabled_menu_item("Agents"))
statuses = recent_statuses(snapshot)
if not statuses:
- empty = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "No recent sessions",
- None,
- "",
- )
- empty.setEnabled_(False)
- menu.addItem_(empty)
+ menu.addItem_(disabled_menu_item("No recent sessions"))
else:
for status in statuses:
menu.addItem_(build_session_menu_item(status, snapshot.collected_at, target))
- menu.addItem_(NSMenuItem.separatorItem())
- sources_title = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Sources",
- None,
- "",
- )
- sources_title.setEnabled_(False)
- menu.addItem_(sources_title)
- for source in snapshot.sources:
- marker = "OK" if source.path.exists() else "Missing"
- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- f"{marker} {source.provider}: {source.path}",
- None,
- "",
- )
- item.setEnabled_(False)
- menu.addItem_(item)
-
menu.addItem_(NSMenuItem.separatorItem())
settings = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
"Settings...",
@@ -1044,16 +1409,8 @@ def build_menu(snapshot, state: StatusBarState, target: StatusBarController) ->
settings.setTarget_(target)
menu.addItem_(settings)
- refresh = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Refresh",
- "forceRefresh:",
- "r",
- )
- refresh.setTarget_(target)
- menu.addItem_(refresh)
-
quit_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- "Quit Agent Status",
+ "Quit",
"quit:",
"q",
)
@@ -1063,26 +1420,34 @@ def build_menu(snapshot, state: StatusBarState, target: StatusBarController) ->
return menu
-def build_device_menu_item(device: StatusBarDevice, target: StatusBarController) -> NSMenuItem:
- title = f"{device.name} - {device_display_label(device.display)}"
- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, None, "")
- item.setImage_(
- image_for_symbol(
- device_display_symbol(device.display),
- device_display_label(device.display),
- )
+def build_closed_lid_awake_policy_item(policy: str, target: StatusBarController) -> NSMenuItem:
+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
+ CLOSED_LID_AWAKE_LABELS[policy],
+ "setClosedLidAwakePolicy:",
+ "",
)
- submenu = NSMenu.alloc().init()
+ item.setTarget_(target)
+ item.setRepresentedObject_(policy)
+ item.setState_(1 if target.settings.closed_lid_awake_policy == policy else 0)
+ return item
- status_text = "Connected" if device.connected else "Not Connected"
- submenu.addItem_(disabled_menu_item(status_text))
- location_text = f"Mounted at {device.root}" if device.connected else f"Last seen at {device.root}"
- submenu.addItem_(disabled_menu_item(location_text))
- if device.connected and device.reason:
- submenu.addItem_(disabled_menu_item(f"Detected by {device.reason}"))
+def build_closed_lid_system_override_item(target: StatusBarController) -> NSMenuItem:
+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
+ "Strong Sleep Override...",
+ "toggleClosedLidSystemOverride:",
+ "",
+ )
+ item.setTarget_(target)
+ item.setState_(1 if target.settings.closed_lid_system_override_enabled else 0)
+ return item
+
+
+def build_device_menu_item(device: StatusBarDevice, target: StatusBarController) -> NSMenuItem:
+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(device.name, None, "")
+ item.setState_(1 if device.connected else 0)
+ submenu = NSMenu.alloc().init()
- submenu.addItem_(NSMenuItem.separatorItem())
agent = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
"Agent Status",
"setDeviceDisplayAgent:",
@@ -1103,13 +1468,48 @@ def build_device_menu_item(device: StatusBarDevice, target: StatusBarController)
battery.setState_(1 if device.display == LED_DISPLAY_BATTERY else 0)
submenu.addItem_(battery)
+ submenu.addItem_(NSMenuItem.separatorItem())
+ submenu.addItem_(disabled_menu_item(f"Brightness {brightness_percent(device.brightness)}%"))
+ submenu.addItem_(build_brightness_slider_item(device, target))
+
+ if not device.connected:
+ submenu.addItem_(NSMenuItem.separatorItem())
+ submenu.addItem_(disabled_menu_item("Not connected"))
+ remove = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
+ "Remove",
+ "removeRememberedDevice:",
+ "",
+ )
+ remove.setTarget_(target)
+ remove.setRepresentedObject_(device.device_id)
+ submenu.addItem_(remove)
+
item.setSubmenu_(submenu)
return item
+def build_brightness_slider_item(
+ device: StatusBarDevice,
+ target: StatusBarController,
+) -> NSMenuItem:
+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("", None, "")
+ view = NSView.alloc().initWithFrame_(((0, 0), (230, 34)))
+ slider = NSSlider.alloc().initWithFrame_(((14, 6), (202, 22)))
+ slider.setMinValue_(0.0)
+ slider.setMaxValue_(255.0)
+ slider.setDoubleValue_(float(normalize_brightness(device.brightness)))
+ slider.setContinuous_(False)
+ slider.setTarget_(target)
+ slider.setAction_("setDeviceBrightness:")
+ slider.setIdentifier_(device.device_id)
+ view.addSubview_(slider)
+ item.setView_(view)
+ return item
+
+
def build_settings_window(target: StatusBarController) -> NSWindow:
- width = 600
- height = 460
+ width = 680
+ height = 840
style = (
NSWindowStyleMaskTitled
| NSWindowStyleMaskClosable
@@ -1125,24 +1525,24 @@ def build_settings_window(target: StatusBarController) -> NSWindow:
window.center()
content = window.contentView()
- add_label(content, "Agent Hooks", 24, 412, 200, 24)
- add_label(content, "Codex", 32, 370, 80, 22)
- codex_status = add_label(content, "", 112, 370, 230, 22)
- add_button(content, "Install", 352, 366, 90, 28, target, "installCodexHooks:")
- add_button(content, "Uninstall", 452, 366, 100, 28, target, "uninstallCodexHooks:")
+ add_label(content, "Agent Hooks", 24, 792, 200, 24)
+ add_label(content, "Codex", 32, 750, 80, 22)
+ codex_status = add_label(content, "", 112, 750, 270, 22)
+ add_button(content, "Install", 432, 746, 90, 28, target, "installCodexHooks:")
+ add_button(content, "Uninstall", 532, 746, 100, 28, target, "uninstallCodexHooks:")
- add_label(content, "Claude", 32, 328, 80, 22)
- claude_status = add_label(content, "", 112, 328, 230, 22)
- add_button(content, "Install", 352, 324, 90, 28, target, "installClaudeHooks:")
- add_button(content, "Uninstall", 452, 324, 100, 28, target, "uninstallClaudeHooks:")
+ add_label(content, "Claude", 32, 708, 80, 22)
+ claude_status = add_label(content, "", 112, 708, 270, 22)
+ add_button(content, "Install", 432, 704, 90, 28, target, "installClaudeHooks:")
+ add_button(content, "Uninstall", 532, 704, 100, 28, target, "uninstallClaudeHooks:")
- add_separator(content, 24, 296, width - 48)
- add_label(content, "Transcript Monitoring", 24, 262, 240, 24)
+ add_separator(content, 24, 676, width - 48)
+ add_label(content, "Transcript Monitoring", 24, 642, 240, 24)
codex_transcripts = add_checkbox(
content,
"CLI fallback: Codex transcripts",
32,
- 228,
+ 608,
260,
24,
target,
@@ -1152,20 +1552,20 @@ def build_settings_window(target: StatusBarController) -> NSWindow:
content,
"CLI fallback: Claude transcripts",
32,
- 196,
+ 576,
260,
24,
target,
"toggleClaudeTranscripts:",
)
- add_separator(content, 24, 176, width - 48)
- add_label(content, "LED Display", 24, 142, 240, 24)
+ add_separator(content, 24, 556, width - 48)
+ add_label(content, "LED Display", 24, 522, 240, 24)
battery_leds = add_checkbox(
content,
"Show battery on LEDs",
32,
- 108,
+ 488,
260,
24,
target,
@@ -1175,20 +1575,50 @@ def build_settings_window(target: StatusBarController) -> NSWindow:
content,
"Show battery for 7s on plug/unplug",
32,
- 76,
+ 456,
320,
24,
target,
"setBatteryPowerPreviewFromCheckbox:",
)
- add_separator(content, 24, 56, width - 48)
- message = add_label(content, "", 24, 30, width - 48, 22)
- settings_path = add_label(content, "", 24, 8, width - 48, 18)
+ add_separator(content, 24, 436, width - 48)
+ add_label(content, "Lid & Sleep", 24, 402, 240, 24)
+ closed_lid_system_override = add_checkbox(
+ content,
+ "Strong sleep override (requires helper)",
+ 300,
+ 402,
+ 300,
+ 24,
+ target,
+ "setClosedLidSystemOverrideFromCheckbox:",
+ )
+ add_label(content, "Lid Closed", 32, 368, 120, 22)
+ add_label(content, "Duration", 520, 368, 70, 22)
+ closed_duration = add_editable_field(content, "", 590, 366, 48, 24)
+ closed_program = add_text_view(content, "", 32, 276, 606, 82)
+ add_button(content, "Preview", 32, 238, 90, 28, target, "previewLidClosedAnimation:")
+ add_button(content, "Reset", 132, 238, 90, 28, target, "resetLidClosedAnimation:")
+
+ add_label(content, "Lid Open", 32, 202, 120, 22)
+ add_label(content, "Duration", 520, 202, 70, 22)
+ open_duration = add_editable_field(content, "", 590, 200, 48, 24)
+ open_program = add_text_view(content, "", 32, 110, 606, 82)
+ add_button(content, "Preview", 32, 72, 90, 28, target, "previewLidOpenAnimation:")
+ add_button(content, "Reset", 132, 72, 90, 28, target, "resetLidOpenAnimation:")
+ add_button(content, "Save Animations", 492, 72, 146, 28, target, "saveLidAnimations:")
+
+ message = add_label(content, "", 24, 34, width - 48, 22)
+ settings_path = add_label(content, "", 24, 12, width - 48, 18)
target.settings_fields = {
"codex_hook_status": codex_status,
"claude_hook_status": claude_status,
+ "closed_animation_program": closed_program,
+ "closed_animation_duration": closed_duration,
+ "open_animation_program": open_program,
+ "open_animation_duration": open_duration,
"message": message,
"settings_path": settings_path,
}
@@ -1197,6 +1627,7 @@ def build_settings_window(target: StatusBarController) -> NSWindow:
"claude_transcripts": claude_transcripts,
"battery_leds": battery_leds,
"battery_power_preview": battery_power_preview,
+ "closed_lid_system_override": closed_lid_system_override,
}
return window
@@ -1250,6 +1681,32 @@ def add_checkbox(
return checkbox
+def add_editable_field(parent, text: str, x: int, y: int, width: int, height: int):
+ field = NSTextField.alloc().initWithFrame_(((x, y), (width, height)))
+ field.setStringValue_(text)
+ field.setEditable_(True)
+ field.setSelectable_(True)
+ parent.addSubview_(field)
+ return field
+
+
+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.setString_(text)
+ text_view.setVerticallyResizable_(True)
+ text_view.setHorizontallyResizable_(False)
+ try:
+ text_view.setFont_(NSFont.monospacedSystemFontOfSize_weight_(11.0, 0.0))
+ except Exception:
+ pass
+ scroll.setDocumentView_(text_view)
+ parent.addSubview_(scroll)
+ return text_view
+
+
def add_separator(parent, x: int, y: int, width: int):
separator = NSTextField.alloc().initWithFrame_(((x, y), (width, 1)))
separator.setStringValue_("")
@@ -1265,11 +1722,63 @@ def set_field_value(field, value: str) -> None:
field.setStringValue_(value)
+def set_text_control_value(control, value: str) -> None:
+ if control is None:
+ return
+ if hasattr(control, "setString_"):
+ control.setString_(value)
+ else:
+ control.setStringValue_(value)
+
+
+def text_control_value(control) -> str:
+ if control is None:
+ return ""
+ if hasattr(control, "string"):
+ return str(control.string())
+ return str(control.stringValue())
+
+
def set_checkbox_state(button, enabled: bool) -> None:
if button is not None:
button.setState_(NSOnState if enabled else NSOffState)
+def validate_lid_animation(animation: LedAnimationSetting) -> None:
+ program = normalize_led_text(animation.program)
+ validate_led_text(program)
+ validate_led_text(apply_brightness(program, 1))
+ normalize_animation_duration(animation.duration_seconds)
+
+
+def program_for_lid_animation(
+ animation: LedAnimationSetting,
+ *,
+ brightness: int | float = 255,
+) -> str:
+ validate_lid_animation(animation)
+ return apply_brightness(normalize_led_text(animation.program), brightness)
+
+
+def restore_led_display(target, token_value) -> None:
+ try:
+ token = int(str(token_value))
+ except ValueError:
+ token = target.led_animation_token
+ if token != target.led_animation_token:
+ return
+ target.led_animation_until_monotonic = 0.0
+ target.reset_led_controllers_for_display_change()
+ if target.last_snapshot is not None:
+ target.sync_leds(
+ target.last_snapshot.aggregate.mode,
+ target.last_battery_snapshot,
+ target.active_led_display_kind(target.last_battery_snapshot),
+ )
+ else:
+ target.refresh_(None)
+
+
def hook_status_text(config: ProviderConfig) -> str:
if not config.exists:
return f"Not installed - config will be created at {config.config_path}"
@@ -1299,12 +1808,6 @@ def device_display_label(display: str) -> str:
return "Agent Status"
-def device_display_symbol(display: str) -> str:
- if display == LED_DISPLAY_BATTERY:
- return "battery.100"
- return "waveform.path.ecg"
-
-
def disabled_menu_item(title: str) -> NSMenuItem:
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, None, "")
item.setEnabled_(False)
@@ -1332,6 +1835,7 @@ def disambiguate_device_names(devices: list[StatusBarDevice]) -> list[StatusBarD
target=device.target,
connected=device.connected,
display=device.display,
+ brightness=device.brightness,
reason=device.reason,
)
)
@@ -1348,44 +1852,6 @@ def duplicate_device_suffix(device: StatusBarDevice) -> str:
return root_name
-def device_connection_detail(target: StatusBarController) -> str:
- if not target.leds_enabled:
- return "LED output disabled"
- if target.last_led_error:
- return f"Device error: {target.last_led_error}"
- if target.led_controller.last_error:
- return f"Device error: {target.led_controller.last_error}"
- if target.battery_led_controller.last_error:
- return f"Device error: {target.battery_led_controller.last_error}"
- devices = target.status_bar_devices(remember=False)
- connected = [device for device in devices if device.connected]
- previous_count = max(0, len(devices) - len(connected))
- if connected:
- suffix = "device" if len(connected) == 1 else "devices"
- if previous_count:
- return f"{len(connected)} connected {suffix}, {previous_count} remembered"
- return f"{len(connected)} connected {suffix}"
- if previous_count:
- suffix = "device" if previous_count == 1 else "devices"
- return f"No devices connected, {previous_count} remembered {suffix}"
- return "No devices connected"
-
-
-def battery_status_detail(target: StatusBarController) -> str:
- if target.last_battery_error:
- return f"Battery error: {target.last_battery_error}"
- snapshot = target.last_battery_snapshot
- if snapshot is None:
- return ""
- state = battery_state_label(snapshot)
- if snapshot.is_plugged:
- return (
- f"Battery: {snapshot.percent}% {state}, "
- f"adapter {format_watts(snapshot.adapter_power)}"
- )
- return f"Battery: {snapshot.percent}% {state}"
-
-
def preferred_status_bar_device(candidates: list[DeviceCandidate]) -> DeviceCandidate:
return sorted(candidates, key=status_bar_device_sort_key)[0]
@@ -1408,27 +1874,81 @@ def build_session_menu_item(
None,
"",
)
- item.setEnabled_(True)
-
+ item.setImage_(provider_icon_for_status(status))
submenu = NSMenu.alloc().init()
- add_action_item(
- submenu,
- "Deep Link",
- "openDeepLink:",
- session_deep_link(status),
- target,
- )
- add_action_item(
- submenu,
- "Resume",
- "resumeSession:",
- session_resume_command(status),
- target,
- )
+ submenu.addItem_(disabled_menu_item(flatten_menu_title(menu_title_for_status(status, now))))
+ submenu.addItem_(disabled_menu_item(session_detail_for_status(status, now)))
+ submenu.addItem_(NSMenuItem.separatorItem())
+
+ selected_action = getattr(target, "settings", None)
+ if selected_action is not None:
+ selected = target.settings.session_open_action(status.provider)
+ else:
+ selected = None
+ selected = selected or default_session_open_action(status)
+ for action in available_session_open_actions(status):
+ add_session_open_action_item(
+ submenu,
+ session_open_action_label(status, action),
+ status,
+ action,
+ target,
+ selected=action == selected,
+ )
item.setSubmenu_(submenu)
+ item.setEnabled_(True)
return item
+def add_session_open_action_item(
+ menu: NSMenu,
+ title: str,
+ status: AgentStatus,
+ action: str,
+ target: StatusBarController,
+ *,
+ selected: bool,
+) -> None:
+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
+ title,
+ "openSessionWithAction:",
+ "",
+ )
+ item.setTarget_(target)
+ item.setRepresentedObject_({"status": status, "action": action})
+ item.setState_(1 if selected else 0)
+ menu.addItem_(item)
+
+
+def provider_icon_for_status(status: AgentStatus):
+ provider = status.provider.lower()
+ if provider == "codex":
+ for path in ("/Applications/Codex.app", "/Applications/ChatGPT.app"):
+ image = app_icon(path)
+ if image is not None:
+ return image
+ return image_for_symbol("sparkles", "Codex")
+ if provider == "claude":
+ image = app_icon("/Applications/Claude.app")
+ if image is not None:
+ return image
+ return image_for_symbol("brain.head.profile", "Claude")
+ return image_for_symbol("terminal", status.provider.title() or "Agent")
+
+
+def app_icon(path: str):
+ if not Path(path).exists():
+ return None
+ image = NSWorkspace.sharedWorkspace().iconForFile_(path)
+ if image is not None:
+ image.setSize_((18, 18))
+ return image
+
+
+def flatten_menu_title(title: str) -> str:
+ return " · ".join(part.strip() for part in title.splitlines() if part.strip())
+
+
def add_action_item(
menu: NSMenu,
title: str,
@@ -1467,11 +1987,55 @@ def recent_statuses(snapshot) -> list[AgentStatus]:
def menu_title_for_status(status: AgentStatus, now: datetime) -> str:
+ state = state_for_mode(status.mode)
+ title, project = session_title_parts(status)
+ first_line = f"{state.label} {title}"
+ if project:
+ return f"{first_line}\n{project}"
+ return first_line
+
+
+def session_detail_for_status(status: AgentStatus, now: datetime) -> str:
state = state_for_mode(status.mode)
age = format_age(status.age_seconds(now))
- tool = f" - {status.tool_name}" if status.tool_name else ""
- cwd = compact_path(status.cwd) if status.cwd else "-"
- return f"{state.label:7} {status.display_name} {age} {status.event_name}{tool} {cwd}"
+ details = [state.label, age]
+ if status.tool_name:
+ details.append(status.tool_name)
+ return " · ".join(details)
+
+
+def session_title_parts(status: AgentStatus) -> tuple[str, str | None]:
+ project = project_name_from_cwd(status.cwd)
+ title = strip_session_short_id(status.display_name, status.session_id)
+ if project and title.startswith(f"{project}: "):
+ title = title[len(project) + 2 :]
+ elif ": " in title:
+ maybe_project, maybe_title = title.split(": ", 1)
+ if not project:
+ project = maybe_project
+ title = maybe_title
+ return title or status.display_name, project
+
+
+def strip_session_short_id(display_name: str, session_id: str | None) -> str:
+ text = display_name.strip()
+ if session_id:
+ suffix = f" ({session_id[:8]})"
+ if text.endswith(suffix):
+ return text[: -len(suffix)].strip()
+ if text.endswith(")") and " (" in text:
+ prefix, suffix = text.rsplit(" (", 1)
+ token = suffix[:-1]
+ if 6 <= len(token) <= 12 and all(char.isalnum() or char == "-" for char in token):
+ return prefix.strip()
+ return text
+
+
+def project_name_from_cwd(cwd: str | None) -> str | None:
+ if not cwd:
+ return None
+ name = Path(cwd).name
+ return name or cwd
def image_for_symbol(symbol: str, description: str):
@@ -1510,6 +2074,12 @@ def format_age(seconds: float) -> str:
return f"{hours}h{minutes:02d}m"
+def open_url(url: str) -> None:
+ ns_url = NSURL.URLWithString_(url)
+ if ns_url is not None:
+ NSWorkspace.sharedWorkspace().openURL_(ns_url)
+
+
def open_terminal_command(command: str) -> None:
script = "\n".join(
[
diff --git a/src/agent_monitor/status_bar_launch.py b/src/agent_monitor/status_bar_launch.py
index 550f715..0c79ada 100644
--- a/src/agent_monitor/status_bar_launch.py
+++ b/src/agent_monitor/status_bar_launch.py
@@ -10,8 +10,10 @@ from typing import Any
from .providers import default_state_dir
-LAUNCH_AGENT_LABEL = "com.sidepulse.agentstatus"
+LAUNCH_AGENT_LABEL = "io.sidepulse.agentstatus"
LAUNCH_AGENT_FILENAME = f"{LAUNCH_AGENT_LABEL}.plist"
+LEGACY_LAUNCH_AGENT_LABEL = "com.sidepulse.agentstatus"
+LEGACY_LAUNCH_AGENT_FILENAME = f"{LEGACY_LAUNCH_AGENT_LABEL}.plist"
@dataclass(frozen=True)
@@ -28,6 +30,11 @@ def launch_agent_path(home: Path | None = None) -> Path:
return base / "Library" / "LaunchAgents" / LAUNCH_AGENT_FILENAME
+def legacy_launch_agent_path(home: Path | None = None) -> Path:
+ base = home or Path.home()
+ return base / "Library" / "LaunchAgents" / LEGACY_LAUNCH_AGENT_FILENAME
+
+
def build_launch_agent_plist(
python_executable: Path | str | None = None,
stdout_path: Path | None = None,
@@ -64,8 +71,12 @@ def install_launch_agent(
start: bool = True,
plist_path: Path | None = None,
python_executable: Path | str | None = None,
+ legacy_plist_path: Path | None = None,
) -> LaunchAgentResult:
target = plist_path or launch_agent_path()
+ legacy_target = legacy_plist_path if legacy_plist_path is not None else (
+ legacy_launch_agent_path() if plist_path is None else None
+ )
plist = build_launch_agent_plist(python_executable=python_executable)
data = plistlib.dumps(plist, sort_keys=False)
existing = target.read_bytes() if target.exists() else None
@@ -75,6 +86,10 @@ def install_launch_agent(
default_state_dir().mkdir(parents=True, exist_ok=True)
if changed:
target.write_bytes(data)
+ legacy_removed = False
+ if legacy_target is not None:
+ legacy_removed = remove_legacy_launch_agent(legacy_target)
+ changed = changed or legacy_removed
started = False
if start:
@@ -124,6 +139,15 @@ def bootout_launch_agent(plist_path: Path) -> None:
)
+def remove_legacy_launch_agent(plist_path: Path | None = None) -> bool:
+ target = plist_path or legacy_launch_agent_path()
+ if not target.exists():
+ return False
+ bootout_launch_agent(target)
+ target.unlink()
+ return True
+
+
def launch_domain() -> str:
return f"gui/{os.getuid()}"
diff --git a/tests/test_agent_monitor.py b/tests/test_agent_monitor.py
index 11874b7..eca72a7 100644
--- a/tests/test_agent_monitor.py
+++ b/tests/test_agent_monitor.py
@@ -3,11 +3,13 @@ from __future__ import annotations
import json
import os
import plistlib
+import subprocess
import tempfile
import time
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
from agent_monitor.battery import (
@@ -52,18 +54,51 @@ from agent_monitor.led_status import (
program_for_display_state,
write_mode_to_leds,
)
+from agent_monitor.lid_sleep import (
+ ClosedLidAwakeController,
+ SleepHelperRequiredError,
+ closed_lid_awake_should_hold,
+ parse_bool_ioreg_property,
+ run_sudo_pmset_disablesleep,
+ sleep_helper_sudoers_rule,
+)
from agent_monitor.models import AgentMode, AgentStatus, AggregateStatus
from agent_monitor.providers import default_log_path, default_state_dir, parse_log_line
-from agent_monitor.session_actions import session_deep_link, session_resume_command
+from agent_monitor.sd_eject_guard_launch import (
+ SD_EJECT_GUARD_LABEL,
+ SdEjectGuardInstallError,
+ SdEjectGuardPaths,
+ build_sd_eject_guard_plist,
+ install_sd_eject_guard,
+ stop_sd_eject_guard,
+)
+from agent_monitor.session_actions import (
+ SESSION_OPEN_TERMINAL,
+ default_session_open_action,
+ session_deep_link,
+ session_open_target,
+ session_resume_command,
+ session_vscode_link,
+)
from agent_monitor.settings import (
+ CLOSED_LID_AWAKE_AGENTS,
+ CLOSED_LID_AWAKE_ALWAYS,
+ CLOSED_LID_AWAKE_NEVER,
+ LID_ANIMATION_CLOSED,
+ LID_ANIMATION_OPEN,
AgentMonitorSettings,
DeviceDisplaySetting,
default_config_dir,
+ default_lid_animation,
default_settings_path,
load_settings,
save_settings,
)
-from agent_monitor.status_bar_launch import LAUNCH_AGENT_LABEL, build_launch_agent_plist
+from agent_monitor.status_bar_launch import (
+ LAUNCH_AGENT_LABEL,
+ build_launch_agent_plist,
+ install_launch_agent,
+)
class FakeProcess:
@@ -270,6 +305,263 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(snapshot.aggregate.mode, AgentMode.WORKING)
self.assertIn("startup replay", snapshot.statuses[0].display_name)
+ def test_status_bar_session_menu_title_is_task_and_project(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ status = AgentStatus(
+ provider="codex",
+ agent_id="codex:session:019ee395",
+ display_name="pixiepulse-bridge: Refine README agent status modes (019ee395)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now,
+ event_name="Stop",
+ session_id="019ee395",
+ cwd="/Users/pero/pgit/pixiepulse-bridge",
+ )
+
+ self.assertEqual(
+ status_bar.menu_title_for_status(status, now),
+ "Done Refine README agent status modes\npixiepulse-bridge",
+ )
+ self.assertEqual(
+ status_bar.session_detail_for_status(status, now).split(" · ")[0],
+ "Done",
+ )
+
+ def test_status_bar_session_row_has_inline_options(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ status = AgentStatus(
+ provider="claude",
+ agent_id="claude:session:abc",
+ display_name="Claude abc",
+ mode=AgentMode.WAITING_FOR_INPUT,
+ updated_at=now,
+ event_name="Notification",
+ session_id="1ca4348e-2aec-4147-9e81-d7d56364d257",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ )
+ target = SimpleNamespace(settings=AgentMonitorSettings())
+
+ row = status_bar.build_session_menu_item(status, now, target)
+ submenu = row.submenu()
+ titles = [
+ submenu.itemAtIndex_(index).title()
+ for index in range(submenu.numberOfItems())
+ if submenu.itemAtIndex_(index).title()
+ ]
+
+ self.assertTrue(row.title().startswith("Ask "))
+ self.assertIsNotNone(row.image())
+ self.assertIsNotNone(row.submenu())
+ self.assertTrue(any(title.startswith("Ask Claude abc") for title in titles))
+ self.assertIn("Open in VS Code", titles)
+ self.assertIn("Resume in Terminal", titles)
+
+ def test_codex_session_options_are_codex_specific(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ status = AgentStatus(
+ provider="codex",
+ agent_id="codex:session:abc",
+ display_name="Codex abc",
+ mode=AgentMode.WORKING,
+ updated_at=now,
+ event_name="PreToolUse",
+ session_id="019ee395-2f64-7cc3-b566-afcc1d626160",
+ cwd="/tmp/project with spaces",
+ )
+ target = SimpleNamespace(settings=AgentMonitorSettings())
+
+ row = status_bar.build_session_menu_item(status, now, target)
+ submenu = row.submenu()
+ titles = [
+ submenu.itemAtIndex_(index).title()
+ for index in range(submenu.numberOfItems())
+ if submenu.itemAtIndex_(index).title()
+ ]
+
+ self.assertTrue(row.title().startswith("Working "))
+ self.assertIsNotNone(row.image())
+ self.assertTrue(any(title.startswith("Working Codex abc") for title in titles))
+ self.assertIn("Open in Codex", titles)
+ self.assertIn("Resume in Terminal", titles)
+ self.assertNotIn("Open in VS Code", titles)
+ self.assertNotIn("Open Claude App", titles)
+
+ def test_status_bar_device_submenu_has_brightness_slider(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ device = status_bar.StatusBarDevice(
+ device_id="/Volumes/PulseDot",
+ name="PulseDot",
+ root=Path("/Volumes/PulseDot"),
+ target=Path("/Volumes/PulseDot/LEDS.LED"),
+ connected=True,
+ display="agent",
+ brightness=128,
+ )
+
+ item = status_bar.build_device_menu_item(device, SimpleNamespace())
+ submenu = item.submenu()
+ titles = [
+ submenu.itemAtIndex_(index).title()
+ for index in range(submenu.numberOfItems())
+ if submenu.itemAtIndex_(index).title()
+ ]
+ custom_view_count = sum(
+ 1
+ for index in range(submenu.numberOfItems())
+ if submenu.itemAtIndex_(index).view() is not None
+ )
+
+ self.assertIn("Brightness 50%", titles)
+ self.assertEqual(custom_view_count, 1)
+
+ def test_status_bar_menu_has_closed_lid_awake_policy_choices(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ snapshot = SimpleNamespace(
+ statuses=[],
+ collected_at=datetime.now(timezone.utc),
+ )
+ target = SimpleNamespace(
+ settings=AgentMonitorSettings(
+ closed_lid_awake_policy=CLOSED_LID_AWAKE_AGENTS,
+ ),
+ closed_lid_awake=SimpleNamespace(last_error=None),
+ status_bar_devices=lambda: [],
+ )
+
+ menu = status_bar.build_menu(snapshot, status_bar.STATE_IDLE, target)
+ items = [menu.itemAtIndex_(index) for index in range(menu.numberOfItems())]
+ by_title = {item.title(): item for item in items if item.title()}
+
+ self.assertIn("Keep Awake With Lid Closed", by_title)
+ self.assertEqual(by_title["Never"].state(), 0)
+ self.assertEqual(by_title["When Agents Work"].state(), 1)
+ self.assertEqual(by_title["Always"].state(), 0)
+ self.assertIn("Strong Sleep Override...", by_title)
+ self.assertEqual(by_title["Strong Sleep Override..."].state(), 0)
+
+ def test_lid_animation_program_uses_device_brightness(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ animation = default_lid_animation(LID_ANIMATION_CLOSED)
+ program = status_bar.program_for_lid_animation(animation, brightness=128)
+
+ validate_led_text(program)
+ self.assertTrue(program.startswith("brightness 128\n"))
+
+ def test_lid_animation_restore_forces_led_resync(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ calls: list[tuple[str, object]] = []
+ fake = SimpleNamespace(
+ led_animation_token=42,
+ led_animation_until_monotonic=100.0,
+ last_snapshot=SimpleNamespace(
+ aggregate=SimpleNamespace(mode=AgentMode.WORKING),
+ ),
+ last_battery_snapshot=object(),
+ reset_led_controllers_for_display_change=lambda: calls.append(("reset", None)),
+ active_led_display_kind=lambda snapshot: "agent",
+ sync_leds=lambda mode, snapshot, display: calls.append(
+ ("sync", (mode, snapshot, display))
+ ),
+ refresh_=lambda sender: calls.append(("refresh", sender)),
+ )
+
+ status_bar.restore_led_display(fake, "41")
+ self.assertEqual(calls, [])
+ self.assertEqual(fake.led_animation_until_monotonic, 100.0)
+
+ status_bar.restore_led_display(fake, "42")
+ self.assertEqual(fake.led_animation_until_monotonic, 0.0)
+ self.assertEqual(calls[0], ("reset", None))
+ self.assertEqual(calls[1][0], "sync")
+ self.assertEqual(calls[1][1][0], AgentMode.WORKING)
+
+ def test_status_bar_settings_window_has_lid_animation_controls(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ target = SimpleNamespace(settings_fields={}, settings_buttons={})
+
+ window = status_bar.build_settings_window(target)
+
+ self.assertEqual(window.title(), "SidePulse Agent Monitor Settings")
+ 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("closed_lid_system_override", target.settings_buttons)
+
+ def test_status_bar_open_session_remembers_action_by_provider(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ status = AgentStatus(
+ provider="claude",
+ agent_id="claude:session:abc",
+ display_name="Claude abc",
+ mode=AgentMode.WAITING_FOR_INPUT,
+ updated_at=datetime.now(timezone.utc),
+ event_name="Notification",
+ session_id="1ca4348e-2aec-4147-9e81-d7d56364d257",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ )
+ fake = SimpleNamespace(
+ settings=AgentMonitorSettings(),
+ messages=[],
+ set_settings_message=lambda message: None,
+ )
+
+ with (
+ patch("agent_monitor.status_bar.open_terminal_command") as open_terminal,
+ patch("agent_monitor.status_bar.save_settings") as save,
+ ):
+ status_bar.StatusBarController.open_session(
+ fake,
+ status,
+ SESSION_OPEN_TERMINAL,
+ remember=True,
+ )
+
+ open_terminal.assert_called_once_with(
+ "cd /Users/pero/pgit/sdstatus_bitbang && claude --resume 1ca4348e-2aec-4147-9e81-d7d56364d257"
+ )
+ self.assertEqual(fake.settings.session_open_action("claude"), SESSION_OPEN_TERMINAL)
+ save.assert_called_once_with(fake.settings)
+
def test_codex_installer_replaces_monitor_hook_and_preserves_state(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
@@ -523,6 +815,211 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(configure.battery_command, "configure")
self.assertEqual(configure.display, "battery")
+ def test_sidepulse_status_bar_root_command_shape(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+
+ default = parser.parse_args(["status-bar"])
+ start = parser.parse_args(["status-bar", "start", "--foreground"])
+ stop = parser.parse_args(["status-bar", "stop"])
+ helper = parser.parse_args(["status-bar", "install-sleep-helper", "--dry-run"])
+
+ self.assertEqual(default.command, "status-bar")
+ self.assertEqual(default.status_bar_command, "start")
+ self.assertFalse(default.foreground)
+ self.assertEqual(start.status_bar_command, "start")
+ self.assertTrue(start.foreground)
+ self.assertEqual(stop.status_bar_command, "stop")
+ self.assertEqual(helper.status_bar_command, "install-sleep-helper")
+ self.assertTrue(helper.dry_run)
+
+ def test_sidepulse_sdejectguard_command_shape(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+
+ start = parser.parse_args(["sdejectguard", "start"])
+ interactive = parser.parse_args(["sdejectguard", "start", "-it", "--scope", "user"])
+ stop = parser.parse_args(["sdejectguard", "stop", "--scope", "system"])
+ logs = parser.parse_args(["sdejectguard", "logs", "--lines", "12", "--follow"])
+
+ self.assertEqual(start.command, "sdejectguard")
+ self.assertEqual(start.sdejectguard_command, "start")
+ self.assertEqual(start.scope, "auto")
+ self.assertFalse(start.interactive)
+ self.assertTrue(interactive.interactive)
+ self.assertEqual(interactive.scope, "user")
+ self.assertEqual(stop.sdejectguard_command, "stop")
+ self.assertEqual(stop.scope, "system")
+ self.assertEqual(logs.sdejectguard_command, "logs")
+ self.assertEqual(logs.lines, 12)
+ self.assertTrue(logs.follow)
+
+ def test_sidepulse_sdejectguard_start_uses_launchd_installer(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+ args = parser.parse_args(["sdejectguard", "start", "--scope", "user"])
+ guard_result = SimpleNamespace(
+ dry_run=False,
+ changed=True,
+ started=True,
+ scope="user",
+ plist_path=Path("/tmp/io.sidepulse.sdejectguard.plist"),
+ binary_path=Path("/tmp/sd_eject_guard"),
+ cleanup_removed=None,
+ cleanup_skipped=None,
+ )
+
+ with patch(
+ "agent_monitor.sd_eject_guard_launch.install_sd_eject_guard",
+ return_value=guard_result,
+ ) as install:
+ result = cli_module.cmd_sidepulse_sdejectguard_start(args)
+
+ self.assertEqual(result, 0)
+ install.assert_called_once_with(scope="user", dry_run=False)
+
+ def test_sidepulse_sdejectguard_start_interactive_runs_foreground(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+ args = parser.parse_args(["sdejectguard", "start", "-it", "--scope", "user"])
+
+ with patch(
+ "agent_monitor.sd_eject_guard_launch.run_sd_eject_guard_interactive",
+ return_value=0,
+ ) as run:
+ result = cli_module.cmd_sidepulse_sdejectguard_start(args)
+
+ self.assertEqual(result, 0)
+ run.assert_called_once_with(scope="user")
+
+ def test_sidepulse_sdejectguard_stop_calls_guard_stop(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+ args = parser.parse_args(["sdejectguard", "stop", "--scope", "user", "--dry-run"])
+ stop_result = SimpleNamespace(
+ scope="user",
+ plist_path=Path("/tmp/io.sidepulse.sdejectguard.plist"),
+ stopped=True,
+ skipped=None,
+ )
+
+ with patch(
+ "agent_monitor.sd_eject_guard_launch.stop_sd_eject_guard",
+ return_value=(stop_result,),
+ ) as stop:
+ result = cli_module.cmd_sidepulse_sdejectguard_stop(args)
+
+ self.assertEqual(result, 0)
+ stop.assert_called_once_with(scope="user", dry_run=True)
+
+ def test_sidepulse_setup_command_shape(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+
+ default = parser.parse_args(["setup"])
+ codex_only = parser.parse_args(
+ [
+ "setup",
+ "codex",
+ "--no-status-bar",
+ "--dry-run",
+ "--sd-eject-guard-scope",
+ "user",
+ ]
+ )
+
+ self.assertEqual(default.command, "setup")
+ self.assertEqual(default.provider, "all")
+ self.assertEqual(default.sd_eject_guard_scope, "auto")
+ self.assertFalse(default.no_status_bar)
+ self.assertFalse(default.dry_run)
+ self.assertEqual(codex_only.provider, "codex")
+ self.assertEqual(codex_only.sd_eject_guard_scope, "user")
+ self.assertTrue(codex_only.no_status_bar)
+ self.assertTrue(codex_only.dry_run)
+
+ def test_sidepulse_setup_installs_hooks_guard_and_status_bar(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+ args = parser.parse_args(["setup"])
+ codex_result = SimpleNamespace(
+ provider="codex",
+ config_path=Path("/tmp/codex.toml"),
+ log_path=Path("/tmp/codex.jsonl"),
+ changed=True,
+ backup_path=None,
+ )
+ claude_result = SimpleNamespace(
+ provider="claude",
+ config_path=Path("/tmp/settings.json"),
+ log_path=Path("/tmp/claude.jsonl"),
+ changed=False,
+ backup_path=None,
+ )
+ launch_result = SimpleNamespace(
+ plist_path=Path("/tmp/io.sidepulse.agentstatus.plist"),
+ changed=True,
+ started=True,
+ )
+ guard_result = SimpleNamespace(
+ dry_run=False,
+ changed=True,
+ started=True,
+ scope="user",
+ plist_path=Path("/tmp/io.sidepulse.sdejectguard.plist"),
+ binary_path=Path("/tmp/sd_eject_guard"),
+ cleanup_removed=None,
+ cleanup_skipped=None,
+ )
+
+ 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(
+ "agent_monitor.sd_eject_guard_launch.install_sd_eject_guard",
+ return_value=guard_result,
+ ) as guard,
+ patch(
+ "agent_monitor.status_bar_launch.install_launch_agent",
+ return_value=launch_result,
+ ) as launch,
+ ):
+ result = cli_module.cmd_sidepulse_setup(args)
+
+ self.assertEqual(result, 0)
+ codex.assert_called_once()
+ claude.assert_called_once()
+ guard.assert_called_once_with(scope="auto", dry_run=False)
+ launch.assert_called_once_with(start=True)
+
+ def test_sidepulse_setup_no_status_bar_still_installs_guard(self) -> None:
+ parser = cli_module.build_sidepulse_parser()
+ args = parser.parse_args(["setup", "--no-status-bar", "--sd-eject-guard-scope", "user"])
+ hook_result = SimpleNamespace(
+ provider="codex",
+ config_path=Path("/tmp/codex.toml"),
+ log_path=Path("/tmp/codex.jsonl"),
+ changed=False,
+ backup_path=None,
+ )
+ guard_result = SimpleNamespace(
+ dry_run=False,
+ changed=False,
+ started=True,
+ scope="user",
+ plist_path=Path("/tmp/io.sidepulse.sdejectguard.plist"),
+ binary_path=Path("/tmp/sd_eject_guard"),
+ cleanup_removed=None,
+ cleanup_skipped=None,
+ )
+
+ with (
+ patch.object(cli_module, "install_hook_results", return_value=[hook_result]),
+ patch(
+ "agent_monitor.sd_eject_guard_launch.install_sd_eject_guard",
+ return_value=guard_result,
+ ) as guard,
+ patch("agent_monitor.status_bar_launch.install_launch_agent") as launch,
+ ):
+ result = cli_module.cmd_sidepulse_setup(args)
+
+ self.assertEqual(result, 0)
+ guard.assert_called_once_with(scope="user", dry_run=False)
+ launch.assert_not_called()
+
def test_sidepulse_write_decodes_escaped_newlines_and_writes_leds_file(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
device = Path(tmp) / "SidePulse"
@@ -536,7 +1033,7 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(target, device / "LEDS.LED")
self.assertEqual(target.read_text(), "off\n#FF00FF pulse")
- def test_sidepulse_write_falls_back_to_existing_legacy_leds_txt(self) -> None:
+ def test_sidepulse_write_uses_leds_led_even_when_old_file_exists(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
device = Path(tmp) / "PulseDot"
device.mkdir()
@@ -547,21 +1044,21 @@ class AgentMonitorTests(unittest.TestCase):
device_path=device,
)
- self.assertEqual(target, device / "LEDS.TXT")
+ self.assertEqual(target, device / "LEDS.LED")
self.assertEqual(target.read_text(), "off\n#FF00FF pulse")
+ self.assertEqual((device / "LEDS.TXT").read_text(), "off")
def test_sidepulse_write_discovers_pulsedot_volume(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
mount_root = Path(tmp)
device = mount_root / "PulseDot"
device.mkdir()
- (device / "LEDS.TXT").write_text("off")
candidates = discover_devices(mount_root=mount_root)
self.assertEqual(len(candidates), 1)
self.assertEqual(candidates[0].root, device)
- self.assertEqual(candidates[0].target, device / "LEDS.TXT")
+ self.assertEqual(candidates[0].target, device / "LEDS.LED")
def test_sidepulse_write_prefers_leds_led_when_available(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
@@ -569,13 +1066,23 @@ class AgentMonitorTests(unittest.TestCase):
device = mount_root / "SidePulse"
device.mkdir()
(device / "LEDS.LED").write_text("off")
- (device / "LEDS.TXT").write_text("legacy")
candidates = discover_devices(mount_root=mount_root)
self.assertEqual(len(candidates), 1)
self.assertEqual(candidates[0].target, device / "LEDS.LED")
+ def test_device_discovery_ignores_old_leds_txt_on_unnamed_volume(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ mount_root = Path(tmp)
+ device = mount_root / "USB Drive"
+ device.mkdir()
+ (device / "LEDS.TXT").write_text("off")
+
+ candidates = discover_devices(mount_root=mount_root)
+
+ self.assertEqual(candidates, [])
+
def test_device_discovery_skips_mount_io_errors(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
mount_root = Path(tmp)
@@ -583,7 +1090,7 @@ class AgentMonitorTests(unittest.TestCase):
bad = mount_root / "SidePulse"
good.mkdir()
bad.mkdir()
- (good / "LEDS.TXT").write_text("off")
+ (good / "LEDS.LED").write_text("off")
original_is_dir = Path.is_dir
def flaky_is_dir(path: Path) -> bool:
@@ -609,13 +1116,12 @@ class AgentMonitorTests(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
device = Path(tmp) / "PulseDot"
device.mkdir()
- (device / "LEDS.TXT").write_text("off")
result = cli_module.sidepulse_main(
["write", r"off\n#FF00FF pulse", "--device", str(device)]
)
self.assertEqual(result, 0)
- self.assertEqual((device / "LEDS.TXT").read_text(), "off\n#FF00FF pulse")
+ self.assertEqual((device / "LEDS.LED").read_text(), "off\n#FF00FF pulse")
def test_led_status_maps_agent_modes_to_programs(self) -> None:
self.assertEqual(
@@ -653,19 +1159,22 @@ class AgentMonitorTests(unittest.TestCase):
len(program_for_display_state(LedDisplayState.WORKING, led_count=8).splitlines()),
3,
)
+ self.assertEqual(
+ program_for_display_state(LedDisplayState.DONE, brightness=128),
+ "brightness 128\n#00FF66",
+ )
def test_write_mode_to_leds_uses_device_specific_program(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
device = Path(tmp) / "PulseDot"
device.mkdir()
- (device / "LEDS.TXT").write_text("off")
result = write_mode_to_leds(AgentMode.WORKING, device_path=device)
self.assertEqual(result.state, LedDisplayState.WORKING)
- self.assertEqual(result.target, device / "LEDS.TXT")
+ self.assertEqual(result.target, device / "LEDS.LED")
self.assertEqual(
- (device / "LEDS.TXT").read_text(),
+ (device / "LEDS.LED").read_text(),
"off 160ms cosine\n"
"0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms\n"
"repeat",
@@ -674,12 +1183,15 @@ class AgentMonitorTests(unittest.TestCase):
write_mode_to_leds(AgentMode.IDLE_READY, device_path=device)
self.assertEqual(
- (device / "LEDS.TXT").read_text(),
+ (device / "LEDS.LED").read_text(),
"off\n#020204 6s pulse\nrepeat",
)
+ write_mode_to_leds(AgentMode.COMPLETED, device_path=device, brightness=64)
+
+ self.assertEqual((device / "LEDS.LED").read_text(), "brightness 64\n#00FF66")
+
def test_led_count_uses_product_name(self) -> None:
- self.assertEqual(led_count_for_target(Path("/Volumes/PulseDot/LEDS.TXT")), 2)
self.assertEqual(led_count_for_target(Path("/Volumes/PulseDot/LEDS.LED")), 2)
self.assertEqual(led_count_for_target(Path("/Volumes/SidePulse/LEDS.LED")), 8)
@@ -795,6 +1307,14 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(segments[4], "4:#008F39 360ms ease")
self.assertEqual(segments[5], "5:#000000 360ms ease")
+ def test_battery_program_uses_brightness_command(self) -> None:
+ snapshot = BatterySnapshot(percent=57, is_plugged=False)
+
+ program = program_for_battery(snapshot, led_count=8, brightness=128)
+
+ validate_led_text(program)
+ self.assertTrue(program.startswith("brightness 128\n"))
+
def test_battery_program_uses_full_speed_steady_pulse(self) -> None:
snapshot = BatterySnapshot(
percent=80,
@@ -913,7 +1433,6 @@ class AgentMonitorTests(unittest.TestCase):
)
self.assertEqual(status_file_for_target(device / "LEDS.LED"), status_path)
- self.assertEqual(status_file_for_target(device / "LEDS.TXT"), status_path)
self.assertEqual(status_file_for_target(device / "STATUS.TXT"), status_path)
self.assertEqual(
controller.poke_status_file(device / "LEDS.LED", now=0),
@@ -926,6 +1445,135 @@ class AgentMonitorTests(unittest.TestCase):
)
self.assertEqual(reads, [status_path, status_path])
+ def test_closed_lid_awake_policy_decisions(self) -> None:
+ self.assertFalse(
+ closed_lid_awake_should_hold(CLOSED_LID_AWAKE_NEVER, agents_active=True)
+ )
+ self.assertFalse(
+ closed_lid_awake_should_hold(CLOSED_LID_AWAKE_AGENTS, agents_active=False)
+ )
+ self.assertTrue(
+ closed_lid_awake_should_hold(CLOSED_LID_AWAKE_AGENTS, agents_active=True)
+ )
+ self.assertTrue(
+ closed_lid_awake_should_hold(CLOSED_LID_AWAKE_ALWAYS, agents_active=False)
+ )
+
+ def test_closed_lid_awake_controller_sets_and_restores_system_disable(self) -> None:
+ processes: list[FakeProcess] = []
+ disabled_calls: list[bool] = []
+
+ def factory(*_args, **_kwargs):
+ process = FakeProcess()
+ processes.append(process)
+ return process
+
+ controller = ClosedLidAwakeController(
+ process_factory=factory,
+ sleep_disabled_reader=lambda: False,
+ sleep_disabled_setter=disabled_calls.append,
+ use_system_disable=True,
+ )
+
+ self.assertTrue(
+ controller.update(CLOSED_LID_AWAKE_ALWAYS, agents_active=False)
+ )
+ self.assertEqual(disabled_calls, [True])
+ self.assertTrue(controller.changed_system_disable)
+ self.assertEqual(len(processes), 1)
+
+ controller.update(CLOSED_LID_AWAKE_ALWAYS, agents_active=False)
+ self.assertEqual(disabled_calls, [True])
+
+ self.assertFalse(
+ controller.update(CLOSED_LID_AWAKE_NEVER, agents_active=False)
+ )
+ self.assertEqual(disabled_calls, [True, False])
+ self.assertTrue(processes[0].terminated)
+
+ def test_closed_lid_awake_controller_defaults_to_user_mode_only(self) -> None:
+ disabled_calls: list[bool] = []
+ controller = ClosedLidAwakeController(
+ process_factory=lambda *_args, **_kwargs: FakeProcess(),
+ sleep_disabled_reader=lambda: False,
+ sleep_disabled_setter=disabled_calls.append,
+ )
+
+ self.assertTrue(
+ controller.update(CLOSED_LID_AWAKE_ALWAYS, agents_active=False)
+ )
+
+ self.assertEqual(disabled_calls, [])
+ self.assertTrue(controller.process_running())
+ self.assertFalse(controller.changed_system_disable)
+
+ def test_closed_lid_awake_controller_preserves_existing_system_disable(self) -> None:
+ disabled_calls: list[bool] = []
+ controller = ClosedLidAwakeController(
+ process_factory=lambda *_args, **_kwargs: FakeProcess(),
+ sleep_disabled_reader=lambda: True,
+ sleep_disabled_setter=disabled_calls.append,
+ use_system_disable=True,
+ )
+
+ controller.update(CLOSED_LID_AWAKE_ALWAYS, agents_active=False)
+ controller.update(CLOSED_LID_AWAKE_NEVER, agents_active=False)
+
+ self.assertEqual(disabled_calls, [])
+
+ def test_sleep_override_uses_noninteractive_sudo(self) -> None:
+ calls = []
+
+ def runner(command, **kwargs):
+ calls.append((command, kwargs))
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ run_sudo_pmset_disablesleep(True, runner=runner)
+
+ self.assertEqual(
+ calls[0][0],
+ ["/usr/bin/sudo", "-n", "/usr/bin/pmset", "-a", "disablesleep", "1"],
+ )
+ self.assertEqual(calls[0][1]["check"], False)
+
+ def test_sleep_override_reports_missing_helper_without_prompting(self) -> None:
+ calls = []
+
+ def runner(command, **kwargs):
+ calls.append(command)
+ return subprocess.CompletedProcess(
+ command,
+ 1,
+ "",
+ "sudo: a password is required",
+ )
+
+ with self.assertRaises(SleepHelperRequiredError) as ctx:
+ run_sudo_pmset_disablesleep(False, runner=runner)
+
+ self.assertIn("install-sleep-helper", str(ctx.exception))
+ self.assertNotIn("/usr/bin/osascript", calls[0])
+
+ def test_sleep_helper_sudoers_rule_is_narrow(self) -> None:
+ self.assertEqual(
+ sleep_helper_sudoers_rule("pero"),
+ "pero ALL=(root) NOPASSWD: "
+ "/usr/bin/pmset -a disablesleep 0, "
+ "/usr/bin/pmset -a disablesleep 1\n",
+ )
+ with self.assertRaises(ValueError):
+ sleep_helper_sudoers_rule("bad user")
+
+ def test_lid_state_parser_reads_ioreg_booleans(self) -> None:
+ self.assertTrue(
+ parse_bool_ioreg_property('"AppleClamshellState" = Yes', "AppleClamshellState")
+ )
+ self.assertFalse(
+ parse_bool_ioreg_property('"AppleClamshellState" = No', "AppleClamshellState")
+ )
+ self.assertTrue(parse_bool_ioreg_property('"SleepDisabled" = true', "SleepDisabled"))
+ self.assertIsNone(parse_bool_ioreg_property('"Other" = Yes', "SleepDisabled"))
+
def test_default_logs_use_sidepulse_xdg_state_dir(self) -> None:
home = Path("/Users/example")
@@ -1009,6 +1657,7 @@ class AgentMonitorTests(unittest.TestCase):
name="PulseDot",
path="/Volumes/PulseDot",
led_display="battery",
+ brightness=128,
),
)
)
@@ -1019,6 +1668,84 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(loaded.devices, settings.devices)
self.assertEqual(loaded.display_for_device("/Volumes/SidePulse"), "agent")
self.assertEqual(loaded.display_for_device("/Volumes/PulseDot"), "battery")
+ self.assertEqual(loaded.brightness_for_device("/Volumes/PulseDot"), 128)
+
+ def test_settings_round_trip_remembered_device_brightness(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ settings_path = Path(tmp) / "settings.json"
+ settings = AgentMonitorSettings().with_device_brightness(
+ "/Volumes/PulseDot",
+ 96,
+ name="PulseDot",
+ path="/Volumes/PulseDot",
+ )
+
+ save_settings(settings, settings_path)
+ loaded = load_settings(settings_path)
+
+ self.assertEqual(loaded.brightness_for_device("/Volumes/PulseDot"), 96)
+
+ def test_settings_round_trip_session_open_preferences(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ settings_path = Path(tmp) / "settings.json"
+ settings = AgentMonitorSettings().with_session_open_action(
+ "Claude",
+ SESSION_OPEN_TERMINAL,
+ )
+
+ save_settings(settings, settings_path)
+ loaded = load_settings(settings_path)
+
+ self.assertEqual(loaded.session_open_action("claude"), SESSION_OPEN_TERMINAL)
+
+ def test_settings_round_trip_closed_lid_policy_and_animations(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ settings_path = Path(tmp) / "settings.json"
+ settings = AgentMonitorSettings().with_closed_lid_awake_policy(
+ CLOSED_LID_AWAKE_AGENTS
+ )
+ settings = settings.with_lid_animation(
+ LID_ANIMATION_CLOSED,
+ program="off\n#FF3A00 200ms ease",
+ duration_seconds=1.4,
+ )
+ settings = settings.with_lid_animation(
+ LID_ANIMATION_OPEN,
+ program="off\n#00FF66 200ms ease",
+ duration_seconds=1.6,
+ )
+
+ save_settings(settings, settings_path)
+ loaded = load_settings(settings_path)
+
+ self.assertEqual(loaded.closed_lid_awake_policy, CLOSED_LID_AWAKE_AGENTS)
+ self.assertEqual(
+ loaded.lid_animation(LID_ANIMATION_CLOSED).program,
+ "off\n#FF3A00 200ms ease",
+ )
+ self.assertEqual(
+ loaded.lid_animation(LID_ANIMATION_OPEN).duration_seconds,
+ 1.6,
+ )
+
+ enabled = settings.with_closed_lid_system_override(True)
+ save_settings(enabled, settings_path)
+ loaded_enabled = load_settings(settings_path)
+ self.assertTrue(loaded_enabled.closed_lid_system_override_enabled)
+
+ def test_settings_migrate_missing_lid_fields_to_defaults(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ settings_path = Path(tmp) / "settings.json"
+ settings_path.write_text(json.dumps({"led_display": "agent"}))
+
+ loaded = load_settings(settings_path)
+
+ self.assertEqual(loaded.closed_lid_awake_policy, CLOSED_LID_AWAKE_NEVER)
+ self.assertFalse(loaded.closed_lid_system_override_enabled)
+ self.assertEqual(
+ loaded.lid_animation(LID_ANIMATION_CLOSED),
+ default_lid_animation(LID_ANIMATION_CLOSED),
+ )
def test_settings_remember_device_preserves_existing_display_choice(self) -> None:
settings = AgentMonitorSettings().with_device_display(
@@ -1035,6 +1762,55 @@ class AgentMonitorTests(unittest.TestCase):
)
self.assertEqual(remembered.display_for_device("/Volumes/PulseDot"), "battery")
+ self.assertEqual(remembered.brightness_for_device("/Volumes/PulseDot"), 255)
+
+ def test_settings_remove_remembered_device(self) -> None:
+ settings = AgentMonitorSettings(
+ devices=(
+ DeviceDisplaySetting(
+ device_id="/Volumes/SidePulse",
+ name="SidePulse",
+ path="/Volumes/SidePulse",
+ led_display="agent",
+ ),
+ DeviceDisplaySetting(
+ device_id="/Volumes/PulseDot",
+ name="PulseDot",
+ path="/Volumes/PulseDot",
+ led_display="battery",
+ ),
+ )
+ )
+
+ updated = settings.without_device("/Volumes/PulseDot")
+
+ self.assertEqual([device.device_id for device in updated.devices], ["/Volumes/SidePulse"])
+ self.assertEqual(updated.display_for_device("/Volumes/PulseDot"), "agent")
+
+ def test_disconnected_device_menu_has_remove_option(self) -> None:
+ try:
+ from agent_monitor import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ device = status_bar.StatusBarDevice(
+ device_id="/Volumes/SidePulse",
+ name="SidePulse",
+ root=Path("/Volumes/SidePulse"),
+ target=Path("/Volumes/SidePulse/LEDS.LED"),
+ connected=False,
+ display="agent",
+ )
+ item = status_bar.build_device_menu_item(device, None)
+ submenu = item.submenu()
+ titles = [
+ submenu.itemAtIndex_(index).title()
+ for index in range(submenu.numberOfItems())
+ if submenu.itemAtIndex_(index).title()
+ ]
+
+ self.assertIn("Not connected", titles)
+ self.assertIn("Remove", titles)
def test_status_bar_launch_agent_plist_runs_foreground_command(self) -> None:
plist = build_launch_agent_plist(
@@ -1059,6 +1835,251 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(plist["StandardErrorPath"], "/tmp/sidepulse.err.log")
self.assertNotIn("KeepAlive", plist)
+ def test_status_bar_install_removes_legacy_com_sidepulse_plist(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ target = base / "io.sidepulse.agentstatus.plist"
+ legacy = base / "com.sidepulse.agentstatus.plist"
+ legacy.write_bytes(b"old")
+
+ with (
+ patch("agent_monitor.status_bar_launch.default_state_dir", return_value=base / "state"),
+ patch("agent_monitor.status_bar_launch.subprocess.run") as run,
+ ):
+ result = install_launch_agent(
+ start=False,
+ plist_path=target,
+ legacy_plist_path=legacy,
+ python_executable="/usr/bin/python3",
+ )
+
+ self.assertTrue(result.changed)
+ self.assertTrue(target.exists())
+ self.assertFalse(legacy.exists())
+ run.assert_called_once()
+ self.assertEqual(run.call_args.args[0][0:2], ["launchctl", "bootout"])
+
+ def test_sd_eject_guard_plist_shapes_for_user_and_system_scopes(self) -> None:
+ for scope in ("user", "system"):
+ paths = SdEjectGuardPaths(
+ scope=scope,
+ plist_path=Path(f"/tmp/{scope}/io.sidepulse.sdejectguard.plist"),
+ binary_path=Path(f"/tmp/{scope}/sd_eject_guard"),
+ stdout_path=Path(f"/tmp/{scope}/sd-eject-guard.out.log"),
+ stderr_path=Path(f"/tmp/{scope}/sd-eject-guard.err.log"),
+ )
+
+ plist = build_sd_eject_guard_plist(paths)
+
+ self.assertEqual(plist["Label"], SD_EJECT_GUARD_LABEL)
+ self.assertEqual(plist["ProgramArguments"], [str(paths.binary_path)])
+ self.assertTrue(plist["RunAtLoad"])
+ self.assertTrue(plist["KeepAlive"])
+ self.assertEqual(plist["StandardOutPath"], str(paths.stdout_path))
+ self.assertEqual(plist["StandardErrorPath"], str(paths.stderr_path))
+
+ def test_sd_eject_guard_auto_falls_back_to_user_scope(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ source = base / "sd_eject_guard.c"
+ source.write_text("int main(void) { return 0; }\n")
+ user_paths = SdEjectGuardPaths(
+ scope="user",
+ plist_path=base / "user" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "user" / "sd_eject_guard",
+ stdout_path=base / "user" / "out.log",
+ stderr_path=base / "user" / "err.log",
+ )
+ system_paths = SdEjectGuardPaths(
+ scope="system",
+ plist_path=base / "system" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "system" / "sd_eject_guard",
+ stdout_path=base / "system" / "out.log",
+ stderr_path=base / "system" / "err.log",
+ )
+ calls = []
+
+ def fake_run(command, *args, **kwargs):
+ calls.append(command)
+ if command[0] == "clang":
+ Path(command[3]).write_bytes(b"binary")
+ return subprocess.CompletedProcess(command, 0)
+
+ with (
+ patch("agent_monitor.sd_eject_guard_launch.os.geteuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.os.getuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.subprocess.run", side_effect=fake_run),
+ ):
+ result = install_sd_eject_guard(
+ scope="auto",
+ source_path=source,
+ user_paths=user_paths,
+ system_paths=system_paths,
+ )
+
+ self.assertEqual(result.scope, "user")
+ self.assertTrue(result.compiled)
+ self.assertTrue(result.started)
+ self.assertTrue(user_paths.binary_path.exists())
+ self.assertTrue(user_paths.plist_path.exists())
+ self.assertEqual(calls[0][0:4], ["clang", "-O2", "-o", str(user_paths.binary_path.with_name("sd_eject_guard.tmp"))])
+ self.assertIn("-framework", calls[0])
+ self.assertIn(["launchctl", "bootstrap", "gui/501", str(user_paths.plist_path)], calls)
+
+ def test_sd_eject_guard_user_install_reports_skipped_system_cleanup(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ source = base / "sd_eject_guard.c"
+ source.write_text("int main(void) { return 0; }\n")
+ user_paths = SdEjectGuardPaths(
+ scope="user",
+ plist_path=base / "user" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "user" / "sd_eject_guard",
+ stdout_path=base / "user" / "out.log",
+ stderr_path=base / "user" / "err.log",
+ )
+ system_paths = SdEjectGuardPaths(
+ scope="system",
+ plist_path=base / "system" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "system" / "sd_eject_guard",
+ stdout_path=base / "system" / "out.log",
+ stderr_path=base / "system" / "err.log",
+ )
+ system_paths.plist_path.parent.mkdir(parents=True)
+ system_paths.plist_path.write_bytes(b"old")
+
+ def fake_run(command, *args, **kwargs):
+ if command[0] == "clang":
+ Path(command[3]).write_bytes(b"binary")
+ return subprocess.CompletedProcess(command, 0)
+
+ with (
+ patch("agent_monitor.sd_eject_guard_launch.os.geteuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.os.getuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.subprocess.run", side_effect=fake_run),
+ ):
+ result = install_sd_eject_guard(
+ scope="user",
+ source_path=source,
+ user_paths=user_paths,
+ system_paths=system_paths,
+ )
+
+ self.assertIsNone(result.cleanup_removed)
+ self.assertIn(str(system_paths.plist_path), result.cleanup_skipped or "")
+ self.assertTrue(system_paths.plist_path.exists())
+
+ def test_sd_eject_guard_stop_auto_stops_user_and_skips_system_without_root(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ user_paths = SdEjectGuardPaths(
+ scope="user",
+ plist_path=base / "user" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "user" / "sd_eject_guard",
+ stdout_path=base / "user" / "out.log",
+ stderr_path=base / "user" / "err.log",
+ )
+ system_paths = SdEjectGuardPaths(
+ scope="system",
+ plist_path=base / "system" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "system" / "sd_eject_guard",
+ stdout_path=base / "system" / "out.log",
+ stderr_path=base / "system" / "err.log",
+ )
+ user_paths.plist_path.parent.mkdir(parents=True)
+ system_paths.plist_path.parent.mkdir(parents=True)
+ user_paths.plist_path.write_bytes(b"user")
+ system_paths.plist_path.write_bytes(b"system")
+
+ with (
+ patch("agent_monitor.sd_eject_guard_launch.os.geteuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.os.getuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.subprocess.run") as run,
+ ):
+ results = stop_sd_eject_guard(
+ scope="auto",
+ user_paths=user_paths,
+ system_paths=system_paths,
+ )
+
+ self.assertEqual(len(results), 2)
+ self.assertTrue(results[0].stopped)
+ self.assertFalse(results[1].stopped)
+ self.assertIn("missing permissions", results[1].skipped or "")
+ run.assert_called_once()
+ self.assertEqual(run.call_args.args[0][0:3], ["launchctl", "bootout", "gui/501"])
+
+ def test_sd_eject_guard_system_scope_requires_root(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ source = base / "sd_eject_guard.c"
+ source.write_text("int main(void) { return 0; }\n")
+ system_paths = SdEjectGuardPaths(
+ scope="system",
+ plist_path=base / "system" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "system" / "sd_eject_guard",
+ stdout_path=base / "system" / "out.log",
+ stderr_path=base / "system" / "err.log",
+ )
+
+ with patch("agent_monitor.sd_eject_guard_launch.os.geteuid", return_value=501):
+ with self.assertRaisesRegex(SdEjectGuardInstallError, "requires root"):
+ install_sd_eject_guard(
+ scope="system",
+ source_path=source,
+ system_paths=system_paths,
+ )
+
+ def test_sd_eject_guard_system_install_cleans_user_scope(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ source = base / "sd_eject_guard.c"
+ source.write_text("int main(void) { return 0; }\n")
+ user_paths = SdEjectGuardPaths(
+ scope="user",
+ plist_path=base / "user" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "user" / "sd_eject_guard",
+ stdout_path=base / "user" / "out.log",
+ stderr_path=base / "user" / "err.log",
+ )
+ system_paths = SdEjectGuardPaths(
+ scope="system",
+ plist_path=base / "system" / "io.sidepulse.sdejectguard.plist",
+ binary_path=base / "system" / "sd_eject_guard",
+ stdout_path=base / "system" / "out.log",
+ stderr_path=base / "system" / "err.log",
+ )
+ user_paths.plist_path.parent.mkdir(parents=True)
+ user_paths.plist_path.write_bytes(b"old")
+ calls = []
+
+ def fake_run(command, *args, **kwargs):
+ calls.append(command)
+ if command[0] == "clang":
+ Path(command[3]).write_bytes(b"binary")
+ return subprocess.CompletedProcess(command, 0)
+
+ with (
+ patch("agent_monitor.sd_eject_guard_launch.os.geteuid", return_value=0),
+ patch("agent_monitor.sd_eject_guard_launch.os.getuid", return_value=501),
+ patch("agent_monitor.sd_eject_guard_launch.os.chown") as chown,
+ patch("agent_monitor.sd_eject_guard_launch.subprocess.run", side_effect=fake_run),
+ ):
+ result = install_sd_eject_guard(
+ scope="system",
+ source_path=source,
+ user_paths=user_paths,
+ system_paths=system_paths,
+ )
+
+ self.assertEqual(result.scope, "system")
+ self.assertEqual(result.cleanup_removed, user_paths.plist_path)
+ self.assertFalse(user_paths.plist_path.exists())
+ self.assertTrue(system_paths.plist_path.exists())
+ self.assertIn(["launchctl", "bootstrap", "system", str(system_paths.plist_path)], calls)
+ chown.assert_any_call(system_paths.binary_path, 0, 0)
+ chown.assert_any_call(system_paths.plist_path, 0, 0)
+
def test_watch_filters_to_recent_statuses(self) -> None:
now = datetime.now(timezone.utc)
recent = AgentStatus(
@@ -2381,6 +3402,18 @@ team id 5QJ7W2AQ8H, push key '/Users/pero/Dropbox/keys/PixieDotPushKey.p8'
session_resume_command(status),
"cd /Users/pero/pgit/sdstatus_bitbang && claude --resume 1ca4348e-2aec-4147-9e81-d7d56364d257",
)
+ self.assertEqual(
+ session_vscode_link(status),
+ "vscode://anthropic.claude-code/open?session=1ca4348e-2aec-4147-9e81-d7d56364d257",
+ )
+ self.assertEqual(default_session_open_action(status), "vscode")
+ self.assertEqual(
+ session_open_target(status, "vscode"),
+ (
+ "url",
+ "vscode://anthropic.claude-code/open?session=1ca4348e-2aec-4147-9e81-d7d56364d257",
+ ),
+ )
if __name__ == "__main__":
diff --git a/tests/test_audio_monitor_example.py b/tests/test_audio_monitor_example.py
index c930fbd..e36f989 100644
--- a/tests/test_audio_monitor_example.py
+++ b/tests/test_audio_monitor_example.py
@@ -29,6 +29,14 @@ class AudioMonitorExampleTests(unittest.TestCase):
self.assertIn("4:#FFDB00", program)
self.assertTrue(program.endswith("7:#FF0000"))
+ def test_max_brightness_uses_firmware_brightness_command(self) -> None:
+ program = build_led_program(1.0, led_count=8, max_brightness=0.5, transition_ms=0)
+
+ validate_led_text(program)
+ self.assertTrue(program.startswith("brightness 128\n"))
+ self.assertIn("0:#00FF00", program)
+ self.assertTrue(program.endswith("7:#FF0000"))
+
def test_half_level_keeps_back_half_dim(self) -> None:
program = build_led_program(0.5, led_count=8, idle_brightness=0.08, transition_ms=0)
segments = program.split("; ")