CLI for SidePulse
Python
cleanup
Peter Kuhar43fcaf7b8dd0
diff --git a/LEDS_FORMAT.txt b/LEDS_FORMAT.txtindex d091883..995067b 100644--- a/LEDS_FORMAT.txt+++ b/LEDS_FORMAT.txt@@ -1,3 +1,39 @@+# SidePulse Pro and SidePulse Dot - How it works++SidePulse Pro and SidePulse Dot expose an LED controller as a virtual filesystem, inspired by Linux sysfs. LED animations are controlled by writing commands to the LEDS.LED file.+No drivers are needed.+SidePulse Pro fits into the SD card slot on MacBook Pro 2021+ models and has 8 RGB LEDs. SidePulse Dot is a tiny 2-LED USB-C device for Mac, iPhone, Linux, and Windows.+++On macOS they mount under `/Volumes/SidePulsePro` and `/Volumes/SidePulseDot`.++The simplest way to change the color is++ $ echo "#FF00FF" > /Volumes/SidePulsePro/LEDS.LED++Or to slowly pulse it.++ $ echo "off\n#FF00FF 1s pulse\nrepeat" > /Volumes/SidePulsePro/LEDS.LED+++There is a quirk with the MacBook SD card reader: it can power off SidePulse Pro after 3 minutes of inactivity.+A simple way to prevent it is to 'touch' it once a minute like++ $ touch /Volumes/SidePulsePro/keepalive++or++ $ while touch /Volumes/SidePulsePro/keepalive; do sleep 60; done++To recap, write to LEDS.LED what you want displayed.+That's all you have to know.++## Initial state.++The content in INIT.LED is played on power up. It can be anything supported by LEDS.LED.+Fresh firmware seeds INIT.LED with the one-second startup fill sequence.+Writing INIT.LED also applies the new startup program immediately for visual confirmation.+# LEDS.LED DSLWrite LED animation programs to `LEDS.LED`. Each non-empty, non-comment line is@@ -58,9 +94,8 @@ assigned more than once on a line, the last assignment wins:## Brightness-Brightness scales the RGB values. It does not change the stored animation-colors. Each successful parse starts with brightness 255 unless the program-includes `brightness N`.+Brightness scales the RGB values. It does not change the stored animation colors. Each successful parse starts with brightness 255 unless+the program includes `brightness N`.```textbrightness 128@@ -117,13 +152,13 @@ color to the target color and back to the start color over one duration. Thetarget color is the peak, not the final hold.```text-# fade to purple+// fade to purple#ff00ff 0.33s cosine-# pulse to purple and return to the current color+// pulse to purple and return to the current color#ff00ff 1.4s pulse-# same pulse using the default 330 ms duration+// same pulse using the default 330 ms duration#ff00ff pulse```@@ -133,6 +168,29 @@ target color is the peak, not the final hold.3:#ffffff 80ms none```+## Roll++Roll the current visible LED state by one full wraparound loop:++```text+roll 2s+roll 2s linear+roll 2s ease+roll-left 800ms ease-in-out+roll-right 1.5s cosine+```++`roll` is an alias for `roll-right`. Missing easing defaults to `linear`.+Duration is the time for one complete loop, so `roll 2s` returns to the+starting arrangement after 2 seconds. Roll always uses the current visible LED+state as its source. To roll a chosen palette, set it first:++```text+#ff0044 #ff8800 #ffff00 #00ff66 #00ccff #004cff #8800ff #ff00cc+roll 2s linear+repeat+```+## Delays And StaggeringDifferent LEDs can use independent timing on the same line:@@ -204,6 +262,16 @@ off 120ms ease-outrepeat```-Compile-time LED count matters. On an 8 LED build, indexes `0` through `7`-target visible LEDs. On a 2 LED build, only indexes `0` and `1` target visible-LEDs. Extra valid indexes and color-list entries are parsed, then ignored.+Smooth seeded roll:++```text+#ff0044 #ff8800 #ffff00 #00ff66 #00ccff #004cff #8800ff #ff00cc+roll 2s linear+repeat+```++Compile-time LED count matters, but shared scripts are portable. On an 8 LED+build, indexes `0` through `7` affect LEDs. On a 2 LED build, only indexes `0`+and `1` affect LEDs. Higher indexes and extra color-list entries are parsed so+bad syntax still fails, but valid out-of-range LED targets are ignored. A line+that only targets ignored LEDs is a no-op.diff --git a/README.md b/README.mdindex ab889ff..0c0c94e 100644--- a/README.md+++ b/README.md@@ -1,31 +1,37 @@-# SidePulse+# sidepulse-SidePulse is the overall product for small LED status devices and the local-agent-monitoring tools that drive them.+`sidepulse` is the command-line and macOS companion project for+[SidePulse](https://sidepulse.io).-The SidePulse device is the eight-LED SD card slot version for MacBook Pro.-PulseDot is the tiny two-LED USB-C version.+SidePulse Pro is the eight-LED SD card device for MacBook Pro.+SidePulse Dot is the tiny two-LED USB-C device.They can display the status of an AI agent, battery level, or other systemsignals.-The device mounts as a flash drive. Control the LEDs by writing to `LEDS.LED`.+The device mounts as a disk drive. You can control the LEDs by writing to `LEDS.LED`.The LED control DSL is described in [`LEDS_FORMAT.txt`](LEDS_FORMAT.txt).-Write an LED program directly to a mounted SidePulse or PulseDot device:+### TLDR+```sh+python3 -m pip install -e .+sidepulse setup+```++Write an LED program directly to a mounted SidePulse Pro or SidePulse Dot device:```shsidepulse 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 or an existing `LEDS.LED`. If more than+SidePulse Pro/SidePulse Dot-style volume name or an existing `LEDS.LED`. If more thanone 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\n#ff3a00 1.6s pulse\nrepeat" --device /Volumes/SidePulsePro+sidepulse write "off" --device /Volumes/SidePulsePro/LEDS.LED```The writer decodes simple escapes such as `\n`, then enforces the controller's@@ -40,15 +46,15 @@ sidepulse battery statussidepulse battery status --json```-Mirror battery level to a mounted SidePulse/PulseDot:+Mirror battery level to a mounted SidePulse Pro/SidePulse Dot:```shsidepulse battery ledssidepulse battery leds --once --dry-run-sidepulse battery leds --device /Volumes/SidePulse --full-watts 140+sidepulse battery leds --device /Volumes/SidePulsePro --full-watts 140```-SidePulse uses all eight LEDs as a battery bar. At 50%, LEDs 0-3 are filled;+SidePulse Pro uses all eight LEDs as a battery bar. At 50%, LEDs 0-3 are filled;when charging, LED 4 is the pulsing frontier LED. Live updates ease the wholestrip into its new base state, then trigger one frontier pulse. The app ownsthe animation cadence by rewriting that one-shot pulse; the device does not run@@ -66,15 +72,16 @@ sidepulse battery configure --full-watts autosidepulse battery configure --show-on-power-change yes --power-change-preview-seconds 7```-## SidePulse Bridge+## sidepulse-SidePulse Bridge is a companion app for macOS that controls SidePulse devices.+`sidepulse` includes a companion menu-bar app for macOS that controls+SidePulse Pro and SidePulse Dot.### Main Functionality#### AI Agent Monitoring-SidePulse can monitor AI agents such as Codex and Claude through hooks, then+SidePulse can monitor AI agents such as Codex, Claude, and Grok through hooks, thentranslate the current agent state into a small, glanceable LED status.Agent status modes:@@ -117,14 +124,16 @@ the display indefinitely.#### Agent Monitor Library-The `agent_monitor` Python package collects and normalizes local AI agent hook+The `sidepulse` Python package collects and normalizes local AI agent hookevents. The macOS status-bar app receives hook events through a lightweightlocal Unix socket, keeps the latest agent states in memory, and writes only a-small `latest.json` restart snapshot plus provider JSONL debug logs. It does-not rescan historical logs or transcripts on every refresh.+small `latest.json` restart snapshot plus provider JSONL debug logs. Hooks also+append `event-status.jsonl`, a compact decision log that records each hook event+and the SidePulse status it produced for debugging/export. The app 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`.+The package can also mirror the aggregate state to a mounted SidePulse Pro or+SidePulse Dot by writing the current LED program to `LEDS.LED`.The monitor currently supports:@@ -132,6 +141,37 @@ The monitor currently supports:| --- | --- | --- || Codex | `~/.codex/config.toml` | `${XDG_STATE_HOME:-~/.local/state}/sidepulse/agent-monitor/codex.jsonl` || Claude | `~/.claude/settings.json` | `${XDG_STATE_HOME:-~/.local/state}/sidepulse/agent-monitor/claude.jsonl` |+| Grok | `~/.grok/hooks/sidepulse.json` | `${XDG_STATE_HOME:-~/.local/state}/sidepulse/agent-monitor/grok.jsonl` |++#### Local reply classifier (Apple Silicon)++Install the optional MLX dependency, then classify a message with the default+4-bit `mlx-community/Qwen2.5-0.5B-Instruct-4bit` model:++```sh+python3 -m pip install -e '.[reply-classifier]'+sidepulse-reply "Could you check this for me?"+echo "Thanks, I received it." | sidepulse-reply --json+```++The model runs locally and uses deterministic greedy decoding. To benchmark the+canonical labeled examples plus recent assistant messages collected in the+SidePulse decision log:++```sh+python3 examples/benchmark_reply_classifier.py --warm-runs 20 --log-examples 12+```++Generate the labeled dataset (eight human-collected examples plus 300 balanced,+reproducible synthetic examples):++```sh+python3 scripts/generate_reply_dataset.py+```++The resulting `data/reply_expectation.jsonl` records `label`, `source`, `split`,+and `category`. Human-collected examples are kept in the test split and synthetic+examples are explicitly marked so evaluation can report them separately.For CLI snapshots, debugging, or recovery after missed hook events, thefile-based monitor can optionally read recent local transcripts as a fallback:@@ -170,17 +210,18 @@ Set up this Mac explicitly after package install:sidepulse setup```-`sidepulse setup` installs or refreshes Codex and Claude hooks, installs the SD-eject guard, writes the status-bar LaunchAgent, starts both helpers+`sidepulse setup` installs or refreshes Codex, Claude, and Grok hooks, installs+SidePulse Pro Eject Prevention, writes the status-bar LaunchAgent, starts both helpersimmediately, and enables them at login. This is intentionally an explicitcommand 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`.+`sidepulse setup codex`, `sidepulse setup claude`, or `sidepulse setup grok`.+To skip the status-bar app but still install hooks and SidePulse Pro Eject Prevention, 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:+SidePulse Pro Eject Prevention 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:```shsidepulse setup --sd-eject-guard-scope auto@@ -191,11 +232,12 @@ sidepulse setup --sd-eject-guard-scope system --no-status-barThe system scope requires the command to already have system installpermissions.-Manage the SD eject guard directly:+Manage SidePulse Pro Eject Prevention directly:```shsidepulse sdejectguard startsidepulse sdejectguard stop+sidepulse sdejectguard uninstallsidepulse sdejectguard logssidepulse sdejectguard start -it```@@ -209,6 +251,13 @@ python3 -m pip install --user --break-system-packages -e .ln -sf "$(python3 -m site --user-base)/bin/sidepulse" ~/.local/bin/sidepulse```+### macOS installer++A signed and notarized PKG release can be built with+[`packaging/build_macos_pkg.sh`](packaging/build_macos_pkg.sh). See+[`packaging/README.md`](packaging/README.md) for the required Developer ID+certificates and notarization profile.+Check the current hook configuration:```sh@@ -221,6 +270,7 @@ Install or refresh the monitor hooks:sidepulse agent-monitor installsidepulse agent-monitor install codexsidepulse agent-monitor install claude+sidepulse agent-monitor install grok```Each hook invokes a small, standard-library-only Python entry point. It writes@@ -252,6 +302,12 @@ By default, `Tool Running` events are not time-limited, so genuinely long toolsremain visible. If a provider drops completion hooks and you want protectionagainst stale tool starts, set `--tool-running-timeout`.+`PostToolUse` means the tool returned, not that the whole turn is finished. The+monitor keeps it as Working for a short settling window while the assistant+writes the response, then treats it as Done if no newer hook event arrives. This+prevents a missed final `Stop` event from leaving the status bar stuck on+Working.+`Completed` remains visible for 20 minutes so the status bar and LEDs can showDone long enough to be noticed. After that it drops out instead of counting asan active session for the full stale window, and the LEDs return to the very@@ -281,8 +337,8 @@ Codex `PermissionRequest` events are treated as Ask and remain sticky until thematching tool command finishes. This prevents unrelated same-session activityfrom hiding an approval prompt that is still waiting on the user.-For Codex or Claude projects that should report this reliably, add guidance like-this to the relevant agent instructions:+For Codex, Claude, or Grok projects that should report this reliably, add+guidance like this to the relevant agent instructions:```textWhen your final response needs user input, approval, or a decision, include@@ -302,12 +358,12 @@ program:```shsidepulse agent-monitor leds --once --dry-run-sidepulse agent-monitor leds --device /Volumes/PulseDot+sidepulse agent-monitor leds --device /Volumes/SidePulseDot```-PulseDot programs are generated for two LEDs. SidePulse programs are generated+SidePulse Dot programs are generated for two LEDs. SidePulse Pro programs are generatedfor eight LEDs. The monitor detects this from the mounted device name and falls-back to the eight-LED SidePulse layout if the name is unknown.+back to the eight-LED SidePulse Pro layout if the name is unknown.Remove monitor hooks:@@ -315,6 +371,7 @@ Remove monitor hooks:sidepulse agent-monitor uninstallsidepulse agent-monitor uninstall codexsidepulse agent-monitor uninstall claude+sidepulse agent-monitor uninstall grok```Install and start the macOS status-bar app:@@ -332,6 +389,14 @@ state to the LEDs. For debugging, run it in the foreground:sidepulse status-bar start --foreground```+On first launch, the status-bar app shows a SidePulse Setup window. It can:++- enable Run at Login;+- install or uninstall SidePulse Pro Eject Prevention, which keeps SidePulse Pro/SidePulse Dot available after sleep;+- open the one-time closed-lid sleep prevention installer in Terminal.++The Setup window can be reopened from the dropdown with `Setup...`.+The status-bar item shows one of four collapsed states:| Label | Meaning |@@ -347,9 +412,9 @@ session's Open Options row to choose and remember another opener, such as theprovider 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.-If both devices are mounted, the status-bar app prefers SidePulse, then-PulseDot. Click the item to disconnect and turn the LEDs off; click it again to+the status-bar app is actively connected to a mounted SidePulse Pro/SidePulse Dot target.+If both devices are mounted, the status-bar app prefers SidePulse Pro, then+SidePulse Dot. Click the item to disconnect and turn the LEDs off; click it again toreconnect.The dropdown and Settings window can switch the LEDs between agent status and@@ -357,12 +422,27 @@ battery status. When agent status is selected, `Show Battery on Plug/Unplug`can briefly show the battery animation for seven seconds after the power sourcechanges.+The Devices section also offers **Add Screen Bar**, an optional virtual+eight-LED device. It appears as a notch-shaped status-bar overlay that covers+the camera island/notch footprint and adds a straight 5 px LED band along the+bottom edge, or the corresponding top-center position on a display without a+notch. Each virtual LED blends across a three-LED footprint: centered on the+target LED, fading one LED width left and right. It shares the physical+device's status animations, display-mode selection, and per-device brightness+control. The Screen Bar evaluates the same `LEDS.LED` programs with the+firmware/websim `sdled.wasm` engine, then AppKit only draws the returned RGB+frames.+Open `Settings...` from the dropdown to manage agent integrations. The settings-window can install or uninstall Codex and Claude hooks. The transcript+window can install or uninstall Codex, Claude, and Grok hooks. The transcriptcheckboxes control the file-based CLI/debug fallback; the status-bar app getslive updates from the local hook event socket. Settings are stored at`${XDG_CONFIG_HOME:-~/.config}/sidepulse/agent-monitor/settings.json`.+Settings can export the hook decision log as CSV or HTML. This log lives at+`${XDG_STATE_HOME:-~/.local/state}/sidepulse/agent-monitor/event-status.jsonl`+and shows the path from provider hook event to interpreted SidePulse status.+The `Keep Awake With Lid Closed` menu section controls the stronger sleepprevention policy:@@ -372,13 +452,11 @@ prevention policy:| 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+The status-bar app still keeps the SidePulse Pro/SidePulse Dot volume active by touchinga `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:+closed-lid policy uses the SidePulse sleep helper when it is installed. The PKG+installer sets this up automatically; source/dev installs can run the one-time+setup command:```shsudo "$(command -v sidepulse)" status-bar install-sleep-helper@@ -386,8 +464,9 @@ sudo "$(command -v sidepulse)" status-bar install-sleep-helperThe 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:+silently with non-interactive `sudo`. SidePulse uses this automatically for+`Keep Awake With Lid Closed` and only restores the setting if SidePulse changed+it. Remove the helper with:```shsudo "$(command -v sidepulse)" status-bar uninstall-sleep-helper@@ -409,7 +488,7 @@ sidepulse status-bar stopUse it from another Python app:```python-from agent_monitor import AgentMonitor, LiveAgentMonitor+from sidepulse import AgentMonitor, LiveAgentMonitorsnapshot = AgentMonitor.from_default_sources().snapshot()print(snapshot.aggregate.mode.value)@@ -422,7 +501,7 @@ live = LiveAgentMonitor()Publish a hook-shaped event to the status-bar app from another local process:```python-from agent_monitor import send_hook_event+from sidepulse import send_hook_eventsend_hook_event("codex",@@ -455,18 +534,18 @@ Preview the meter in the terminal without touching a device:python3 examples/audio_monitor.py --dry-run --terminal```-Write to a mounted SidePulse or PulseDot:+Write to a mounted SidePulse Pro or SidePulse Dot:```sh-python3 examples/audio_monitor.py --device /Volumes/SidePulse --terminal-python3 examples/audio_monitor.py --device /Volumes/PulseDot --terminal+python3 examples/audio_monitor.py --device /Volumes/SidePulsePro --terminal+python3 examples/audio_monitor.py --device /Volumes/SidePulseDot --terminal```List audio inputs or tune sensitivity:```shpython3 examples/audio_monitor.py --list-inputs-python3 examples/audio_monitor.py --device /Volumes/SidePulse --gain-db 8 --release 0.45+python3 examples/audio_monitor.py --device /Volumes/SidePulsePro --gain-db 8 --release 0.45```#### Battery Monitordiff --git a/examples/audio_monitor.py b/examples/audio_monitor.pyindex aea7ce4..1861c8e 100644--- a/examples/audio_monitor.py+++ b/examples/audio_monitor.py@@ -14,13 +14,13 @@ REPO_SRC = Path(__file__).resolve().parents[1] / "src"if REPO_SRC.exists():sys.path.insert(0, str(REPO_SRC))-from agent_monitor.device_writer import ( # noqa: E402+from sidepulse.device_writer import ( # noqa: E402DEFAULT_FILE_NAME,DeviceWriteError,validate_led_text,write_led_program,)-from agent_monitor.led_status import apply_brightness, led_count_for_target # noqa: E402+from sidepulse.led_status import apply_brightness, led_count_for_target # noqa: E402DEFAULT_FPS = 25.0@@ -440,7 +440,11 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--input-device", help="sounddevice input index or name.")parser.add_argument("--list-inputs", action="store_true", help="List audio input devices and exit.")parser.add_argument("--terminal", action="store_true", help="Show a terminal meter while running.")- parser.add_argument("--dry-run", action="store_true", help="Preview without writing to a SidePulse device.")+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Preview without writing to a SidePulse Pro or SidePulse Dot device.",+ )parser.add_argument("--off-on-exit", action="store_true", help="Write 'off' when the monitor exits.")return parserdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter.xcodeproj/project.pbxproj b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter.xcodeproj/project.pbxprojdeleted file mode 100644index 28371ce..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter.xcodeproj/project.pbxproj+++ /dev/null@@ -1,369 +0,0 @@-// !$*UTF8*$!-{- archiveVersion = 1;- classes = {- };- objectVersion = 56;- objects = {--/* Begin PBXBuildFile section */- 9F0000010000000000000001 /* PixiePulseUSBWriterApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000101 /* PixiePulseUSBWriterApp.swift */; };- 9F0000010000000000000002 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000102 /* ContentView.swift */; };- 9F0000010000000000000003 /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000103 /* AppModel.swift */; };- 9F0000010000000000000004 /* DriveWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000104 /* DriveWriter.swift */; };- 9F0000010000000000000005 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000105 /* AppDelegate.swift */; };- 9F0000010000000000000006 /* FolderPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000106 /* FolderPicker.swift */; };- 9F0000010000000000000007 /* WriteLEDsIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000107 /* WriteLEDsIntent.swift */; };- 9F0000010000000000000008 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000108 /* Assets.xcassets */; };- 9F0000010000000000000009 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000112 /* EventLog.swift */; };- 9F0000010000000000000010 /* PushPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F0000010000000000000113 /* PushPayload.swift */; };-/* End PBXBuildFile section */--/* Begin PBXFileReference section */- 9F0000010000000000000101 /* PixiePulseUSBWriterApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PixiePulseUSBWriterApp.swift; sourceTree = "<group>"; };- 9F0000010000000000000102 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };- 9F0000010000000000000103 /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = "<group>"; };- 9F0000010000000000000104 /* DriveWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DriveWriter.swift; sourceTree = "<group>"; };- 9F0000010000000000000105 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };- 9F0000010000000000000106 /* FolderPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FolderPicker.swift; sourceTree = "<group>"; };- 9F0000010000000000000107 /* WriteLEDsIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WriteLEDsIntent.swift; sourceTree = "<group>"; };- 9F0000010000000000000108 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };- 9F0000010000000000000109 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };- 9F0000010000000000000110 /* PixiePulseUSBWriter.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = PixiePulseUSBWriter.entitlements; sourceTree = "<group>"; };- 9F0000010000000000000111 /* SidePulse.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SidePulse.app; sourceTree = BUILT_PRODUCTS_DIR; };- 9F0000010000000000000112 /* EventLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLog.swift; sourceTree = "<group>"; };- 9F0000010000000000000113 /* PushPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushPayload.swift; sourceTree = "<group>"; };-/* End PBXFileReference section */--/* Begin PBXFrameworksBuildPhase section */- 9F0000010000000000000201 /* Frameworks */ = {- isa = PBXFrameworksBuildPhase;- buildActionMask = 2147483647;- files = (- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXFrameworksBuildPhase section */--/* Begin PBXGroup section */- 9F0000010000000000000301 = {- isa = PBXGroup;- children = (- 9F0000010000000000000302 /* PixiePulseUSBWriter */,- 9F0000010000000000000303 /* Products */,- );- sourceTree = "<group>";- };- 9F0000010000000000000302 /* PixiePulseUSBWriter */ = {- isa = PBXGroup;- children = (- 9F0000010000000000000101 /* PixiePulseUSBWriterApp.swift */,- 9F0000010000000000000102 /* ContentView.swift */,- 9F0000010000000000000103 /* AppModel.swift */,- 9F0000010000000000000104 /* DriveWriter.swift */,- 9F0000010000000000000105 /* AppDelegate.swift */,- 9F0000010000000000000112 /* EventLog.swift */,- 9F0000010000000000000113 /* PushPayload.swift */,- 9F0000010000000000000106 /* FolderPicker.swift */,- 9F0000010000000000000107 /* WriteLEDsIntent.swift */,- 9F0000010000000000000108 /* Assets.xcassets */,- 9F0000010000000000000109 /* Info.plist */,- 9F0000010000000000000110 /* PixiePulseUSBWriter.entitlements */,- );- path = PixiePulseUSBWriter;- sourceTree = "<group>";- };- 9F0000010000000000000303 /* Products */ = {- isa = PBXGroup;- children = (- 9F0000010000000000000111 /* SidePulse.app */,- );- name = Products;- sourceTree = "<group>";- };-/* End PBXGroup section */--/* Begin PBXNativeTarget section */- 9F0000010000000000000401 /* PixiePulseUSBWriter */ = {- isa = PBXNativeTarget;- buildConfigurationList = 9F0000010000000000000902 /* Build configuration list for PBXNativeTarget "PixiePulseUSBWriter" */;- buildPhases = (- 9F0000010000000000000501 /* Sources */,- 9F0000010000000000000201 /* Frameworks */,- 9F0000010000000000000601 /* Resources */,- );- buildRules = (- );- dependencies = (- );- name = PixiePulseUSBWriter;- productName = SidePulse;- productReference = 9F0000010000000000000111 /* SidePulse.app */;- productType = "com.apple.product-type.application";- };-/* End PBXNativeTarget section */--/* Begin PBXProject section */- 9F0000010000000000000701 /* Project object */ = {- isa = PBXProject;- attributes = {- BuildIndependentTargetsInParallel = 1;- LastSwiftUpdateCheck = 1530;- LastUpgradeCheck = 1530;- TargetAttributes = {- 9F0000010000000000000401 = {- CreatedOnToolsVersion = 15.3;- };- };- };- buildConfigurationList = 9F0000010000000000000901 /* Build configuration list for PBXProject "PixiePulseUSBWriter" */;- compatibilityVersion = "Xcode 14.0";- developmentRegion = en;- hasScannedForEncodings = 0;- knownRegions = (- en,- Base,- );- mainGroup = 9F0000010000000000000301;- productRefGroup = 9F0000010000000000000303 /* Products */;- projectDirPath = "";- projectRoot = "";- targets = (- 9F0000010000000000000401 /* PixiePulseUSBWriter */,- );- };-/* End PBXProject section */--/* Begin PBXResourcesBuildPhase section */- 9F0000010000000000000601 /* Resources */ = {- isa = PBXResourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 9F0000010000000000000008 /* Assets.xcassets in Resources */,- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXResourcesBuildPhase section */--/* Begin PBXSourcesBuildPhase section */- 9F0000010000000000000501 /* Sources */ = {- isa = PBXSourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 9F0000010000000000000001 /* PixiePulseUSBWriterApp.swift in Sources */,- 9F0000010000000000000002 /* ContentView.swift in Sources */,- 9F0000010000000000000003 /* AppModel.swift in Sources */,- 9F0000010000000000000004 /* DriveWriter.swift in Sources */,- 9F0000010000000000000005 /* AppDelegate.swift in Sources */,- 9F0000010000000000000009 /* EventLog.swift in Sources */,- 9F0000010000000000000010 /* PushPayload.swift in Sources */,- 9F0000010000000000000006 /* FolderPicker.swift in Sources */,- 9F0000010000000000000007 /* WriteLEDsIntent.swift in Sources */,- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXSourcesBuildPhase section */--/* Begin XCBuildConfiguration section */- 9F0000010000000000000801 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ALWAYS_SEARCH_USER_PATHS = NO;- CLANG_ANALYZER_NONNULL = YES;- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;- CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";- CLANG_ENABLE_MODULES = YES;- CLANG_ENABLE_OBJC_ARC = YES;- CLANG_ENABLE_OBJC_WEAK = YES;- CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;- CLANG_WARN_BOOL_CONVERSION = YES;- CLANG_WARN_COMMA = YES;- CLANG_WARN_CONSTANT_CONVERSION = YES;- CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;- CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;- CLANG_WARN_EMPTY_BODY = YES;- CLANG_WARN_ENUM_CONVERSION = YES;- CLANG_WARN_INFINITE_RECURSION = YES;- CLANG_WARN_INT_CONVERSION = YES;- CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;- CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;- CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;- CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;- CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;- CLANG_WARN_STRICT_PROTOTYPES = YES;- CLANG_WARN_SUSPICIOUS_MOVE = YES;- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;- CLANG_WARN_UNREACHABLE_CODE = YES;- CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;- COPY_PHASE_STRIP = NO;- DEBUG_INFORMATION_FORMAT = dwarf;- ENABLE_STRICT_OBJC_MSGSEND = YES;- ENABLE_TESTABILITY = YES;- ENABLE_USER_SCRIPT_SANDBOXING = YES;- GCC_C_LANGUAGE_STANDARD = gnu17;- GCC_DYNAMIC_NO_PIC = NO;- GCC_NO_COMMON_BLOCKS = YES;- GCC_OPTIMIZATION_LEVEL = 0;- GCC_PREPROCESSOR_DEFINITIONS = (- "DEBUG=1",- "$(inherited)",- );- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;- GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;- GCC_WARN_UNDECLARED_SELECTOR = YES;- GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;- GCC_WARN_UNUSED_FUNCTION = YES;- GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 16.0;- MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;- MTL_FAST_MATH = YES;- ONLY_ACTIVE_ARCH = YES;- SDKROOT = iphoneos;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";- SWIFT_OPTIMIZATION_LEVEL = "-Onone";- };- name = Debug;- };- 9F0000010000000000000802 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ALWAYS_SEARCH_USER_PATHS = NO;- CLANG_ANALYZER_NONNULL = YES;- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;- CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";- CLANG_ENABLE_MODULES = YES;- CLANG_ENABLE_OBJC_ARC = YES;- CLANG_ENABLE_OBJC_WEAK = YES;- CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;- CLANG_WARN_BOOL_CONVERSION = YES;- CLANG_WARN_COMMA = YES;- CLANG_WARN_CONSTANT_CONVERSION = YES;- CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;- CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;- CLANG_WARN_EMPTY_BODY = YES;- CLANG_WARN_ENUM_CONVERSION = YES;- CLANG_WARN_INFINITE_RECURSION = YES;- CLANG_WARN_INT_CONVERSION = YES;- CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;- CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;- CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;- CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;- CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;- CLANG_WARN_STRICT_PROTOTYPES = YES;- CLANG_WARN_SUSPICIOUS_MOVE = YES;- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;- CLANG_WARN_UNREACHABLE_CODE = YES;- CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;- COPY_PHASE_STRIP = NO;- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";- ENABLE_NS_ASSERTIONS = NO;- ENABLE_STRICT_OBJC_MSGSEND = YES;- ENABLE_USER_SCRIPT_SANDBOXING = YES;- GCC_C_LANGUAGE_STANDARD = gnu17;- GCC_NO_COMMON_BLOCKS = YES;- GCC_WARN_64_TO_32_BIT_CONVERSION = YES;- GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;- GCC_WARN_UNDECLARED_SELECTOR = YES;- GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;- GCC_WARN_UNUSED_FUNCTION = YES;- GCC_WARN_UNUSED_VARIABLE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 16.0;- MTL_ENABLE_DEBUG_INFO = NO;- MTL_FAST_MATH = YES;- SDKROOT = iphoneos;- SWIFT_COMPILATION_MODE = wholemodule;- VALIDATE_PRODUCT = YES;- };- name = Release;- };- 9F0000010000000000000803 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = PixiePulseUSBWriter/PixiePulseUSBWriter.entitlements;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 1;- DEVELOPMENT_ASSET_PATHS = "";- DEVELOPMENT_TEAM = 5QJ7W2AQ8H;- ENABLE_PREVIEWS = YES;- GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = PixiePulseUSBWriter/Info.plist;- INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;- INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;- INFOPLIST_KEY_UILaunchScreen_Generation = YES;- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/Frameworks",- );- MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = xyz.inteliwear.iphone.pixiedot;- PRODUCT_NAME = SidePulse;- SWIFT_EMIT_LOC_STRINGS = YES;- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- };- name = Debug;- };- 9F0000010000000000000804 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;- CODE_SIGN_ENTITLEMENTS = PixiePulseUSBWriter/PixiePulseUSBWriter.entitlements;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 1;- DEVELOPMENT_ASSET_PATHS = "";- DEVELOPMENT_TEAM = 5QJ7W2AQ8H;- ENABLE_PREVIEWS = YES;- GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = PixiePulseUSBWriter/Info.plist;- INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;- INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;- INFOPLIST_KEY_UILaunchScreen_Generation = YES;- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/Frameworks",- );- MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = xyz.inteliwear.iphone.pixiedot;- PRODUCT_NAME = SidePulse;- SWIFT_EMIT_LOC_STRINGS = YES;- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- };- name = Release;- };-/* End XCBuildConfiguration section */--/* Begin XCConfigurationList section */- 9F0000010000000000000901 /* Build configuration list for PBXProject "PixiePulseUSBWriter" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 9F0000010000000000000801 /* Debug */,- 9F0000010000000000000802 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };- 9F0000010000000000000902 /* Build configuration list for PBXNativeTarget "PixiePulseUSBWriter" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 9F0000010000000000000803 /* Debug */,- 9F0000010000000000000804 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };-/* End XCConfigurationList section */- };- rootObject = 9F0000010000000000000701 /* Project object */;-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppDelegate.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppDelegate.swiftdeleted file mode 100644index 3591328..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppDelegate.swift+++ /dev/null@@ -1,131 +0,0 @@-import Foundation-import UIKit-import UserNotifications--final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {- func application(- _ application: UIApplication,- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil- ) -> Bool {- UNUserNotificationCenter.current().delegate = self- application.registerForRemoteNotifications()- EventLog.append("App launched; registered for remote notifications")-- if let userInfo = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {- processNotification(userInfo, source: "Launch notification")- }-- return true- }-- func application(- _ application: UIApplication,- didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data- ) {- Task { @MainActor in- AppModel.shared.setPushToken(from: deviceToken)- }- }-- func application(- _ application: UIApplication,- didFailToRegisterForRemoteNotificationsWithError error: Error- ) {- EventLog.append("APNs registration failed: \(error.localizedDescription)")- Task { @MainActor in- AppModel.shared.recordError(error)- }- }-- func application(- _ application: UIApplication,- didReceiveRemoteNotification userInfo: [AnyHashable: Any],- fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void- ) {- let didHandle = processNotification(userInfo, source: "Background push")- completionHandler(didHandle ? .newData : .failed)- }-- func application(- _ app: UIApplication,- open url: URL,- options: [UIApplication.OpenURLOptionsKey: Any] = [:]- ) -> Bool {- guard let resolution = PushPayloadResolver.resolve(url: url) else {- return false- }-- return processResolvedPayload(resolution, source: "Shortcut URL")- }-- func userNotificationCenter(- _ center: UNUserNotificationCenter,- willPresent notification: UNNotification- ) async -> UNNotificationPresentationOptions {- [.banner, .sound]- }-- func userNotificationCenter(- _ center: UNUserNotificationCenter,- didReceive response: UNNotificationResponse- ) async {- processNotification(- response.notification.request.content.userInfo,- source: "Opened notification"- )- }-- @discardableResult- private func processNotification(_ userInfo: [AnyHashable: Any], source: String) -> Bool {- let keys = userInfo.keys.map { String(describing: $0) }.sorted().joined(separator: ",")- EventLog.append("\(source) received; keys=[\(keys)]")-- let resolution = PushPayloadResolver.resolve(userInfo: userInfo)- return processResolvedPayload(resolution, source: source)- }-- @discardableResult- private func processResolvedPayload(_ resolution: PushPayloadResolution, source: String) -> Bool {- var status: ReceivedPush.WriteStatus = .received- var errorMessage: String?-- if resolution.isUnsupportedPattern {- status = .unsupportedPattern- EventLog.append("\(source) stored unsupported pattern \(resolution.patternName ?? "")")- } else if let ledText = resolution.resolvedLEDText {- if DriveWriter.shared.hasSavedFolder {- do {- let targetURL = try DriveWriter.shared.write(ledText)- status = .wrote- EventLog.append("\(source) wrote \(targetURL.lastPathComponent)")- } catch {- status = .failed- errorMessage = error.localizedDescription- EventLog.append("\(source) failed: \(error.localizedDescription)")- }- } else {- status = .noFolder- EventLog.append("\(source) stored LED payload; no PulseDot folder selected")- }- } else {- EventLog.append("\(source) stored general push")- }-- let push = ReceivedPush(- source: source,- title: resolution.displayTitle,- body: resolution.displayBody,- patternName: resolution.patternName,- ledText: resolution.resolvedLEDText,- payloadSummary: resolution.payloadSummary,- writeStatus: status,- errorMessage: errorMessage- )-- Task { @MainActor in- AppModel.shared.recordReceivedPush(push)- }-- return status != .failed- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppModel.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppModel.swiftdeleted file mode 100644index 6c2da3f..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppModel.swift+++ /dev/null@@ -1,215 +0,0 @@-import Foundation-import UIKit--@MainActor-final class AppModel: ObservableObject {- static let shared = AppModel()-- @Published var pushToken: String {- didSet { UserDefaults.standard.set(pushToken, forKey: Defaults.pushToken) }- }-- @Published var selectedFolderPath: String = "No USB folder selected"- @Published var hasFolderAccess: Bool = false-- @Published var ledText: String {- didSet { UserDefaults.standard.set(ledText, forKey: Defaults.ledText) }- }-- @Published var serverBaseURL: String {- didSet { UserDefaults.standard.set(serverBaseURL, forKey: Defaults.serverBaseURL) }- }-- @Published var sharedSecret: String {- didSet { UserDefaults.standard.set(sharedSecret, forKey: Defaults.sharedSecret) }- }-- @Published var lastMessage: String = "Ready"- @Published var eventLog: [String] = []- @Published var receivedPushes: [ReceivedPush] {- didSet { persistReceivedPushes() }- }-- private enum Defaults {- static let pushToken = "pushToken"- static let ledText = "ledText"- static let serverBaseURL = "serverBaseURL"- static let sharedSecret = "sharedSecret"- static let receivedPushes = "receivedPushes"- }-- private init() {- self.pushToken = UserDefaults.standard.string(forKey: Defaults.pushToken) ?? ""- self.ledText = UserDefaults.standard.string(forKey: Defaults.ledText) ?? """- #404040 1.4s pulse- off 400ms none- repeat- """- self.serverBaseURL = UserDefaults.standard.string(forKey: Defaults.serverBaseURL) ?? "http://127.0.0.1:8787"- self.sharedSecret = UserDefaults.standard.string(forKey: Defaults.sharedSecret) ?? ""- self.receivedPushes = Self.loadReceivedPushes()- self.eventLog = EventLog.entries()- refreshFolderStatus()- }-- func setPushToken(from deviceToken: Data) {- pushToken = deviceToken.map { String(format: "%02x", $0) }.joined()- EventLog.append("APNs token updated")- lastMessage = "Push token updated"- refreshEventLog()- }-- func refreshFolderStatus() {- hasFolderAccess = DriveWriter.shared.hasSavedFolder- selectedFolderPath = DriveWriter.shared.savedFolderDisplayName- }-- func recordWriteSuccess(_ message: String) {- EventLog.append(message)- lastMessage = message- refreshFolderStatus()- refreshEventLog()- }-- func recordError(_ error: Error) {- let message = error.localizedDescription- EventLog.append("Error: \(message)")- lastMessage = message- refreshFolderStatus()- refreshEventLog()- }-- func recordReceivedPush(_ push: ReceivedPush) {- var next = [push]- next.append(contentsOf: receivedPushes)- if next.count > 50 {- next.removeLast(next.count - 50)- }- receivedPushes = next-- let status = push.writeStatus.displayName- EventLog.append("\(push.source): \(push.title) (\(status))")- lastMessage = "\(push.title) - \(status)"- refreshFolderStatus()- refreshEventLog()- }-- func clearReceivedPushes() {- receivedPushes = []- lastMessage = "Cleared received pushes"- }-- func refreshEventLog() {- eventLog = EventLog.entries()- }-- func clearEventLog() {- EventLog.clear()- refreshEventLog()- }-- var preauthenticatedPostURL: String? {- let trimmedBase = serverBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)- .trimmingCharacters(in: CharacterSet(charactersIn: "/"))- guard !trimmedBase.isEmpty, !pushToken.isEmpty else {- return nil- }-- var components = URLComponents(string: trimmedBase + "/v1/push")- var items = [- URLQueryItem(name: "device_token", value: pushToken)- ]-- if !sharedSecret.isEmpty {- items.append(URLQueryItem(name: "key", value: sharedSecret))- }-- components?.queryItems = items- return components?.url?.absoluteString- }-- var pushEndpointURL: String? {- let trimmedBase = serverBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)- .trimmingCharacters(in: CharacterSet(charactersIn: "/"))- guard !trimmedBase.isEmpty else {- return nil- }- return trimmedBase + "/v1/push"- }-- var curlExample: String? {- guard let pushEndpointURL else {- return nil- }-- let tokenLine = pushToken.isEmpty ? "" : "\n -d '{\"device_token\":\"\(pushToken)\",\"pattern\":\"green_pulse_2\"}'"- let authHeader = sharedSecret.isEmpty ? "" : " \\\n -H \"Authorization: Bearer \(sharedSecret)\""- if tokenLine.isEmpty {- return """- curl -X POST \(pushEndpointURL)\(authHeader) \\- -H "content-type: application/json" \\- -d '{"pattern":"green_pulse_2"}'- """- }-- return """- curl -X POST \(pushEndpointURL)\(authHeader) \\- -H "content-type: application/json" \(tokenLine)- """- }-- var shortcutWriteURL: String? {- guard !ledText.isEmpty else {- return nil- }-- var components = URLComponents()- components.scheme = "sidepulse"- components.host = "write"- components.queryItems = [- URLQueryItem(name: "text", value: ledText)- ]- return components.url?.absoluteString- }-- func shortcutPatternURL(for pattern: LEDPattern) -> String? {- var components = URLComponents()- components.scheme = "sidepulse"- components.host = "write"- components.queryItems = [- URLQueryItem(name: "pattern", value: pattern.name)- ]- return components.url?.absoluteString- }-- private func persistReceivedPushes() {- if let data = try? JSONEncoder().encode(receivedPushes) {- UserDefaults.standard.set(data, forKey: Defaults.receivedPushes)- }- }-- private static func loadReceivedPushes() -> [ReceivedPush] {- guard let data = UserDefaults.standard.data(forKey: Defaults.receivedPushes),- let pushes = try? JSONDecoder().decode([ReceivedPush].self, from: data) else {- return []- }- return Array(pushes.prefix(50))- }-}--extension ReceivedPush.WriteStatus {- var displayName: String {- switch self {- case .received:- return "Received"- case .wrote:- return "Wrote LEDS.TXT"- case .noFolder:- return "Folder needed"- case .failed:- return "Failed"- case .unsupportedPattern:- return "Unknown pattern"- }- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AccentColor.colorset/Contents.jsondeleted file mode 100644index eb87897..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AccentColor.colorset/Contents.json+++ /dev/null@@ -1,11 +0,0 @@-{- "colors" : [- {- "idiom" : "universal"- }- ],- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Contents.jsondeleted file mode 100644index 374b093..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Contents.json+++ /dev/null@@ -1,116 +0,0 @@-{- "images" : [- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "20x20"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "20x20"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "29x29"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "29x29"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "40x40"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "40x40"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "2x",- "size" : "60x60"- },- {- "filename" : "[email protected]",- "idiom" : "iphone",- "scale" : "3x",- "size" : "60x60"- },- {- "filename" : "Icon-App-20x20@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "20x20"- },- {- "filename" : "Icon-App-20x20@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "20x20"- },- {- "filename" : "Icon-App-29x29@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "29x29"- },- {- "filename" : "Icon-App-29x29@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "29x29"- },- {- "filename" : "Icon-App-40x40@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "40x40"- },- {- "filename" : "Icon-App-40x40@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "40x40"- },- {- "filename" : "Icon-App-76x76@1x~ipad.png",- "idiom" : "ipad",- "scale" : "1x",- "size" : "76x76"- },- {- "filename" : "Icon-App-76x76@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "76x76"- },- {- "filename" : "Icon-App-83.5x83.5@2x~ipad.png",- "idiom" : "ipad",- "scale" : "2x",- "size" : "83.5x83.5"- },- {- "filename" : "[email protected]",- "idiom" : "ios-marketing",- "scale" : "1x",- "size" : "1024x1024"- }- ],- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index acbb0e7..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.pngdeleted file mode 100644index 50e9661..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index e66f18c..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.pngdeleted file mode 100644index e66f18c..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 518b435..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.pngdeleted file mode 100644index 888668e..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index b085ce1..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.pngdeleted file mode 100644index b085ce1..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 43966c2..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.pngdeleted file mode 100644index e66f18c..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 0ab6e63..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.pngdeleted file mode 100644index 0ab6e63..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 1b10f4c..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 1b10f4c..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]deleted file mode 100644index 7d2ea8a..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.pngdeleted file mode 100644index 5737d59..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.pngdeleted file mode 100644index 930b0e0..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.png b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.pngdeleted file mode 100644index 9862c50..0000000Binary files a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/Contents.json b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/Contents.jsondeleted file mode 100644index 73c0059..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/Contents.json+++ /dev/null@@ -1,6 +0,0 @@-{- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/ContentView.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/ContentView.swiftdeleted file mode 100644index 3cda74a..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/ContentView.swift+++ /dev/null@@ -1,679 +0,0 @@-import SwiftUI-import UIKit-import UserNotifications--@MainActor-struct ContentView: View {- @StateObject private var model: AppModel- @State private var isShowingFolderPicker = false- @State private var activeSheet: ActiveSheet?-- init() {- _model = StateObject(wrappedValue: AppModel.shared)- }-- init(model: AppModel) {- _model = StateObject(wrappedValue: model)- }-- var body: some View {- NavigationStack {- ScrollView {- VStack(alignment: .leading, spacing: 16) {- HeaderPanel(model: model) {- activeSheet = .token- requestPushToken()- }-- RecentPushesPanel(pushes: Array(model.receivedPushes.prefix(5)))-- PulseDotSetupPanel(model: model) {- activeSheet = .folderSetup- }-- QuickPatternsPanel { pattern in- write(pattern)- }- }- .padding(16)- }- .background(Color(.systemGroupedBackground))- .navigationTitle("SidePulse")- .toolbar {- ToolbarItem(placement: .topBarTrailing) {- NavigationLink {- SettingsView(- model: model,- requestPushToken: requestPushToken,- showFolderPicker: showFolderPicker- )- } label: {- Image(systemName: "gearshape")- }- .accessibilityLabel("Settings")- }- }- }- .sheet(item: $activeSheet) { sheet in- switch sheet {- case .token:- TokenSheet(model: model, requestPushToken: requestPushToken)- case .folderSetup:- FolderSetupSheet {- showFolderPicker()- }- }- }- .sheet(isPresented: $isShowingFolderPicker) {- FolderPicker { url in- isShowingFolderPicker = false- do {- try DriveWriter.shared.saveFolder(url)- model.refreshFolderStatus()- model.lastMessage = "Selected \(url.lastPathComponent)"- } catch {- model.recordError(error)- }- } onCancel: {- isShowingFolderPicker = false- }- }- .onAppear {- model.refreshFolderStatus()- }- }-- private func requestPushToken() {- UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, error in- Task { @MainActor in- if let error {- model.recordError(error)- return- }-- UIApplication.shared.registerForRemoteNotifications()- model.lastMessage = "Registering with APNs"- }- }- }-- private func showFolderPicker() {- activeSheet = nil- DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {- isShowingFolderPicker = true- }- }-- private func write(_ pattern: LEDPattern) {- let pushBase = ReceivedPush(- source: "Quick Pattern",- title: pattern.displayName,- body: pattern.detail,- patternName: pattern.name,- ledText: pattern.ledText,- payloadSummary: "{\"pattern\":\"\(pattern.name)\"}",- writeStatus: .received- )-- guard model.hasFolderAccess else {- var push = pushBase- push.writeStatus = .noFolder- model.recordReceivedPush(push)- activeSheet = .folderSetup- return- }-- do {- let targetURL = try DriveWriter.shared.write(pattern.ledText)- var push = pushBase- push.body = "Wrote \(targetURL.lastPathComponent)"- push.writeStatus = .wrote- model.recordReceivedPush(push)- } catch {- var push = pushBase- push.writeStatus = .failed- push.errorMessage = error.localizedDescription- model.recordReceivedPush(push)- }- }-}--private enum ActiveSheet: Identifiable {- case token- case folderSetup-- var id: String {- switch self {- case .token:- return "token"- case .folderSetup:- return "folderSetup"- }- }-}--private struct HeaderPanel: View {- @ObservedObject var model: AppModel- let getToken: () -> Void-- var body: some View {- Panel {- VStack(alignment: .leading, spacing: 14) {- HStack(alignment: .top) {- VStack(alignment: .leading, spacing: 5) {- Label("SidePulse", systemImage: "dot.radiowaves.left.and.right")- .font(.title2.weight(.semibold))- Text("Push inbox and PulseDot writer")- .font(.subheadline)- .foregroundStyle(.secondary)- }-- Spacer()-- StatusPill(isConnected: model.hasFolderAccess)- }-- Button {- getToken()- } label: {- Label(model.pushToken.isEmpty ? "Get Push Token" : "Show Push Token", systemImage: "key.horizontal")- .frame(maxWidth: .infinity)- }- .buttonStyle(.borderedProminent)- }- }- }-}--private struct StatusPill: View {- let isConnected: Bool-- var body: some View {- Label(isConnected ? "Folder connected" : "No folder", systemImage: isConnected ? "checkmark.circle.fill" : "exclamationmark.circle")- .font(.caption.weight(.semibold))- .foregroundStyle(isConnected ? Color.green : Color.orange)- .lineLimit(1)- }-}--private struct RecentPushesPanel: View {- let pushes: [ReceivedPush]-- var body: some View {- VStack(alignment: .leading, spacing: 10) {- HStack {- Text("Latest Pushes")- .font(.headline)- Spacer()- Text("\(pushes.count)")- .font(.caption.weight(.semibold))- .foregroundStyle(.secondary)- }-- if pushes.isEmpty {- EmptyInboxView()- } else {- VStack(spacing: 8) {- ForEach(pushes) { push in- ReceivedPushRow(push: push)- }- }- }- }- }-}--private struct EmptyInboxView: View {- var body: some View {- Panel {- HStack(spacing: 12) {- Image(systemName: "tray")- .font(.title3)- .foregroundStyle(.secondary)- .frame(width: 32, height: 32)-- VStack(alignment: .leading, spacing: 3) {- Text("No pushes received")- .font(.subheadline.weight(.semibold))- Text("SidePulse will store general pushes here even without a PulseDot device.")- .font(.footnote)- .foregroundStyle(.secondary)- }- }- }- }-}--private struct ReceivedPushRow: View {- let push: ReceivedPush-- var body: some View {- Panel {- HStack(alignment: .top, spacing: 12) {- Image(systemName: push.writeStatus.symbolName)- .font(.headline)- .foregroundStyle(push.writeStatus.tint)- .frame(width: 28, height: 28)-- VStack(alignment: .leading, spacing: 5) {- HStack(alignment: .firstTextBaseline) {- Text(push.title)- .font(.subheadline.weight(.semibold))- .lineLimit(1)- Spacer(minLength: 8)- Text(push.receivedAt, style: .relative)- .font(.caption)- .foregroundStyle(.secondary)- }-- Text(push.body)- .font(.footnote)- .foregroundStyle(.secondary)- .lineLimit(2)-- HStack(spacing: 8) {- Text(push.writeStatus.displayName)- .font(.caption.weight(.medium))- .foregroundStyle(push.writeStatus.tint)-- if let patternName = push.patternName {- Text(patternName)- .font(.caption.monospaced())- .foregroundStyle(.secondary)- } else if push.ledByteCount > 0 {- Text("\(push.ledByteCount) bytes")- .font(.caption.monospaced())- .foregroundStyle(.secondary)- }- }- }- }- }- }-}--private struct PulseDotSetupPanel: View {- @ObservedObject var model: AppModel- let openSetup: () -> Void-- var body: some View {- Panel {- VStack(alignment: .leading, spacing: 12) {- HStack(alignment: .top, spacing: 12) {- Image(systemName: "externaldrive")- .font(.title2)- .foregroundStyle(model.hasFolderAccess ? Color.green : Color.accentColor)- .frame(width: 34, height: 34)-- VStack(alignment: .leading, spacing: 5) {- Text("PulseDot Folder")- .font(.headline)- Text(model.selectedFolderPath)- .font(.footnote)- .foregroundStyle(.secondary)- .lineLimit(2)- }- }-- Button {- openSetup()- } label: {- Label(model.hasFolderAccess ? "Change LED Folder" : "Set Up PulseDot Folder", systemImage: "folder.badge.plus")- .frame(maxWidth: .infinity)- }- .buttonStyle(.bordered)- }- }- }-}--private struct QuickPatternsPanel: View {- let writePattern: (LEDPattern) -> Void- private let columns = [- GridItem(.adaptive(minimum: 150), spacing: 10)- ]-- var body: some View {- VStack(alignment: .leading, spacing: 10) {- Text("Quick Patterns")- .font(.headline)-- LazyVGrid(columns: columns, spacing: 10) {- ForEach(LEDPatternCatalog.patterns) { pattern in- Button {- writePattern(pattern)- } label: {- PatternButtonLabel(pattern: pattern)- }- .buttonStyle(.plain)- }- }- }- }-}--private struct PatternButtonLabel: View {- let pattern: LEDPattern-- var body: some View {- Panel {- HStack(spacing: 10) {- Circle()- .fill(Color(hex: pattern.tintHex))- .frame(width: 12, height: 12)-- VStack(alignment: .leading, spacing: 3) {- Text(pattern.displayName)- .font(.subheadline.weight(.semibold))- .foregroundStyle(.primary)- .lineLimit(1)- Text(pattern.name)- .font(.caption.monospaced())- .foregroundStyle(.secondary)- .lineLimit(1)- }-- Spacer(minLength: 0)- }- .frame(maxWidth: .infinity, minHeight: 52, alignment: .leading)- }- }-}--private struct TokenSheet: View {- @ObservedObject var model: AppModel- let requestPushToken: () -> Void- @Environment(\.dismiss) private var dismiss-- var body: some View {- NavigationStack {- Form {- Section("Push Token") {- if model.pushToken.isEmpty {- Text("No token yet")- .foregroundStyle(.secondary)- } else {- Text(model.pushToken)- .font(.system(.footnote, design: .monospaced))- .textSelection(.enabled)-- Button {- UIPasteboard.general.string = model.pushToken- model.lastMessage = "Copied push token"- } label: {- Label("Copy Token", systemImage: "doc.on.doc")- }- }-- Button {- requestPushToken()- } label: {- Label("Request Token", systemImage: "bell.badge")- }- }- }- .navigationTitle("Push Token")- .toolbar {- ToolbarItem(placement: .topBarTrailing) {- Button("Done") {- dismiss()- }- }- }- }- }-}--private struct FolderSetupSheet: View {- let openPicker: () -> Void- @Environment(\.dismiss) private var dismiss-- var body: some View {- NavigationStack {- VStack(alignment: .leading, spacing: 18) {- Label("PulseDot Device in Files", systemImage: "externaldrive")- .font(.title3.weight(.semibold))-- VStack(alignment: .leading, spacing: 10) {- Text("1. Attach the PulseDot USB drive to this iPhone or iPad.")- Text("2. Open Files and select the PulseDot USB drive folder containing LEDS.TXT.")- Text("3. SidePulse will remember that folder for later pushes and Shortcuts.")- }- .font(.body)- .foregroundStyle(.secondary)-- Button {- dismiss()- openPicker()- } label: {- Label("Open Files", systemImage: "folder")- .frame(maxWidth: .infinity)- }- .buttonStyle(.borderedProminent)-- Spacer()- }- .padding(20)- .navigationTitle("Set Up Folder")- .toolbar {- ToolbarItem(placement: .topBarTrailing) {- Button("Done") {- dismiss()- }- }- }- }- }-}--private struct SettingsView: View {- @ObservedObject var model: AppModel- let requestPushToken: () -> Void- let showFolderPicker: () -> Void-- var body: some View {- Form {- Section("Push Token") {- Button {- requestPushToken()- } label: {- Label("Get Push Token", systemImage: "key.horizontal")- }-- if model.pushToken.isEmpty {- Text("No token yet")- .foregroundStyle(.secondary)- } else {- Text(model.pushToken)- .font(.system(.footnote, design: .monospaced))- .textSelection(.enabled)-- Button {- UIPasteboard.general.string = model.pushToken- model.lastMessage = "Copied push token"- } label: {- Label("Copy Token", systemImage: "doc.on.doc")- }- }- }-- Section("PulseDot") {- LabeledContent("Folder", value: model.selectedFolderPath)-- Button {- showFolderPicker()- } label: {- Label("Set Up LED Folder", systemImage: "folder.badge.plus")- }- }-- Section("Advanced Server") {- TextField("Proxy base URL", text: $model.serverBaseURL)- .textInputAutocapitalization(.never)- .autocorrectionDisabled()- .keyboardType(.URL)-- SecureField("Shared secret", text: $model.sharedSecret)- .textInputAutocapitalization(.never)- .autocorrectionDisabled()-- if let endpoint = model.pushEndpointURL {- Text(endpoint)- .font(.system(.footnote, design: .monospaced))- .textSelection(.enabled)- }-- if let curlExample = model.curlExample {- Text(curlExample)- .font(.system(.caption, design: .monospaced))- .textSelection(.enabled)-- Button {- UIPasteboard.general.string = curlExample- model.lastMessage = "Copied curl example"- } label: {- Label("Copy Curl", systemImage: "terminal")- }- }- }-- Section("Raw LED Editor") {- TextEditor(text: $model.ledText)- .font(.system(.body, design: .monospaced))- .frame(minHeight: 140)-- Button {- writeLocalTest()- } label: {- Label("Write to USB", systemImage: "square.and.arrow.down")- }-- if let shortcutURL = model.shortcutWriteURL {- Button {- UIPasteboard.general.string = shortcutURL- model.lastMessage = "Copied Shortcut URL"- } label: {- Label("Copy Shortcut URL", systemImage: "link.badge.plus")- }- }- }-- Section("Diagnostics") {- Button {- model.refreshEventLog()- } label: {- Label("Refresh Log", systemImage: "arrow.clockwise")- }-- Button(role: .destructive) {- model.clearEventLog()- } label: {- Label("Clear Log", systemImage: "trash")- }-- if model.eventLog.isEmpty {- Text("No events")- .foregroundStyle(.secondary)- } else {- ForEach(model.eventLog.reversed(), id: \.self) { line in- Text(line)- .font(.system(.caption, design: .monospaced))- .textSelection(.enabled)- }- }- }-- Section("Inbox") {- Button(role: .destructive) {- model.clearReceivedPushes()- } label: {- Label("Clear Received Pushes", systemImage: "tray.and.arrow.down")- }- }- }- .navigationTitle("Settings")- }-- private func writeLocalTest() {- do {- let targetURL = try DriveWriter.shared.write(model.ledText)- model.recordWriteSuccess("Wrote \(targetURL.lastPathComponent)")- } catch {- model.recordError(error)- }- }-}--private struct Panel<Content: View>: View {- @ViewBuilder let content: () -> Content-- var body: some View {- content()- .padding(14)- .background(Color(.secondarySystemGroupedBackground))- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))- }-}--private extension ReceivedPush.WriteStatus {- var symbolName: String {- switch self {- case .received:- return "tray.fill"- case .wrote:- return "checkmark.circle.fill"- case .noFolder:- return "folder.badge.questionmark"- case .failed:- return "xmark.octagon.fill"- case .unsupportedPattern:- return "questionmark.circle.fill"- }- }-- var tint: Color {- switch self {- case .received:- return .blue- case .wrote:- return .green- case .noFolder:- return .orange- case .failed:- return .red- case .unsupportedPattern:- return .purple- }- }-}--private extension Color {- init(hex: String) {- let cleaned = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)- var value: UInt64 = 0- Scanner(string: cleaned).scanHexInt64(&value)-- let red: UInt64- let green: UInt64- let blue: UInt64-- switch cleaned.count {- case 6:- red = (value >> 16) & 0xff- green = (value >> 8) & 0xff- blue = value & 0xff- default:- red = 0x3b- green = 0x82- blue = 0xf6- }-- self.init(- .sRGB,- red: Double(red) / 255,- green: Double(green) / 255,- blue: Double(blue) / 255,- opacity: 1- )- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/DriveWriter.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/DriveWriter.swiftdeleted file mode 100644index 63c994e..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/DriveWriter.swift+++ /dev/null@@ -1,125 +0,0 @@-import Foundation--enum DriveWriterError: LocalizedError {- case noFolderSelected- case bookmarkStale- case accessDenied- case textTooLarge(Int)- case missingText-- var errorDescription: String? {- switch self {- case .noFolderSelected:- return "Pick the USB drive folder first."- case .bookmarkStale:- return "The saved Files permission is stale. Pick the USB folder again."- case .accessDenied:- return "iOS did not grant access to the selected USB folder."- case .textTooLarge(let byteCount):- return "LEDS.TXT is \(byteCount) bytes. Keep it at or below 512 bytes."- case .missingText:- return "No LED text was provided."- }- }-}--final class DriveWriter {- static let shared = DriveWriter()-- private let bookmarkKey = "usbFolderBookmark"- private let fileNameKey = "ledFileName"- private let defaultFileName = "LEDS.TXT"- private let maxLEDBytes = 512-- private init() {}-- var fileName: String {- get {- let stored = UserDefaults.standard.string(forKey: fileNameKey) ?? defaultFileName- let trimmed = stored.trimmingCharacters(in: .whitespacesAndNewlines)- return trimmed.isEmpty ? defaultFileName : trimmed- }- set {- UserDefaults.standard.set(newValue, forKey: fileNameKey)- }- }-- var hasSavedFolder: Bool {- UserDefaults.standard.data(forKey: bookmarkKey) != nil- }-- var savedFolderDisplayName: String {- guard let url = try? resolveFolderURL() else {- return "No USB folder selected"- }-- return url.path- }-- func saveFolder(_ url: URL) throws {- EventLog.append("Saving USB folder bookmark: \(url.lastPathComponent)")- let startedAccess = url.startAccessingSecurityScopedResource()- defer {- if startedAccess {- url.stopAccessingSecurityScopedResource()- }- }-- let bookmark = try url.bookmarkData(- options: [],- includingResourceValuesForKeys: nil,- relativeTo: nil- )- UserDefaults.standard.set(bookmark, forKey: bookmarkKey)- EventLog.append("Saved USB folder bookmark")- }-- @discardableResult- func write(_ text: String) throws -> URL {- let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else {- throw DriveWriterError.missingText- }-- let byteCount = text.data(using: .utf8)?.count ?? 0- guard byteCount <= maxLEDBytes else {- throw DriveWriterError.textTooLarge(byteCount)- }-- let folderURL = try resolveFolderURL()- let startedAccess = folderURL.startAccessingSecurityScopedResource()- guard startedAccess else {- throw DriveWriterError.accessDenied- }-- defer {- folderURL.stopAccessingSecurityScopedResource()- }-- let targetURL = folderURL.appendingPathComponent(fileName, isDirectory: false)- let data = Data(text.utf8)- try data.write(to: targetURL)- EventLog.append("Wrote \(data.count) bytes to \(targetURL.lastPathComponent)")- return targetURL- }-- private func resolveFolderURL() throws -> URL {- guard let bookmark = UserDefaults.standard.data(forKey: bookmarkKey) else {- throw DriveWriterError.noFolderSelected- }-- var isStale = false- let url = try URL(- resolvingBookmarkData: bookmark,- options: [],- relativeTo: nil,- bookmarkDataIsStale: &isStale- )-- if isStale {- throw DriveWriterError.bookmarkStale- }-- return url- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/EventLog.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/EventLog.swiftdeleted file mode 100644index 5d3fcf3..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/EventLog.swift+++ /dev/null@@ -1,30 +0,0 @@-import Foundation-import OSLog--enum EventLog {- private static let logger = Logger(subsystem: "xyz.inteliwear.iphone.pixiedot", category: "SidePulse")- private static let defaultsKey = "eventLog"- private static let maxEntries = 40-- static func append(_ message: String) {- let timestamp = ISO8601DateFormatter().string(from: Date())- let line = "\(timestamp) \(message)"- logger.info("\(line, privacy: .public)")-- let defaults = UserDefaults.standard- var entries = defaults.stringArray(forKey: defaultsKey) ?? []- entries.append(line)- if entries.count > maxEntries {- entries.removeFirst(entries.count - maxEntries)- }- defaults.set(entries, forKey: defaultsKey)- }-- static func entries() -> [String] {- UserDefaults.standard.stringArray(forKey: defaultsKey) ?? []- }-- static func clear() {- UserDefaults.standard.removeObject(forKey: defaultsKey)- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/FolderPicker.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/FolderPicker.swiftdeleted file mode 100644index 242f91a..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/FolderPicker.swift+++ /dev/null@@ -1,41 +0,0 @@-import SwiftUI-import UniformTypeIdentifiers--struct FolderPicker: UIViewControllerRepresentable {- let onPick: (URL) -> Void- let onCancel: () -> Void-- func makeUIViewController(context: Context) -> UIDocumentPickerViewController {- let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false)- picker.allowsMultipleSelection = false- picker.delegate = context.coordinator- return picker- }-- func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}-- func makeCoordinator() -> Coordinator {- Coordinator(parent: self)- }-- final class Coordinator: NSObject, UIDocumentPickerDelegate {- private let parent: FolderPicker-- init(parent: FolderPicker) {- self.parent = parent- }-- func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {- guard let url = urls.first else {- parent.onCancel()- return- }-- parent.onPick(url)- }-- func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {- parent.onCancel()- }- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Info.plist b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Info.plistdeleted file mode 100644index 8563d77..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Info.plist+++ /dev/null@@ -1,61 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>CFBundleDevelopmentRegion</key>- <string>$(DEVELOPMENT_LANGUAGE)</string>- <key>CFBundleDisplayName</key>- <string>SidePulse</string>- <key>CFBundleExecutable</key>- <string>$(EXECUTABLE_NAME)</string>- <key>CFBundleIdentifier</key>- <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>- <key>CFBundleInfoDictionaryVersion</key>- <string>6.0</string>- <key>CFBundleName</key>- <string>$(PRODUCT_NAME)</string>- <key>CFBundlePackageType</key>- <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>- <key>CFBundleShortVersionString</key>- <string>1.0</string>- <key>CFBundleURLTypes</key>- <array>- <dict>- <key>CFBundleURLName</key>- <string>xyz.inteliwear.iphone.sidepulse.url</string>- <key>CFBundleURLSchemes</key>- <array>- <string>sidepulse</string>- <string>pixiepulse</string>- </array>- </dict>- </array>- <key>CFBundleVersion</key>- <string>1</string>- <key>LSRequiresIPhoneOS</key>- <true/>- <key>LSSupportsOpeningDocumentsInPlace</key>- <true/>- <key>UIApplicationSupportsIndirectInputEvents</key>- <true/>- <key>UIBackgroundModes</key>- <array>- <string>remote-notification</string>- </array>- <key>UILaunchScreen</key>- <dict/>- <key>UISupportedInterfaceOrientations</key>- <array>- <string>UIInterfaceOrientationPortrait</string>- <string>UIInterfaceOrientationLandscapeLeft</string>- <string>UIInterfaceOrientationLandscapeRight</string>- </array>- <key>UISupportedInterfaceOrientations~ipad</key>- <array>- <string>UIInterfaceOrientationPortrait</string>- <string>UIInterfaceOrientationPortraitUpsideDown</string>- <string>UIInterfaceOrientationLandscapeLeft</string>- <string>UIInterfaceOrientationLandscapeRight</string>- </array>-</dict>-</plist>diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriter.entitlements b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriter.entitlementsdeleted file mode 100644index 2cf0210..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriter.entitlements+++ /dev/null@@ -1,8 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>aps-environment</key>- <string>development</string>-</dict>-</plist>diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriterApp.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriterApp.swiftdeleted file mode 100644index 4867e02..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriterApp.swift+++ /dev/null@@ -1,12 +0,0 @@-import SwiftUI--@main-struct SidePulseApp: App {- @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate-- var body: some Scene {- WindowGroup {- ContentView()- }- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PushPayload.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PushPayload.swiftdeleted file mode 100644index 3404ce4..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PushPayload.swift+++ /dev/null@@ -1,301 +0,0 @@-import Foundation--struct LEDPattern: Identifiable, Codable, Hashable {- let name: String- let displayName: String- let detail: String- let ledText: String- let tintHex: String-- var id: String { name }-- var byteCount: Int {- ledText.data(using: .utf8)?.count ?? 0- }-}--enum LEDPatternCatalog {- static let patterns: [LEDPattern] = [- LEDPattern(- name: "off",- displayName: "Off",- detail: "Clear the LEDs",- ledText: "off\n",- tintHex: "#6b7280"- ),- LEDPattern(- name: "green_pulse_2",- displayName: "Two Green Pulses",- detail: "Two quick confirmation pulses",- ledText: "#00ff00 280ms pulse\noff 160ms none\n#00ff00 280ms pulse\noff 320ms none\n",- tintHex: "#20c997"- ),- LEDPattern(- name: "success",- displayName: "Success",- detail: "Soft green success glow",- ledText: "#00ff66 450ms cosine\noff 160ms none\n",- tintHex: "#22c55e"- ),- LEDPattern(- name: "error",- displayName: "Error",- detail: "Red attention blink",- ledText: "#ff1f3d 120ms none\noff 120ms none\nrepeat 3\n",- tintHex: "#ef4444"- ),- LEDPattern(- name: "working",- displayName: "Working",- detail: "Blue activity pulse",- ledText: "#0066ff 900ms pulse\n#00ccff 900ms pulse\nrepeat\n",- tintHex: "#0ea5e9"- ),- LEDPattern(- name: "waiting",- displayName: "Waiting",- detail: "Amber waiting breath",- ledText: "#ffaa00 1.2s pulse\noff 500ms none\nrepeat\n",- tintHex: "#f59e0b"- ),- LEDPattern(- name: "white_breathe",- displayName: "White Breathe",- detail: "Soft neutral breathing",- ledText: "#404040 1.4s pulse\noff 400ms none\nrepeat\n",- tintHex: "#f8fafc"- )- ]-- static func pattern(named name: String?) -> LEDPattern? {- guard let name else {- return nil- }-- let normalized = name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()- return patterns.first { $0.name.lowercased() == normalized }- }-}--struct ReceivedPush: Identifiable, Codable, Hashable {- enum WriteStatus: String, Codable, Hashable {- case received- case wrote- case noFolder- case failed- case unsupportedPattern- }-- var id: UUID = UUID()- var receivedAt: Date = Date()- var source: String- var title: String- var body: String- var patternName: String?- var ledText: String?- var payloadSummary: String- var writeStatus: WriteStatus- var errorMessage: String?-- var ledByteCount: Int {- ledText?.data(using: .utf8)?.count ?? 0- }-}--struct PushPayloadResolution {- let sourceTitle: String- let sourceBody: String- let patternName: String?- let pattern: LEDPattern?- let ledText: String?- let payloadSummary: String-- var resolvedLEDText: String? {- ledText ?? pattern?.ledText- }-- var isUnsupportedPattern: Bool {- patternName != nil && pattern == nil && ledText == nil- }-- var displayTitle: String {- if !sourceTitle.isEmpty {- return sourceTitle- }- if let pattern {- return pattern.displayName- }- if isUnsupportedPattern {- return "Unknown Pattern"- }- if ledText != nil {- return "LEDS.TXT Push"- }- return "Push Received"- }-- var displayBody: String {- if !sourceBody.isEmpty {- return sourceBody- }- if let pattern {- return pattern.detail- }- if let patternName {- return patternName- }- if let ledText {- let byteCount = ledText.data(using: .utf8)?.count ?? 0- return "\(byteCount) bytes"- }- return payloadSummary- }-}--enum PushPayloadResolver {- private static let ledKeys = ["leds", "LEDS.txt", "LEDS.TXT", "text"]-- static func resolve(userInfo: [AnyHashable: Any]) -> PushPayloadResolution {- let payload = normalizedDictionary(userInfo)- let candidates = candidateDictionaries(from: payload)- let ledText = firstString(in: candidates, keys: ledKeys)- let requestedPattern = firstString(in: candidates, keys: ["pattern"])- let pattern = ledText == nil ? LEDPatternCatalog.pattern(named: requestedPattern) : nil- let alert = alertText(from: payload)-- return PushPayloadResolution(- sourceTitle: alert.title,- sourceBody: alert.body,- patternName: requestedPattern,- pattern: pattern,- ledText: ledText,- payloadSummary: summary(from: payload)- )- }-- static func resolve(url: URL) -> PushPayloadResolution? {- guard ["sidepulse", "pixiepulse"].contains(url.scheme) else {- return nil- }-- let command = url.host ?? url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))- guard command == "write" else {- return nil- }-- let components = URLComponents(url: url, resolvingAgainstBaseURL: false)- var payload: [String: Any] = [:]- components?.queryItems?.forEach { item in- payload[item.name] = item.value ?? ""- }-- guard !payload.isEmpty else {- return nil- }-- var userInfo: [AnyHashable: Any] = [:]- payload.forEach { key, value in- userInfo[AnyHashable(key)] = value- }- return resolve(userInfo: userInfo)- }-- private static func candidateDictionaries(from payload: [String: Any]) -> [[String: Any]] {- var dictionaries = [payload]- for key in ["payload", "data"] {- if let nested = payload[key] as? [String: Any] {- dictionaries.append(nested)- }- }- return dictionaries- }-- private static func firstString(in dictionaries: [[String: Any]], keys: [String]) -> String? {- for dictionary in dictionaries {- for key in keys {- if let value = dictionary[key] as? String {- let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)- return trimmed.isEmpty ? value : value- }- }- }- return nil- }-- private static func alertText(from payload: [String: Any]) -> (title: String, body: String) {- let directTitle = payload["title"] as? String ?? ""- let directBody = payload["body"] as? String ?? ""-- guard let aps = payload["aps"] as? [String: Any] else {- return (directTitle, directBody)- }-- if let alert = aps["alert"] as? String {- return (directTitle, directBody.isEmpty ? alert : directBody)- }-- if let alert = aps["alert"] as? [String: Any] {- return (- directTitle.isEmpty ? (alert["title"] as? String ?? "") : directTitle,- directBody.isEmpty ? (alert["body"] as? String ?? "") : directBody- )- }-- return (directTitle, directBody)- }-- private static func summary(from payload: [String: Any]) -> String {- let visiblePayload = payload.filter { key, _ in- key != "aps"- }-- guard !visiblePayload.isEmpty else {- return "APNs notification"- }-- if JSONSerialization.isValidJSONObject(visiblePayload),- let data = try? JSONSerialization.data(withJSONObject: visiblePayload, options: [.sortedKeys]),- let json = String(data: data, encoding: .utf8) {- return truncated(json)- }-- return truncated(visiblePayload.keys.sorted().joined(separator: ", "))- }-- private static func truncated(_ value: String) -> String {- guard value.count > 280 else {- return value- }-- let endIndex = value.index(value.startIndex, offsetBy: 280)- return String(value[..<endIndex]) + "..."- }-- private static func normalizedDictionary(_ input: [AnyHashable: Any]) -> [String: Any] {- var output: [String: Any] = [:]- for (key, value) in input {- output[String(describing: key)] = normalizedValue(value)- }- return output- }-- private static func normalizedValue(_ value: Any) -> Any {- if let dictionary = value as? [AnyHashable: Any] {- return normalizedDictionary(dictionary)- }-- if let dictionary = value as? NSDictionary {- var output: [String: Any] = [:]- dictionary.forEach { key, value in- output[String(describing: key)] = normalizedValue(value)- }- return output- }-- if let array = value as? [Any] {- return array.map { normalizedValue($0) }- }-- return value- }-}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/WriteLEDsIntent.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/WriteLEDsIntent.swiftdeleted file mode 100644index 3ecdcc0..0000000--- a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/WriteLEDsIntent.swift+++ /dev/null@@ -1,41 +0,0 @@-import AppIntents-import Foundation--@available(iOS 16.0, *)-struct WriteLEDsIntent: AppIntent {- static var title: LocalizedStringResource = "Write SidePulse LEDS.TXT"- static var description = IntentDescription("Writes the supplied LED program to LEDS.TXT on the selected USB drive.")- static var openAppWhenRun = false-- @Parameter(title: "LEDS.TXT Text")- var ledsText: String-- init() {}-- init(ledsText: String) {- self.ledsText = ledsText- }-- func perform() async throws -> some IntentResult {- _ = try DriveWriter.shared.write(ledsText)- await MainActor.run {- AppModel.shared.recordWriteSuccess("Shortcut wrote LEDS.TXT")- }- return .result()- }-}--@available(iOS 16.0, *)-struct SidePulseShortcuts: AppShortcutsProvider {- static var appShortcuts: [AppShortcut] {- AppShortcut(- intent: WriteLEDsIntent(),- phrases: [- "Write \(.applicationName) LEDs",- "Send \(.applicationName) LEDs"- ],- shortTitle: "Write LEDs",- systemImageName: "externaldrive"- )- }-}diff --git a/ios/PixiePulseUSBWriter/README.md b/ios/PixiePulseUSBWriter/README.mddeleted file mode 100644index 9a4844f..0000000--- a/ios/PixiePulseUSBWriter/README.md+++ /dev/null@@ -1,192 +0,0 @@-# SidePulse for iOS--SidePulse is a push inbox that can optionally write LED programs to `LEDS.TXT`-on a PulseDot USB drive attached to an iPhone or iPad.--The app supports:--- General-purpose APNs pushes, stored newest-first in the inbox.-- Tiny named-pattern pushes such as `{"pattern":"green_pulse_2"}`.-- Raw LED pushes using `leds`, `LEDS.txt`, `LEDS.TXT`, or `text`.-- Shortcuts or URL actions such as `sidepulse://write?pattern=success`.-- Optional PulseDot folder writes through Files.--The bundle identifier remains `xyz.inteliwear.iphone.pixiedot` for APNs and-provisioning continuity.--## iOS setup--1. Open `PixiePulseUSBWriter.xcodeproj` in Xcode.-2. Select the `PixiePulseUSBWriter` target.-3. Confirm Apple Developer Team `5QJ7W2AQ8H`.-4. Confirm the bundle identifier is `xyz.inteliwear.iphone.pixiedot`.-5. Confirm these capabilities:- - Push Notifications- - Background Modes -> Remote notifications-6. Build and run on a real iPhone or iPad. APNs push tokens do not work on the- simulator.-7. Tap **Get Push Token** and copy the token.-8. Tap **Set Up PulseDot Folder**, then select the PulseDot USB drive folder- containing `LEDS.TXT` in Files.--If no PulseDot folder is configured, pushes still appear in the inbox. The app-does not treat that as a user-facing failure.--## Background pushes--SidePulse handles silent pushes in-`application(_:didReceiveRemoteNotification:fetchCompletionHandler:)`. Silent-delivery is still controlled by iOS: Background App Refresh must be enabled, the-app must not be force-quit, and delivery can be delayed. Visible alert pushes-are also processed when delivered or opened.--For silent/background writes, APNs should use:--```text-apns-push-type: background-apns-priority: 5-apns-topic: xyz.inteliwear.iphone.pixiedot-```--## Payloads--Full LED text wins over pattern names:--```json-{- "aps": {"content-available": 1},- "leds": "#00ff00 280ms pulse\noff 160ms none\n"-}-```--Tiny named-pattern push:--```json-{- "aps": {"content-available": 1},- "pattern": "green_pulse_2"-}-```--Supported pattern names:--```text-off-green_pulse_2-success-error-working-waiting-white_breathe-```--The app also accepts arbitrary `data` or custom payload fields and stores them-as general pushes when no LED text or known pattern is present.--## Fast push server--Create a virtual environment:--```sh-cd ios/PixiePulseUSBWriter/tools-python3 -m venv .venv-source .venv/bin/activate-python -m pip install -r requirements.txt-```--Set APNs credentials and server defaults:--```sh-export APNS_TEAM_ID="5QJ7W2AQ8H"-export APNS_KEY_ID="DV88U59RY7"-export APNS_AUTH_KEY="/Users/pero/Dropbox (Personal)/keys/PixieDotPushKey_DV88U59RY7.p8"-export APNS_BUNDLE_ID="xyz.inteliwear.iphone.pixiedot"-export APNS_ENV="sandbox"-export SIDE_DEVICE_TOKEN="token copied from the app"-export SIDE_SHARED_SECRET="choose-a-local-testing-secret"-```--Run the server:--```sh-python server.py-```--Open `http://127.0.0.1:8787` for the simple sender page, or use curl:--```sh-curl -X POST http://127.0.0.1:8787/v1/push \- -H "Authorization: Bearer $SIDE_SHARED_SECRET" \- -H "content-type: application/json" \- -d '{"pattern":"green_pulse_2"}'-```--Send raw LED text:--```sh-curl -X POST http://127.0.0.1:8787/v1/push \- -H "Authorization: Bearer $SIDE_SHARED_SECRET" \- -H "content-type: application/json" \- -d '{"leds":"#00ff00 280ms pulse\noff 160ms none\n"}'-```--The helper script calls the same endpoint:--```sh-python send_push.py --pattern green_pulse_2-```--## API--`GET /health`--Returns server health.--`GET /v1/patterns`--Returns server-known pattern names and LED text.--`POST /v1/push`--Friendly envelope:--```json-{- "device_token": "optional if SIDE_DEVICE_TOKEN is set",- "pattern": "green_pulse_2",- "leds": "optional raw LEDS.TXT",- "payload": {"optional": "extra custom payload fields"},- "apns": {- "push_type": "background",- "priority": 5,- "collapse_id": "optional",- "expiration": "optional"- }-}-```--`POST /v1/push/raw`--Passes the JSON body through as the exact APNs payload. Provide the device token-with `?device_token=...`, `X-Side-Device-Token`, or `SIDE_DEVICE_TOKEN`.-Optional APNs overrides can be sent as `apns-push-type`, `apns-priority`,-`apns-collapse-id`, `apns-expiration`, or `apns-topic` request headers.--```sh-curl -X POST "http://127.0.0.1:8787/v1/push/raw?device_token=$SIDE_DEVICE_TOKEN" \- -H "Authorization: Bearer $SIDE_SHARED_SECRET" \- -H "content-type: application/json" \- -H "apns-push-type: background" \- -H "apns-priority: 5" \- -d '{"aps":{"content-available":1},"pattern":"success","data":{"source":"curl"}}'-```--## Notes--- The server uses FastAPI, uvicorn, a shared `httpx.AsyncClient(http2=True)`,- connection pooling, and cached APNs JWT refresh.-- `SIDE_*` environment variables are preferred. The server still accepts the old- `PIXIE_*` names for local compatibility.-- Keep LED programs at or below 512 bytes for the PulseDot writer. The DSL is- documented in the repo root at `LEDS_FORMAT.txt`.-- The generated source app icon is kept at `SidePulseIconSource.png`.diff --git a/ios/PixiePulseUSBWriter/SidePulseIconSource.png b/ios/PixiePulseUSBWriter/SidePulseIconSource.pngdeleted file mode 100644index acbb0e7..0000000Binary files a/ios/PixiePulseUSBWriter/SidePulseIconSource.png and /dev/null differdiff --git a/ios/PixiePulseUSBWriter/examples/LEDS.example.txt b/ios/PixiePulseUSBWriter/examples/LEDS.example.txtdeleted file mode 100644index 4ad13f5..0000000--- a/ios/PixiePulseUSBWriter/examples/LEDS.example.txt+++ /dev/null@@ -1,3 +0,0 @@-#404040 1.4s pulse-off 400ms none-repeatdiff --git a/ios/PixiePulseUSBWriter/tools/.gitignore b/ios/PixiePulseUSBWriter/tools/.gitignoredeleted file mode 100644index bf5305e..0000000--- a/ios/PixiePulseUSBWriter/tools/.gitignore+++ /dev/null@@ -1,5 +0,0 @@-.venv/-__pycache__/-*.pyc-*.env-pixiedot.envdiff --git a/ios/PixiePulseUSBWriter/tools/apns_client.py b/ios/PixiePulseUSBWriter/tools/apns_client.pydeleted file mode 100644index 4057cfe..0000000--- a/ios/PixiePulseUSBWriter/tools/apns_client.py+++ /dev/null@@ -1,239 +0,0 @@-from __future__ import annotations--import base64-import json-import os-import time-from dataclasses import dataclass-from pathlib import Path-from typing import Any--import httpx-from cryptography.hazmat.primitives import hashes, serialization-from cryptography.hazmat.primitives.asymmetric import ec, utils---MAX_LEDS_BYTES = 512-APNS_JWT_REFRESH_SECONDS = 50 * 60---class APNsConfigError(RuntimeError):- pass---class LEDPayloadError(ValueError):- pass---@dataclass(frozen=True)-class APNsConfig:- team_id: str- key_id: str- auth_key_path: Path- bundle_id: str- environment: str = "sandbox"-- @classmethod- def from_env(cls) -> "APNsConfig":- missing = [- name- for name in ("APNS_TEAM_ID", "APNS_KEY_ID", "APNS_AUTH_KEY", "APNS_BUNDLE_ID")- if not os.environ.get(name)- ]- if missing:- raise APNsConfigError(f"Missing environment variables: {', '.join(missing)}")-- return cls(- team_id=os.environ["APNS_TEAM_ID"],- key_id=os.environ["APNS_KEY_ID"],- auth_key_path=Path(os.environ["APNS_AUTH_KEY"]).expanduser(),- bundle_id=os.environ["APNS_BUNDLE_ID"],- environment=os.environ.get("APNS_ENV", "sandbox"),- )-- @property- def host(self) -> str:- if self.environment.lower() in {"prod", "production"}:- return "api.push.apple.com"- return "api.sandbox.push.apple.com"---@dataclass(frozen=True)-class APNsResponse:- status_code: int- apns_id: str | None- body: dict[str, Any] | str-- @property- def ok(self) -> bool:- return 200 <= self.status_code < 300---class APNsProviderTokenCache:- def __init__(self, config: APNsConfig) -> None:- self.config = config- self._private_key: ec.EllipticCurvePrivateKey | None = None- self._token: str | None = None- self._refresh_at = 0-- def token(self) -> str:- now = int(time.time())- if self._token and now < self._refresh_at:- return self._token-- private_key = self._load_private_key()- self._token = make_provider_token(self.config, issued_at=now, private_key=private_key)- self._refresh_at = now + APNS_JWT_REFRESH_SECONDS- return self._token-- def _load_private_key(self) -> ec.EllipticCurvePrivateKey:- if self._private_key is not None:- return self._private_key-- private_key = serialization.load_pem_private_key(- self.config.auth_key_path.read_bytes(),- password=None,- )-- if not isinstance(private_key, ec.EllipticCurvePrivateKey):- raise APNsConfigError("APNs auth key must be an EC private key")-- self._private_key = private_key- return private_key---class APNsClient:- def __init__(- self,- config: APNsConfig,- *,- client: httpx.AsyncClient | None = None,- timeout: float = 10.0,- ) -> None:- self.config = config- self._token_cache = APNsProviderTokenCache(config)- self._owns_client = client is None- self._client = client or httpx.AsyncClient(- http2=True,- timeout=httpx.Timeout(timeout),- limits=httpx.Limits(max_connections=1000, max_keepalive_connections=250),- )-- async def __aenter__(self) -> "APNsClient":- return self-- async def __aexit__(self, *_: object) -> None:- await self.aclose()-- async def aclose(self) -> None:- if self._owns_client:- await self._client.aclose()-- async def send(- self,- device_token: str,- payload: dict[str, Any],- *,- headers: dict[str, str] | None = None,- ) -> APNsResponse:- token = device_token.strip()- if not token:- raise ValueError("Missing device token")-- request_headers = {- "authorization": f"bearer {self._token_cache.token()}",- "apns-topic": self.config.bundle_id,- "apns-push-type": "background",- "apns-priority": "5",- }- if headers:- request_headers.update({key: str(value) for key, value in headers.items() if value is not None})-- url = f"https://{self.config.host}/3/device/{token}"- response = await self._client.post(url, headers=request_headers, json=payload)-- try:- body: dict[str, Any] | str = response.json()- except json.JSONDecodeError:- body = response.text-- return APNsResponse(- status_code=response.status_code,- apns_id=response.headers.get("apns-id"),- body=body,- )---def validate_leds_text(leds_text: str) -> None:- if not leds_text.strip():- raise LEDPayloadError("LEDS.TXT payload is empty")-- byte_count = len(leds_text.encode("utf-8"))- if byte_count > MAX_LEDS_BYTES:- raise LEDPayloadError(f"LEDS.TXT payload is {byte_count} bytes; max is {MAX_LEDS_BYTES}")---def make_provider_token(- config: APNsConfig,- issued_at: int | None = None,- *,- private_key: ec.EllipticCurvePrivateKey | None = None,-) -> str:- issued_at = issued_at or int(time.time())- private_key = private_key or serialization.load_pem_private_key(- config.auth_key_path.read_bytes(),- password=None,- )-- if not isinstance(private_key, ec.EllipticCurvePrivateKey):- raise APNsConfigError("APNs auth key must be an EC private key")-- header = {"alg": "ES256", "kid": config.key_id}- claims = {"iss": config.team_id, "iat": issued_at}- signing_input = b".".join(- [- _b64url_json(header),- _b64url_json(claims),- ]- )- der_signature = private_key.sign(signing_input, ec.ECDSA(hashes.SHA256()))- r_value, s_value = utils.decode_dss_signature(der_signature)- raw_signature = r_value.to_bytes(32, "big") + s_value.to_bytes(32, "big")- return signing_input.decode("ascii") + "." + _b64url(raw_signature).decode("ascii")---async def send_leds_push(- config: APNsConfig,- device_token: str,- leds_text: str,- *,- alert: str | None = None,-) -> APNsResponse:- validate_leds_text(leds_text)-- push_type = "alert" if alert else "background"- priority = "10" if alert else "5"- aps: dict[str, Any] = {"content-available": 1}- if alert:- aps["alert"] = {"title": "SidePulse", "body": alert}- aps["sound"] = "default"-- payload = {- "aps": aps,- "leds": leds_text,- }- headers = {- "apns-push-type": push_type,- "apns-priority": priority,- }-- async with APNsClient(config) as client:- return await client.send(device_token, payload, headers=headers)---def _b64url_json(value: dict[str, Any]) -> bytes:- return _b64url(json.dumps(value, separators=(",", ":")).encode("utf-8"))---def _b64url(value: bytes) -> bytes:- return base64.urlsafe_b64encode(value).rstrip(b"=")diff --git a/ios/PixiePulseUSBWriter/tools/patterns.py b/ios/PixiePulseUSBWriter/tools/patterns.pydeleted file mode 100644index 41e05b1..0000000--- a/ios/PixiePulseUSBWriter/tools/patterns.py+++ /dev/null@@ -1,70 +0,0 @@-from __future__ import annotations--from dataclasses import dataclass, asdict---@dataclass(frozen=True)-class LEDPattern:- name: str- display_name: str- detail: str- leds: str-- @property- def byte_count(self) -> int:- return len(self.leds.encode("utf-8"))-- def as_public_dict(self) -> dict[str, object]:- payload = asdict(self)- payload["byte_count"] = self.byte_count- return payload---PATTERNS: dict[str, LEDPattern] = {- "off": LEDPattern(- name="off",- display_name="Off",- detail="Clear the LEDs",- leds="off\n",- ),- "green_pulse_2": LEDPattern(- name="green_pulse_2",- display_name="Two Green Pulses",- detail="Two quick confirmation pulses",- leds="#00ff00 280ms pulse\noff 160ms none\n#00ff00 280ms pulse\noff 320ms none\n",- ),- "success": LEDPattern(- name="success",- display_name="Success",- detail="Soft green success glow",- leds="#00ff66 450ms cosine\noff 160ms none\n",- ),- "error": LEDPattern(- name="error",- display_name="Error",- detail="Red attention blink",- leds="#ff1f3d 120ms none\noff 120ms none\nrepeat 3\n",- ),- "working": LEDPattern(- name="working",- display_name="Working",- detail="Blue activity pulse",- leds="#0066ff 900ms pulse\n#00ccff 900ms pulse\nrepeat\n",- ),- "waiting": LEDPattern(- name="waiting",- display_name="Waiting",- detail="Amber waiting breath",- leds="#ffaa00 1.2s pulse\noff 500ms none\nrepeat\n",- ),- "white_breathe": LEDPattern(- name="white_breathe",- display_name="White Breathe",- detail="Soft neutral breathing",- leds="#404040 1.4s pulse\noff 400ms none\nrepeat\n",- ),-}---def pattern_names() -> list[str]:- return list(PATTERNS)diff --git a/ios/PixiePulseUSBWriter/tools/pixiedot.env.example b/ios/PixiePulseUSBWriter/tools/pixiedot.env.exampledeleted file mode 100644index 549c770..0000000--- a/ios/PixiePulseUSBWriter/tools/pixiedot.env.example+++ /dev/null@@ -1,9 +0,0 @@-export APNS_TEAM_ID="5QJ7W2AQ8H"-export APNS_KEY_ID="DV88U59RY7"-export APNS_AUTH_KEY="/Users/pero/Dropbox (Personal)/keys/PixieDotPushKey_DV88U59RY7.p8"-export APNS_BUNDLE_ID="xyz.inteliwear.iphone.pixiedot"-export APNS_ENV="sandbox"-export SIDE_DEVICE_TOKEN="paste-device-token-from-app"-export SIDE_SHARED_SECRET="choose-a-local-testing-secret"-export SIDE_SERVER_HOST="127.0.0.1"-export SIDE_SERVER_PORT="8787"diff --git a/ios/PixiePulseUSBWriter/tools/requirements.txt b/ios/PixiePulseUSBWriter/tools/requirements.txtdeleted file mode 100644index ba1e45a..0000000--- a/ios/PixiePulseUSBWriter/tools/requirements.txt+++ /dev/null@@ -1,4 +0,0 @@-cryptography>=42.0-fastapi>=0.115-httpx[http2]>=0.27-uvicorn[standard]>=0.30diff --git a/ios/PixiePulseUSBWriter/tools/send_push.py b/ios/PixiePulseUSBWriter/tools/send_push.pydeleted file mode 100644index 17def73..0000000--- a/ios/PixiePulseUSBWriter/tools/send_push.py+++ /dev/null@@ -1,70 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--import argparse-import json-import os-import sys-from pathlib import Path-from urllib.error import HTTPError, URLError-from urllib.request import Request, urlopen---def main() -> int:- parser = argparse.ArgumentParser(description="Send a SidePulse push through the local push server.")- parser.add_argument("--server", default=os.environ.get("SIDE_SERVER_URL", "http://127.0.0.1:8787"))- parser.add_argument("--secret", default=os.environ.get("SIDE_SHARED_SECRET"))- parser.add_argument("--device-token", default=os.environ.get("SIDE_DEVICE_TOKEN") or os.environ.get("PIXIE_DEVICE_TOKEN"))- parser.add_argument("--pattern", default="green_pulse_2")- parser.add_argument("--leds", help="Inline LEDS.TXT text. If set, this wins over pattern in the app.")- parser.add_argument("--file", type=Path, help="Path to a LEDS.TXT file.")- parser.add_argument("--payload", help="Extra JSON object merged into the APNs payload.")- parser.add_argument("--alert", help="Optional visible notification body.")- args = parser.parse_args()-- if args.leds and args.file:- parser.error("Use either --leds or --file, not both")-- payload: dict[str, object] = {}- if args.payload:- loaded = json.loads(args.payload)- if not isinstance(loaded, dict):- parser.error("--payload must be a JSON object")- payload = loaded-- body: dict[str, object] = {- "pattern": args.pattern,- }- if args.device_token:- body["device_token"] = args.device_token- if args.alert:- body["alert"] = args.alert- if payload:- body["payload"] = payload-- if args.leds is not None:- body["leds"] = args.leds- elif args.file:- body["leds"] = args.file.read_text(encoding="utf-8")-- url = args.server.rstrip("/") + "/v1/push"- headers = {"content-type": "application/json"}- if args.secret:- headers["authorization"] = f"Bearer {args.secret}"-- request = Request(url, data=json.dumps(body).encode("utf-8"), headers=headers, method="POST")-- try:- with urlopen(request, timeout=20) as response:- print(response.read().decode("utf-8"))- return 0- except HTTPError as exc:- print(exc.read().decode("utf-8"), file=sys.stderr)- return 1- except URLError as exc:- print(f"error: {exc.reason}", file=sys.stderr)- return 2---if __name__ == "__main__":- raise SystemExit(main())diff --git a/ios/PixiePulseUSBWriter/tools/server.py b/ios/PixiePulseUSBWriter/tools/server.pydeleted file mode 100644index d314b4a..0000000--- a/ios/PixiePulseUSBWriter/tools/server.py+++ /dev/null@@ -1,382 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--import copy-import html-import json-import os-from typing import Any-from urllib.parse import parse_qs--import uvicorn-from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request-from fastapi.responses import HTMLResponse--from apns_client import APNsClient, APNsConfig, APNsConfigError, APNsResponse-from patterns import PATTERNS, pattern_names---DEFAULT_PORT = 8787-APNS_HEADER_ALIASES = {- "push_type": "apns-push-type",- "priority": "apns-priority",- "collapse_id": "apns-collapse-id",- "expiration": "apns-expiration",- "topic": "apns-topic",-}-RESERVED_ENVELOPE_KEYS = {- "device_token",- "pattern",- "leds",- "LEDS.txt",- "LEDS.TXT",- "text",- "payload",- "apns",- "alert",-}---app = FastAPI(title="SidePulse Push Server", version="1.0")---async def require_bearer_auth(authorization: str | None = Header(default=None)) -> None:- shared_secret = shared_secret_from_env()- if not shared_secret:- return-- if authorization == f"Bearer {shared_secret}":- return-- raise HTTPException(status_code=401, detail="Unauthorized")--[email protected]_event("shutdown")-async def shutdown() -> None:- client = getattr(app.state, "apns_client", None)- if client is not None and hasattr(client, "aclose"):- await client.aclose()--[email protected]("/health")-async def health() -> dict[str, Any]:- return {"ok": True, "service": "sidepulse-push"}--[email protected]("/v1/patterns")-async def patterns() -> dict[str, Any]:- return {- "patterns": [PATTERNS[name].as_public_dict() for name in pattern_names()],- }--[email protected]("/", response_class=HTMLResponse)-async def index() -> str:- return index_html()--[email protected]("/v1/push")-async def push(- request: Request,- _: None = Depends(require_bearer_auth),-) -> dict[str, Any]:- envelope = await read_json_object(request)- device_token = resolve_device_token(envelope.get("device_token"))- if not device_token:- raise HTTPException(status_code=400, detail="Missing device token")-- payload = build_friendly_payload(envelope)- headers = apns_headers_from_options(envelope.get("apns"), payload)- response = await send_apns(device_token, payload, headers)-- pattern = envelope.get("pattern")- return response_payload(- response,- extra={- "pattern": pattern if isinstance(pattern, str) else None,- "known_pattern": isinstance(pattern, str) and pattern in PATTERNS,- },- )--[email protected]("/v1/push/raw")-async def push_raw(- request: Request,- device_token: str | None = Query(default=None),- _: None = Depends(require_bearer_auth),-) -> dict[str, Any]:- payload = await read_json_object(request)- token = resolve_device_token(device_token or request.headers.get("x-side-device-token"))- if not token:- raise HTTPException(status_code=400, detail="Missing device token")-- headers = apns_headers_from_request(request, payload)- response = await send_apns(token, payload, headers)- return response_payload(response)--[email protected]("/push")-async def legacy_push(- request: Request,- device_token: str | None = Query(default=None),- key: str | None = Query(default=None),-) -> dict[str, Any]:- require_legacy_auth(key, request.headers.get("authorization"))- envelope = await read_legacy_body(request)- if device_token:- envelope["device_token"] = device_token- if "key" in envelope:- envelope.pop("key", None)-- token = resolve_device_token(envelope.get("device_token"))- if not token:- raise HTTPException(status_code=400, detail="Missing device token")-- payload = build_friendly_payload(envelope)- headers = apns_headers_from_options(envelope.get("apns"), payload)- response = await send_apns(token, payload, headers)- return response_payload(response, extra={"legacy": True})---def require_legacy_auth(key: str | None, authorization: str | None) -> None:- shared_secret = shared_secret_from_env()- if not shared_secret:- return-- if authorization == f"Bearer {shared_secret}" or key == shared_secret:- return-- raise HTTPException(status_code=401, detail="Unauthorized")---def shared_secret_from_env() -> str:- return os.environ.get("SIDE_SHARED_SECRET") or os.environ.get("PIXIE_SHARED_SECRET", "")---def resolve_device_token(value: Any) -> str | None:- if isinstance(value, str) and value.strip():- return value.strip()- return os.environ.get("SIDE_DEVICE_TOKEN") or os.environ.get("PIXIE_DEVICE_TOKEN")---async def read_json_object(request: Request) -> dict[str, Any]:- try:- loaded = await request.json()- except json.JSONDecodeError as exc:- raise HTTPException(status_code=400, detail=f"Invalid JSON: {exc}") from exc-- if not isinstance(loaded, dict):- raise HTTPException(status_code=400, detail="JSON body must be an object")- return loaded---async def read_legacy_body(request: Request) -> dict[str, Any]:- content_type = request.headers.get("content-type", "")- if "application/json" in content_type:- return await read_json_object(request)-- body = await request.body()- if not body:- return {}-- if "application/x-www-form-urlencoded" in content_type:- parsed = parse_qs(body.decode("utf-8"), keep_blank_values=True)- return {key: values[-1] for key, values in parsed.items()}-- return {"leds": body.decode("utf-8")}---def build_friendly_payload(envelope: dict[str, Any]) -> dict[str, Any]:- payload = envelope.get("payload")- if payload is None:- payload = {}- if not isinstance(payload, dict):- raise HTTPException(status_code=400, detail="payload must be an object")-- apns_payload = copy.deepcopy(payload)- for key, value in envelope.items():- if key not in RESERVED_ENVELOPE_KEYS:- apns_payload.setdefault(key, value)-- aps = apns_payload.get("aps")- if aps is None:- aps = {}- if not isinstance(aps, dict):- raise HTTPException(status_code=400, detail="payload.aps must be an object")-- alert = envelope.get("alert")- if isinstance(alert, str) and alert:- aps["alert"] = {"title": "SidePulse", "body": alert}- aps["sound"] = "default"- else:- aps.setdefault("content-available", 1)-- apns_payload["aps"] = aps-- led_text = first_led_text(envelope)- if led_text is not None:- apns_payload["leds"] = led_text-- pattern = envelope.get("pattern")- if isinstance(pattern, str) and pattern:- apns_payload["pattern"] = pattern-- data = envelope.get("data")- if isinstance(data, dict):- apns_payload.setdefault("data", data)-- return apns_payload---def first_led_text(envelope: dict[str, Any]) -> str | None:- for key in ("leds", "LEDS.txt", "LEDS.TXT", "text"):- value = envelope.get(key)- if isinstance(value, str):- return value- return None---def apns_headers_from_options(options: Any, payload: dict[str, Any]) -> dict[str, str]:- if options is None:- options = {}- if not isinstance(options, dict):- raise HTTPException(status_code=400, detail="apns must be an object")-- headers: dict[str, str] = {}- for key, value in options.items():- if value is None:- continue- header_name = APNS_HEADER_ALIASES.get(key, key)- if header_name.startswith("apns-"):- headers[header_name] = str(value)-- headers.setdefault("apns-push-type", default_push_type(payload))- headers.setdefault("apns-priority", "10" if headers["apns-push-type"] == "alert" else "5")- return headers---def apns_headers_from_request(request: Request, payload: dict[str, Any]) -> dict[str, str]:- headers: dict[str, str] = {}- for header_name in ("apns-push-type", "apns-priority", "apns-collapse-id", "apns-expiration", "apns-topic"):- value = request.headers.get(header_name) or request.headers.get("x-" + header_name)- if value:- headers[header_name] = value-- for option_name, header_name in APNS_HEADER_ALIASES.items():- value = request.query_params.get(option_name) or request.query_params.get(header_name)- if value:- headers[header_name] = value-- headers.setdefault("apns-push-type", default_push_type(payload))- headers.setdefault("apns-priority", "10" if headers["apns-push-type"] == "alert" else "5")- return headers---def default_push_type(payload: dict[str, Any]) -> str:- aps = payload.get("aps")- if isinstance(aps, dict) and "alert" in aps:- return "alert"- return "background"---async def send_apns(device_token: str, payload: dict[str, Any], headers: dict[str, str]) -> APNsResponse:- client = await get_apns_client()- try:- return await client.send(device_token, payload, headers=headers)- except (APNsConfigError, OSError, ValueError) as exc:- raise HTTPException(status_code=400, detail=str(exc)) from exc---async def get_apns_client() -> APNsClient:- client = getattr(app.state, "apns_client", None)- if client is not None:- return client-- client = APNsClient(APNsConfig.from_env())- app.state.apns_client = client- return client---def response_payload(response: APNsResponse, *, extra: dict[str, Any] | None = None) -> dict[str, Any]:- payload: dict[str, Any] = {- "ok": response.ok,- "status_code": response.status_code,- "apns_id": response.apns_id,- "response": response.body,- }- if extra:- payload.update(extra)-- if not response.ok:- raise HTTPException(status_code=502, detail=payload)-- return payload---def index_html() -> str:- default_token = html.escape(os.environ.get("SIDE_DEVICE_TOKEN") or os.environ.get("PIXIE_DEVICE_TOKEN", ""))- default_secret = html.escape(shared_secret_from_env())- options = "\n".join(- f'<option value="{html.escape(name)}">{html.escape(name)}</option>' for name in pattern_names()- )- return f"""<!doctype html>-<html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">- <title>SidePulse Push Server</title>- <style>- body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; margin: 2rem; max-width: 760px; color: #111827; }}- label {{ display: block; font-weight: 650; margin-top: 1rem; }}- input, select, textarea {{ box-sizing: border-box; border: 1px solid #cbd5e1; border-radius: 6px; font: inherit; padding: 0.55rem; width: 100%; }}- textarea {{ min-height: 150px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }}- button {{ background: #111827; border: 0; border-radius: 6px; color: white; font: inherit; font-weight: 700; margin-top: 1rem; padding: 0.65rem 0.9rem; }}- pre {{ background: #f1f5f9; border-radius: 6px; overflow: auto; padding: 0.8rem; }}- </style>-</head>-<body>- <h1>SidePulse Push Server</h1>- <label>Device token</label>- <input id="deviceToken" value="{default_token}" autocomplete="off">- <label>Bearer secret</label>- <input id="secret" value="{default_secret}" autocomplete="off">- <label>Pattern</label>- <select id="pattern">{options}</select>- <label>Optional raw LEDS.TXT</label>- <textarea id="leds" placeholder="#00ff00 250ms pulse off 150ms none"></textarea>- <button id="send">Send Push</button>- <pre id="result">Ready</pre>- <script>- document.getElementById("send").addEventListener("click", async () => {{- const body = {{- device_token: document.getElementById("deviceToken").value,- pattern: document.getElementById("pattern").value,- }};- const leds = document.getElementById("leds").value;- if (leds.trim()) body.leds = leds;- const secret = document.getElementById("secret").value;- const response = await fetch("/v1/push", {{- method: "POST",- headers: {{- "content-type": "application/json",- ...(secret ? {{ "authorization": "Bearer " + secret }} : {{}})- }},- body: JSON.stringify(body)- }});- document.getElementById("result").textContent = JSON.stringify(await response.json(), null, 2);- }});- </script>-</body>-</html>"""---def main() -> int:- host = os.environ.get("SIDE_SERVER_HOST") or os.environ.get("PIXIE_SERVER_HOST", "127.0.0.1")- port = int(os.environ.get("SIDE_SERVER_PORT") or os.environ.get("PIXIE_SERVER_PORT", str(DEFAULT_PORT)))- print(f"Serving SidePulse push server at http://{host}:{port}")- uvicorn.run("server:app", host=host, port=port, log_level=os.environ.get("SIDE_LOG_LEVEL", "info"))- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/ios/PixiePulseUSBWriter/tools/tests/test_server.py b/ios/PixiePulseUSBWriter/tools/tests/test_server.pydeleted file mode 100644index 8f58e3e..0000000--- a/ios/PixiePulseUSBWriter/tools/tests/test_server.py+++ /dev/null@@ -1,175 +0,0 @@-from __future__ import annotations--import asyncio-import copy-import os-import sys-import unittest-from pathlib import Path-from unittest.mock import patch--import httpx-from fastapi.testclient import TestClient--TOOLS_DIR = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(TOOLS_DIR))--from apns_client import APNsResponse # noqa: E402-from server import app # noqa: E402---class FakeAPNsClient:- def __init__(self) -> None:- self.calls: list[dict[str, object]] = []-- async def send(- self,- device_token: str,- payload: dict[str, object],- *,- headers: dict[str, str] | None = None,- ) -> APNsResponse:- await asyncio.sleep(0)- self.calls.append(- {- "device_token": device_token,- "payload": copy.deepcopy(payload),- "headers": dict(headers or {}),- }- )- return APNsResponse(status_code=200, apns_id="test-apns-id", body={"sent": True})-- async def aclose(self) -> None:- pass---class ServerTestCase(unittest.TestCase):- def setUp(self) -> None:- self.fake = FakeAPNsClient()- app.state.apns_client = self.fake- self.env = patch.dict(- os.environ,- {- "SIDE_SHARED_SECRET": "secret",- "SIDE_DEVICE_TOKEN": "env-device-token",- },- clear=False,- )- self.env.start()-- def tearDown(self) -> None:- self.env.stop()- if hasattr(app.state, "apns_client"):- delattr(app.state, "apns_client")-- def test_requires_bearer_auth(self) -> None:- with TestClient(app) as client:- response = client.post("/v1/push", json={"pattern": "green_pulse_2"})-- self.assertEqual(response.status_code, 401)- self.assertEqual(self.fake.calls, [])-- def test_friendly_pattern_envelope(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"pattern": "green_pulse_2"},- )-- self.assertEqual(response.status_code, 200)- self.assertTrue(response.json()["known_pattern"])- self.assertEqual(len(self.fake.calls), 1)- call = self.fake.calls[0]- self.assertEqual(call["device_token"], "env-device-token")- self.assertEqual(call["payload"]["pattern"], "green_pulse_2")- self.assertEqual(call["payload"]["aps"], {"content-available": 1})- self.assertEqual(call["headers"]["apns-push-type"], "background")- self.assertEqual(call["headers"]["apns-priority"], "5")-- def test_apns_header_mapping(self) -> None:- with TestClient(app) as client:- response = client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={- "device_token": "explicit-token",- "pattern": "success",- "apns": {- "push_type": "alert",- "priority": 10,- "collapse_id": "pulse-status",- "expiration": "0",- },- },- )-- self.assertEqual(response.status_code, 200)- call = self.fake.calls[0]- self.assertEqual(call["device_token"], "explicit-token")- self.assertEqual(call["headers"]["apns-push-type"], "alert")- self.assertEqual(call["headers"]["apns-priority"], "10")- self.assertEqual(call["headers"]["apns-collapse-id"], "pulse-status")- self.assertEqual(call["headers"]["apns-expiration"], "0")-- def test_raw_payload_passthrough(self) -> None:- raw_payload = {- "aps": {"content-available": 1},- "custom": {"nested": [1, 2, 3]},- "pattern": "working",- }-- with TestClient(app) as client:- response = client.post(- "/v1/push/raw?device_token=query-token",- headers={- "authorization": "Bearer secret",- "x-apns-push-type": "background",- "x-apns-priority": "5",- },- json=raw_payload,- )-- self.assertEqual(response.status_code, 200)- call = self.fake.calls[0]- self.assertEqual(call["device_token"], "query-token")- self.assertEqual(call["payload"], raw_payload)- self.assertEqual(call["headers"]["apns-push-type"], "background")- self.assertEqual(call["headers"]["apns-priority"], "5")---class ConcurrentServerTestCase(unittest.IsolatedAsyncioTestCase):- async def asyncSetUp(self) -> None:- self.fake = FakeAPNsClient()- app.state.apns_client = self.fake- self.env = patch.dict(- os.environ,- {- "SIDE_SHARED_SECRET": "secret",- "SIDE_DEVICE_TOKEN": "env-device-token",- },- clear=False,- )- self.env.start()-- async def asyncTearDown(self) -> None:- self.env.stop()- if hasattr(app.state, "apns_client"):- delattr(app.state, "apns_client")-- async def test_mocked_concurrent_sends(self) -> None:- transport = httpx.ASGITransport(app=app)- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:- responses = await asyncio.gather(- *[- client.post(- "/v1/push",- headers={"authorization": "Bearer secret"},- json={"pattern": "green_pulse_2"},- )- for _ in range(40)- ]- )-- self.assertTrue(all(response.status_code == 200 for response in responses))- self.assertEqual(len(self.fake.calls), 40)diff --git a/pyproject.toml b/pyproject.tomlindex 806b05c..082c1a3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -3,23 +3,28 @@ requires = ["setuptools>=68"]build-backend = "setuptools.build_meta"[project]-name = "sidepulse-agent-monitor"+name = "sidepulse"version = "0.1.0"-description = "Provider-neutral agent status collection for Codex and Claude hooks."+description = "Command-line and macOS tools for SidePulse Pro and SidePulse Dot."readme = "README.md"requires-python = ">=3.10"dependencies = []+[project.urls]+Homepage = "https://sidepulse.io"+[project.optional-dependencies]-status-bar = ["pyobjc-framework-Cocoa>=10"]+status-bar = ["pyobjc-framework-Cocoa>=10", "pyobjc-framework-JavaScriptCore>=10"]+reply-classifier = ["mlx-lm>=0.24,<1"][project.scripts]-sidepulse = "agent_monitor.cli:sidepulse_main"-agent-monitor = "agent_monitor.cli:main"-agent-status-bar = "agent_monitor.status_bar:main"+sidepulse = "sidepulse.cli:sidepulse_main"+agent-monitor = "sidepulse.cli:main"+agent-status-bar = "sidepulse.status_bar:main"+sidepulse-reply = "sidepulse.reply_classifier:main"[tool.setuptools.packages.find]where = ["src"][tool.setuptools.package-data]-"agent_monitor.resources" = ["sd_eject_guard.c"]+"sidepulse.resources" = ["sd_eject_guard.c", "sdled.wasm"]diff --git a/src/agent_monitor/__init__.py b/src/agent_monitor/__init__.pydeleted file mode 100644index fa63c1e..0000000--- a/src/agent_monitor/__init__.py+++ /dev/null@@ -1,67 +0,0 @@-"""Provider-neutral AI agent status monitoring."""--from .battery import (- BatteryLedController,- BatterySnapshot,- program_for_battery,- read_battery_snapshot,-)-from .collector import AgentMonitor, LiveAgentMonitor, MonitorSnapshot, SourceSpec-from .ipc import (- HookEventServer,- default_event_socket_path,- default_latest_state_path,- send_hook_event,-)-from .led_status import (- AgentLedController,- LedDisplayState,- display_state_for_mode,- 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__ = [- "AgentLedController",- "AgentMode",- "AgentStatus",- "AggregateStatus",- "BatteryLedController",- "BatterySnapshot",- "AgentMonitor",- "LiveAgentMonitor",- "HookEvent",- "HookEventServer",- "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",-]--__version__ = "0.1.0"diff --git a/src/agent_monitor/__main__.py b/src/agent_monitor/__main__.pydeleted file mode 100644index bfdcd0c..0000000--- a/src/agent_monitor/__main__.py+++ /dev/null@@ -1,4 +0,0 @@-from .cli import main--if __name__ == "__main__":- raise SystemExit(main())diff --git a/src/agent_monitor/battery.py b/src/agent_monitor/battery.pydeleted file mode 100644index 6c822bd..0000000--- a/src/agent_monitor/battery.py+++ /dev/null@@ -1,679 +0,0 @@-from __future__ import annotations--import json-import math-import plistlib-import re-import subprocess-import time-from dataclasses import dataclass-from functools import lru_cache-from pathlib import Path-from typing import Any, Callable--from .device_writer import (- DEFAULT_FILE_NAME,- DeviceWriteError,- resolve_target_path,- write_led_program,-)-from .led_status import led_count_for_target-from .led_status import apply_brightness, normalize_brightness---BATTERY_LOW_RED = "#FF2600"-BATTERY_MID_AMBER = "#FFB000"-BATTERY_HIGH_GREEN = "#00FF66"-BATTERY_CHARGING_MINT = "#80FFC8"-BATTERY_OFF = "#000000"-DEFAULT_POWER_CHANGE_PREVIEW_SECONDS = 7.0---@dataclass(frozen=True)-class PDProfile:- voltage: float- current: float-- @property- def watts(self) -> float:- return self.voltage * self.current-- def to_dict(self) -> dict[str, float]:- return {- "voltage": self.voltage,- "current": self.current,- "watts": self.watts,- }---@dataclass(frozen=True)-class BatterySnapshot:- percent: int = 0- is_charging: bool = False- is_charged: bool = False- is_plugged: bool = False- battery_present: bool = True- voltage: float = 0.0- amperage: float = 0.0- battery_watts: float = 0.0- time_to_full: int = -1- time_to_empty: int = -1- cycle_count: int = -1- temperature_c: float | None = None- design_capacity_mah: int = -1- max_capacity_mah: int = -1- current_capacity_mah: int = -1- health_percent: int = -1- condition: str = ""- adapter_connected: bool = False- adapter_watts: int = -1- adapter_voltage: float = 0.0- adapter_current: float = 0.0- adapter_name: str = ""- adapter_manufacturer: str = ""- adapter_model: str = ""- adapter_serial: str = ""- adapter_family: str = ""- pd_profiles: tuple[PDProfile, ...] = ()- full_charge_watts: float = 100.0-- @property- def adapter_power(self) -> float:- if self.adapter_watts > 0:- return float(self.adapter_watts)- negotiated = self.adapter_voltage * self.adapter_current- if negotiated > 0:- return negotiated- if self.pd_profiles:- return max(profile.watts for profile in self.pd_profiles)- return 0.0-- @property- def battery_power_magnitude(self) -> float:- return abs(self.battery_watts)-- def charge_speed_ratio(self, full_charge_watts: float | None = None) -> float:- baseline = full_charge_watts or self.full_charge_watts- if baseline <= 0:- return 0.0- return clamp(self.adapter_power / baseline)-- def to_dict(self) -> dict[str, Any]:- return {- "percent": self.percent,- "is_charging": self.is_charging,- "is_charged": self.is_charged,- "is_plugged": self.is_plugged,- "battery_present": self.battery_present,- "voltage": self.voltage,- "amperage": self.amperage,- "battery_watts": self.battery_watts,- "time_to_full": self.time_to_full,- "time_to_empty": self.time_to_empty,- "cycle_count": self.cycle_count,- "temperature_c": self.temperature_c,- "design_capacity_mah": self.design_capacity_mah,- "max_capacity_mah": self.max_capacity_mah,- "current_capacity_mah": self.current_capacity_mah,- "health_percent": self.health_percent,- "condition": self.condition,- "adapter_connected": self.adapter_connected,- "adapter_watts": self.adapter_watts,- "adapter_voltage": self.adapter_voltage,- "adapter_current": self.adapter_current,- "adapter_power": self.adapter_power,- "adapter_name": self.adapter_name,- "adapter_manufacturer": self.adapter_manufacturer,- "adapter_model": self.adapter_model,- "adapter_serial": self.adapter_serial,- "adapter_family": self.adapter_family,- "pd_profiles": [profile.to_dict() for profile in self.pd_profiles],- "full_charge_watts": self.full_charge_watts,- "charge_speed_ratio": self.charge_speed_ratio(),- }---@dataclass(frozen=True)-class BatteryLedWrite:- target: Path | None- program: str- changed: bool- error: str | None = None-- @property- def label(self) -> str:- return "Battery"---CommandRunner = Callable[..., subprocess.CompletedProcess]---def read_battery_snapshot(- *,- full_charge_watts: float | None = None,- runner: CommandRunner = subprocess.run,-) -> BatterySnapshot:- result = runner(- ["ioreg", "-r", "-n", "AppleSmartBattery", "-a"],- check=True,- capture_output=True,- )- data = result.stdout- if isinstance(data, str):- data = data.encode("utf-8")- snapshot = parse_ioreg_battery_plist(data)- return snapshot_with_full_charge_watts(snapshot, full_charge_watts)---def parse_ioreg_battery_plist(data: bytes | str) -> BatterySnapshot:- if isinstance(data, str):- data = data.encode("utf-8")- parsed = plistlib.loads(data)- if not isinstance(parsed, list) or not parsed:- return BatterySnapshot(full_charge_watts=default_full_charge_watts())- props = parsed[0]- if not isinstance(props, dict):- return BatterySnapshot(full_charge_watts=default_full_charge_watts())- return snapshot_from_ioreg_props(props)---def snapshot_from_ioreg_props(props: dict[str, Any]) -> BatterySnapshot:- voltage = int_value(props.get("Voltage")) / 1000.0- amperage_ma = int_value(props.get("Amperage"))- if amperage_ma == 0:- amperage_ma = int_value(props.get("InstantAmperage"))- amperage = amperage_ma / 1000.0-- raw_max = int_value(props.get("AppleRawMaxCapacity"), default=-1)- raw_current = int_value(props.get("AppleRawCurrentCapacity"), default=-1)- design = int_value(props.get("DesignCapacity"), default=-1)- max_capacity = raw_max if raw_max > 0 else int_value(props.get("MaxCapacity"), default=-1)- current_capacity = (- raw_current if raw_current >= 0 else int_value(props.get("CurrentCapacity"), default=-1)- )- health_percent = -1- if raw_max > 0 and design > 0:- health_percent = round(raw_max / design * 100)-- adapter_details = props.get("AdapterDetails")- adapter = parse_adapter_details(adapter_details if isinstance(adapter_details, dict) else {})- percent = int_value(props.get("CurrentCapacity"), default=0)- if percent < 0 or percent > 100:- percent = int_value(props.get("StateOfCharge"), default=0)-- condition = ""- permanent_failure = int_value(props.get("PermanentFailureStatus"), default=0)- if permanent_failure:- condition = "Service Recommended"- elif props.get("BatteryInstalled") is not False:- condition = "Normal"-- return BatterySnapshot(- percent=max(0, min(100, percent)),- is_charging=bool(props.get("IsCharging", False)),- is_charged=bool(props.get("FullyCharged", False)),- is_plugged=bool(props.get("ExternalConnected", False)),- battery_present=bool(props.get("BatteryInstalled", True)),- voltage=voltage,- amperage=amperage,- battery_watts=voltage * amperage,- time_to_full=int_value(props.get("AvgTimeToFull"), default=-1),- time_to_empty=int_value(props.get("AvgTimeToEmpty"), default=-1),- cycle_count=int_value(props.get("CycleCount"), default=-1),- temperature_c=temperature_celsius(props.get("Temperature")),- design_capacity_mah=design,- max_capacity_mah=max_capacity,- current_capacity_mah=current_capacity,- health_percent=health_percent,- condition=condition,- adapter_connected=adapter["connected"],- adapter_watts=adapter["watts"],- adapter_voltage=adapter["voltage"],- adapter_current=adapter["current"],- adapter_name=adapter["name"],- adapter_manufacturer=adapter["manufacturer"],- adapter_model=adapter["model"],- adapter_serial=adapter["serial"],- adapter_family=adapter["family"],- pd_profiles=tuple(adapter["pd_profiles"]),- full_charge_watts=default_full_charge_watts(),- )---def parse_adapter_details(details: dict[str, Any]) -> dict[str, Any]:- profiles: list[PDProfile] = []- menu = details.get("UsbHvcMenu")- if isinstance(menu, list):- for entry in menu:- if not isinstance(entry, dict):- continue- voltage = int_value(entry.get("MaxVoltage")) / 1000.0- current = int_value(entry.get("MaxCurrent")) / 1000.0- if voltage > 0 and current > 0:- profiles.append(PDProfile(voltage=voltage, current=current))- profiles.sort(key=lambda profile: profile.watts)- voltage_mv = int_value(details.get("AdapterVoltage", details.get("Voltage")))- return {- "connected": bool(details),- "watts": int_value(details.get("Watts"), default=-1),- "voltage": voltage_mv / 1000.0,- "current": int_value(details.get("Current")) / 1000.0,- "name": str_value(details.get("Name")),- "manufacturer": str_value(details.get("Manufacturer")),- "model": str_value(details.get("Model")),- "serial": str_value(details.get("SerialString", details.get("SerialNumber"))),- "family": adapter_family_name(int_value(details.get("FamilyCode"), default=-1)),- "pd_profiles": profiles,- }---def snapshot_with_full_charge_watts(- snapshot: BatterySnapshot,- full_charge_watts: float | None,-) -> BatterySnapshot:- value = full_charge_watts if full_charge_watts is not None else default_full_charge_watts()- return BatterySnapshot(- **{- **snapshot.__dict__,- "full_charge_watts": max(1.0, float(value)),- }- )---def program_for_battery(- snapshot: BatterySnapshot,- *,- 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)))- fill = battery_fill(percent, count)- pulse_index = min(fill.full, count - 1)- transition = max(0, int(transition_ms))-- if not snapshot.is_plugged or snapshot.is_charged:- color = battery_color(percent)- if snapshot.is_charged or percent >= 100:- return apply_brightness(- ";".join(- battery_segment(index, BATTERY_HIGH_GREEN, transition)- for index in range(count)- ),- brightness,- )- return apply_brightness(- ";".join(- battery_segment(index, battery_fill_color(index, fill, color), transition)- for index in range(count)- ),- brightness,- )-- color = BATTERY_CHARGING_MINT- ratio = snapshot.charge_speed_ratio(full_charge_watts)- pulse_ms = charging_pulse_length_ms(ratio)- lines = [- ";".join(- battery_segment(- index,- battery_fill_color(index, fill, color),- transition,- )- for index in range(count)- )- ]- lines.extend(- [- f"{pulse_index}:{color} {pulse_ms}ms pulse",- ]- )- return apply_brightness("\n".join(lines), brightness)---@dataclass(frozen=True)-class BatteryFill:- full: int- partial: float- count: int---def battery_fill(percent: int, led_count: int) -> BatteryFill:- count = max(1, min(8, int(led_count)))- clamped = max(0, min(100, int(percent)))- raw = count * (clamped / 100.0)- full = min(count, int(math.floor(raw)))- partial = 0.0 if full >= count else raw - full- return BatteryFill(full=full, partial=partial, count=count)---def battery_fill_color(index: int, fill: BatteryFill, color: str) -> str:- if index < fill.full:- return color- if index == fill.full and fill.partial > 0:- return scale_hex_color(color, fill.partial)- return BATTERY_OFF---def scale_hex_color(color: str, ratio: float) -> str:- if not re.fullmatch(r"#[0-9a-fA-F]{6}", color):- return color- amount = max(0.0, min(1.0, ratio))- channels = [- round(int(color[index : index + 2], 16) * amount)- for index in (1, 3, 5)- ]- return "#" + "".join(f"{channel:02X}" for channel in channels)---def battery_segment(index: int, color: str, transition_ms: int) -> str:- if transition_ms <= 0:- return f"{index}:{color}"- return f"{index}:{color} {transition_ms}ms ease"---def write_battery_to_leds(- snapshot: BatterySnapshot,- *,- device_path: Path | None = None,- 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,- device_path=target,- file_name=file_name,- dry_run=dry_run,- )- return BatteryLedWrite(- target=written_target,- program=program,- changed=True,- )---class BatteryLedController:- def __init__(- self,- *,- device_path: Path | None = None,- 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- self.last_attempt_monotonic = 0.0- self.last_write_monotonic = 0.0-- def reset(self) -> None:- self.last_program = None- self.last_error = None- self.last_target = None- self.last_attempt_monotonic = 0.0- self.last_write_monotonic = 0.0-- def sync_snapshot(self, snapshot: BatterySnapshot) -> BatteryLedWrite:- 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),- brightness=self.brightness,- )- except (DeviceWriteError, OSError) as exc:- self.last_error = str(exc)- return BatteryLedWrite(- target=self.last_target,- program="",- changed=False,- error=self.last_error,- )-- if (- program == self.last_program- and self.last_error is None- and not should_rewrite_battery_program(snapshot, now - self.last_write_monotonic)- ):- return BatteryLedWrite(- target=self.last_target,- program="",- changed=False,- )- if (- program == self.last_program- and self.last_error is not None- and now - self.last_attempt_monotonic < self.error_retry_seconds- ):- return BatteryLedWrite(- target=self.last_target,- program="",- changed=False,- error=self.last_error,- )-- self.last_attempt_monotonic = now- try:- written_target = write_led_program(- program,- device_path=target,- file_name=self.file_name,- dry_run=self.dry_run,- )- except (DeviceWriteError, OSError) as exc:- self.last_program = program- self.last_error = str(exc)- return BatteryLedWrite(- target=self.last_target,- program="",- changed=False,- error=self.last_error,- )-- self.last_program = program- self.last_error = None- self.last_target = written_target- self.last_write_monotonic = now- return BatteryLedWrite(- target=written_target,- program=program,- changed=True,- )---def render_battery_snapshot(snapshot: BatterySnapshot) -> str:- state = battery_state_label(snapshot)- lines = [f"Battery: {snapshot.percent}% ({state})"]- if snapshot.is_plugged:- lines.append(- f"Adapter: {format_watts(snapshot.adapter_power)} "- f"of {format_watts(snapshot.full_charge_watts)} "- f"({snapshot.charge_speed_ratio() * 100:.0f}% speed)"- )- if abs(snapshot.battery_watts) >= 0.1:- label = "Battery charging" if snapshot.battery_watts > 0 else "Battery draining"- lines.append(f"{label}: {format_watts(abs(snapshot.battery_watts))}")- if snapshot.time_to_full > 0 and snapshot.is_charging:- lines.append(f"Time to full: {format_minutes(snapshot.time_to_full)}")- elif snapshot.time_to_empty > 0 and not snapshot.is_plugged:- lines.append(f"Time remaining: {format_minutes(snapshot.time_to_empty)}")- if snapshot.health_percent >= 0:- lines.append(f"Health: {snapshot.health_percent}%")- if snapshot.cycle_count >= 0:- lines.append(f"Cycle count: {snapshot.cycle_count}")- if snapshot.condition:- lines.append(f"Condition: {snapshot.condition}")- return "\n".join(lines)---def battery_state_label(snapshot: BatterySnapshot) -> str:- if snapshot.is_charged:- return "charged"- if snapshot.is_charging:- return "charging"- if snapshot.is_plugged:- return "plugged in"- return "on battery"---def battery_color(percent: int) -> str:- if percent <= 20:- return BATTERY_LOW_RED- if percent <= 50:- return BATTERY_MID_AMBER- return BATTERY_HIGH_GREEN---def charging_pulse_length_ms(ratio: float) -> int:- speed = clamp(ratio)- return round(180 + (1220 * speed))---def charging_update_interval_seconds(ratio: float) -> float:- speed = clamp(ratio)- return max(0.9, 3.0 - (2.1 * speed))---def should_rewrite_battery_program(snapshot: BatterySnapshot, elapsed_seconds: float) -> bool:- if not snapshot.is_plugged or snapshot.is_charged:- return False- return elapsed_seconds >= charging_update_interval_seconds(snapshot.charge_speed_ratio())---def parse_full_watts(value: str | float | int | None) -> float | None:- if value is None:- return None- if isinstance(value, (int, float)):- return None if float(value) <= 0 else float(value)- text = value.strip().lower()- if text in {"", "auto", "default"}:- return None- return max(1.0, float(text))---@lru_cache(maxsize=1)-def default_full_charge_watts() -> float:- product_text = read_product_tree_text()- product_lower = product_text.lower()- chip_match = re.search(r'"product-soc-name"\s*=\s*<"([^"]+)">', product_text)- chip = chip_match.group(1).lower() if chip_match else ""- if "macbook pro" in product_lower:- if "16-inch" in product_lower:- return 140.0- if "14-inch" in product_lower:- if "pro" in chip or "max" in chip:- return 96.0- return 70.0-- try:- result = subprocess.run(- ["system_profiler", "SPHardwareDataType", "-json"],- check=True,- capture_output=True,- text=True,- )- data = json.loads(result.stdout)- items = data.get("SPHardwareDataType") or []- hardware = items[0] if items else {}- except Exception:- hardware = {}-- chip = str(hardware.get("chip_type", "")).lower()- model = " ".join(- str(hardware.get(key, ""))- for key in ("machine_name", "machine_model", "model_number")- ).lower()- if "macbook pro" in model:- if "16-inch" in model:- return 140.0- if "14-inch" in model:- if "pro" in chip or "max" in chip:- return 96.0- return 70.0- return 100.0---def read_product_tree_text() -> str:- try:- result = subprocess.run(- ["ioreg", "-p", "IODeviceTree", "-r", "-d", "1", "-n", "product"],- check=True,- capture_output=True,- text=True,- )- return result.stdout- except Exception:- return ""---def int_value(value: object, default: int = 0) -> int:- if isinstance(value, bool):- return int(value)- if isinstance(value, int):- return value- if isinstance(value, float):- return int(value)- return default---def str_value(value: object) -> str:- return value if isinstance(value, str) else ""---def temperature_celsius(value: object) -> float | None:- raw = int_value(value, default=-1)- if raw < 0:- return None- return raw / 100.0---def adapter_family_name(code: int) -> str:- if 0xE0004000 <= code <= 0xE0004FFF:- return "USB-C Power Delivery"- if code == 0x00000003:- return "MagSafe"- if code == 0x00000004:- return "MagSafe 2"- if code == 0x0000FF00:- return "USB-C"- if code >= 0:- return f"0x{code:08x}"- return ""---def clamp(value: float) -> float:- return max(0.0, min(1.0, float(value)))---def format_watts(value: float) -> str:- if value <= 0:- return "0W"- if value >= 10:- return f"{value:.0f}W"- return f"{value:.1f}W"---def format_minutes(minutes: int) -> str:- if minutes < 60:- return f"{minutes}m"- hours, rest = divmod(minutes, 60)- return f"{hours}h{rest:02d}m"diff --git a/src/agent_monitor/cli.py b/src/agent_monitor/cli.pydeleted file mode 100644index 2180bf7..0000000--- a/src/agent_monitor/cli.py+++ /dev/null@@ -1,1074 +0,0 @@-from __future__ import annotations--import argparse-import json-import os-import shutil-import subprocess-import sys-import time-from pathlib import Path--from .battery import (- BatteryLedController,- format_watts,- parse_full_watts,- read_battery_snapshot,- render_battery_snapshot,-)-from .collector import AgentMonitor, SourceSpec, default_sources-from .device_writer import DEFAULT_FILE_NAME, DeviceWriteError, write_led_program-from .hook import hook_log_main-from .install import (- install_claude_hooks,- install_codex_hooks,- uninstall_claude_hooks,- 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,- detect_codex_config,- detect_log_path,- default_log_path,-)-from .settings import (- LED_DISPLAY_BATTERY,- LED_DISPLAY_CHOICES,- load_settings,- save_settings,-)---def main(argv: list[str] | None = None, *, prog: str = "agent-monitor") -> int:- parser = build_parser(prog=prog)- args = parser.parse_args(argv)- return args.func(args)---def sidepulse_main(argv: list[str] | None = None) -> int:- args = list(sys.argv[1:] if argv is None else argv)- if args[:1] == ["agent-monitor"]:- return main(args[1:], prog="sidepulse agent-monitor")-- parser = build_sidepulse_parser()- if not args:- parser.print_help()- return 0-- parsed = parser.parse_args(args)- return parsed.func(parsed)---def build_sidepulse_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(- prog="sidepulse",- description="SidePulse command line tools.",- )- subparsers = parser.add_subparsers(dest="command", required=True)- subparsers.add_parser(- "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.",- )- write.add_argument("text", help=r"LED program text. Backslash escapes like \n are decoded.")- write.add_argument(- "--device",- type=Path,- help="Mounted device folder or LED program file path. Defaults to auto-detecting /Volumes.",- )- write.add_argument(- "--file-name",- default=DEFAULT_FILE_NAME,- 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",- help="Show or mirror Mac battery state to SidePulse/PulseDot LEDs.",- )- battery_subparsers = battery.add_subparsers(dest="battery_command", required=True)-- status = battery_subparsers.add_parser("status", help="Show current Mac battery state.")- status.add_argument("--json", action="store_true", help="Print machine-readable JSON.")- status.add_argument(- "--full-watts",- help="Full-speed charger wattage baseline, or 'auto'. Defaults to saved settings.",- )- status.set_defaults(func=cmd_sidepulse_battery_status)-- leds = battery_subparsers.add_parser("leds", help="Mirror Mac battery state to LEDs.")- leds.add_argument("--interval", type=float, default=1.0, help="Refresh interval in seconds.")- leds.add_argument(- "--device",- type=Path,- help="Mounted device folder or LED program file path. Defaults to auto-detecting /Volumes.",- )- leds.add_argument(- "--file-name",- default=DEFAULT_FILE_NAME,- 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.")- leds.add_argument(- "--full-watts",- help="Full-speed charger wattage baseline, or 'auto'. Defaults to saved settings.",- )- leds.set_defaults(func=cmd_sidepulse_battery_leds)-- configure = battery_subparsers.add_parser("configure", help="Save battery LED settings.")- configure.add_argument("--display", choices=LED_DISPLAY_CHOICES, help="Status-bar LED display source.")- configure.add_argument(- "--full-watts",- help="Full-speed charger wattage baseline, or 'auto' to use laptop defaults.",- )- configure.add_argument(- "--show-on-power-change",- choices=("yes", "no"),- help="Briefly show battery LEDs when power is plugged/unplugged.",- )- configure.add_argument(- "--power-change-preview-seconds",- type=float,- help="Seconds to show battery LEDs after plug/unplug.",- )- configure.set_defaults(func=cmd_sidepulse_battery_configure)---def cmd_sidepulse_write(args: argparse.Namespace) -> int:- try:- target = write_led_program(- args.text,- device_path=args.device,- file_name=args.file_name,- dry_run=args.dry_run,- )- except DeviceWriteError as exc:- print(f"sidepulse write: {exc}", file=sys.stderr)- return 2- except OSError as exc:- print(f"sidepulse write: {exc}", file=sys.stderr)- return 1-- action = "would write" if args.dry_run else "wrote"- print(f"{action}: {target}")- return 0---def cmd_sidepulse_battery_status(args: argparse.Namespace) -> int:- try:- snapshot = read_battery_snapshot(full_charge_watts=full_watts_from_args(args))- except Exception as exc:- print(f"sidepulse battery status: {exc}", file=sys.stderr)- return 1-- if args.json:- print(json.dumps(snapshot.to_dict(), indent=2))- else:- print(render_battery_snapshot(snapshot))- return 0---def cmd_sidepulse_battery_leds(args: argparse.Namespace) -> int:- leds = BatteryLedController(- device_path=args.device,- file_name=args.file_name,- dry_run=args.dry_run,- )- full_watts = full_watts_from_args(args)-- try:- while True:- snapshot = read_battery_snapshot(full_charge_watts=full_watts)- result = leds.sync_snapshot(snapshot)- if result.changed or result.error or args.once:- print(render_battery_led_result(result, snapshot, dry_run=args.dry_run))- sys.stdout.flush()-- if args.once:- return 2 if result.error else 0-- time.sleep(args.interval)- except KeyboardInterrupt:- return 0- except Exception as exc:- print(f"sidepulse battery leds: {exc}", file=sys.stderr)- return 1---def cmd_sidepulse_battery_configure(args: argparse.Namespace) -> int:- settings = load_settings()- try:- if args.display is not None:- settings = settings.with_led_display(args.display)- if args.full_watts is not None:- settings = settings.with_battery_full_charge_watts(parse_full_watts(args.full_watts))- if args.show_on_power_change is not None:- settings = settings.with_battery_power_change_preview(- enabled=args.show_on_power_change == "yes",- )- if args.power_change_preview_seconds is not None:- settings = settings.with_battery_power_change_preview(- seconds=args.power_change_preview_seconds,- )- target = save_settings(settings)- except Exception as exc:- print(f"sidepulse battery configure: {exc}", file=sys.stderr)- return 1-- full_watts = (- "auto"- if settings.battery_full_charge_watts is None- else format_watts(settings.battery_full_charge_watts)- )- preview = "on" if settings.battery_show_on_power_change else "off"- print(f"settings: {target}")- print(f" led display: {settings.led_display}")- print(f" full charge watts: {full_watts}")- print(- " power-change preview: "- f"{preview} ({settings.battery_power_change_preview_seconds:g}s)"- )- if settings.led_display == LED_DISPLAY_BATTERY:- print(" status bar LEDs will show battery.")- 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,- description="Collect and aggregate local AI agent statuses.",- )- subparsers = parser.add_subparsers(dest="command", required=True)-- doctor = subparsers.add_parser("doctor", help="Show detected agent hook config.")- doctor.add_argument("--json", action="store_true", help="Print machine-readable JSON.")- doctor.set_defaults(func=cmd_doctor)-- status = subparsers.add_parser("status", help="Show current aggregate status once.")- add_status_args(status)- status.set_defaults(func=cmd_status)-- add_live_parser(subparsers, "live", "Show live statuses in the terminal.")- add_live_parser(subparsers, "watch", "Alias for live.")-- leds = subparsers.add_parser("leds", help="Mirror aggregate agent status to SidePulse/PulseDot LEDs.")- add_status_args(leds, include_json=False)- leds.add_argument("--interval", type=float, default=1.0, help="Refresh interval in seconds.")- leds.add_argument(- "--device",- type=Path,- help="Mounted device folder or LED program file path. Defaults to auto-detecting /Volumes.",- )- leds.add_argument(- "--file-name",- default=DEFAULT_FILE_NAME,- 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.")- leds.set_defaults(func=cmd_leds)-- status_bar = subparsers.add_parser("status-bar", help="Install and start the macOS menu-bar app.")- status_bar_mode = status_bar.add_mutually_exclusive_group()- status_bar_mode.add_argument(- "--foreground",- action="store_true",- help="Run the menu-bar app in the foreground instead of installing a LaunchAgent.",- )- status_bar_mode.add_argument(- "--uninstall",- action="store_true",- help="Stop and remove the status-bar LaunchAgent.",- )- status_bar.add_argument(- "--no-start",- action="store_true",- help="Install the LaunchAgent without starting it immediately.",- )- status_bar.set_defaults(func=cmd_status_bar)-- install = subparsers.add_parser("install", help="Install Codex and/or Claude monitor hooks.")- install.add_argument("provider", choices=("all", "codex", "claude"), nargs="?", default="all")- install.add_argument("--log-dir", type=Path, help="Directory for provider JSONL files.")- install.add_argument("--codex-log", type=Path, help="Codex JSONL log path.")- install.add_argument("--claude-log", type=Path, help="Claude JSONL log path.")- install.add_argument("--dry-run", action="store_true", help="Show what would change.")- install.set_defaults(func=cmd_install)-- uninstall = subparsers.add_parser("uninstall", help="Remove Codex and/or Claude monitor hooks.")- uninstall.add_argument("provider", choices=("all", "codex", "claude"), nargs="?", default="all")- uninstall.add_argument("--codex-log", type=Path, help="Codex JSONL log path.")- uninstall.add_argument("--claude-log", type=Path, help="Claude JSONL log path.")- uninstall.add_argument("--dry-run", action="store_true", help="Show what would change.")- uninstall.set_defaults(func=cmd_uninstall)-- hook_log = subparsers.add_parser("hook-log", help="Internal hook logging entry point.")- hook_log.add_argument("--provider", choices=("codex", "claude"), required=True)- hook_log.add_argument("--log", type=Path, required=True)- hook_log.set_defaults(func=cmd_hook_log)-- return parser---def add_live_parser(- subparsers: argparse._SubParsersAction,- name: str,- help_text: str,-) -> None:- live = subparsers.add_parser(name, help=help_text)- add_status_args(live, include_json=False)- live.add_argument("--interval", type=float, default=1.0, help="Refresh interval in seconds.")- live.add_argument(- "--recent-seconds",- type=float,- default=3600.0,- help="Only show agents updated within this many seconds unless --all is set.",- )- live.add_argument("--no-color", action="store_true", help="Disable ANSI color output.")- live.set_defaults(func=cmd_watch)---def add_status_args(parser: argparse.ArgumentParser, include_json: bool = True) -> None:- if include_json:- parser.add_argument("--json", action="store_true", help="Print machine-readable JSON.")- parser.add_argument("--all", action="store_true", help="Include stale statuses in table output.")- parser.add_argument("--stale-after", type=float, default=3600.0, help="Seconds before a status is stale.")- parser.add_argument(- "--tool-running-timeout",- type=float,- default=0.0,- help="Seconds before an unmatched Tool Running event is treated as stale; 0 disables this.",- )- parser.add_argument("--max-lines", type=int, default=5000, help="Recent JSONL lines to scan per source.")- parser.add_argument("--codex-log", type=Path, help="Codex JSONL log path.")- parser.add_argument("--claude-log", type=Path, help="Claude JSONL log path.")---def cmd_doctor(args: argparse.Namespace) -> int:- configs = [detect_codex_config(), detect_claude_config()]- payload = {"providers": [config.to_dict() for config in configs]}- if args.json:- print(json.dumps(payload, indent=2))- return 0-- for config in configs:- print(f"{config.provider}:")- print(f" config: {config.config_path} ({'found' if config.exists else 'missing'})")- print(f" hooks enabled: {config.hooks_enabled}")- print(f" events: {', '.join(config.hook_events) if config.hook_events else '-'}")- print(f" logs: {', '.join(str(path) for path in config.log_paths) if config.log_paths else '-'}")- return 0---def cmd_status(args: argparse.Namespace) -> int:- monitor = monitor_from_args(args)- snapshot = monitor.snapshot(include_stale=args.all)- if args.json:- print(json.dumps(snapshot.to_dict(), indent=2))- else:- print(render_snapshot(snapshot, include_stale=args.all))- return 0---def cmd_watch(args: argparse.Namespace) -> int:- monitor = monitor_from_args(args)- color = should_use_color(args.no_color)- try:- if sys.stdout.isatty():- print("\033[?25l", end="")- while True:- snapshot = monitor.snapshot(include_stale=args.all)- print("\033[2J\033[H", end="")- print(- render_watch_dashboard(- snapshot,- interval=args.interval,- recent_seconds=args.recent_seconds,- include_stale=args.all,- color=color,- )- )- sys.stdout.flush()- time.sleep(args.interval)- except KeyboardInterrupt:- return 0- finally:- if sys.stdout.isatty():- print("\033[?25h", end="")---def cmd_leds(args: argparse.Namespace) -> int:- monitor = monitor_from_args(args)- leds = AgentLedController(- device_path=args.device,- file_name=args.file_name,- dry_run=args.dry_run,- )-- try:- while True:- snapshot = monitor.snapshot(include_stale=args.all)- result = leds.sync_mode(snapshot.aggregate.mode)- if result.changed or result.error or args.once:- print(render_led_sync_result(result, snapshot, dry_run=args.dry_run))- sys.stdout.flush()-- if args.once:- return 2 if result.error else 0-- time.sleep(args.interval)- except KeyboardInterrupt:- return 0---def cmd_status_bar(args: argparse.Namespace) -> int:- if args.foreground:- from .status_bar import main as status_bar_main-- return status_bar_main()-- from .status_bar_launch import install_launch_agent, uninstall_launch_agent-- if args.uninstall:- result = uninstall_launch_agent()- action = "removed" if result.changed else "already removed"- print(f"status-bar: {action}")- print(f" plist: {result.plist_path}")- return 0-- result = install_launch_agent(start=not args.no_start)- 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 cmd_install(args: argparse.Namespace) -> int:- 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)- if provider == "codex":- 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 dry_run and result.changed else "updated"- if not result.changed:- action = "already configured"- print(f"{result.provider}: {action}")- print(f" config: {result.config_path}")- print(f" log: {result.log_path}")- if result.backup_path:- print(f" backup: {result.backup_path}")---def cmd_uninstall(args: argparse.Namespace) -> int:- providers = ("codex", "claude") if args.provider == "all" else (args.provider,)- results = []- for provider in providers:- log_path = uninstall_log_path(provider, args)- if provider == "codex":- results.append(uninstall_codex_hooks(log_path=log_path, dry_run=args.dry_run))- else:- results.append(uninstall_claude_hooks(log_path=log_path, dry_run=args.dry_run))-- for result in results:- action = "would remove" if args.dry_run and result.changed else "removed"- if not result.changed:- action = "already uninstalled"- print(f"{result.provider}: {action}")- print(f" config: {result.config_path}")- print(f" log: {result.log_path}")- if result.backup_path:- print(f" backup: {result.backup_path}")- return 0---def cmd_hook_log(args: argparse.Namespace) -> int:- return hook_log_main(args.provider, args.log)---def monitor_from_args(args: argparse.Namespace) -> AgentMonitor:- if args.codex_log or args.claude_log:- fallback_sources = default_sources()- sources = []- if args.codex_log:- sources.append(SourceSpec("codex", args.codex_log.expanduser()))- else:- sources.extend(source for source in fallback_sources if source.provider == "codex")- if args.claude_log:- sources.append(SourceSpec("claude", args.claude_log.expanduser()))- else:- sources.extend(source for source in fallback_sources if source.provider == "claude")- else:- sources = list(default_sources())-- return AgentMonitor(- sources=sources,- stale_after_seconds=args.stale_after,- tool_running_timeout_seconds=args.tool_running_timeout,- max_lines_per_source=args.max_lines,- )---def install_log_path(provider: str, args: argparse.Namespace) -> Path:- explicit = getattr(args, "codex_log", None) if provider == "codex" else getattr(args, "claude_log", None)- if explicit:- return explicit.expanduser()- log_dir = getattr(args, "log_dir", None)- if log_dir:- return log_dir.expanduser() / f"{provider}.jsonl"- return default_log_path(provider)---def uninstall_log_path(provider: str, args: argparse.Namespace) -> Path | None:- explicit = args.codex_log if provider == "codex" else args.claude_log- return explicit.expanduser() if explicit else None---def full_watts_from_args(args: argparse.Namespace) -> float | None:- if getattr(args, "full_watts", None) is not None:- return parse_full_watts(args.full_watts)- return load_settings().battery_full_charge_watts---def render_snapshot(snapshot, include_stale: bool = False) -> str:- lines = []- aggregate = snapshot.aggregate- lines.append(- f"Aggregate: {aggregate.mode_label} "- f"({aggregate.active_count} active, {aggregate.stale_count} stale)"- )- if aggregate.representative:- lines.append(f"Reason: {describe_status(aggregate.representative, snapshot.collected_at)}")- lines.append("")- lines.append("Sources:")- for source in snapshot.sources:- marker = "ok" if source.path.exists() else "missing"- lines.append(f" {source.provider}: {source.path} [{marker}]")-- statuses = list(snapshot.statuses)- if include_stale:- statuses.extend(snapshot.stale_statuses)-- lines.append("")- lines.append("Agents:")- if not statuses:- lines.append(" none")- else:- for status in statuses:- lines.append(f" {describe_status(status, snapshot.collected_at)}")- return "\n".join(lines)---def render_watch_dashboard(- snapshot,- interval: float,- recent_seconds: float,- include_stale: bool = False,- color: bool = False,-) -> str:- width = max(80, shutil.get_terminal_size((120, 24)).columns)- statuses = visible_watch_statuses(snapshot, recent_seconds, include_stale)- aggregate = snapshot.aggregate- timestamp = snapshot.collected_at.astimezone().strftime("%Y-%m-%d %H:%M:%S")- title = colorize("Agent Monitor", "1", color)- aggregate_text = colorize(aggregate.mode_label, mode_color(aggregate.mode), color)- recent_text = "all known agents" if include_stale else f"last {format_duration(recent_seconds)}"-- lines = [- f"{title} aggregate={aggregate_text} agents={len(statuses)} updated={timestamp}",- f"refresh={interval:g}s showing={recent_text} active={aggregate.active_count} stale={aggregate.stale_count} quit=Ctrl-C",- "=" * min(width, 120),- ]-- if aggregate.representative:- lines.append(- "reason: "- + colorize(- describe_status(aggregate.representative, snapshot.collected_at),- mode_color(aggregate.representative.mode),- color,- )- )- else:- lines.append("reason: no recent agent status")-- lines.extend(["", "Sources"])- for source in snapshot.sources:- ok = source.path.exists()- marker = colorize("OK", "32", color) if ok else colorize("MISS", "31", color)- lines.append(f" {marker:<4} {source.provider:<7} {source.path}")-- lines.extend(["", "Recently Active Agents"])- if not statuses:- lines.append(" none")- return "\n".join(lines)-- table_width = min(width, 140)- fixed_width = 9 + 22 + 20 + 8 + 18 + 16 + 18- cwd_width = max(18, table_width - fixed_width)- widths = [9, 22, 20, 8, 18, 16, cwd_width]- headers = ["Provider", "Agent", "Mode", "Age", "Event", "Tool", "Cwd"]- lines.append(table_separator(widths))- lines.append(table_row(headers, widths))- lines.append(table_separator(widths))- for status in statuses:- age = format_duration(status.age_seconds(snapshot.collected_at))- row = [- status.provider,- status.display_name,- status.mode_label,- age,- status.event_name,- status.tool_name or "-",- status.cwd or "-",- ]- lines.append(table_row(row, widths, mode_index=2, mode=status.mode, color=color))- lines.append(table_separator(widths))- return "\n".join(lines)---def visible_watch_statuses(snapshot, recent_seconds: float, include_stale: bool) -> list[AgentStatus]:- statuses = list(snapshot.statuses)- if include_stale:- statuses.extend(snapshot.stale_statuses)- return sorted(statuses, key=lambda status: (status.priority, -status.updated_at.timestamp()))-- if recent_seconds > 0:- statuses = [- status- for status in statuses- if status.age_seconds(snapshot.collected_at) <= recent_seconds- ]-- return sorted(statuses, key=lambda status: (status.priority, -status.updated_at.timestamp()))---def describe_status(status: AgentStatus, now) -> str:- age = int(status.age_seconds(now))- stale = " stale" if status.stale else ""- tool = f" tool={status.tool_name}" if status.tool_name else ""- cwd = f" cwd={status.cwd}" if status.cwd else ""- return (- f"{status.display_name}: {status.mode_label}"- f" event={status.event_name}{tool} age={age}s{stale}{cwd}"- )---def render_led_sync_result(result: LedStatusWrite, snapshot, dry_run: bool = False) -> str:- if result.error:- return f"LEDs: {result.label} error={result.error}"-- action = "would write" if dry_run else "wrote"- target = result.target if result.target is not None else "-"- lines = [- (- f"LEDs: {action} {result.label} to {target} "- f"(aggregate={snapshot.aggregate.mode_label}, active={snapshot.aggregate.active_count})"- )- ]- if dry_run and result.program:- lines.append(result.program)- return "\n".join(lines)---def render_battery_led_result(result, snapshot, dry_run: bool = False) -> str:- if result.error:- return f"Battery LEDs: error={result.error}"-- action = "would write" if dry_run else "wrote"- target = result.target if result.target is not None else "-"- lines = [- (- f"Battery LEDs: {action} {snapshot.percent}% "- f"({format_watts(snapshot.adapter_power)}/"- f"{format_watts(snapshot.full_charge_watts)}, "- f"{snapshot.charge_speed_ratio() * 100:.0f}% speed) to {target}"- )- ]- if dry_run and result.program:- lines.append(result.program)- return "\n".join(lines)---def table_separator(widths: list[int]) -> str:- return "+" + "+".join("-" * (width + 2) for width in widths) + "+"---def table_row(- cells: list[str],- widths: list[int],- mode_index: int | None = None,- mode=None,- color: bool = False,-) -> str:- padded = []- for index, (cell, width) in enumerate(zip(cells, widths)):- text = truncate(str(cell), width).ljust(width)- if mode_index is not None and index == mode_index and mode is not None:- text = colorize(text, mode_color(mode), color)- padded.append(f" {text} ")- return "|" + "|".join(padded) + "|"---def truncate(text: str, width: int) -> str:- if len(text) <= width:- return text- if width <= 1:- return text[:width]- return text[: width - 1] + "."---def format_duration(seconds: float) -> str:- seconds = max(0, int(seconds))- if seconds < 60:- return f"{seconds}s"- minutes, rest = divmod(seconds, 60)- if minutes < 60:- return f"{minutes}m{rest:02d}s"- hours, minutes = divmod(minutes, 60)- return f"{hours}h{minutes:02d}m"---def should_use_color(no_color: bool) -> bool:- return (- not no_color- and "NO_COLOR" not in os.environ- and sys.stdout.isatty()- )---def colorize(text: str, code: str, enabled: bool) -> str:- if not enabled:- return text- return f"\033[{code}m{text}\033[0m"---def mode_color(mode) -> str:- return {- "blocked_error": "31;1",- "waiting_for_input": "33;1",- "tool_running": "36;1",- "long_task_progress": "35;1",- "working": "34;1",- "completed": "32;1",- "idle_ready": "37",- }.get(getattr(mode, "value", str(mode)), "37")diff --git a/src/agent_monitor/collector.py b/src/agent_monitor/collector.pydeleted file mode 100644index ec03fe3..0000000--- a/src/agent_monitor/collector.py+++ /dev/null@@ -1,1622 +0,0 @@-from __future__ import annotations--import json-import re-import threading-import time-from dataclasses import dataclass-from datetime import datetime, timezone-from pathlib import Path-from typing import Any, Callable, Iterable--from .models import (- MODE_PRIORITY,- AgentMode,- AgentStatus,- AggregateStatus,- HookEvent,- parse_datetime,- provider_label,-)-from .providers import detect_log_path, parse_log_line-from .settings import AgentMonitorSettings, load_settings---CODEX_TRANSCRIPT_PROVIDER = "codex-transcripts"-CLAUDE_TRANSCRIPT_PROVIDER = "claude-transcripts"-CODEX_TRANSCRIPT_MAX_FILES = 12-CODEX_TRANSCRIPT_MAX_LINES = 500-CLAUDE_TRANSCRIPT_MAX_FILES = 24-CLAUDE_TRANSCRIPT_MAX_LINES = 500-TRANSCRIPT_FILE_LIST_CACHE_SECONDS = 5.0-CLAUDE_TRANSCRIPT_MTIME_HEARTBEAT_SKEW_SECONDS = 30.0-CODEX_SESSION_INDEX_MAX_LINES = 5000-COMPLETED_VISIBLE_SECONDS = 20 * 60.0-IDLE_VISIBLE_SECONDS = 0.0---@dataclass(frozen=True)-class SourceSpec:- provider: str- path: Path---@dataclass-class StatusMetadata:- cwd: str | None = None- title: str | None = None---@dataclass(frozen=True)-class CachedTranscriptRecords:- mtime: float- size: int- records: tuple[HookEvent, ...]---@dataclass(frozen=True)-class CachedTranscriptFileList:- expires_at: float- paths: tuple[Path, ...]---@dataclass(frozen=True)-class CachedCodexSessionIndex:- path: Path- mtime: float- size: int- titles: dict[str, str]---_codex_session_index_cache: CachedCodexSessionIndex | None = None-_codex_session_index_lock = threading.RLock()---@dataclass(frozen=True)-class MonitorSnapshot:- aggregate: AggregateStatus- statuses: tuple[AgentStatus, ...]- stale_statuses: tuple[AgentStatus, ...]- sources: tuple[SourceSpec, ...]- collected_at: datetime-- def to_dict(self) -> dict:- return {- "collected_at": self.collected_at.isoformat(),- "sources": [- {"provider": source.provider, "path": str(source.path)}- for source in self.sources- ],- "aggregate": self.aggregate.to_dict(self.collected_at),- "statuses": [- status.to_dict(self.collected_at) for status in self.statuses- ],- "stale_statuses": [- status.to_dict(self.collected_at) for status in self.stale_statuses- ],- }---class AgentMonitor:- def __init__(- self,- sources: Iterable[SourceSpec] | None = None,- stale_after_seconds: float = 3600.0,- tool_running_timeout_seconds: float = 0.0,- completed_visible_seconds: float = COMPLETED_VISIBLE_SECONDS,- idle_visible_seconds: float = IDLE_VISIBLE_SECONDS,- max_lines_per_source: int = 5000,- ) -> None:- self.sources = tuple(sources) if sources is not None else default_sources()- self.stale_after_seconds = stale_after_seconds- self.tool_running_timeout_seconds = tool_running_timeout_seconds- self.completed_visible_seconds = completed_visible_seconds- self.idle_visible_seconds = idle_visible_seconds- self.max_lines_per_source = max_lines_per_source- self._log_records_cache: dict[tuple[str, str, int], CachedTranscriptRecords] = {}- self._transcript_records_cache: dict[tuple[str, str], CachedTranscriptRecords] = {}- self._transcript_file_list_cache: dict[tuple[str, int], CachedTranscriptFileList] = {}- self._latest_status_signature: tuple[Any, ...] | None = None- self._latest_statuses_by_key: dict[str, AgentStatus] | None = None-- @classmethod- def from_default_sources(- cls,- stale_after_seconds: float = 3600.0,- tool_running_timeout_seconds: float = 0.0,- completed_visible_seconds: float = COMPLETED_VISIBLE_SECONDS,- idle_visible_seconds: float = IDLE_VISIBLE_SECONDS,- max_lines_per_source: int = 5000,- ) -> "AgentMonitor":- return cls(- stale_after_seconds=stale_after_seconds,- tool_running_timeout_seconds=tool_running_timeout_seconds,- completed_visible_seconds=completed_visible_seconds,- idle_visible_seconds=idle_visible_seconds,- max_lines_per_source=max_lines_per_source,- )-- def snapshot(self, include_stale: bool = False) -> MonitorSnapshot:- now = datetime.now(timezone.utc)- statuses_by_key = self._latest_statuses()-- fresh: list[AgentStatus] = []- stale: list[AgentStatus] = []- for status in statuses_by_key.values():- is_stale = self.is_stale_status(status, now)- current = _replace_stale(status, is_stale)- if is_stale:- stale.append(current)- else:- fresh.append(current)-- if any(status_counts_active(status) for status in fresh):- inactive = [status for status in fresh if not status_counts_active(status)]- fresh = [status for status in fresh if status_counts_active(status)]- stale.extend(_replace_stale(status, True) for status in inactive)-- fresh.sort(key=lambda status: (status.priority, -status.updated_at.timestamp()))- stale.sort(key=lambda status: (status.priority, -status.updated_at.timestamp()))-- visible = tuple(fresh)- stale_visible = tuple(stale if include_stale else stale)- aggregate = aggregate_status(visible, stale_visible)-- return MonitorSnapshot(- aggregate=aggregate,- statuses=visible,- stale_statuses=stale_visible,- sources=self.sources,- collected_at=now,- )-- def _latest_statuses(self) -> dict[str, AgentStatus]:- signature = self._input_signature()- if (- self._latest_status_signature == signature- and self._latest_statuses_by_key is not None- ):- return dict(self._latest_statuses_by_key)-- statuses_by_key: dict[str, AgentStatus] = {}- metadata_by_session: dict[str, StatusMetadata] = {}- metadata_by_status: dict[str, StatusMetadata] = {}- pending_permissions_by_key: dict[str, set[str]] = {}-- records = sorted(- self._iter_records(),- key=lambda record: record.logged_at,- )-- for record in records:- metadata = metadata_for_record(- record,- metadata_by_session,- metadata_by_status,- )- status = status_from_event(record, metadata)- if status is not None:- track_pending_permissions(record, pending_permissions_by_key)- previous = statuses_by_key.get(status.agent_id)- if should_ignore_status_transition(- previous,- status,- pending_permissions_by_key.get(status.agent_id, set()),- ):- continue- statuses_by_key[status.agent_id] = status-- self._latest_status_signature = signature- self._latest_statuses_by_key = dict(statuses_by_key)- return statuses_by_key-- def _input_signature(self) -> tuple[Any, ...]:- parts: list[Any] = []- for source in self.sources:- if source.provider == CODEX_TRANSCRIPT_PROVIDER:- parts.append(- (- source.provider,- str(source.path),- self._transcript_source_signature(- source.path,- limit=CODEX_TRANSCRIPT_MAX_FILES,- ),- )- )- continue- if source.provider == CLAUDE_TRANSCRIPT_PROVIDER:- parts.append(- (- source.provider,- str(source.path),- self._transcript_source_signature(- source.path,- limit=CLAUDE_TRANSCRIPT_MAX_FILES,- ),- )- )- continue-- parts.append((source.provider, str(source.path), file_signature(source.path)))- return tuple(parts)-- def _transcript_source_signature(- self,- root: Path,- *,- limit: int,- ) -> tuple[tuple[str, tuple[float, int] | None], ...]:- return tuple(- (str(path), file_signature(path))- for path in self._recent_transcript_files(root, limit=limit)- )-- def _iter_records(self) -> Iterable[HookEvent]:- for source in self.sources:- if not source.path.exists():- continue- if source.provider == CODEX_TRANSCRIPT_PROVIDER:- yield from self._iter_codex_transcript_records(source.path)- continue- if source.provider == CLAUDE_TRANSCRIPT_PROVIDER:- yield from self._iter_claude_transcript_records(source.path)- continue- yield from self._cached_log_records(source)-- def _cached_log_records(self, source: SourceSpec) -> tuple[HookEvent, ...]:- try:- stat = source.path.stat()- except OSError:- return ()-- key = (source.provider, str(source.path), self.max_lines_per_source)- cached = self._log_records_cache.get(key)- if cached is not None and cached.mtime == stat.st_mtime and cached.size == stat.st_size:- return cached.records-- records: list[HookEvent] = []- for line in read_recent_lines(source.path, self.max_lines_per_source):- record = parse_log_line(source.provider, line)- if record is not None:- records.append(record)-- cached_records = tuple(records)- self._log_records_cache[key] = CachedTranscriptRecords(- mtime=stat.st_mtime,- size=stat.st_size,- records=cached_records,- )- return cached_records-- def _iter_codex_transcript_records(self, root: Path) -> Iterable[HookEvent]:- for path in self._recent_transcript_files(root, limit=CODEX_TRANSCRIPT_MAX_FILES):- yield from self._cached_transcript_records(- CODEX_TRANSCRIPT_PROVIDER,- path,- iter_codex_transcript_file,- )-- def _iter_claude_transcript_records(self, root: Path) -> Iterable[HookEvent]:- for path in self._recent_transcript_files(root, limit=CLAUDE_TRANSCRIPT_MAX_FILES):- yield from self._cached_transcript_records(- CLAUDE_TRANSCRIPT_PROVIDER,- path,- iter_claude_transcript_file,- )-- def _recent_transcript_files(self, root: Path, *, limit: int) -> tuple[Path, ...]:- key = (str(root), limit)- now = time.monotonic()- cached = self._transcript_file_list_cache.get(key)- if cached is not None and now < cached.expires_at:- return cached.paths-- paths = tuple(recent_transcript_files(root, limit=limit))- self._transcript_file_list_cache[key] = CachedTranscriptFileList(- expires_at=now + TRANSCRIPT_FILE_LIST_CACHE_SECONDS,- paths=paths,- )- return paths-- def _cached_transcript_records(- self,- provider: str,- path: Path,- parser: Callable[[Path], Iterable[HookEvent]],- ) -> tuple[HookEvent, ...]:- try:- stat = path.stat()- except OSError:- return ()-- key = (provider, str(path))- cached = self._transcript_records_cache.get(key)- if cached is not None and cached.mtime == stat.st_mtime and cached.size == stat.st_size:- return cached.records-- records = tuple(parser(path))- self._transcript_records_cache[key] = CachedTranscriptRecords(- mtime=stat.st_mtime,- size=stat.st_size,- records=records,- )- return records-- def is_stale_status(self, status: AgentStatus, now: datetime) -> bool:- age = status.age_seconds(now)- if status.mode == AgentMode.COMPLETED and self.completed_visible_seconds >= 0:- return age > self.completed_visible_seconds- if status.mode == AgentMode.IDLE_READY and self.idle_visible_seconds >= 0:- return age > self.idle_visible_seconds- return (- age > self.stale_after_seconds- or self.is_expired_tool_running(status, now)- )-- def is_expired_tool_running(self, status: AgentStatus, now: datetime) -> bool:- return (- status.mode == AgentMode.TOOL_RUNNING- and self.tool_running_timeout_seconds > 0- and status.age_seconds(now) > self.tool_running_timeout_seconds- )---class LiveAgentMonitor:- def __init__(- self,- *,- sources: Iterable[SourceSpec] = (),- stale_after_seconds: float = 3600.0,- tool_running_timeout_seconds: float = 0.0,- completed_visible_seconds: float = COMPLETED_VISIBLE_SECONDS,- idle_visible_seconds: float = IDLE_VISIBLE_SECONDS,- latest_state_path: Path | None = None,- ) -> None:- self.sources = tuple(sources)- self.stale_after_seconds = stale_after_seconds- self.tool_running_timeout_seconds = tool_running_timeout_seconds- self.completed_visible_seconds = completed_visible_seconds- self.idle_visible_seconds = idle_visible_seconds- self.latest_state_path = latest_state_path- self.lock = threading.RLock()- self.statuses_by_key: dict[str, AgentStatus] = {}- self.metadata_by_session: dict[str, StatusMetadata] = {}- self.metadata_by_status: dict[str, StatusMetadata] = {}- self.pending_permissions_by_key: dict[str, set[str]] = {}- self.load_latest_state()-- def ingest_record(self, record: HookEvent) -> None:- with self.lock:- metadata = metadata_for_record(- record,- self.metadata_by_session,- self.metadata_by_status,- )- status = status_from_event(record, metadata)- if status is None:- return-- track_pending_permissions(record, self.pending_permissions_by_key)- previous = self.statuses_by_key.get(status.agent_id)- if should_ignore_status_transition(- previous,- status,- self.pending_permissions_by_key.get(status.agent_id, set()),- ):- return- self.statuses_by_key[status.agent_id] = status- self.write_latest_state()-- def snapshot(self, include_stale: bool = False) -> MonitorSnapshot:- now = datetime.now(timezone.utc)- with self.lock:- statuses = tuple(self.statuses_by_key.values())- return snapshot_from_statuses(- statuses,- sources=self.sources,- collected_at=now,- stale_after_seconds=self.stale_after_seconds,- tool_running_timeout_seconds=self.tool_running_timeout_seconds,- completed_visible_seconds=self.completed_visible_seconds,- idle_visible_seconds=self.idle_visible_seconds,- include_stale=include_stale,- )-- def load_latest_state(self) -> None:- if self.latest_state_path is None or not self.latest_state_path.exists():- return- try:- data = json.loads(self.latest_state_path.read_text())- except Exception:- return- statuses = data.get("statuses") if isinstance(data, dict) else None- if not isinstance(statuses, list):- return- loaded: dict[str, AgentStatus] = {}- for status_data in statuses:- status = agent_status_from_dict(status_data)- if status is not None:- loaded[status.agent_id] = status- self.statuses_by_key.update(loaded)-- def write_latest_state(self) -> None:- if self.latest_state_path is None:- return- now = datetime.now(timezone.utc)- payload = {- "updated_at": now.isoformat(),- "statuses": [- status.to_dict(now) for status in self.statuses_by_key.values()- ],- }- try:- self.latest_state_path.parent.mkdir(parents=True, exist_ok=True)- temp_path = self.latest_state_path.with_suffix(".json.tmp")- temp_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")- temp_path.replace(self.latest_state_path)- except OSError:- pass---def default_sources(settings: AgentMonitorSettings | None = None) -> tuple[SourceSpec, ...]:- active_settings = load_settings() if settings is None else settings- sources = [- SourceSpec("codex", detect_log_path("codex")),- ]- if active_settings.codex_transcripts_enabled:- sources.append(SourceSpec(CODEX_TRANSCRIPT_PROVIDER, Path.home() / ".codex" / "sessions"))- sources.append(SourceSpec("claude", detect_log_path("claude")))- if active_settings.claude_transcripts_enabled:- sources.append(SourceSpec(CLAUDE_TRANSCRIPT_PROVIDER, Path.home() / ".claude" / "projects"))- return unique_sources(sources)---def unique_sources(sources: Iterable[SourceSpec]) -> tuple[SourceSpec, ...]:- seen: set[tuple[str, str]] = set()- result: list[SourceSpec] = []- for source in sources:- key = (source.provider, str(source.path.expanduser()))- if key in seen:- continue- seen.add(key)- result.append(SourceSpec(source.provider, source.path.expanduser()))- return tuple(result)---def iter_codex_transcript_records(root: Path) -> Iterable[HookEvent]:- for path in recent_transcript_files(root):- yield from iter_codex_transcript_file(path)---def recent_transcript_files(- root: Path,- *,- limit: int = CODEX_TRANSCRIPT_MAX_FILES,-) -> list[Path]:- try:- files = [path for path in root.rglob("*.jsonl") if path.is_file()]- except OSError:- return []-- files.sort(key=lambda path: safe_mtime(path), reverse=True)- return files[:limit]---def safe_mtime(path: Path) -> float:- try:- return path.stat().st_mtime- except OSError:- return 0.0---def file_signature(path: Path) -> tuple[float, int] | None:- try:- stat = path.stat()- except OSError:- return None- return (stat.st_mtime, stat.st_size)---def iter_codex_transcript_file(path: Path) -> Iterable[HookEvent]:- session_id = codex_session_id_from_path(path)- if session_id is None:- return-- cwd = None- turn_id = None- for line in read_recent_lines(path, CODEX_TRANSCRIPT_MAX_LINES):- try:- row = json.loads(line)- except json.JSONDecodeError:- continue- if not isinstance(row, dict):- continue-- timestamp = parse_transcript_timestamp(row)- row_type = row.get("type")- payload = row.get("payload")- if not isinstance(payload, dict):- continue-- if row_type == "turn_context":- cwd = _string_or_none(payload.get("cwd")) or cwd- turn_id = _string_or_none(payload.get("turn_id")) or turn_id- continue-- event = codex_transcript_event(- payload,- session_id=session_id,- turn_id=turn_id,- cwd=cwd,- timestamp=timestamp,- path=path,- )- if event is not None:- yield event---def codex_session_id_from_path(path: Path) -> str | None:- match = re.search(- r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})",- path.name,- flags=re.IGNORECASE,- )- return match.group(1) if match else None---def parse_transcript_timestamp(row: dict[str, Any]) -> datetime:- from .models import parse_datetime-- return parse_datetime(row.get("timestamp"))---def codex_transcript_event(- payload: dict[str, Any],- *,- session_id: str,- turn_id: str | None,- cwd: str | None,- timestamp: datetime,- path: Path,-) -> HookEvent | None:- payload_type = payload.get("type")-- if payload_type == "message":- role = payload.get("role")- if role == "user":- prompt = message_text_from_content(payload.get("content"))- return HookEvent(- provider="codex",- logged_at=timestamp,- event_name="UserPromptSubmit",- raw={- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "turn_id": turn_id,- "cwd": cwd,- "prompt": prompt,- "transcript_path": str(path),- "source": CODEX_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- turn_id=turn_id,- cwd=cwd,- message=prompt,- )- if role == "assistant":- message = message_text_from_content(payload.get("content"))- return HookEvent(- provider="codex",- logged_at=timestamp,- event_name="Stop",- raw={- "hook_event_name": "Stop",- "session_id": session_id,- "turn_id": turn_id,- "cwd": cwd,- "last_assistant_message": message,- "transcript_path": str(path),- "source": CODEX_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- turn_id=turn_id,- cwd=cwd,- message=message,- )-- if payload_type == "function_call":- tool_name = _string_or_none(payload.get("name"))- return HookEvent(- provider="codex",- logged_at=timestamp,- event_name="PreToolUse",- raw={- "hook_event_name": "PreToolUse",- "session_id": session_id,- "turn_id": turn_id,- "cwd": cwd,- "tool_name": tool_name,- "tool_input": payload.get("arguments"),- "tool_use_id": payload.get("call_id"),- "transcript_path": str(path),- "source": CODEX_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- turn_id=turn_id,- cwd=cwd,- tool_name=tool_name,- )-- if payload_type == "function_call_output":- return HookEvent(- provider="codex",- logged_at=timestamp,- event_name="PostToolUse",- raw={- "hook_event_name": "PostToolUse",- "session_id": session_id,- "turn_id": turn_id,- "cwd": cwd,- "tool_response": payload.get("output"),- "tool_use_id": payload.get("call_id"),- "transcript_path": str(path),- "source": CODEX_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- turn_id=turn_id,- cwd=cwd,- )-- if payload_type == "task_complete":- message = _string_or_none(payload.get("last_agent_message")) or ""- return HookEvent(- provider="codex",- logged_at=timestamp,- event_name="Stop",- raw={- "hook_event_name": "Stop",- "session_id": session_id,- "turn_id": turn_id,- "cwd": cwd,- "last_assistant_message": message,- "transcript_path": str(path),- "source": CODEX_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- turn_id=turn_id,- cwd=cwd,- message=message,- )-- return None---def iter_claude_transcript_records(root: Path) -> Iterable[HookEvent]:- for path in recent_transcript_files(root, limit=CLAUDE_TRANSCRIPT_MAX_FILES):- yield from iter_claude_transcript_file(path)---def iter_claude_transcript_file(path: Path) -> Iterable[HookEvent]:- session_id = claude_session_id_from_path(path)- if session_id is None:- return-- last_event_at = None- last_event_name = None- last_cwd = None- emitted_event = False- for line in read_recent_lines(path, CLAUDE_TRANSCRIPT_MAX_LINES):- try:- row = json.loads(line)- except json.JSONDecodeError:- continue- if not isinstance(row, dict):- continue-- last_cwd = _string_or_none(row.get("cwd")) or last_cwd- event = claude_transcript_event(- row,- session_id=session_id,- timestamp=parse_transcript_timestamp(row),- path=path,- )- if event is not None:- emitted_event = True- last_event_at = event.logged_at- last_event_name = event.event_name- last_cwd = event.cwd or last_cwd- yield event-- if not emitted_event or last_event_at is None:- return- if not claude_mtime_can_extend_event(last_event_name):- return-- mtime = datetime.fromtimestamp(safe_mtime(path), timezone.utc)- if (mtime - last_event_at).total_seconds() <= CLAUDE_TRANSCRIPT_MTIME_HEARTBEAT_SKEW_SECONDS:- return-- yield HookEvent(- provider="claude",- logged_at=mtime,- event_name="Notification",- raw={- "hook_event_name": "Notification",- "session_id": session_id,- "cwd": last_cwd,- "notification_type": "transcript_mtime",- "message": "Claude transcript file changed after the last embedded event.",- "transcript_path": str(path),- "source": CLAUDE_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- cwd=last_cwd,- message="Claude transcript file changed after the last embedded event.",- )---def claude_mtime_can_extend_event(event_name: str | None) -> bool:- return event_name in {- "UserPromptSubmit",- "PreToolUse",- "PostToolUse",- "PreCompact",- "PostCompact",- "SubagentStart",- }---def claude_session_id_from_path(path: Path) -> str | None:- match = re.search(- r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})",- path.name,- flags=re.IGNORECASE,- )- return match.group(1) if match else None---def claude_transcript_event(- row: dict[str, Any],- *,- session_id: str,- timestamp: datetime,- path: Path,-) -> HookEvent | None:- row_type = row.get("type")- cwd = _string_or_none(row.get("cwd"))-- if row_type == "user":- if row.get("isMeta") is True:- return None-- message = row.get("message")- content = message.get("content") if isinstance(message, dict) else None- if claude_content_has_tool_result(content) or row.get("toolUseResult") is not None:- failed = claude_tool_result_failed(content, row.get("toolUseResult"))- event_name = "PostToolUseFailure" if failed else "PostToolUse"- return HookEvent(- provider="claude",- logged_at=timestamp,- event_name=event_name,- raw={- "hook_event_name": event_name,- "session_id": session_id,- "cwd": cwd,- "tool_response": row.get("toolUseResult") or content,- "tool_use_id": row.get("sourceToolAssistantUUID"),- "transcript_path": str(path),- "source": CLAUDE_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- cwd=cwd,- )-- prompt = message_text_from_content(content)- if not prompt:- return None- if prompt.strip().startswith("<task-notification>"):- return None- return HookEvent(- provider="claude",- logged_at=timestamp,- event_name="UserPromptSubmit",- raw={- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": cwd,- "prompt": prompt,- "transcript_path": str(path),- "source": CLAUDE_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- cwd=cwd,- message=prompt,- )-- if row_type == "assistant":- message = row.get("message")- if not isinstance(message, dict):- return None-- content = message.get("content")- tool_use = first_claude_tool_use(content)- if tool_use is not None:- tool_name = _string_or_none(tool_use.get("name"))- return HookEvent(- provider="claude",- logged_at=timestamp,- event_name="PreToolUse",- raw={- "hook_event_name": "PreToolUse",- "session_id": session_id,- "cwd": cwd,- "tool_name": tool_name,- "tool_input": tool_use.get("input"),- "tool_use_id": tool_use.get("id"),- "transcript_path": str(path),- "source": CLAUDE_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- cwd=cwd,- tool_name=tool_name,- )-- if message.get("stop_reason") == "end_turn":- text = message_text_from_content(content)- return HookEvent(- provider="claude",- logged_at=timestamp,- event_name="Stop",- raw={- "hook_event_name": "Stop",- "session_id": session_id,- "cwd": cwd,- "last_assistant_message": text,- "transcript_path": str(path),- "source": CLAUDE_TRANSCRIPT_PROVIDER,- },- session_id=session_id,- cwd=cwd,- message=text,- )-- return None---def claude_content_has_tool_result(content: object) -> bool:- if not isinstance(content, list):- return False- return any(- isinstance(item, dict) and item.get("type") == "tool_result"- for item in content- )---def claude_tool_result_failed(content: object, tool_use_result: object) -> bool:- if isinstance(content, list):- for item in content:- if isinstance(item, dict) and item.get("type") == "tool_result":- if item.get("is_error") is True:- return True- if _tool_response_looks_failed(item.get("content")):- return True- return _tool_response_looks_failed(tool_use_result)---def first_claude_tool_use(content: object) -> dict[str, Any] | None:- if not isinstance(content, list):- return None- for item in content:- if isinstance(item, dict) and item.get("type") == "tool_use":- return item- return None---def message_text_from_content(content: object) -> str:- if isinstance(content, str):- return content- if not isinstance(content, list):- return ""-- parts: list[str] = []- for item in content:- if not isinstance(item, dict):- continue- text = item.get("text")- if isinstance(text, str):- parts.append(text)- return "\n".join(parts)---def _string_or_none(value: object) -> str | None:- return value if isinstance(value, str) and value else None---def metadata_for_record(- record: HookEvent,- metadata_by_session: dict[str, StatusMetadata],- metadata_by_status: dict[str, StatusMetadata],-) -> StatusMetadata:- session_metadata = None- if record.session_id:- session_metadata = metadata_by_session.setdefault(- f"{record.provider}:session:{record.session_id}",- StatusMetadata(),- )- update_metadata(session_metadata, record)-- status_metadata = metadata_by_status.setdefault(record.status_key, StatusMetadata())- update_metadata(status_metadata, record)-- if session_metadata is None:- return status_metadata- return StatusMetadata(- cwd=status_metadata.cwd or session_metadata.cwd,- title=status_metadata.title or session_metadata.title,- )---def update_metadata(metadata: StatusMetadata, record: HookEvent) -> None:- if record.cwd:- metadata.cwd = record.cwd-- title = title_from_event(record)- if title:- metadata.title = title---def status_from_event(record: HookEvent, metadata: StatusMetadata | None = None) -> AgentStatus | None:- mode = mode_for_event(record)- if mode is None:- return None-- metadata = metadata or StatusMetadata(cwd=record.cwd)- if should_ignore_record(record, metadata):- return None-- if record.agent_id:- short_id = record.agent_id[:8]- fallback = f"{provider_label(record.provider)} agent {short_id}"- display_name = display_name_for_record(record, metadata, f"agent {short_id}", fallback)- elif record.session_id:- short_id = record.session_id[:8]- fallback = f"{provider_label(record.provider)} session {short_id}"- display_name = display_name_for_record(record, metadata, short_id, fallback)- else:- display_name = provider_label(record.provider)-- return AgentStatus(- provider=record.provider,- agent_id=record.status_key,- display_name=display_name,- mode=mode,- updated_at=record.logged_at,- event_name=record.event_name,- session_id=record.session_id,- cwd=record.cwd,- tool_name=record.tool_name,- message=record.message,- )---def mode_for_event(record: HookEvent) -> AgentMode | None:- event = record.event_name- raw = record.raw- explicit_mode = explicit_mode_for_record(record)- if explicit_mode is not None:- return explicit_mode-- if event in {"PostToolUseFailure"}:- return AgentMode.BLOCKED_ERROR- if event in {"PermissionRequest"}:- return AgentMode.WAITING_FOR_INPUT- if event == "Notification":- text = " ".join(- str(raw.get(key, ""))- for key in ("notification_type", "message")- ).lower()- if "waiting" in text or "idle_prompt" in text or "input" in text:- return AgentMode.WAITING_FOR_INPUT- return AgentMode.WORKING- if event in {"PreToolUse"}:- return AgentMode.TOOL_RUNNING- if event in {"PostToolUse"}:- if _tool_response_looks_failed(raw.get("tool_response")):- return AgentMode.BLOCKED_ERROR- return AgentMode.WORKING- if event in {"UserPromptSubmit", "PreCompact", "PostCompact", "SubagentStart"}:- return AgentMode.WORKING- if event in {"Stop", "SubagentStop"}:- if _assistant_message_asks_question(raw.get("last_assistant_message")):- return AgentMode.WAITING_FOR_INPUT- return AgentMode.COMPLETED- if event in {"SessionEnd"}:- return AgentMode.COMPLETED- if event == "SessionStart":- return AgentMode.IDLE_READY- return None---def explicit_mode_for_record(record: HookEvent) -> AgentMode | None:- raw = record.raw- for key in ("sidepulse_status", "sidepulse_mode", "agent_monitor_status", "agent_monitor_mode"):- mode = explicit_mode_from_value(raw.get(key))- if mode is not None:- return mode-- return explicit_mode_from_message(- raw.get("last_assistant_message") or raw.get("message")- )---def explicit_mode_from_value(value: object) -> AgentMode | None:- if not isinstance(value, str):- return None-- normalized = re.sub(r"[^a-z0-9]+", "_", value.strip().lower()).strip("_")- return {- "ask": AgentMode.WAITING_FOR_INPUT,- "question": AgentMode.WAITING_FOR_INPUT,- "waiting": AgentMode.WAITING_FOR_INPUT,- "waiting_for_input": AgentMode.WAITING_FOR_INPUT,- "input": AgentMode.WAITING_FOR_INPUT,- "blocked": AgentMode.BLOCKED_ERROR,- "error": AgentMode.BLOCKED_ERROR,- "blocked_error": AgentMode.BLOCKED_ERROR,- "working": AgentMode.WORKING,- "tool_running": AgentMode.TOOL_RUNNING,- "progress": AgentMode.LONG_TASK_PROGRESS,- "long_task_progress": AgentMode.LONG_TASK_PROGRESS,- "done": AgentMode.COMPLETED,- "complete": AgentMode.COMPLETED,- "completed": AgentMode.COMPLETED,- "idle": AgentMode.IDLE_READY,- "ready": AgentMode.IDLE_READY,- "idle_ready": AgentMode.IDLE_READY,- }.get(normalized)---def explicit_mode_from_message(message: object) -> AgentMode | None:- if not isinstance(message, str):- return None-- text = strip_markdown_code_blocks(message)- patterns = (- r"(?im)^\s*<!--\s*(?:sidepulse|agent[-_ ]monitor)\s*:\s*([a-z0-9_ -]+)\s*-->\s*$",- r"(?im)^\s*<!--\s*(?:sidepulse|agent[-_ ]monitor)\s+(?:status|mode)\s*:\s*([a-z0-9_ -]+)\s*-->\s*$",- r"(?im)^\s*\[(?:sidepulse|agent[-_ ]monitor)\s+(?:status|mode)\s*:\s*([a-z0-9_ -]+)\]\s*$",- )- for pattern in patterns:- for match in re.finditer(pattern, text):- mode = explicit_mode_from_value(match.group(1))- if mode is not None:- return mode-- return None---def strip_markdown_code_blocks(text: str) -> str:- return re.sub(r"```.*?```", "", text, flags=re.DOTALL)---def strip_markdown_inline_code(text: str) -> str:- return re.sub(r"`[^`\n]*`", "", text)---def aggregate_status(- statuses: tuple[AgentStatus, ...],- stale_statuses: tuple[AgentStatus, ...] = (),-) -> AggregateStatus:- if not statuses:- return AggregateStatus(- mode=AgentMode.IDLE_READY,- active_count=0,- stale_count=len(stale_statuses),- representative=None,- )-- representative = min(- statuses,- key=lambda status: (- MODE_PRIORITY.get(status.mode, MODE_PRIORITY[AgentMode.UNKNOWN]),- -status.updated_at.timestamp(),- ),- )-- return AggregateStatus(- mode=representative.mode,- active_count=sum(1 for status in statuses if status_counts_active(status)),- stale_count=len(stale_statuses),- representative=representative,- )---def snapshot_from_statuses(- statuses: tuple[AgentStatus, ...],- *,- sources: tuple[SourceSpec, ...],- collected_at: datetime,- stale_after_seconds: float,- tool_running_timeout_seconds: float,- completed_visible_seconds: float,- idle_visible_seconds: float,- include_stale: bool = False,-) -> MonitorSnapshot:- fresh: list[AgentStatus] = []- stale: list[AgentStatus] = []- for status in statuses:- is_stale = status_is_stale(- status,- collected_at,- stale_after_seconds=stale_after_seconds,- tool_running_timeout_seconds=tool_running_timeout_seconds,- completed_visible_seconds=completed_visible_seconds,- idle_visible_seconds=idle_visible_seconds,- )- current = _replace_stale(status, is_stale)- if is_stale:- stale.append(current)- else:- fresh.append(current)-- if any(status_counts_active(status) for status in fresh):- inactive = [status for status in fresh if not status_counts_active(status)]- fresh = [status for status in fresh if status_counts_active(status)]- stale.extend(_replace_stale(status, True) for status in inactive)-- fresh.sort(key=lambda status: (status.priority, -status.updated_at.timestamp()))- stale.sort(key=lambda status: (status.priority, -status.updated_at.timestamp()))-- visible = tuple(fresh)- stale_visible = tuple(stale if include_stale else stale)- return MonitorSnapshot(- aggregate=aggregate_status(visible, stale_visible),- statuses=visible,- stale_statuses=stale_visible,- sources=sources,- collected_at=collected_at,- )---def status_is_stale(- status: AgentStatus,- now: datetime,- *,- stale_after_seconds: float,- tool_running_timeout_seconds: float,- completed_visible_seconds: float,- idle_visible_seconds: float,-) -> bool:- age = status.age_seconds(now)- if status.mode == AgentMode.COMPLETED and completed_visible_seconds >= 0:- return age > completed_visible_seconds- if status.mode == AgentMode.IDLE_READY and idle_visible_seconds >= 0:- return age > idle_visible_seconds- return (- age > stale_after_seconds- or (- status.mode == AgentMode.TOOL_RUNNING- and tool_running_timeout_seconds > 0- and age > tool_running_timeout_seconds- )- )---def agent_status_from_dict(data: object) -> AgentStatus | None:- if not isinstance(data, dict):- return None- try:- provider = str(data["provider"])- agent_id = str(data["agent_id"])- session_id = _string_or_none(data.get("session_id"))- cwd = _string_or_none(data.get("cwd"))- display_name = str(data["display_name"])- if provider == "codex" and session_id:- title = codex_session_title(session_id)- if title:- display_name = display_name_from_parts(- project_name(cwd),- title,- session_id[:8],- display_name,- )-- mode = AgentMode(str(data["mode"]))- updated_at = parse_datetime(data["updated_at"])- return AgentStatus(- provider=provider,- agent_id=agent_id,- display_name=display_name,- mode=mode,- updated_at=updated_at,- event_name=str(data["event_name"]),- session_id=session_id,- cwd=cwd,- tool_name=_string_or_none(data.get("tool_name")),- message=_string_or_none(data.get("message")),- stale=bool(data.get("stale", False)),- )- except Exception:- return None---def status_counts_active(status: AgentStatus) -> bool:- return status.mode not in {AgentMode.COMPLETED, AgentMode.IDLE_READY}---def track_pending_permissions(- record: HookEvent,- pending_permissions_by_key: dict[str, set[str]],-) -> None:- signature = permission_signature(record)- if record.event_name == "PermissionRequest" and signature:- pending_permissions_by_key.setdefault(record.status_key, set()).add(signature)- return-- if record.event_name == "PostToolUse" and signature:- pending = pending_permissions_by_key.get(record.status_key)- if pending is not None:- pending.discard(signature)- if not pending:- pending_permissions_by_key.pop(record.status_key, None)- return-- if record.event_name in {"Stop", "SessionEnd", "UserPromptSubmit"}:- pending_permissions_by_key.pop(record.status_key, None)---def permission_signature(record: HookEvent) -> str | None:- raw = record.raw- tool_name = _string_or_none(raw.get("tool_name")) or record.tool_name- tool_input = raw.get("tool_input")- if not isinstance(tool_input, dict):- return None-- command = _string_or_none(tool_input.get("command"))- if command:- return f"{tool_name or ''}\0{command}"-- return None---def should_ignore_status_transition(- previous: AgentStatus | None,- current: AgentStatus,- pending_permission_signatures: set[str],-) -> bool:- if (- previous is not None- and previous.mode == AgentMode.COMPLETED- and current.event_name == "Notification"- ):- return True-- return (- previous is not None- and previous.mode == AgentMode.WAITING_FOR_INPUT- and previous.event_name == "PermissionRequest"- and current.event_name != "PermissionRequest"- and bool(pending_permission_signatures)- )---def should_ignore_record(record: HookEvent, metadata: StatusMetadata) -> bool:- if record.provider != "codex":- return False-- raw = record.raw- text = " ".join(- part- for part in (- metadata.title,- _string_or_none(raw.get("prompt")),- _string_or_none(raw.get("message")),- _string_or_none(raw.get("last_assistant_message")),- )- if part- ).lower()- if not text:- return False-- internal_prompts = (- "generate 0 to 3 hyperpersonalized suggestions",- "you are an expert at upholding safety and compliance standards",- )- return any(prompt in text for prompt in internal_prompts)---def read_recent_lines(path: Path, max_lines: int) -> list[str]:- if max_lines <= 0:- return []-- chunk_size = 8192- chunks: list[bytes] = []- newline_count = 0-- with path.open("rb") as handle:- handle.seek(0, 2)- position = handle.tell()- while position > 0 and newline_count <= max_lines:- read_size = min(chunk_size, position)- position -= read_size- handle.seek(position)- chunk = handle.read(read_size)- chunks.append(chunk)- newline_count += chunk.count(b"\n")-- data = b"".join(reversed(chunks))- lines = data.decode("utf-8", errors="replace").splitlines()- return lines[-max_lines:]---def _replace_stale(status: AgentStatus, stale: bool) -> AgentStatus:- if status.stale == stale:- return status- return AgentStatus(- provider=status.provider,- agent_id=status.agent_id,- display_name=status.display_name,- mode=status.mode,- updated_at=status.updated_at,- event_name=status.event_name,- session_id=status.session_id,- cwd=status.cwd,- tool_name=status.tool_name,- message=status.message,- stale=stale,- )---def title_from_event(record: HookEvent) -> str | None:- if record.provider == "codex":- title = codex_session_title(record.session_id)- if title:- return title-- if record.event_name != "UserPromptSubmit":- return None- return summarize_prompt(record.raw.get("prompt"))---def codex_session_title(session_id: str | None) -> str | None:- if not session_id:- return None- return codex_session_titles().get(session_id)---def codex_session_titles(path: Path | None = None) -> dict[str, str]:- index_path = path or codex_session_index_path()- try:- stat = index_path.stat()- except OSError:- return {}-- with _codex_session_index_lock:- global _codex_session_index_cache- cached = _codex_session_index_cache- if (- cached is not None- and cached.path == index_path- and cached.mtime == stat.st_mtime- and cached.size == stat.st_size- ):- return cached.titles-- titles: dict[str, str] = {}- for line in read_recent_lines(index_path, CODEX_SESSION_INDEX_MAX_LINES):- try:- row = json.loads(line)- except json.JSONDecodeError:- continue- if not isinstance(row, dict):- continue-- session_id = _string_or_none(row.get("id"))- title = _string_or_none(row.get("thread_name"))- if session_id and title:- titles[session_id] = truncate_text(title.strip(), 72)-- _codex_session_index_cache = CachedCodexSessionIndex(- path=index_path,- mtime=stat.st_mtime,- size=stat.st_size,- titles=titles,- )- return titles---def codex_session_index_path() -> Path:- return Path.home() / ".codex" / "session_index.jsonl"---def summarize_prompt(value: object, max_len: int = 72) -> str | None:- if not isinstance(value, str):- return None-- text = value.strip()- if not text or text.startswith("<task-notification>"):- return None-- marker = re.search(- r"##\s+My request for [^:\n]+:\s*(.*)",- text,- flags=re.IGNORECASE | re.DOTALL,- )- if marker:- text = marker.group(1)-- text = re.sub(r"```.*?```", " ", text, flags=re.DOTALL)- text = re.sub(r"`([^`]+)`", r"\1", text)- text = re.sub(- r"(['\"])(?:~|/Users|/var|/private|/tmp)[^'\"]+\1",- r"\1...\1",- text,- )- text = re.sub(r"(?:~|/Users|/var|/private|/tmp)/[^\s,;)'\"`]+", "...", text)- text = re.sub(r"<[^>]+>", " ", text)- text = re.sub(r"#+\s*", " ", text)- text = re.sub(r"\s+", " ", text).strip(" -:\n\t")-- if not text:- return None- return truncate_text(text, max_len)---def display_name_for_record(- record: HookEvent,- metadata: StatusMetadata,- short_id: str,- fallback: str,-) -> str:- project = project_name(metadata.cwd or record.cwd)- title = metadata.title-- return display_name_from_parts(project, title, short_id, fallback)---def display_name_from_parts(- project: str | None,- title: str | None,- short_id: str,- fallback: str,-) -> str:- if project and title:- return truncate_text(f"{project}: {title} ({short_id})", 96)- if title:- return truncate_text(f"{title} ({short_id})", 96)- if project:- return truncate_text(f"{project} ({short_id})", 96)- return fallback---def project_name(cwd: str | None) -> str | None:- if not cwd:- return None- name = Path(cwd).name- return name or cwd---def truncate_text(text: str, max_len: int) -> str:- if len(text) <= max_len:- return text- trimmed = text[: max_len - 1].rstrip()- boundary = max(trimmed.rfind(" "), trimmed.rfind(","), trimmed.rfind(";"))- if boundary >= max_len // 2:- trimmed = trimmed[:boundary].rstrip()- return f"{trimmed}..."---def _tool_response_looks_failed(response: object) -> bool:- if isinstance(response, dict):- if response.get("interrupted") is True:- return True- if response.get("success") is False:- return True- if response.get("exit_code") not in (None, 0):- return True- return False-- if isinstance(response, str):- text = response.lower()- return "exit code: 1" in text or "traceback" in text-- return False---def _assistant_message_asks_question(message: object) -> bool:- if not isinstance(message, str):- return False-- text = strip_markdown_inline_code(strip_markdown_code_blocks(message))- lines = [line.strip() for line in text.splitlines() if line.strip()]- if not lines:- return False-- for line in reversed(lines[-8:]):- if _assistant_status_line(line):- continue- if _assistant_line_asks_question(line):- return True-- return False---def _assistant_status_line(line: str) -> bool:- text = line.strip().lower()- return text.startswith(- (- "* cogitated ",- "* recap:",- "※ recap:",- "recap:",- )- )---def _assistant_line_asks_question(line: str) -> bool:- text = line.strip()- if not text:- return False-- lowered = text.lower()- if text.endswith(":"):- return False- if _assistant_line_is_casual_closing_question(lowered):- return False- if re.search(- r"(?:^|[.!?]\s+)(?:want me to|need me to|should i|should we|do you want me to)\b",- lowered,- ):- return True-- required_question_prefixes = (- "which ",- "what ",- "where ",- "when ",- "who ",- "why ",- "how ",- "can you ",- "could you ",- "please confirm",- "please choose",- "choose ",- "need me to ",- "want me to ",- "should i ",- "should we ",- "do you want me to ",- )- if text.endswith("?"):- return lowered.startswith(required_question_prefixes)-- return lowered.startswith(- (- "please confirm",- "please choose",- "choose ",- "need me to ",- "want me to ",- "should i ",- "should we ",- "do you want me to ",- )- )---def _assistant_line_is_casual_closing_question(lowered: str) -> bool:- return lowered.startswith(- (- "anything else",- "any other",- "all good",- "need anything else",- "want anything else",- "anything you want",- "anything you'd like",- "anything else you want",- "anything else you'd like",- )- )diff --git a/src/agent_monitor/device_writer.py b/src/agent_monitor/device_writer.pydeleted file mode 100644index 3f6a753..0000000--- a/src/agent_monitor/device_writer.py+++ /dev/null@@ -1,175 +0,0 @@-from __future__ import annotations--from dataclasses import dataclass-from pathlib import Path-from typing import Iterable--DEFAULT_FILE_NAME = "LEDS.LED"-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-MOUNT_ROOT = Path("/Volumes")-DEVICE_NAME_HINTS = (- "sidepulse",- "pulsedot",- "pixiepulse",- "pixiedot",-)---class DeviceWriteError(RuntimeError):- pass---@dataclass(frozen=True)-class DeviceCandidate:- root: Path- target: Path- reason: str---def write_led_program(- text: str,- *,- device_path: Path | None = None,- file_name: str = DEFAULT_FILE_NAME,- dry_run: bool = False,-) -> Path:- program = normalize_led_text(text)- validate_led_text(program)- target = resolve_target_path(device_path=device_path, file_name=file_name)-- if dry_run:- return target-- target.parent.mkdir(parents=True, exist_ok=True)- target.write_text(program, encoding="utf-8")- return target---def normalize_led_text(text: str) -> str:- return decode_simple_escapes(text)---def decode_simple_escapes(text: str) -> str:- output: list[str] = []- index = 0- while index < len(text):- char = text[index]- if char != "\\" or index + 1 >= len(text):- output.append(char)- index += 1- continue-- next_char = text[index + 1]- if next_char == "n":- output.append("\n")- index += 2- elif next_char == "r":- output.append("\r")- index += 2- elif next_char == "t":- output.append("\t")- index += 2- elif next_char == "\\":- output.append("\\")- index += 2- else:- output.append(char)- index += 1- return "".join(output)---def validate_led_text(text: str) -> None:- if not text:- raise DeviceWriteError("LED program is empty.")-- byte_count = len(text.encode("utf-8"))- if byte_count > MAX_LED_BYTES:- raise DeviceWriteError(- f"LED program is {byte_count} bytes; max is {MAX_LED_BYTES}."- )-- line_count = len(text.splitlines()) or 1- if line_count > MAX_LED_LINES:- raise DeviceWriteError(- f"LED program has {line_count} lines; max is {MAX_LED_LINES}."- )---def resolve_target_path(- *,- device_path: Path | None = None,- file_name: str = DEFAULT_FILE_NAME,-) -> Path:- if device_path is not None:- return target_from_device_path(device_path.expanduser(), file_name)-- candidates = discover_devices(file_name=file_name)- if not candidates:- raise DeviceWriteError(- "No SidePulse or PulseDot device found. "- "Mount the device, or pass --device /Volumes/PulseDot."- )- if len(candidates) > 1:- lines = "\n".join(f" {candidate.root}" for candidate in candidates)- raise DeviceWriteError(- "Multiple possible devices found. Pass --device with one of:\n" + lines- )- return candidates[0].target---def target_from_device_path(path: Path, file_name: str) -> Path:- if path.name.upper() in KNOWN_LED_FILE_NAMES:- return path- return path / file_name---def discover_devices(- *,- mount_root: Path = MOUNT_ROOT,- file_name: str = DEFAULT_FILE_NAME,-) -> list[DeviceCandidate]:- if not mount_root.exists():- return []-- candidates: list[DeviceCandidate] = []- for volume in sorted(iter_mounts(mount_root), key=lambda path: path.name.lower()):- target = target_from_device_path(volume, file_name)- name_matches = is_device_name(volume.name)- file_exists = path_exists(target)- if file_exists:- candidates.append(DeviceCandidate(volume, target, f"contains {target.name}"))- elif name_matches:- candidates.append(DeviceCandidate(volume, target, "name matches device"))- return candidates--def iter_mounts(mount_root: Path) -> Iterable[Path]:- try:- children = list(mount_root.iterdir())- except OSError:- return ()-- mounts: list[Path] = []- for child in children:- if child.name in {".timemachine", "Macintosh HD"}:- continue- try:- if child.is_dir():- mounts.append(child)- except OSError:- continue- return mounts---def path_exists(path: Path) -> bool:- try:- return path.exists()- except OSError:- return False---def is_device_name(name: str) -> bool:- normalized = "".join(char for char in name.lower() if char.isalnum())- return any(hint in normalized for hint in DEVICE_NAME_HINTS)diff --git a/src/agent_monitor/hook.py b/src/agent_monitor/hook.pydeleted file mode 100644index 9879464..0000000--- a/src/agent_monitor/hook.py+++ /dev/null@@ -1,56 +0,0 @@-from __future__ import annotations--import json-import sys-from datetime import datetime, timezone-from pathlib import Path-from typing import Any--from .ipc import send_hook_event---def format_hook_payload(- provider: str,- payload_text: str,- *,- logged_at: str | None = None,-) -> dict[str, Any]:- timestamp = logged_at or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")- try:- payload: Any = json.loads(payload_text or "{}")- except json.JSONDecodeError as exc:- payload = {- "hook_event_name": "ParseError",- "raw": payload_text,- "parse_error": str(exc),- }-- if provider == "codex":- return {"logged_at": timestamp, "event": payload}- if isinstance(payload, dict):- line = dict(payload)- line["logged_at"] = line.get("logged_at") or timestamp- return line- return {"logged_at": timestamp, "event": payload}---def write_hook_line(log_path: Path, line: dict[str, Any]) -> None:- log_path = log_path.expanduser()- log_path.parent.mkdir(parents=True, exist_ok=True)- with log_path.open("a", encoding="utf-8") as handle:- handle.write(json.dumps(line, separators=(",", ":"), ensure_ascii=False) + "\n")---def write_hook_payload(provider: str, log_path: Path, payload_text: str) -> None:- line = format_hook_payload(provider, payload_text)- write_hook_line(log_path, line)---def hook_log_main(provider: str, log_path: Path) -> int:- try:- line = format_hook_payload(provider, sys.stdin.read())- send_hook_event(provider, line)- write_hook_line(log_path, line)- except Exception:- return 0- return 0diff --git a/src/agent_monitor/hook_entry.py b/src/agent_monitor/hook_entry.pyindex 8b545f5..a13eada 100644--- a/src/agent_monitor/hook_entry.py+++ b/src/agent_monitor/hook_entry.py@@ -1,28 +1,20 @@-"""Minimal, dependency-free process entry point for Codex and Claude hooks."""+"""Compatibility launcher for installations that predate the sidepulse rename."""++from __future__ import annotations-import json-import os-import socketimport sys-from datetime import datetime, timezonefrom pathlib import Path-provider, log_path = sys.argv[sys.argv.index("--provider") + 1], Path(sys.argv[sys.argv.index("--log") + 1]).expanduser()-try:- event = json.loads(sys.stdin.read() or "{}")-except json.JSONDecodeError:- event = {"hook_event_name": "ParseError"}-now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")-line = {"logged_at": now, "event": event} if provider == "codex" else dict(event, logged_at=event.get("logged_at", now)) if isinstance(event, dict) else {"logged_at": now, "event": event}-log_path.parent.mkdir(parents=True, exist_ok=True)-with log_path.open("a", encoding="utf-8") as output:- output.write(json.dumps(line, separators=(",", ":"), ensure_ascii=False) + "\n")-state = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state")) / "sidepulse/agent-monitor/events.sock"+SOURCE_ROOT = Path(__file__).resolve().parents[1]+if str(SOURCE_ROOT) not in sys.path:+ sys.path.insert(0, str(SOURCE_ROOT))+try:- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:- client.settimeout(0.05)- client.connect(str(state))- client.sendall(json.dumps({"provider": provider, "line": line}, separators=(",", ":"), ensure_ascii=False).encode())-except OSError:- pass+ from sidepulse.hook import hook_log_main+except ImportError:+ from sidepulse.hook import hook_log_main+++if __name__ == "__main__":+ raise SystemExit(hook_log_main())diff --git a/src/agent_monitor/install.py b/src/agent_monitor/install.pydeleted file mode 100644index 5c9b763..0000000--- a/src/agent_monitor/install.py+++ /dev/null@@ -1,531 +0,0 @@-from __future__ import annotations--import json-import os-import queue-import re-import shutil-import shlex-import subprocess-import sys-import threading-import time-from dataclasses import dataclass-from datetime import datetime, timezone-from pathlib import Path-from typing import Any--from .providers import CLAUDE_EVENTS, CODEX_EVENTS, detect_log_path--MANAGED_START = "# >>> agent-monitor hooks >>>"-MANAGED_END = "# <<< agent-monitor hooks <<<"---@dataclass(frozen=True)-class InstallResult:- provider: str- config_path: Path- log_path: Path- changed: bool- backup_path: Path | None = None- dry_run: bool = False-- def to_dict(self) -> dict[str, Any]:- return {- "provider": self.provider,- "config_path": str(self.config_path),- "log_path": str(self.log_path),- "changed": self.changed,- "backup_path": str(self.backup_path) if self.backup_path else None,- "dry_run": self.dry_run,- }---def install_codex_hooks(- log_path: Path | None = None,- config_path: Path | None = None,- dry_run: bool = False,- python_executable: str | None = None,-) -> InstallResult:- config = config_path or Path.home() / ".codex" / "config.toml"- target_log = (log_path or detect_log_path("codex")).expanduser()- original = config.read_text() if config.exists() else ""-- text = strip_managed_block(original)- text = remove_codex_hook_blocks_for_log(text, target_log)- text = ensure_codex_hooks_feature(text)- block = codex_hook_block(target_log, python_executable)- new_text = _ensure_trailing_newline(text) + "\n" + block- changed = new_text != original-- backup = None- if not dry_run:- config.parent.mkdir(parents=True, exist_ok=True)- if changed:- backup = backup_file(config)- config.write_text(new_text)-- if should_refresh_codex_hook_trust(config, config_path):- trusted_hashes = resolve_codex_hook_hashes(config)- if trusted_hashes:- current_text = config.read_text() if config.exists() else ""- trusted_text = update_codex_trusted_hashes(current_text, trusted_hashes)- if trusted_text != current_text:- if backup is None:- backup = backup_file(config)- config.write_text(trusted_text)- changed = True-- target_log.parent.mkdir(parents=True, exist_ok=True)- target_log.touch(exist_ok=True)-- return InstallResult("codex", config, target_log, changed, backup, dry_run)---def install_claude_hooks(- log_path: Path | None = None,- config_path: Path | None = None,- dry_run: bool = False,- python_executable: str | None = None,-) -> InstallResult:- config = config_path or Path.home() / ".claude" / "settings.json"- target_log = (log_path or detect_log_path("claude")).expanduser()-- if config.exists():- data = json.loads(config.read_text())- else:- data = {}-- original = json.dumps(data, sort_keys=True)- hooks = data.setdefault("hooks", {})- command = hook_command("claude", target_log, python_executable)-- for event_name in CLAUDE_EVENTS:- entries = hooks.get(event_name, [])- if not isinstance(entries, list):- entries = []- cleaned = remove_claude_hooks_for_log(entries, target_log)- cleaned.append({"matcher": "*", "hooks": [{"type": "command", "command": command}]})- hooks[event_name] = cleaned-- changed = json.dumps(data, sort_keys=True) != original- backup = None- if changed and not dry_run:- config.parent.mkdir(parents=True, exist_ok=True)- backup = backup_file(config)- config.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")- target_log.parent.mkdir(parents=True, exist_ok=True)- target_log.touch(exist_ok=True)-- return InstallResult("claude", config, target_log, changed, backup, dry_run)---def uninstall_codex_hooks(- log_path: Path | None = None,- config_path: Path | None = None,- dry_run: bool = False,-) -> InstallResult:- config = config_path or Path.home() / ".codex" / "config.toml"- target_log = (log_path or detect_log_path("codex")).expanduser()- original = config.read_text() if config.exists() else ""-- text = strip_managed_block(original)- text = remove_codex_hook_blocks_for_log(text, target_log)- new_text = _normalize_config_text(text) if text != original else original- changed = new_text != original-- backup = None- if changed and not dry_run:- config.parent.mkdir(parents=True, exist_ok=True)- backup = backup_file(config)- config.write_text(new_text)-- return InstallResult("codex", config, target_log, changed, backup, dry_run)---def uninstall_claude_hooks(- log_path: Path | None = None,- config_path: Path | None = None,- dry_run: bool = False,-) -> InstallResult:- config = config_path or Path.home() / ".claude" / "settings.json"- target_log = (log_path or detect_log_path("claude")).expanduser()-- if config.exists():- data = json.loads(config.read_text())- else:- data = {}-- original = json.dumps(data, sort_keys=True)- hooks = data.get("hooks")- if isinstance(hooks, dict):- for event_name in list(hooks):- entries = hooks.get(event_name)- if event_name not in CLAUDE_EVENTS or not isinstance(entries, list):- continue-- cleaned = remove_claude_hooks_for_log(entries, target_log)- if cleaned:- hooks[event_name] = cleaned- else:- hooks.pop(event_name, None)-- if not hooks:- data.pop("hooks", None)-- changed = json.dumps(data, sort_keys=True) != original- backup = None- if changed and not dry_run:- config.parent.mkdir(parents=True, exist_ok=True)- backup = backup_file(config)- config.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")-- return InstallResult("claude", config, target_log, changed, backup, dry_run)---def hook_command(- provider: str,- log_path: Path,- python_executable: str | None = None,-) -> str:- executable = python_executable or sys.executable or "python3"- entry_point = Path(__file__).with_name("hook_entry.py")- command = " ".join(- [- shlex.quote(executable),- shlex.quote(str(entry_point)),- "--provider",- shlex.quote(provider),- "--log",- shlex.quote(str(log_path.expanduser())),- ]- )- return command---def hook_pythonpath_assignment() -> str:- package_root = Path(__file__).resolve().parents[1]- if not package_root.exists():- return ""- return f"PYTHONPATH={shlex.quote(str(package_root))} "---def codex_hook_block(- log_path: Path,- python_executable: str | None = None,-) -> str:- command = hook_command("codex", log_path, python_executable)- lines = [- MANAGED_START,- "# Provider-neutral status collection. Do not edit inside this block.",- ]- for event_name in CODEX_EVENTS:- lines.extend(- [- f"[[hooks.{event_name}]]",- 'matcher = "*"',- f"[[hooks.{event_name}.hooks]]",- 'type = "command"',- f"command = '''{command}'''",- "",- ]- )- lines.append(MANAGED_END)- return "\n".join(lines) + "\n"---def should_refresh_codex_hook_trust(config: Path, explicit_config: Path | None) -> bool:- default_config = Path.home() / ".codex" / "config.toml"- try:- return config.expanduser().resolve() == default_config.expanduser().resolve()- except OSError:- return explicit_config is None---def resolve_codex_hook_hashes(- config_path: Path,- cwd: Path | None = None,- timeout_seconds: float = 8.0,-) -> dict[str, str]:- codex = codex_cli_path()- if codex is None:- return {}-- try:- process = subprocess.Popen(- [str(codex), "app-server", "--stdio"],- stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- bufsize=1,- cwd=str(cwd or Path.cwd()),- )- except OSError:- return {}-- messages: queue.Queue[tuple[str, str]] = queue.Queue()-- def read_stream(name: str, stream: Any) -> None:- for line in stream:- messages.put((name, line.rstrip("\n")))-- for name, stream in (("out", process.stdout), ("err", process.stderr)):- if stream is not None:- threading.Thread(target=read_stream, args=(name, stream), daemon=True).start()-- def send(payload: dict[str, Any]) -> bool:- if process.stdin is None:- return False- try:- process.stdin.write(json.dumps(payload, separators=(",", ":")) + "\n")- process.stdin.flush()- except OSError:- return False- return True-- def wait_for_id(message_id: int) -> dict[str, Any] | None:- deadline = time.time() + timeout_seconds- while time.time() < deadline:- try:- name, line = messages.get(timeout=0.1)- except queue.Empty:- continue- if name != "out":- continue- try:- payload = json.loads(line)- except json.JSONDecodeError:- continue- if payload.get("id") == message_id:- return payload- return None-- try:- if not send(- {- "jsonrpc": "2.0",- "id": 1,- "method": "initialize",- "params": {- "clientInfo": {"name": "sidepulse-agent-monitor", "version": "0"},- "capabilities": None,- },- }- ):- return {}- wait_for_id(1)- if not send(- {- "jsonrpc": "2.0",- "id": 2,- "method": "hooks/list",- "params": {"cwds": [str(cwd or Path.cwd())]},- }- ):- return {}- response = wait_for_id(2)- finally:- process.terminate()- try:- process.wait(timeout=1)- except subprocess.TimeoutExpired:- process.kill()-- if not response:- return {}-- try:- hooks = response["result"]["data"][0]["hooks"]- except (KeyError, IndexError, TypeError):- return {}-- source_path = str(config_path.expanduser())- trusted_hashes: dict[str, str] = {}- for hook in hooks:- if not isinstance(hook, dict):- continue- command = hook.get("command")- current_hash = hook.get("currentHash")- key = hook.get("key")- if hook.get("sourcePath") != source_path:- continue- if not isinstance(command, str) or "hook_entry.py" not in command:- continue- if not isinstance(current_hash, str) or not isinstance(key, str):- continue- trusted_hashes[key] = current_hash- return trusted_hashes---def codex_cli_path() -> Path | None:- env_path = os.environ.get("CODEX_CLI_PATH")- candidates = [- Path(env_path).expanduser() if env_path else None,- Path("/Applications/ChatGPT.app/Contents/Resources/codex"),- Path("/Applications/Codex.app/Contents/Resources/codex"),- Path(shutil.which("codex")).expanduser() if shutil.which("codex") else None,- ]- for candidate in candidates:- if candidate and candidate.exists():- return candidate- return None---def update_codex_trusted_hashes(text: str, trusted_hashes: dict[str, str]) -> str:- if not trusted_hashes:- return text-- result = _ensure_hooks_state_table(text)- for key, trusted_hash in trusted_hashes.items():- result = _set_codex_trusted_hash(result, key, trusted_hash)- return result---def _ensure_hooks_state_table(text: str) -> str:- if re.search(r"^\s*\[hooks\.state\]\s*$", text, re.MULTILINE):- return text- return _ensure_trailing_newline(text) + "\n[hooks.state]\n"---def _set_codex_trusted_hash(text: str, key: str, trusted_hash: str) -> str:- header = f'[hooks.state."{toml_basic_string_escape(key)}"]'- lines = text.splitlines(keepends=True)- header_index = None- for index, line in enumerate(lines):- if line.strip() == header:- header_index = index- break-- if header_index is None:- block = f'\n{header}\ntrusted_hash = "{toml_basic_string_escape(trusted_hash)}"\n'- return _ensure_trailing_newline(text) + block-- end = len(lines)- for index in range(header_index + 1, len(lines)):- if re.match(r"\s*\[.*\]\s*$", lines[index]):- end = index- break-- trusted_line = f'trusted_hash = "{toml_basic_string_escape(trusted_hash)}"\n'- for index in range(header_index + 1, end):- if re.match(r"\s*trusted_hash\s*=", lines[index]):- lines[index] = trusted_line- return "".join(lines)-- lines.insert(header_index + 1, trusted_line)- return "".join(lines)---def toml_basic_string_escape(value: str) -> str:- return value.replace("\\", "\\\\").replace('"', '\\"')---def strip_managed_block(text: str) -> str:- # Codex may append its own tables between these comments when it rewrites- # config.toml. Remove only the comments; hook tables are removed below.- return "\n".join(- line for line in text.splitlines() if line.strip() not in {MANAGED_START, MANAGED_END}- ) + ("\n" if text.endswith("\n") else "")---def remove_codex_hook_blocks_for_log(text: str, log_path: Path) -> str:- target = str(log_path)- lines = text.splitlines(keepends=True)- out: list[str] = []- index = 0-- while index < len(lines):- event_match = re.match(r"\s*\[\[hooks\.([A-Za-z0-9_]+)\]\]\s*$", lines[index])- if event_match and event_match.group(1) in CODEX_EVENTS:- event_name = event_match.group(1)- end = index + 1- nested = re.compile(rf"\s*\[\[hooks\.{re.escape(event_name)}\.hooks\]\]\s*$")- table = re.compile(r"\s*\[.*\]\s*$")- while end < len(lines):- if table.match(lines[end]) and not nested.match(lines[end]):- break- end += 1- block = "".join(lines[index:end])- if target in block or "agent_monitor hook-log" in block or "hook_entry.py" in block:- index = end- continue-- if "Event logging hooks:" in lines[index] and target in text:- index += 1- continue-- out.append(lines[index])- index += 1-- return "".join(out)---def remove_claude_hooks_for_log(entries: list[Any], log_path: Path) -> list[dict[str, Any]]:- target = str(log_path)- cleaned_entries: list[dict[str, Any]] = []- for entry in entries:- if not isinstance(entry, dict):- continue- hooks = entry.get("hooks")- if not isinstance(hooks, list):- continue- cleaned_hooks = []- for hook in hooks:- if not isinstance(hook, dict):- continue- command = hook.get("command", "")- if target in command or "agent_monitor hook-log" in command or "hook_entry.py" in command:- continue- cleaned_hooks.append(hook)- if cleaned_hooks:- kept = dict(entry)- kept["hooks"] = cleaned_hooks- cleaned_entries.append(kept)- return cleaned_entries---def ensure_codex_hooks_feature(text: str) -> str:- lines = text.splitlines(keepends=True)- features_index = None- for index, line in enumerate(lines):- if re.match(r"\s*\[features\]\s*$", line):- features_index = index- break-- if features_index is None:- return _ensure_trailing_newline(text) + "\n[features]\nhooks = true\n"-- end = len(lines)- for index in range(features_index + 1, len(lines)):- if re.match(r"\s*\[.*\]\s*$", lines[index]):- end = index- break-- for index in range(features_index + 1, end):- if re.match(r"\s*hooks\s*=", lines[index]):- lines[index] = "hooks = true\n"- return "".join(lines)-- lines.insert(end, "hooks = true\n")- return "".join(lines)---def backup_file(path: Path) -> Path | None:- if not path.exists():- return None- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- backup = path.with_name(f"{path.name}.bak.{stamp}")- backup.write_bytes(path.read_bytes())- return backup---def _ensure_trailing_newline(text: str) -> str:- return text if not text or text.endswith("\n") else text + "\n"---def _normalize_config_text(text: str) -> str:- stripped = text.strip()- if not stripped:- return ""- return stripped + "\n"diff --git a/src/agent_monitor/ipc.py b/src/agent_monitor/ipc.pydeleted file mode 100644index f941a28..0000000--- a/src/agent_monitor/ipc.py+++ /dev/null@@ -1,137 +0,0 @@-from __future__ import annotations--import json-import socket-import threading-from pathlib import Path-from typing import Callable--from .providers import default_state_dir---MAX_EVENT_BYTES = 1024 * 1024---def default_event_socket_path() -> Path:- return default_state_dir() / "events.sock"---def default_latest_state_path() -> Path:- return default_state_dir() / "latest.json"---def send_hook_event(- provider: str,- line: dict,- *,- socket_path: Path | None = None,- timeout: float = 0.05,-) -> bool:- target = (socket_path or default_event_socket_path()).expanduser()- payload = json.dumps(- {"provider": provider, "line": line},- separators=(",", ":"),- ensure_ascii=False,- ).encode("utf-8")- if len(payload) > MAX_EVENT_BYTES:- return False-- client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- client.settimeout(timeout)- try:- client.connect(str(target))- client.sendall(payload)- return True- except OSError:- return False- finally:- client.close()---class HookEventServer:- def __init__(- self,- on_event: Callable[[str, dict], None],- *,- socket_path: Path | None = None,- ) -> None:- self.on_event = on_event- self.socket_path = (socket_path or default_event_socket_path()).expanduser()- self.socket: socket.socket | None = None- self.thread: threading.Thread | None = None- self.running = False-- def start(self) -> Path:- self.socket_path.parent.mkdir(parents=True, exist_ok=True)- try:- self.socket_path.unlink()- except FileNotFoundError:- pass-- server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- server.bind(str(self.socket_path))- server.listen(16)- server.settimeout(0.5)- self.socket = server- self.running = True- self.thread = threading.Thread(target=self._serve, daemon=True)- self.thread.start()- return self.socket_path-- def stop(self) -> None:- self.running = False- server = self.socket- self.socket = None- if server is not None:- try:- server.close()- except OSError:- pass- try:- self.socket_path.unlink()- except FileNotFoundError:- pass- except OSError:- pass-- def _serve(self) -> None:- while self.running:- server = self.socket- if server is None:- return- try:- connection, _ = server.accept()- except socket.timeout:- continue- except OSError:- return-- with connection:- self._handle_connection(connection)-- def _handle_connection(self, connection: socket.socket) -> None:- chunks: list[bytes] = []- total = 0- while True:- try:- chunk = connection.recv(65536)- except OSError:- return- if not chunk:- break- total += len(chunk)- if total > MAX_EVENT_BYTES:- return- chunks.append(chunk)-- try:- message = json.loads(b"".join(chunks).decode("utf-8"))- except Exception:- return-- if not isinstance(message, dict):- return- provider = message.get("provider")- line = message.get("line")- if isinstance(provider, str) and isinstance(line, dict):- self.on_event(provider, line)diff --git a/src/agent_monitor/keep_awake.py b/src/agent_monitor/keep_awake.pydeleted file mode 100644index db99dc1..0000000--- a/src/agent_monitor/keep_awake.py+++ /dev/null@@ -1,216 +0,0 @@-from __future__ import annotations--import os-import subprocess-import threading-import time-from pathlib import Path-from typing import Callable, Sequence--from .device_writer import KNOWN_LED_FILE_NAMES-from .models import AgentMode---AWAKE_GRACE_SECONDS = 300.0-SD_STATUS_READ_SECONDS = 60.0-KEEPALIVE_FILE_NAME = "keepalive"-STATUS_FILE_NAME = KEEPALIVE_FILE_NAME-CAFFEINATE_COMMAND = ("/usr/bin/caffeinate", "-dimsu")---class KeepAwakeController:- def __init__(- self,- *,- enabled: bool = True,- grace_seconds: float = AWAKE_GRACE_SECONDS,- status_read_seconds: float = SD_STATUS_READ_SECONDS,- command: Sequence[str] = CAFFEINATE_COMMAND,- process_factory: Callable[..., object] | None = None,- status_reader: Callable[[Path], None] | None = None,- status_read_async: bool = True,- watch_current_process: bool = True,- ) -> None:- self.enabled = enabled- self.grace_seconds = grace_seconds- self.status_read_seconds = status_read_seconds- self.command = tuple(command)- self.process_factory = process_factory or subprocess.Popen- self.status_reader = status_reader or touch_keepalive_file- self.status_read_async = status_read_async- 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] = {}- self.last_status_error: str | None = None- self.status_read_in_flight_by_path: set[Path] = set()-- def set_enabled(self, enabled: bool) -> None:- if self.enabled == enabled:- return- 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()- self.status_read_in_flight_by_path.clear()-- 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:- self.release()- return False-- self.ensure_awake()- return self.process_running()-- def should_hold_for_mode(self, mode: AgentMode, now: float) -> bool:- if mode in {- AgentMode.WORKING,- AgentMode.TOOL_RUNNING,- AgentMode.LONG_TASK_PROGRESS,- }:- self.grace_until_monotonic = None- return True-- if mode in {- AgentMode.COMPLETED,- AgentMode.WAITING_FOR_INPUT,- AgentMode.BLOCKED_ERROR,- }:- if self.last_mode != mode or self.grace_until_monotonic is None:- self.grace_until_monotonic = now + self.grace_seconds- return now < self.grace_until_monotonic-- return self.grace_until_monotonic is not None and now < self.grace_until_monotonic-- def ensure_awake(self) -> None:- if self.process_running():- return-- try:- self.process = self.process_factory(- self.caffeinate_command(),- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- self.last_error = None- except Exception as exc:- self.process = None- self.last_error = str(exc)-- def release(self) -> None:- process = self.process- self.process = None- if process is None:- return-- try:- if process.poll() is None:- process.terminate()- process.wait(timeout=1)- except Exception:- try:- process.kill()- except Exception:- pass-- def process_running(self) -> bool:- return self.process is not None and self.process.poll() is None-- def poke_status_file(self, target: Path | None, *, now: float | None = None) -> Path | None:- if not self.enabled or target is None:- return None-- current = time.monotonic() if now is None else now- status_path = keepalive_file_for_target(target)- last_read = self.last_status_read_monotonic_by_path.get(status_path)- if last_read is not None and current - last_read < self.status_read_seconds:- return None-- self.last_status_read_monotonic_by_path[status_path] = current- if self.status_read_async:- if status_path in self.status_read_in_flight_by_path:- return None- self.status_read_in_flight_by_path.add(status_path)- thread = threading.Thread(- target=self._run_status_reader,- args=(status_path,),- daemon=True,- )- thread.start()- return status_path-- return self._run_status_reader(status_path)-- def caffeinate_command(self) -> list[str]:- command = list(self.command)- if self.watch_current_process:- command.extend(["-w", str(os.getpid())])- return command-- def _run_status_reader(self, status_path: Path) -> Path | None:- try:- self.status_reader(status_path)- self.last_status_error = None- return status_path- except Exception as exc:- self.last_status_error = str(exc)- return None- finally:- self.status_read_in_flight_by_path.discard(status_path)-- def detail(self, *, now: float | None = None) -> str:- if not self.enabled:- return "Keep awake disabled"- if self.last_error:- return f"Keep awake error: {self.last_error}"- current = time.monotonic() if now is None else now- if self.grace_until_monotonic is not None and current < self.grace_until_monotonic:- remaining = int(self.grace_until_monotonic - current)- return f"Keep awake grace: {format_duration(remaining)}"- if self.process_running():- return "Keep awake active"- return "Keep awake standby"---def status_file_for_target(target: Path) -> Path:- return keepalive_file_for_target(target)---def keepalive_file_for_target(target: Path) -> Path:- known_file_names = KNOWN_LED_FILE_NAMES | {KEEPALIVE_FILE_NAME.upper(), "STATUS.TXT"}- if target.name.upper() in known_file_names:- return target.parent / KEEPALIVE_FILE_NAME- return target / KEEPALIVE_FILE_NAME---def read_status_file(path: Path) -> None:- touch_keepalive_file(path)---def touch_keepalive_file(path: Path) -> None:- subprocess.run(- ["/usr/bin/touch", str(path)],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- timeout=2,- check=True,- )---def format_duration(seconds: int) -> str:- seconds = max(0, int(seconds))- minutes, rest = divmod(seconds, 60)- if minutes:- return f"{minutes}m{rest:02d}s"- return f"{rest}s"diff --git a/src/agent_monitor/led_status.py b/src/agent_monitor/led_status.pydeleted file mode 100644index f3c23e4..0000000--- a/src/agent_monitor/led_status.py+++ /dev/null@@ -1,259 +0,0 @@-from __future__ import annotations--import time-from dataclasses import dataclass-from enum import Enum-from pathlib import Path--from .device_writer import (- DEFAULT_FILE_NAME,- DeviceWriteError,- resolve_target_path,- write_led_program,-)-from .models import AgentMode---class LedDisplayState(str, Enum):- IDLE = "idle"- WORKING = "working"- DONE = "done"- ASK = "ask"---LED_STATE_LABELS: dict[LedDisplayState, str] = {- LedDisplayState.IDLE: "Idle",- LedDisplayState.WORKING: "Working",- LedDisplayState.DONE: "Done",- LedDisplayState.ASK: "Ask",-}---ASK_AMBER = "#FF3A00"-WORKING_CYAN = "#00E5FF"-DONE_GREEN = "#00FF66"-IDLE_DIM = "#020204"-DEVICE_LED_COUNTS = {- "pulsedot": 2,- "pixiedot": 2,- "sidepulse": 8,- "pixiepulse": 8,-}---@dataclass(frozen=True)-class LedStatusWrite:- state: LedDisplayState- target: Path | None- program: str- changed: bool- error: str | None = None-- @property- def label(self) -> str:- return LED_STATE_LABELS[self.state]---def display_state_for_mode(mode: AgentMode) -> LedDisplayState:- if mode in {AgentMode.WAITING_FOR_INPUT, AgentMode.BLOCKED_ERROR}:- return LedDisplayState.ASK- if mode in {- AgentMode.WORKING,- AgentMode.TOOL_RUNNING,- AgentMode.LONG_TASK_PROGRESS,- }:- return LedDisplayState.WORKING- if mode == AgentMode.COMPLETED:- return LedDisplayState.DONE- return LedDisplayState.IDLE---def program_for_display_state(- state: LedDisplayState,- *,- led_count: int = 8,- brightness: int | float = 255,-) -> str:- if state == LedDisplayState.IDLE:- return apply_brightness(- "\n".join(- [- "off",- f"{IDLE_DIM} 6s pulse",- "repeat",- ]- ),- brightness,- )- if state == LedDisplayState.ASK:- return apply_brightness(- "\n".join(- [- "off",- f"{ASK_AMBER} 1.6s pulse",- "repeat",- ]- ),- brightness,- )- if state == LedDisplayState.DONE:- return apply_brightness(DONE_GREEN, brightness)- if state == LedDisplayState.WORKING:- return apply_brightness(rolling_program(WORKING_CYAN, led_count=led_count), brightness)- raise ValueError(f"Unknown LED display state: {state}")---def rolling_program(color: str, *, led_count: int = 8) -> str:- count = max(2, min(8, int(led_count)))- delay_ms = 260 if count == 2 else 95- duration_ms = 760- segments: list[str] = []- for active_index in range(count):- delay = active_index * delay_ms- segments.append(f"{active_index}:{color} {duration_ms}ms pulse {delay}ms")- return "\n".join(- [- "off 160ms cosine",- "; ".join(segments),- "repeat",- ]- )---def write_mode_to_leds(- mode: AgentMode,- *,- 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,- device_path=target,- file_name=file_name,- dry_run=dry_run,- )- return LedStatusWrite(- state=state,- target=written_target,- program=program,- changed=True,- )---def led_count_for_target(target: Path) -> int:- name = normalized_device_name(target.parent.name)- for hint, led_count in DEVICE_LED_COUNTS.items():- if hint in name:- return led_count- return 8---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,- *,- device_path: Path | None = None,- 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 brightness == self.last_brightness and self.last_error is None:- return LedStatusWrite(- state=state,- target=self.last_target,- program="",- changed=False,- )- 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- ):- return LedStatusWrite(- state=state,- target=self.last_target,- program="",- changed=False,- error=self.last_error,- )-- self.last_attempt_monotonic = now- try:- result = write_mode_to_leds(- mode,- 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,- target=self.last_target,- program="",- changed=False,- error=self.last_error,- )-- self.last_state = state- self.last_brightness = brightness- self.last_error = None- self.last_target = result.target- return resultdiff --git a/src/agent_monitor/lid_sleep.py b/src/agent_monitor/lid_sleep.pydeleted file mode 100644index f37f769..0000000--- a/src/agent_monitor/lid_sleep.py+++ /dev/null@@ -1,382 +0,0 @@-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 commanddiff --git a/src/agent_monitor/models.py b/src/agent_monitor/models.pydeleted file mode 100644index c4b5dae..0000000--- a/src/agent_monitor/models.py+++ /dev/null@@ -1,157 +0,0 @@-from __future__ import annotations--from dataclasses import dataclass-from datetime import datetime, timezone-from enum import Enum-from typing import Any---class AgentMode(str, Enum):- IDLE_READY = "idle_ready"- WORKING = "working"- TOOL_RUNNING = "tool_running"- WAITING_FOR_INPUT = "waiting_for_input"- LONG_TASK_PROGRESS = "long_task_progress"- BLOCKED_ERROR = "blocked_error"- COMPLETED = "completed"- UNKNOWN = "unknown"---MODE_PRIORITY: dict[AgentMode, int] = {- AgentMode.BLOCKED_ERROR: 1,- AgentMode.WAITING_FOR_INPUT: 2,- AgentMode.TOOL_RUNNING: 3,- AgentMode.LONG_TASK_PROGRESS: 4,- AgentMode.WORKING: 5,- AgentMode.COMPLETED: 6,- AgentMode.IDLE_READY: 7,- AgentMode.UNKNOWN: 99,-}---MODE_LABELS: dict[AgentMode, str] = {- AgentMode.IDLE_READY: "Idle / Ready",- AgentMode.WORKING: "Working",- AgentMode.TOOL_RUNNING: "Tool Running",- AgentMode.WAITING_FOR_INPUT: "Waiting for Input",- AgentMode.LONG_TASK_PROGRESS: "Long Task Progress",- AgentMode.BLOCKED_ERROR: "Blocked / Error",- AgentMode.COMPLETED: "Completed",- AgentMode.UNKNOWN: "Unknown",-}---@dataclass(frozen=True)-class HookEvent:- provider: str- logged_at: datetime- event_name: str- raw: dict[str, Any]- session_id: str | None = None- turn_id: str | None = None- agent_id: str | None = None- cwd: str | None = None- tool_name: str | None = None- message: str | None = None-- @property- def status_key(self) -> str:- if self.agent_id:- return f"{self.provider}:agent:{self.agent_id}"- if self.session_id:- return f"{self.provider}:session:{self.session_id}"- return f"{self.provider}:unknown"---@dataclass(frozen=True)-class AgentStatus:- provider: str- agent_id: str- display_name: str- mode: AgentMode- updated_at: datetime- event_name: str- session_id: str | None = None- cwd: str | None = None- tool_name: str | None = None- message: str | None = None- stale: bool = False-- @property- def priority(self) -> int:- return MODE_PRIORITY.get(self.mode, MODE_PRIORITY[AgentMode.UNKNOWN])-- @property- def mode_label(self) -> str:- return MODE_LABELS.get(self.mode, self.mode.value)-- def age_seconds(self, now: datetime | None = None) -> float:- current = now or datetime.now(timezone.utc)- return max(0.0, (current - self.updated_at).total_seconds())-- def to_dict(self, now: datetime | None = None) -> dict[str, Any]:- return {- "provider": self.provider,- "agent_id": self.agent_id,- "display_name": self.display_name,- "mode": self.mode.value,- "mode_label": self.mode_label,- "priority": self.priority,- "updated_at": self.updated_at.isoformat(),- "age_seconds": round(self.age_seconds(now), 3),- "event_name": self.event_name,- "session_id": self.session_id,- "cwd": self.cwd,- "tool_name": self.tool_name,- "message": self.message,- "stale": self.stale,- }---@dataclass(frozen=True)-class AggregateStatus:- mode: AgentMode- active_count: int- stale_count: int- representative: AgentStatus | None = None-- @property- def mode_label(self) -> str:- return MODE_LABELS.get(self.mode, self.mode.value)-- def to_dict(self, now: datetime | None = None) -> dict[str, Any]:- return {- "mode": self.mode.value,- "mode_label": self.mode_label,- "active_count": self.active_count,- "stale_count": self.stale_count,- "representative": (- self.representative.to_dict(now) if self.representative else None- ),- }---def parse_datetime(value: Any, fallback: datetime | None = None) -> datetime:- if isinstance(value, datetime):- parsed = value- elif isinstance(value, str) and value:- text = value.strip()- if text.endswith("Z"):- text = f"{text[:-1]}+00:00"- try:- parsed = datetime.fromisoformat(text)- except ValueError:- parsed = fallback or datetime.now(timezone.utc)- else:- parsed = fallback or datetime.now(timezone.utc)-- if parsed.tzinfo is None:- return parsed.replace(tzinfo=timezone.utc)- return parsed.astimezone(timezone.utc)---def provider_label(provider: str) -> str:- return {- "codex": "Codex",- "claude": "Claude",- }.get(provider, provider.title())diff --git a/src/agent_monitor/providers.py b/src/agent_monitor/providers.pydeleted file mode 100644index 7c8ec47..0000000--- a/src/agent_monitor/providers.py+++ /dev/null@@ -1,282 +0,0 @@-from __future__ import annotations--import json-import os-import re-import shlex-from dataclasses import dataclass-from pathlib import Path-from typing import Any--from .models import HookEvent, parse_datetime--try:- import tomllib-except ModuleNotFoundError: # Python 3.10 compatibility.- tomllib = None--CODEX_EVENTS = (- "SessionStart",- "UserPromptSubmit",- "PreToolUse",- "PostToolUse",- "PermissionRequest",- "PreCompact",- "PostCompact",- "SubagentStart",- "SubagentStop",- "Stop",-)--CLAUDE_EVENTS = (- "SessionStart",- "UserPromptSubmit",- "PreToolUse",- "PostToolUse",- "PostToolUseFailure",- "PermissionRequest",- "Notification",- "PreCompact",- "PostCompact",- "SubagentStop",- "Stop",- "SessionEnd",-)---@dataclass(frozen=True)-class ProviderConfig:- provider: str- config_path: Path- exists: bool- hooks_enabled: bool- hook_events: tuple[str, ...]- log_paths: tuple[Path, ...]-- def to_dict(self) -> dict[str, Any]:- return {- "provider": self.provider,- "config_path": str(self.config_path),- "exists": self.exists,- "hooks_enabled": self.hooks_enabled,- "hook_events": list(self.hook_events),- "log_paths": [str(path) for path in self.log_paths],- }---def default_state_dir(home: Path | None = None) -> Path:- if home is None:- xdg_state_home = os.environ.get("XDG_STATE_HOME")- if xdg_state_home:- return Path(xdg_state_home).expanduser() / "sidepulse" / "agent-monitor"-- base = home or Path.home()- return base / ".local" / "state" / "sidepulse" / "agent-monitor"---def default_log_path(provider: str, home: Path | None = None) -> Path:- suffix = "jsonl"- return default_state_dir(home) / f"{provider}.{suffix}"---def detect_provider_configs(home: Path | None = None) -> list[ProviderConfig]:- return [detect_codex_config(home), detect_claude_config(home)]---def detect_codex_config(home: Path | None = None) -> ProviderConfig:- base = home or Path.home()- config_path = base / ".codex" / "config.toml"- if not config_path.exists():- return ProviderConfig("codex", config_path, False, False, (), ())-- text = config_path.read_text()- try:- if tomllib is None:- raise RuntimeError("tomllib unavailable")- data = tomllib.loads(text)- except Exception:- return detect_codex_config_from_text(config_path, text)-- features = data.get("features") or {}- hooks = data.get("hooks") or {}- hook_events: list[str] = []- paths: list[Path] = []-- if isinstance(hooks, dict):- for event_name, entries in hooks.items():- if event_name not in CODEX_EVENTS or not isinstance(entries, list):- continue- hook_events.append(event_name)- paths.extend(_paths_from_hook_entries(entries))-- return ProviderConfig(- "codex",- config_path,- True,- bool(features.get("hooks")),- tuple(sorted(set(hook_events))),- _dedupe_paths(paths),- )---def detect_codex_config_from_text(config_path: Path, text: str) -> ProviderConfig:- hook_events = tuple(- sorted(- {- match.group(1)- for match in re.finditer(r"^\s*\[\[hooks\.([A-Za-z0-9_]+)\]\]\s*$", text, re.MULTILINE)- if match.group(1) in CODEX_EVENTS- }- )- )-- paths: list[Path] = []- for match in re.finditer(r"command\s*=\s*'''(.*?)'''", text, re.DOTALL):- paths.extend(extract_log_paths_from_command(match.group(1)))- for match in re.finditer(r'command\s*=\s*"(.*?)"', text):- paths.extend(extract_log_paths_from_command(match.group(1)))-- return ProviderConfig(- "codex",- config_path,- True,- codex_hooks_feature_enabled(text),- hook_events,- _dedupe_paths(paths),- )---def codex_hooks_feature_enabled(text: str) -> bool:- match = re.search(r"^\s*\[features\]\s*$(.*?)(?=^\s*\[|\Z)", text, re.MULTILINE | re.DOTALL)- if not match:- return False- return bool(re.search(r"^\s*hooks\s*=\s*true\s*$", match.group(1), re.MULTILINE))---def detect_claude_config(home: Path | None = None) -> ProviderConfig:- base = home or Path.home()- config_path = base / ".claude" / "settings.json"- if not config_path.exists():- return ProviderConfig("claude", config_path, False, False, (), ())-- try:- data = json.loads(config_path.read_text())- except Exception:- return ProviderConfig("claude", config_path, True, False, (), ())-- hooks = data.get("hooks") or {}- hook_events: list[str] = []- paths: list[Path] = []-- if isinstance(hooks, dict):- for event_name, entries in hooks.items():- if event_name not in CLAUDE_EVENTS or not isinstance(entries, list):- continue- hook_events.append(event_name)- paths.extend(_paths_from_hook_entries(entries))-- return ProviderConfig(- "claude",- config_path,- True,- bool(hook_events),- tuple(sorted(set(hook_events))),- _dedupe_paths(paths),- )---def detect_log_path(provider: str, home: Path | None = None) -> Path:- config = detect_codex_config(home) if provider == "codex" else detect_claude_config(home)- if config.log_paths:- return config.log_paths[0]- return default_log_path(provider, home)---def parse_log_line(provider: str, line: str) -> HookEvent | None:- line = line.strip()- if not line:- return None-- try:- obj = json.loads(line)- except json.JSONDecodeError:- return None-- if not isinstance(obj, dict):- return None-- if provider == "codex" and isinstance(obj.get("event"), dict):- raw = obj["event"]- logged_at = obj.get("logged_at") or raw.get("logged_at")- else:- raw = obj- logged_at = raw.get("logged_at")-- event_name = raw.get("hook_event_name")- if not event_name:- return None-- return HookEvent(- provider=provider,- logged_at=parse_datetime(logged_at),- event_name=str(event_name),- raw=raw,- session_id=_string_or_none(raw.get("session_id")),- turn_id=_string_or_none(raw.get("turn_id")),- agent_id=_string_or_none(raw.get("agent_id")),- cwd=_string_or_none(raw.get("cwd")),- tool_name=_string_or_none(raw.get("tool_name")),- message=_string_or_none(raw.get("message") or raw.get("last_assistant_message")),- )---def _paths_from_hook_entries(entries: list[Any]) -> list[Path]:- paths: list[Path] = []- for entry in entries:- if not isinstance(entry, dict):- continue- for hook in entry.get("hooks") or []:- if not isinstance(hook, dict):- continue- command = hook.get("command")- if isinstance(command, str):- paths.extend(extract_log_paths_from_command(command))- return paths---def extract_log_paths_from_command(command: str) -> list[Path]:- paths: list[Path] = []-- for match in re.finditer(r">>\s+(['\"]?)([^'\"\s]+)\1", command):- paths.append(Path(match.group(2)).expanduser())-- try:- parts = shlex.split(command)- except ValueError:- parts = []-- for index, part in enumerate(parts):- if part == "--log" and index + 1 < len(parts):- paths.append(Path(parts[index + 1]).expanduser())- elif part.startswith("--log="):- paths.append(Path(part.split("=", 1)[1]).expanduser())-- return _dedupe_paths(paths)---def _dedupe_paths(paths: list[Path]) -> tuple[Path, ...]:- seen: set[str] = set()- result: list[Path] = []- for path in paths:- key = str(path)- if key in seen:- continue- seen.add(key)- result.append(path)- return tuple(result)---def _string_or_none(value: Any) -> str | None:- if value is None:- return None- return str(value)diff --git a/src/agent_monitor/resources/__init__.py b/src/agent_monitor/resources/__init__.pydeleted file mode 100644index e0611b7..0000000--- a/src/agent_monitor/resources/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""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.cdeleted file mode 100644index 46ca028..0000000--- a/src/agent_monitor/resources/sd_eject_guard.c+++ /dev/null@@ -1,127 +0,0 @@-// 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.pydeleted file mode 100644index 4f51548..0000000--- a/src/agent_monitor/sd_eject_guard_launch.py+++ /dev/null@@ -1,441 +0,0 @@-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 Nonediff --git a/src/agent_monitor/session_actions.py b/src/agent_monitor/session_actions.pydeleted file mode 100644index 48b5a84..0000000--- a/src/agent_monitor/session_actions.py+++ /dev/null@@ -1,87 +0,0 @@-from __future__ import annotations--import shlex-from pathlib import Path-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()- session_id = status.session_id-- if provider == "codex" and session_id:- return f"codex://threads/{quote(session_id, safe='')}"- if provider == "claude":- return "claude://"- 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-- provider = status.provider.lower()- cwd = shlex.quote(status.cwd or str(Path.home()))- session_id = shlex.quote(status.session_id)-- if provider == "codex":- return f"cd {cwd} && codex resume {session_id}"- 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 actiondiff --git a/src/agent_monitor/settings.py b/src/agent_monitor/settings.pydeleted file mode 100644index cd76d9a..0000000--- a/src/agent_monitor/settings.py+++ /dev/null@@ -1,529 +0,0 @@-from __future__ import annotations--import json-import os-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)-class DeviceDisplaySetting:- device_id: str- name: str- path: str- led_display: str = LED_DISPLAY_AGENT- brightness: int = 255-- 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,- }---@dataclass(frozen=True)-class AgentMonitorSettings:- codex_transcripts_enabled: bool = False- 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":- return self.codex_transcripts_enabled- if provider == "claude":- return self.claude_transcripts_enabled- return False-- def with_transcript_provider(self, provider: str, enabled: bool) -> "AgentMonitorSettings":- if provider == "codex":- return replace(self, codex_transcripts_enabled=enabled)- if provider == "claude":- return replace(self, claude_transcripts_enabled=enabled)- raise ValueError(f"Unknown transcript provider: {provider}")-- def with_led_display(self, display: str) -> "AgentMonitorSettings":- if display not in LED_DISPLAY_CHOICES:- raise ValueError(f"Unknown LED display: {display}")- return replace(self, led_display=display)-- def display_for_device(self, device_id: str) -> str:- for device in self.devices:- if device.device_id == device_id:- 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,- display: str,- *,- name: str | None = None,- path: str | None = None,- ) -> "AgentMonitorSettings":- if display not in LED_DISPLAY_CHOICES:- raise ValueError(f"Unknown LED display: {display}")-- 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=display,- brightness=device.brightness,- )- )- 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=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))-- def with_remembered_device(- self,- *,- device_id: str,- name: str,- path: str,- ) -> "AgentMonitorSettings":- return self.with_device_display(- device_id,- self.display_for_device(device_id),- name=name,- 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- return replace(self, battery_full_charge_watts=watts)-- def with_battery_power_change_preview(- self,- *,- enabled: bool | None = None,- seconds: float | None = None,- ) -> "AgentMonitorSettings":- preview_seconds = self.battery_power_change_preview_seconds- if seconds is not None:- preview_seconds = max(0.0, float(seconds))- return replace(- self,- battery_show_on_power_change=(- self.battery_show_on_power_change if enabled is None else enabled- ),- 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,- },- "battery_monitoring": {- "full_charge_watts": self.battery_full_charge_watts,- "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())),- }---def default_config_dir(home: Path | None = None) -> Path:- if home is None:- xdg_config_home = os.environ.get("XDG_CONFIG_HOME")- if xdg_config_home:- return Path(xdg_config_home).expanduser() / "sidepulse" / "agent-monitor"-- base = home or Path.home()- return base / ".config" / "sidepulse" / "agent-monitor"---def default_settings_path(home: Path | None = None) -> Path:- return default_config_dir(home) / "settings.json"---def load_settings(path: Path | None = None) -> AgentMonitorSettings:- target = (path or default_settings_path()).expanduser()- if not target.exists():- return AgentMonitorSettings()-- try:- data = json.loads(target.read_text())- except Exception:- return AgentMonitorSettings()-- if not isinstance(data, dict):- return AgentMonitorSettings()-- transcript = data.get("transcript_monitoring")- if not isinstance(transcript, dict):- transcript = {}-- battery = data.get("battery_monitoring")- if not isinstance(battery, dict):- battery = {}-- led_display = _led_display_setting(data.get("led_display"), LED_DISPLAY_AGENT)- return AgentMonitorSettings(- codex_transcripts_enabled=_bool_setting(transcript.get("codex"), False),- 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"),- ),- battery_show_on_power_change=_bool_setting(- battery.get("show_on_power_change"),- True,- ),- battery_power_change_preview_seconds=_float_setting(- battery.get("power_change_preview_seconds"),- DEFAULT_POWER_CHANGE_PREVIEW_SECONDS,- ),- session_open_preferences=_session_open_preferences(data.get("session_open_preferences")),- )---def save_settings(- settings: AgentMonitorSettings,- path: Path | None = None,-) -> Path:- target = (path or default_settings_path()).expanduser()- target.parent.mkdir(parents=True, exist_ok=True)- target.write_text(json.dumps(settings.to_dict(), indent=2, sort_keys=True) + "\n")- return target---def _bool_setting(value: object, default: bool) -> bool:- if isinstance(value, bool):- return value- return default---def _led_display_setting(value: object, default: str) -> str:- if isinstance(value, str) and value in LED_DISPLAY_CHOICES:- return value- 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 ()-- devices: list[DeviceDisplaySetting] = []- seen: set[str] = set()- for item in value:- if not isinstance(item, dict):- continue- device_id = item.get("id")- path = item.get("path")- if not isinstance(device_id, str) or not device_id:- continue- if not isinstance(path, str) or not path:- path = device_id- if device_id in seen:- continue- name = item.get("name")- 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- if isinstance(value, (int, float)) and value > 0:- return float(value)- return None---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.pydeleted file mode 100644index 2dba06c..0000000--- a/src/agent_monitor/status_bar.py+++ /dev/null@@ -1,2116 +0,0 @@-from __future__ import annotations--import json-import subprocess-import threading-import time-from dataclasses import dataclass-from datetime import datetime-from pathlib import Path--try:- import objc- from AppKit import (- NSApp,- NSApplication,- NSApplicationActivationPolicyAccessory,- NSBackingStoreBuffered,- NSBezelStyleRounded,- NSButton,- NSButtonTypeSwitch,- NSFont,- NSImage,- NSMenu,- NSMenuItem,- NSOffState,- NSOnState,- NSScrollView,- NSSlider,- NSStatusBar,- NSTextField,- NSTextView,- NSView,- NSWorkspace,- NSWindow,- NSWindowStyleMaskClosable,- NSWindowStyleMaskMiniaturizable,- NSWindowStyleMaskTitled,- NSVariableStatusItemLength,- )- from Foundation import NSObject, NSTimer, NSURL-except ImportError as exc: # pragma: no cover - only exercised on non-macOS setups.- raise SystemExit(- "The status-bar app requires PyObjC/AppKit:\n"- " python3 -m pip install pyobjc-framework-Cocoa"- ) from exc--from .battery import (- BatteryLedController,- BatterySnapshot,- format_watts,- read_battery_snapshot,-)-from .collector import LiveAgentMonitor, SourceSpec, read_recent_lines-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-from .install import (- install_claude_hooks,- install_codex_hooks,- uninstall_claude_hooks,- uninstall_codex_hooks,-)-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,- detect_claude_config,- detect_codex_config,- detect_log_path,- parse_log_line,-)-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,-)---@dataclass(frozen=True)-class StatusBarState:- label: str- symbol: str- priority: int---@dataclass(frozen=True)-class StatusBarDevice:- device_id: str- name: str- root: Path- target: Path- connected: bool- display: str- brightness: int = 255- reason: str = ""---STATE_IDLE = StatusBarState("Idle", "circle", 4)-STATE_WORKING = StatusBarState("Working", "arrow.triangle.2.circlepath", 2)-STATE_DONE = StatusBarState("Done", "checkmark.circle", 3)-STATE_ASK = StatusBarState("Ask", "questionmark.circle", 1)-STATUS_BAR_DEVICE_PRIORITY = ("sidepulse", "pixiepulse", "pulsedot", "pixiedot")-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:- if mode in {AgentMode.WAITING_FOR_INPUT, AgentMode.BLOCKED_ERROR}:- return STATE_ASK- if mode in {- AgentMode.WORKING,- AgentMode.TOOL_RUNNING,- AgentMode.LONG_TASK_PROGRESS,- }:- return STATE_WORKING- if mode == AgentMode.COMPLETED:- return STATE_DONE- return STATE_IDLE---def replay_recent_debug_logs(- monitor: LiveAgentMonitor,- *,- providers: tuple[str, ...] = ("codex", "claude"),- max_lines: int = STATUS_BAR_STARTUP_REPLAY_LINES,-) -> int:- replayed = 0- for provider in providers:- try:- path = detect_log_path(provider)- lines = read_recent_lines(path, max_lines) if path.exists() else []- except Exception as exc:- log_status_bar(f"startup_replay {provider} error: {exc}")- continue-- for line in lines:- record = parse_log_line(provider, line)- if record is None:- continue- monitor.ingest_record(record)- replayed += 1- return replayed---class StatusBarController(NSObject):- def init(self):- self = objc.super(StatusBarController, self).init()- if self is None:- return None-- self.settings = load_settings()- self.monitor = self.build_monitor()- 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 = {}- self.last_snapshot = None- self.last_battery_snapshot = None- self.last_battery_error = None- self.last_power_connected = None- self.battery_preview_until = 0.0- self.current_state = STATE_IDLE- self.led_controller = AgentLedController()- self.battery_led_controller = BatteryLedController()- self.agent_led_controllers_by_device = {}- self.battery_led_controllers_by_device = {}- self.last_led_display_kind_by_device = {}- self.device_errors = {}- self.leds_enabled = True- self.led_sync_in_flight = False- 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):- NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)- log_status_bar("launching status item")- self.start_event_server()- self.replay_debug_logs()-- self.status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(- NSVariableStatusItemLength- )- button = self.status_item.button()- button.setTitle_(" Idle")- button.setImage_(image_for_symbol(STATE_IDLE.symbol, STATE_IDLE.label))- button.setToolTip_("SidePulse Agent Monitor: Idle")- log_status_bar("status item created")-- self.refresh_(None)- self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(- STATUS_BAR_REFRESH_SECONDS,- self,- "refresh:",- None,- True,- )- self.lid_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(- LID_POLL_SECONDS,- self,- "pollLid:",- None,- True,- )-- @objc.IBAction- def refresh_(self, _sender):- try:- snapshot = self.monitor.snapshot(include_stale=False)- except Exception as exc:- log_status_bar(f"refresh error: {exc}")- self.set_status(STATE_ASK)- self.sync_keep_awake(AgentMode.BLOCKED_ERROR)- self.sync_leds(AgentMode.BLOCKED_ERROR, None, LED_DISPLAY_AGENT)- self.status_item.setMenu_(build_error_menu(exc))- return-- self.last_snapshot = snapshot- battery_snapshot = self.read_battery_snapshot()- state = state_for_mode(snapshot.aggregate.mode)- self.set_status(state)- self.sync_keep_awake(snapshot.aggregate.mode)- self.sync_leds(- snapshot.aggregate.mode,- battery_snapshot,- self.active_led_display_kind(battery_snapshot),- )- self.status_item.setMenu_(build_menu(snapshot, state, self))-- @objc.IBAction- def forceRefresh_(self, _sender):- self.refresh_(None)-- @objc.IBAction- def openDeepLink_(self, sender):- url = sender.representedObject()- if not url:- return- open_url(str(url))-- @objc.IBAction- def resumeSession_(self, sender):- command = sender.representedObject()- 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():- self.disconnect_device()- else:- self.connect_device()- self.refresh_(None)-- @objc.IBAction- def toggleKeepAwake_(self, _sender):- self.keep_awake.set_enabled(not self.keep_awake.enabled)- 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()-- @objc.IBAction- def installCodexHooks_(self, _sender):- self.update_hooks("codex", install=True)-- @objc.IBAction- def uninstallCodexHooks_(self, _sender):- self.update_hooks("codex", install=False)-- @objc.IBAction- def installClaudeHooks_(self, _sender):- self.update_hooks("claude", install=True)-- @objc.IBAction- def uninstallClaudeHooks_(self, _sender):- self.update_hooks("claude", install=False)-- @objc.IBAction- def toggleCodexTranscripts_(self, sender):- self.set_transcript_monitoring("codex", sender.state() == NSOnState)-- @objc.IBAction- def toggleClaudeTranscripts_(self, sender):- self.set_transcript_monitoring("claude", sender.state() == NSOnState)-- @objc.IBAction- def toggleBatteryLedDisplay_(self, _sender):- self.set_battery_led_display(self.settings.led_display != LED_DISPLAY_BATTERY)-- @objc.IBAction- def setBatteryLedDisplayFromCheckbox_(self, sender):- self.set_battery_led_display(sender.state() == NSOnState)-- @objc.IBAction- def toggleBatteryPowerPreview_(self, _sender):- self.set_battery_power_preview(not self.settings.battery_show_on_power_change)-- @objc.IBAction- 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)-- @objc.IBAction- 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:- previous = self.current_state- self.current_state = state- if self.status_item is None:- return- button = self.status_item.button()- if button is None:- return- button.setTitle_(f" {state.label}")- button.setImage_(image_for_symbol(state.symbol, state.label))- button.setToolTip_(f"SidePulse Agent Monitor: {state.label}")- if previous != state:- log_status_bar(f"state={state.label}")-- def build_monitor(self) -> LiveAgentMonitor:- socket_path = default_event_socket_path()- return LiveAgentMonitor(- sources=(SourceSpec("event-bus", socket_path),),- stale_after_seconds=3600,- latest_state_path=default_latest_state_path(),- )-- def reload_monitor(self) -> None:- self.monitor = self.build_monitor()-- def start_event_server(self) -> None:- self.stop_event_server()- self.event_server = HookEventServer(self.handle_hook_event_message)- try:- socket_path = self.event_server.start()- log_status_bar(f"event_server listening={socket_path}")- except Exception as exc:- self.event_server = None- log_status_bar(f"event_server error: {exc}")-- def stop_event_server(self) -> None:- if self.event_server is not None:- self.event_server.stop()- self.event_server = None-- def handle_hook_event_message(self, provider: str, line: dict) -> None:- try:- record = parse_log_line(- provider,- json.dumps(line, separators=(",", ":"), ensure_ascii=False),- )- if record is not None:- self.monitor.ingest_record(record)- self.schedule_event_refresh()- except Exception as exc:- log_status_bar(f"event_server ingest error: {exc}")-- def schedule_event_refresh(self) -> None:- if self.event_refresh_pending:- return- self.event_refresh_pending = True- self.performSelectorOnMainThread_withObject_waitUntilDone_(- "refreshFromEvent:",- None,- False,- )-- @objc.IBAction- def refreshFromEvent_(self, _sender):- self.event_refresh_pending = False- self.refresh_(None)-- def replay_debug_logs(self) -> None:- replayed = replay_recent_debug_logs(self.monitor)- if replayed:- log_status_bar(f"startup_replay events={replayed}")-- def show_settings_window(self) -> None:- if self.settings_window is None:- self.settings_window = build_settings_window(self)- self.refresh_settings_window()- self.settings_window.makeKeyAndOrderFront_(None)- NSApp.activateIgnoringOtherApps_(True)-- def refresh_settings_window(self) -> None:- if self.settings_window is None:- return-- codex = detect_codex_config()- claude = detect_claude_config()- set_field_value(- self.settings_fields.get("codex_hook_status"),- hook_status_text(codex),- )- set_field_value(- self.settings_fields.get("claude_hook_status"),- hook_status_text(claude),- )- set_field_value(- self.settings_fields.get("settings_path"),- f"Settings: {default_settings_path()}",- )- set_checkbox_state(- self.settings_buttons.get("codex_transcripts"),- self.settings.codex_transcripts_enabled,- )- set_checkbox_state(- self.settings_buttons.get("claude_transcripts"),- self.settings.claude_transcripts_enabled,- )- set_checkbox_state(- self.settings_buttons.get("battery_leds"),- self.settings.led_display == LED_DISPLAY_BATTERY,- )- set_checkbox_state(- 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)- if message:- log_status_bar(f"settings: {message}")-- def update_hooks(self, provider: str, *, install: bool) -> None:- try:- if provider == "codex" and install:- result = install_codex_hooks()- elif provider == "codex":- result = uninstall_codex_hooks()- elif provider == "claude" and install:- result = install_claude_hooks()- else:- result = uninstall_claude_hooks()- except Exception as exc:- self.set_settings_message(f"{provider.title()} hooks failed: {exc}")- self.refresh_settings_window()- return-- action = "installed" if install else "removed"- if not result.changed:- action = "already installed" if install else "already removed"- self.set_settings_message(f"{provider.title()} hooks {action}.")- self.reload_monitor()- self.refresh_settings_window()- self.refresh_(None)-- def set_transcript_monitoring(self, provider: str, enabled: bool) -> None:- try:- self.settings = self.settings.with_transcript_provider(provider, enabled)- save_settings(self.settings)- except Exception as exc:- self.set_settings_message(f"Could not save settings: {exc}")- self.settings = load_settings()- self.refresh_settings_window()- return-- self.reload_monitor()- self.set_settings_message(- f"{provider.title()} transcript CLI fallback {'enabled' if enabled else 'disabled'}."- )- self.refresh_settings_window()- self.refresh_(None)-- def set_battery_led_display(self, enabled: bool) -> None:- try:- display = LED_DISPLAY_BATTERY if enabled else LED_DISPLAY_AGENT- self.settings = self.settings.with_led_display(display)- save_settings(self.settings)- except Exception as exc:- self.set_settings_message(f"Could not save settings: {exc}")- self.settings = load_settings()- self.refresh_settings_window()- return-- self.reset_led_controllers_for_display_change()- self.set_settings_message(f"LED display set to {self.settings.led_display}.")- self.refresh_settings_window()- self.refresh_(None)-- def set_device_display(self, device_id: str | None, display: str) -> 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.with_device_display(- str(device_id),- display,- 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 device display: {exc}")- self.settings = load_settings()- return-- self.reset_led_controllers_for_device(str(device_id))- label = "Battery Level" if display == LED_DISPLAY_BATTERY else "Agent Status"- self.set_settings_message(f"{device.name if device else device_id}: {label}.")- 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)- save_settings(self.settings)- except Exception as exc:- self.set_settings_message(f"Could not save settings: {exc}")- self.settings = load_settings()- self.refresh_settings_window()- return-- self.set_settings_message(- f"Battery power-change preview {'enabled' if enabled else 'disabled'}."- )- self.refresh_settings_window()- self.refresh_(None)-- def read_battery_snapshot(self) -> BatterySnapshot | None:- try:- snapshot = read_battery_snapshot(- full_charge_watts=self.settings.battery_full_charge_watts,- )- except Exception as exc:- error = str(exc)- if error != self.last_battery_error:- log_status_bar(f"battery error: {error}")- self.last_battery_error = error- return None-- self.last_battery_error = None- self.last_battery_snapshot = snapshot- self.update_battery_power_preview(snapshot)- return snapshot-- def update_battery_power_preview(self, snapshot: BatterySnapshot) -> None:- plugged = snapshot.is_plugged- if self.last_power_connected is not None and self.last_power_connected != plugged:- if self.settings.battery_show_on_power_change:- self.battery_preview_until = (- time.monotonic()- + self.settings.battery_power_change_preview_seconds- )- log_status_bar(- f"battery preview power={'plugged' if plugged else 'unplugged'}"- )- self.last_power_connected = plugged-- def active_led_display_kind(self, snapshot: BatterySnapshot | None) -> str:- if self.settings.led_display == LED_DISPLAY_BATTERY:- return LED_DISPLAY_BATTERY- if snapshot is not None and time.monotonic() < self.battery_preview_until:- return LED_DISPLAY_BATTERY- return LED_DISPLAY_AGENT-- def reset_led_controllers_for_display_change(self) -> None:- self.led_controller.reset()- self.battery_led_controller.reset()- for controller in self.agent_led_controllers_by_device.values():- controller.reset()- for controller in self.battery_led_controllers_by_device.values():- controller.reset()- self.last_led_display_kind_by_device.clear()- self.last_led_error = None-- def reset_led_controllers_for_device(self, device_id: str) -> None:- agent_controller = self.agent_led_controllers_by_device.get(device_id)- if agent_controller is not None:- agent_controller.reset()- battery_controller = self.battery_led_controllers_by_device.get(device_id)- if battery_controller is not None:- battery_controller.reset()- self.last_led_display_kind_by_device.pop(device_id, None)- self.device_errors.pop(device_id, None)- self.last_led_error = None-- def agent_controller_for_device(self, device: StatusBarDevice) -> AgentLedController:- controller = self.agent_led_controllers_by_device.get(device.device_id)- if controller is None:- 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:- controller = self.battery_led_controllers_by_device.get(device.device_id)- if controller is None:- 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]:- entries_by_id: dict[str, StatusBarDevice] = {}- try:- candidates = discover_devices()- except Exception as exc:- log_status_bar(f"device discovery error: {exc}")- candidates = []-- for candidate in candidates:- device_id = device_id_for_root(candidate.root)- name = device_display_name(candidate.root.name)- entries_by_id[device_id] = StatusBarDevice(- device_id=device_id,- name=name,- root=candidate.root,- target=candidate.target,- connected=True,- display=self.settings.display_for_device(device_id),- brightness=self.settings.brightness_for_device(device_id),- reason=candidate.reason,- )-- for device in self.settings.devices:- if device.device_id in entries_by_id:- continue- root = Path(device.path).expanduser()- entries_by_id[device.device_id] = StatusBarDevice(- device_id=device.device_id,- name=device.name,- root=root,- target=target_from_device_path(root, DEFAULT_FILE_NAME),- connected=False,- display=device.led_display,- brightness=device.brightness,- reason="previously connected",- )-- entries = sorted(- entries_by_id.values(),- key=lambda item: (not item.connected, normalized_device_name(item.name), str(item.root)),- )- entries = disambiguate_device_names(entries)- if remember:- self.remember_connected_devices(entries)- return entries-- def remember_connected_devices(self, devices: list[StatusBarDevice]) -> None:- settings = self.settings- for device in devices:- if not device.connected:- continue- settings = settings.with_remembered_device(- device_id=device.device_id,- name=device.name,- path=str(device.root),- )- if settings != self.settings:- self.settings = settings- try:- save_settings(self.settings)- except Exception as exc:- log_status_bar(f"device remember error: {exc}")-- def active_led_display_kind_for_device(- self,- device: StatusBarDevice,- battery_snapshot: BatterySnapshot | None,- ) -> str:- if device.display == LED_DISPLAY_BATTERY:- return LED_DISPLAY_BATTERY- if battery_snapshot is not None and time.monotonic() < self.battery_preview_until:- return LED_DISPLAY_BATTERY- return LED_DISPLAY_AGENT-- def sync_leds(- self,- mode: AgentMode,- battery_snapshot: BatterySnapshot | None,- display_kind: str,- ) -> None:- 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- thread = threading.Thread(- target=self.sync_leds_worker,- args=(mode, battery_snapshot, display_kind),- daemon=True,- )- thread.start()-- def sync_leds_worker(- self,- mode: AgentMode,- battery_snapshot: BatterySnapshot | None,- display_kind: str,- ) -> None:- try:- self.sync_leds_now(mode, battery_snapshot, display_kind)- finally:- self.led_sync_in_flight = False-- def sync_leds_now(- self,- mode: AgentMode,- battery_snapshot: BatterySnapshot | None,- display_kind: str,- ) -> None:- devices = [device for device in self.status_bar_devices() if device.connected]- if not devices:- self.ensure_device_selection()- devices = [- device for device in self.status_bar_devices(remember=False) if device.connected- ]- if not devices:- self.last_led_error = None- return-- active_errors: dict[str, str] = {}- for device in devices:- device_display_kind = self.active_led_display_kind_for_device(- device,- battery_snapshot,- )- if self.last_led_display_kind_by_device.get(device.device_id) != device_display_kind:- self.reset_led_controllers_for_device(device.device_id)- self.last_led_display_kind_by_device[device.device_id] = device_display_kind-- if device_display_kind == LED_DISPLAY_BATTERY and battery_snapshot is not None:- result = self.battery_controller_for_device(device).sync_snapshot(battery_snapshot)- label = (- f"{device.name} Battery {battery_snapshot.percent}% "- f"{format_watts(battery_snapshot.adapter_power)}"- )- else:- result = self.agent_controller_for_device(device).sync_mode(mode)- label = f"{device.name} {result.label}"-- if result.error:- active_errors[device.device_id] = result.error- previous_error = self.device_errors.get(device.device_id)- if result.error != previous_error:- log_status_bar(f"led error {device.name}: {result.error}")- continue-- self.device_errors.pop(device.device_id, None)- if result.changed:- target = result.target if result.target is not None else "-"- log_status_bar(f"leds={label} target={target}")-- 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()- self.reset_led_controllers_for_display_change()- self.last_led_error = None- self.last_status_read_error = None- log_status_bar("device connect requested")-- def disconnect_device(self) -> None:- self.leds_enabled = False- targets = self.current_led_targets()- if not targets:- targets = [device.target for device in self.status_bar_devices() if device.connected]- for target in targets:- try:- result = write_mode_to_leds(AgentMode.IDLE_READY, device_path=target)- log_status_bar(f"device disconnected target={result.target}")- except Exception as exc:- log_status_bar(f"device disconnect error: {exc}")- self.reset_led_controllers_for_display_change()- self.last_led_error = None- self.last_status_read_error = None-- def device_connected(self) -> bool:- connected = [- device- for device in self.status_bar_devices(remember=False)- if device.connected- ]- return (- self.leds_enabled- and bool(self.current_led_targets() or connected)- and self.last_led_error is None- and not self.device_errors- )-- def current_led_target(self) -> Path | None:- targets = self.current_led_targets()- return targets[0] if targets else None-- def current_led_targets(self) -> list[Path]:- targets: list[Path] = []- seen: set[str] = set()- for controller in (- *self.battery_led_controllers_by_device.values(),- *self.agent_led_controllers_by_device.values(),- self.battery_led_controller,- self.led_controller,- ):- target = controller.last_target or controller.device_path- if target is None:- continue- if not path_exists(Path(target).parent):- continue- key = str(target)- if key in seen:- continue- targets.append(Path(target))- seen.add(key)- return targets-- def ensure_device_selection(self) -> None:- selected = self.led_controller.device_path or self.battery_led_controller.device_path- if selected is not None:- target = target_from_device_path(- Path(selected),- DEFAULT_FILE_NAME,- )- if path_exists(target.parent):- self.led_controller.device_path = target- self.battery_led_controller.device_path = target- return- self.led_controller.device_path = None- self.battery_led_controller.device_path = None- self.reset_led_controllers_for_display_change()- self.last_led_error = None-- candidates = discover_devices()- if not candidates:- return- target = preferred_status_bar_device(candidates).target- 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)- is_running = self.keep_awake.process_running()- if was_running != is_running:- log_status_bar(f"keep_awake={'active' if is_running else 'released'}")- if self.keep_awake.last_error != self.last_keep_awake_error:- self.last_keep_awake_error = self.keep_awake.last_error- 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- for target in self.status_keepalive_targets():- status_path = self.keep_awake.poke_status_file(target)- if status_path is not None:- read_any = True- log_status_bar(f"sd_keepalive touch={status_path}")- if not read_any and self.keep_awake.last_status_error != self.last_status_read_error:- self.last_status_read_error = self.keep_awake.last_status_error- 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:- return targets- connected_targets = [- device.target for device in self.status_bar_devices(remember=False) if device.connected- ]- if connected_targets:- return connected_targets- return [MOUNT_ROOT / name / KEEPALIVE_FILE_NAME for name in STATUS_BAR_KEEPALIVE_VOLUME_NAMES]---def build_menu(snapshot, state: StatusBarState, target: StatusBarController) -> NSMenu:- menu = NSMenu.alloc().init()-- menu.addItem_(disabled_menu_item("SidePulse"))- menu.addItem_(NSMenuItem.separatorItem())-- menu.addItem_(disabled_menu_item("Devices"))- devices = target.status_bar_devices()- if devices:- for device in devices:- menu.addItem_(build_device_menu_item(device, target))- else:- menu.addItem_(disabled_menu_item("No devices"))-- menu.addItem_(NSMenuItem.separatorItem())- 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"- )- 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:- 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())- settings = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- "Settings...",- "openSettings:",- ",",- )- settings.setTarget_(target)- menu.addItem_(settings)-- quit_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- "Quit",- "quit:",- "q",- )- quit_item.setTarget_(target)- menu.addItem_(quit_item)-- return menu---def build_closed_lid_awake_policy_item(policy: str, target: StatusBarController) -> NSMenuItem:- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- CLOSED_LID_AWAKE_LABELS[policy],- "setClosedLidAwakePolicy:",- "",- )- item.setTarget_(target)- item.setRepresentedObject_(policy)- item.setState_(1 if target.settings.closed_lid_awake_policy == policy else 0)- return item---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()-- agent = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- "Agent Status",- "setDeviceDisplayAgent:",- "",- )- agent.setTarget_(target)- agent.setRepresentedObject_(device.device_id)- agent.setState_(1 if device.display == LED_DISPLAY_AGENT else 0)- submenu.addItem_(agent)-- battery = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- "Battery Level",- "setDeviceDisplayBattery:",- "",- )- battery.setTarget_(target)- battery.setRepresentedObject_(device.device_id)- 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 = 680- height = 840- style = (- NSWindowStyleMaskTitled- | NSWindowStyleMaskClosable- | NSWindowStyleMaskMiniaturizable- )- window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(- ((0, 0), (width, height)),- style,- NSBackingStoreBuffered,- False,- )- window.setTitle_("SidePulse Agent Monitor Settings")- window.center()- content = window.contentView()-- 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, 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, 676, width - 48)- add_label(content, "Transcript Monitoring", 24, 642, 240, 24)- codex_transcripts = add_checkbox(- content,- "CLI fallback: Codex transcripts",- 32,- 608,- 260,- 24,- target,- "toggleCodexTranscripts:",- )- claude_transcripts = add_checkbox(- content,- "CLI fallback: Claude transcripts",- 32,- 576,- 260,- 24,- target,- "toggleClaudeTranscripts:",- )-- 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,- 488,- 260,- 24,- target,- "setBatteryLedDisplayFromCheckbox:",- )- battery_power_preview = add_checkbox(- content,- "Show battery for 7s on plug/unplug",- 32,- 456,- 320,- 24,- target,- "setBatteryPowerPreviewFromCheckbox:",- )-- 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,- }- target.settings_buttons = {- "codex_transcripts": codex_transcripts,- "claude_transcripts": claude_transcripts,- "battery_leds": battery_leds,- "battery_power_preview": battery_power_preview,- "closed_lid_system_override": closed_lid_system_override,- }- return window---def add_label(parent, text: str, x: int, y: int, width: int, height: int):- label = NSTextField.alloc().initWithFrame_(((x, y), (width, height)))- label.setStringValue_(text)- label.setBezeled_(False)- label.setDrawsBackground_(False)- label.setEditable_(False)- label.setSelectable_(False)- parent.addSubview_(label)- return label---def add_button(- parent,- title: str,- x: int,- y: int,- width: int,- height: int,- target: StatusBarController,- selector: str,-):- button = NSButton.alloc().initWithFrame_(((x, y), (width, height)))- button.setTitle_(title)- button.setBezelStyle_(NSBezelStyleRounded)- button.setTarget_(target)- button.setAction_(selector)- parent.addSubview_(button)- return button---def add_checkbox(- parent,- title: str,- x: int,- y: int,- width: int,- height: int,- target: StatusBarController,- selector: str,-):- checkbox = NSButton.alloc().initWithFrame_(((x, y), (width, height)))- checkbox.setButtonType_(NSButtonTypeSwitch)- checkbox.setTitle_(title)- checkbox.setTarget_(target)- checkbox.setAction_(selector)- parent.addSubview_(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_("")- separator.setBezeled_(False)- separator.setEditable_(False)- separator.setDrawsBackground_(True)- parent.addSubview_(separator)- return separator---def set_field_value(field, value: str) -> None:- if field is not 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}"- if config.hook_events:- event_count = len(config.hook_events)- suffix = "event" if event_count == 1 else "events"- return f"Installed ({event_count} {suffix})"- return "Not installed"---def device_id_for_root(root: Path) -> str:- return str(root.expanduser())---def device_display_name(name: str) -> str:- normalized = normalized_device_name(name)- if "pulsedot" in normalized or "pixiedot" in normalized:- return "PulseDot"- if "sidepulse" in normalized or "pixiepulse" in normalized:- return "SidePulse"- return name or "SidePulse Device"---def device_display_label(display: str) -> str:- if display == LED_DISPLAY_BATTERY:- return "Battery Level"- return "Agent Status"---def disabled_menu_item(title: str) -> NSMenuItem:- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, None, "")- item.setEnabled_(False)- return item---def disambiguate_device_names(devices: list[StatusBarDevice]) -> list[StatusBarDevice]:- counts: dict[str, int] = {}- for device in devices:- counts[device.name] = counts.get(device.name, 0) + 1- if all(count == 1 for count in counts.values()):- return devices-- result: list[StatusBarDevice] = []- for device in devices:- if counts.get(device.name, 0) <= 1:- result.append(device)- continue- suffix = duplicate_device_suffix(device)- result.append(- StatusBarDevice(- device_id=device.device_id,- name=f"{device.name} {suffix}" if suffix else device.name,- root=device.root,- target=device.target,- connected=device.connected,- display=device.display,- brightness=device.brightness,- reason=device.reason,- )- )- return result---def duplicate_device_suffix(device: StatusBarDevice) -> str:- root_name = device.root.name- normalized_root = normalized_device_name(root_name)- normalized_name = normalized_device_name(device.name)- if normalized_root.startswith(normalized_name):- suffix = root_name[len(device.name) :].strip()- return suffix- return root_name---def preferred_status_bar_device(candidates: list[DeviceCandidate]) -> DeviceCandidate:- return sorted(candidates, key=status_bar_device_sort_key)[0]---def status_bar_device_sort_key(candidate: DeviceCandidate) -> tuple[int, str]:- name = normalized_device_name(candidate.root.name)- for index, hint in enumerate(STATUS_BAR_DEVICE_PRIORITY):- if hint in name:- return (index, candidate.root.name.lower())- return (len(STATUS_BAR_DEVICE_PRIORITY), candidate.root.name.lower())---def build_session_menu_item(- status: AgentStatus,- now: datetime,- target: StatusBarController,-) -> NSMenuItem:- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- menu_title_for_status(status, now),- None,- "",- )- item.setImage_(provider_icon_for_status(status))- submenu = NSMenu.alloc().init()- 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,- selector: str,- represented_object: str | None,- target: StatusBarController,-) -> None:- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- title if represented_object else f"{title} unavailable",- selector,- "",- )- item.setTarget_(target)- item.setEnabled_(represented_object is not None)- if represented_object is not None:- item.setRepresentedObject_(represented_object)- menu.addItem_(item)---def build_error_menu(exc: Exception) -> NSMenu:- menu = NSMenu.alloc().init()- item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(- f"Agent monitor error: {exc}",- None,- "",- )- item.setEnabled_(False)- menu.addItem_(item)- return menu---def recent_statuses(snapshot) -> list[AgentStatus]:- statuses = list(snapshot.statuses)- statuses.sort(key=lambda status: (status.priority, -status.updated_at.timestamp()))- return statuses[:12]---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))- 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):- try:- image = NSImage.imageWithSystemSymbolName_accessibilityDescription_(- symbol,- description,- )- if image is not None:- image.setTemplate_(True)- except Exception:- image = None- return image---def log_status_bar(message: str) -> None:- timestamp = datetime.now().astimezone().isoformat(timespec="seconds")- print(f"{timestamp} {message}", flush=True)---def compact_path(path: str, max_len: int = 48) -> str:- if len(path) <= max_len:- return path- keep = max_len - 1- return "." + path[-keep:]---def format_age(seconds: float) -> str:- seconds = max(0, int(seconds))- if seconds < 60:- return f"{seconds}s"- minutes, rest = divmod(seconds, 60)- if minutes < 60:- return f"{minutes}m{rest:02d}s"- hours, minutes = divmod(minutes, 60)- 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(- [- 'tell application "Terminal"',- " activate",- f" do script {applescript_quote(command)}",- "end tell",- ]- )- subprocess.Popen(- ["/usr/bin/osascript", "-e", script],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )---def applescript_quote(value: str) -> str:- return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'---def run_status_bar() -> None:- app = NSApplication.sharedApplication()- controller = StatusBarController.alloc().init()- app.setDelegate_(controller)- app.run()---def main() -> int:- run_status_bar()- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/src/agent_monitor/status_bar_launch.py b/src/agent_monitor/status_bar_launch.pydeleted file mode 100644index 0c79ada..0000000--- a/src/agent_monitor/status_bar_launch.py+++ /dev/null@@ -1,184 +0,0 @@-from __future__ import annotations--import os-import plistlib-import subprocess-import sys-from dataclasses import dataclass-from pathlib import Path-from typing import Any--from .providers import default_state_dir--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)-class LaunchAgentResult:- label: str- plist_path: Path- changed: bool- started: bool = False- stopped: bool = False---def launch_agent_path(home: Path | None = None) -> Path:- base = home or Path.home()- 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,- stderr_path: Path | None = None,-) -> dict[str, Any]:- executable = str(python_executable or sys.executable or "python3")- state_dir = default_state_dir()- stdout = stdout_path or state_dir / "status-bar.out.log"- stderr = stderr_path or state_dir / "status-bar.err.log"-- plist: dict[str, Any] = {- "Label": LAUNCH_AGENT_LABEL,- "ProgramArguments": [- executable,- "-m",- "agent_monitor",- "status-bar",- "--foreground",- ],- "RunAtLoad": True,- "StandardOutPath": str(stdout),- "StandardErrorPath": str(stderr),- "WorkingDirectory": str(Path.home()),- "EnvironmentVariables": {- "PYTHONUNBUFFERED": "1",- "PATH": launch_agent_path_env(executable),- },- }- return plist---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- changed = existing != data-- target.parent.mkdir(parents=True, exist_ok=True)- 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:- restart_launch_agent(target)- started = True-- return LaunchAgentResult(- label=LAUNCH_AGENT_LABEL,- plist_path=target,- changed=changed,- started=started,- )---def uninstall_launch_agent(plist_path: Path | None = None) -> LaunchAgentResult:- target = plist_path or launch_agent_path()- bootout_launch_agent(target)- changed = target.exists()- if target.exists():- target.unlink()- return LaunchAgentResult(- label=LAUNCH_AGENT_LABEL,- plist_path=target,- changed=changed,- stopped=True,- )---def restart_launch_agent(plist_path: Path) -> None:- bootout_launch_agent(plist_path)- subprocess.run(- ["launchctl", "bootstrap", launch_domain(), str(plist_path)],- check=True,- )- subprocess.run(- ["launchctl", "kickstart", "-k", f"{launch_domain()}/{LAUNCH_AGENT_LABEL}"],- check=False,- )---def bootout_launch_agent(plist_path: Path) -> None:- subprocess.run(- ["launchctl", "bootout", launch_domain(), str(plist_path)],- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- check=False,- )---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()}"---def launch_agent_path_env(python_executable: str) -> str:- candidates = [- Path.home() / ".local" / "bin",- executable_parent(python_executable),- Path("/opt/homebrew/bin"),- Path("/usr/local/bin"),- Path("/usr/bin"),- Path("/bin"),- Path("/usr/sbin"),- Path("/sbin"),- Path("/opt/anaconda3/bin"),- ]- seen: set[str] = set()- result: list[str] = []- for candidate in candidates:- if candidate is None:- continue- text = str(candidate)- if text in seen:- continue- seen.add(text)- result.append(text)- return ":".join(result)---def executable_parent(python_executable: str) -> Path | None:- path = Path(python_executable)- if not path.is_absolute():- return None- return path.parentdiff --git a/tests/test_agent_monitor.py b/tests/test_agent_monitor.pydeleted file mode 100644index eca72a7..0000000--- a/tests/test_agent_monitor.py+++ /dev/null@@ -1,3420 +0,0 @@-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 (- BATTERY_CHARGING_MINT,- BatteryLedController,- BatterySnapshot,- parse_ioreg_battery_plist,- program_for_battery,-)-from agent_monitor import collector as collector_module-from agent_monitor import cli as cli_module-from agent_monitor.collector import (- AgentMonitor,- LiveAgentMonitor,- MonitorSnapshot,- SourceSpec,- default_sources,-)-from agent_monitor.cli import build_parser, visible_watch_statuses-from agent_monitor.device_writer import (- DeviceWriteError,- discover_devices,- normalize_led_text,- validate_led_text,- write_led_program,-)-from agent_monitor.hook import write_hook_payload-from agent_monitor.ipc import HookEventServer, send_hook_event-from agent_monitor.install import (- install_claude_hooks,- install_codex_hooks,- uninstall_claude_hooks,- uninstall_codex_hooks,- update_codex_trusted_hashes,-)-from agent_monitor.keep_awake import KeepAwakeController, status_file_for_target-from agent_monitor.led_status import (- AgentLedController,- LedDisplayState,- display_state_for_mode,- led_count_for_target,- 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.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,- install_launch_agent,-)---class FakeProcess:- def __init__(self) -> None:- self.terminated = False- self.killed = False-- def poll(self):- return 0 if self.terminated or self.killed else None-- def terminate(self) -> None:- self.terminated = True-- def wait(self, timeout=None):- return 0-- def kill(self) -> None:- self.killed = True---class AgentMonitorTests(unittest.TestCase):- def test_aggregates_highest_priority_status(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- codex = base / "codex.jsonl"- claude = base / "claude.jsonl"-- codex.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:00Z",- "event": {- "hook_event_name": "PreToolUse",- "session_id": "codex-session",- "tool_name": "Bash",- },- }- )- + "\n"- )- claude.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:01Z",- "hook_event_name": "Notification",- "session_id": "claude-session",- "notification_type": "idle_prompt",- "message": "Claude is waiting for your input",- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", codex), SourceSpec("claude", claude)),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)- self.assertEqual(len(snapshot.statuses), 2)-- def test_hook_log_writes_provider_formats(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- codex = base / "codex.jsonl"- claude = base / "claude.jsonl"-- write_hook_payload(- "codex",- codex,- '{"hook_event_name":"Stop","session_id":"abc"}',- )- write_hook_payload(- "claude",- claude,- '{"hook_event_name":"Stop","session_id":"xyz"}',- )-- codex_obj = json.loads(codex.read_text())- claude_obj = json.loads(claude.read_text())-- self.assertIn("event", codex_obj)- self.assertEqual(codex_obj["event"]["session_id"], "abc")- self.assertNotIn("event", claude_obj)- self.assertEqual(claude_obj["session_id"], "xyz")- self.assertTrue(- datetime.fromisoformat(codex_obj["logged_at"].replace("Z", "+00:00")).tzinfo- is not None- )-- def test_hook_event_server_receives_socket_message(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- received: list[tuple[str, dict]] = []- server = HookEventServer(- lambda provider, line: received.append((provider, line)),- socket_path=Path(tmp) / "events.sock",- )- try:- server.start()- sent = send_hook_event(- "codex",- {- "logged_at": "2026-06-20T06:00:00Z",- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Done.",- },- },- socket_path=server.socket_path,- timeout=0.5,- )-- deadline = time.time() + 1- while sent and not received and time.time() < deadline:- time.sleep(0.01)-- self.assertTrue(sent)- self.assertTrue(received)- self.assertEqual(received[0][0], "codex")- self.assertEqual(- received[0][1]["event"]["hook_event_name"],- "Stop",- )- finally:- server.stop()-- def test_live_agent_monitor_ingests_events_and_persists_latest_state(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- latest = base / "latest.json"- source = SourceSpec("event-bus", base / "events.sock")- monitor = LiveAgentMonitor(- sources=(source,),- stale_after_seconds=3600,- latest_state_path=latest,- )- line = {- "logged_at": datetime.now(timezone.utc).isoformat(),- "event": {- "hook_event_name": "PreToolUse",- "session_id": "codex-session",- "cwd": "/tmp/project",- "tool_name": "Bash",- },- }- record = parse_log_line("codex", json.dumps(line))-- self.assertIsNotNone(record)- monitor.ingest_record(record)- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(snapshot.statuses[0].tool_name, "Bash")- self.assertTrue(latest.exists())-- reloaded = LiveAgentMonitor(- sources=(source,),- stale_after_seconds=3600,- latest_state_path=latest,- )- self.assertEqual(reloaded.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)-- def test_status_bar_startup_replay_ingests_recent_debug_logs(self) -> None:- try:- from agent_monitor import status_bar- except SystemExit as exc:- self.skipTest(str(exc))-- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- log = base / "codex.jsonl"- session_id = "eeeeeeee-ffff-7aaa-8bbb-cccccccccccc"- log.write_text(- json.dumps(- {- "logged_at": datetime.now(timezone.utc).isoformat(),- "event": {- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": "/tmp/project",- "prompt": "startup replay should restore this",- },- }- )- + "\n"- )- monitor = LiveAgentMonitor()-- with patch(- "agent_monitor.status_bar.detect_log_path",- return_value=log,- ):- replayed = status_bar.replay_recent_debug_logs(- monitor,- providers=("codex",),- max_lines=20,- )-- snapshot = monitor.snapshot()- self.assertEqual(replayed, 1)- 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)- config = base / "config.toml"- log = base / "codex.jsonl"- config.write_text(- "\n".join(- [- '[features]',- 'js_repl = false',- '',- '[[hooks.PreToolUse]]',- '[[hooks.PreToolUse.hooks]]',- 'type = "command"',- f"command = '''echo old >> {log}'''",- '',- '[hooks.state]',- 'source = "keep-me"',- '',- ]- )- )-- result = install_codex_hooks(- log_path=log,- config_path=config,- python_executable="python3",- )-- self.assertTrue(result.changed)- text = config.read_text()- self.assertIn("hooks = true", text)- self.assertIn('[hooks.state]', text)- self.assertIn('source = "keep-me"', text)- self.assertIn("hook_entry.py", text)- self.assertIn("--provider codex", text)- self.assertIn(str(log), text)- self.assertNotIn("echo old", text)-- def test_codex_installer_refreshes_managed_hook_trust_hashes(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- config = base / "config.toml"- log = base / "codex.jsonl"- key = f"{config}:pre_tool_use:0:0"- config.write_text("[features]\nhooks = true\n")-- with patch("agent_monitor.install.should_refresh_codex_hook_trust", return_value=True):- with patch(- "agent_monitor.install.resolve_codex_hook_hashes",- return_value={key: "sha256:new-current-hash"},- ):- result = install_codex_hooks(- log_path=log,- config_path=config,- python_executable="python3",- )-- self.assertTrue(result.changed)- text = config.read_text()- self.assertIn(f'[hooks.state."{key}"]', text)- self.assertIn('trusted_hash = "sha256:new-current-hash"', text)-- def test_update_codex_trusted_hashes_preserves_other_state(self) -> None:- text = "\n".join(- [- "[hooks.state]",- 'source = "keep-me"',- "",- '[hooks.state."/tmp/config.toml:pre_tool_use:0:0"]',- 'trusted_hash = "sha256:old"',- "",- ]- )-- updated = update_codex_trusted_hashes(- text,- {- "/tmp/config.toml:pre_tool_use:0:0": "sha256:new",- "/tmp/config.toml:stop:0:0": "sha256:stop",- },- )-- self.assertIn('source = "keep-me"', updated)- self.assertIn('trusted_hash = "sha256:new"', updated)- self.assertIn('[hooks.state."/tmp/config.toml:stop:0:0"]', updated)- self.assertIn('trusted_hash = "sha256:stop"', updated)- self.assertNotIn("sha256:old", updated)-- def test_claude_installer_replaces_target_hook_and_preserves_other_hooks(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- config = base / "settings.json"- log = base / "claude.jsonl"- config.write_text(- json.dumps(- {- "permissions": {"allow": ["Bash(date)"]},- "hooks": {- "PreToolUse": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": f"jq -c . >> {log}",- },- {- "type": "command",- "command": "echo keep >> /tmp/other.log",- },- ],- }- ]- },- }- )- )-- result = install_claude_hooks(- log_path=log,- config_path=config,- python_executable="python3",- )-- self.assertTrue(result.changed)- data = json.loads(config.read_text())- commands = [- hook["command"]- for entry in data["hooks"]["PreToolUse"]- for hook in entry["hooks"]- ]- self.assertIn("echo keep >> /tmp/other.log", commands)- self.assertTrue(any("hook_entry.py" in command for command in commands))- self.assertFalse(any(command.startswith("jq -c") for command in commands))- self.assertEqual(data["permissions"]["allow"], ["Bash(date)"])-- def test_codex_uninstaller_removes_monitor_hooks_and_preserves_config(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- config = base / "config.toml"- log = base / "codex.jsonl"- config.write_text(- "\n".join(- [- "[features]",- "js_repl = false",- "",- "[hooks.state]",- 'source = "keep-me"',- "",- ]- )- )- install_codex_hooks(log_path=log, config_path=config, python_executable="python3")-- result = uninstall_codex_hooks(log_path=log, config_path=config)-- self.assertTrue(result.changed)- text = config.read_text()- self.assertIn("[features]", text)- self.assertIn("js_repl = false", text)- self.assertIn("[hooks.state]", text)- self.assertIn('source = "keep-me"', text)- self.assertNotIn("agent-monitor hooks", text)- self.assertNotIn(str(log), text)-- def test_claude_uninstaller_removes_monitor_hooks_and_preserves_other_hooks(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- config = base / "settings.json"- log = base / "claude.jsonl"- config.write_text(- json.dumps(- {- "permissions": {"allow": ["Bash(date)"]},- "hooks": {- "PreToolUse": [- {- "matcher": "*",- "hooks": [- {- "type": "command",- "command": "echo keep >> /tmp/other.log",- }- ],- }- ]- },- }- )- )- install_claude_hooks(log_path=log, config_path=config, python_executable="python3")-- result = uninstall_claude_hooks(log_path=log, config_path=config)-- self.assertTrue(result.changed)- data = json.loads(config.read_text())- commands = [- hook["command"]- for entry in data["hooks"]["PreToolUse"]- for hook in entry["hooks"]- ]- self.assertEqual(commands, ["echo keep >> /tmp/other.log"])- self.assertEqual(data["permissions"]["allow"], ["Bash(date)"])-- def test_sidepulse_agent_monitor_command_shape(self) -> None:- parser = build_parser(prog="sidepulse agent-monitor")-- install = parser.parse_args(["install"])- live = parser.parse_args(["live", "--recent-seconds", "120"])- leds = parser.parse_args(["leds", "--once", "--dry-run"])- uninstall = parser.parse_args(["uninstall"])- status_bar = parser.parse_args(["status-bar"])- status_bar_foreground = parser.parse_args(["status-bar", "--foreground"])-- self.assertEqual(install.provider, "all")- self.assertEqual(live.command, "live")- self.assertEqual(live.recent_seconds, 120)- self.assertEqual(leds.command, "leds")- self.assertTrue(leds.once)- self.assertTrue(leds.dry_run)- self.assertEqual(uninstall.provider, "all")- self.assertEqual(status_bar.command, "status-bar")- self.assertFalse(status_bar.foreground)- self.assertFalse(status_bar.uninstall)- self.assertTrue(status_bar_foreground.foreground)- self.assertIn("sidepulse agent-monitor", parser.format_usage())-- def test_sidepulse_entrypoint_dispatches_to_agent_monitor(self) -> None:- with patch.object(cli_module, "main", return_value=17) as main:- result = cli_module.sidepulse_main(["agent-monitor", "live"])-- self.assertEqual(result, 17)- main.assert_called_once_with(["live"], prog="sidepulse agent-monitor")-- def test_sidepulse_battery_command_shape(self) -> None:- parser = cli_module.build_sidepulse_parser()-- status = parser.parse_args(["battery", "status", "--json"])- leds = parser.parse_args(["battery", "leds", "--once", "--dry-run", "--full-watts", "140"])- configure = parser.parse_args(["battery", "configure", "--display", "battery"])-- self.assertEqual(status.command, "battery")- self.assertEqual(status.battery_command, "status")- self.assertTrue(status.json)- self.assertEqual(leds.battery_command, "leds")- self.assertTrue(leds.once)- self.assertTrue(leds.dry_run)- self.assertEqual(leds.full_watts, "140")- 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"- device.mkdir()-- target = write_led_program(- r"off\n#FF00FF pulse",- device_path=device,- )-- self.assertEqual(target, device / "LEDS.LED")- self.assertEqual(target.read_text(), "off\n#FF00FF pulse")-- 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()- (device / "LEDS.TXT").write_text("off")-- target = write_led_program(- r"off\n#FF00FF pulse",- device_path=device,- )-- 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()-- 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.LED")-- def test_sidepulse_write_prefers_leds_led_when_available(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- mount_root = Path(tmp)- device = mount_root / "SidePulse"- device.mkdir()- (device / "LEDS.LED").write_text("off")-- 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)- good = mount_root / "PulseDot"- bad = mount_root / "SidePulse"- good.mkdir()- bad.mkdir()- (good / "LEDS.LED").write_text("off")- original_is_dir = Path.is_dir-- def flaky_is_dir(path: Path) -> bool:- if path == bad:- raise OSError("offline")- return original_is_dir(path)-- with patch.object(Path, "is_dir", flaky_is_dir):- candidates = discover_devices(mount_root=mount_root)-- self.assertEqual(len(candidates), 1)- self.assertEqual(candidates[0].root, good)-- def test_sidepulse_write_validates_device_limits(self) -> None:- self.assertEqual(normalize_led_text(r"off\n#FF00FF pulse"), "off\n#FF00FF pulse")- with self.assertRaises(DeviceWriteError):- write_led_program("x" * 513, device_path=Path("/tmp/device"), dry_run=True)- write_led_program("\n".join(["off"] * 20), device_path=Path("/tmp/device"), dry_run=True)- with self.assertRaises(DeviceWriteError):- write_led_program("\n".join(["off"] * 21), device_path=Path("/tmp/device"), dry_run=True)-- def test_sidepulse_write_entrypoint(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- device = Path(tmp) / "PulseDot"- device.mkdir()- result = cli_module.sidepulse_main(- ["write", r"off\n#FF00FF pulse", "--device", str(device)]- )-- self.assertEqual(result, 0)- self.assertEqual((device / "LEDS.LED").read_text(), "off\n#FF00FF pulse")-- def test_led_status_maps_agent_modes_to_programs(self) -> None:- self.assertEqual(- display_state_for_mode(AgentMode.WAITING_FOR_INPUT),- LedDisplayState.ASK,- )- self.assertEqual(- display_state_for_mode(AgentMode.TOOL_RUNNING),- LedDisplayState.WORKING,- )- self.assertEqual(- display_state_for_mode(AgentMode.COMPLETED),- LedDisplayState.DONE,- )- self.assertEqual(- display_state_for_mode(AgentMode.IDLE_READY),- LedDisplayState.IDLE,- )-- self.assertEqual(- program_for_display_state(LedDisplayState.IDLE),- "off\n#020204 6s pulse\nrepeat",- )- self.assertEqual(program_for_display_state(LedDisplayState.DONE), "#00FF66")- self.assertIn("#FF3A00 1.6s pulse", program_for_display_state(LedDisplayState.ASK))- self.assertEqual(- program_for_display_state(LedDisplayState.WORKING, led_count=2).splitlines(),- [- "off 160ms cosine",- "0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms",- "repeat",- ],- )- self.assertEqual(- 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()-- result = write_mode_to_leds(AgentMode.WORKING, device_path=device)-- self.assertEqual(result.state, LedDisplayState.WORKING)- self.assertEqual(result.target, device / "LEDS.LED")- self.assertEqual(- (device / "LEDS.LED").read_text(),- "off 160ms cosine\n"- "0:#00E5FF 760ms pulse 0ms; 1:#00E5FF 760ms pulse 260ms\n"- "repeat",- )-- write_mode_to_leds(AgentMode.IDLE_READY, device_path=device)-- self.assertEqual(- (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.LED")), 2)- self.assertEqual(led_count_for_target(Path("/Volumes/SidePulse/LEDS.LED")), 8)-- def test_sidepulse_working_program_uses_eight_leds(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- device = Path(tmp) / "SidePulse"- device.mkdir()-- write_mode_to_leds(AgentMode.WORKING, device_path=device)-- lines = (device / "LEDS.LED").read_text().splitlines()- self.assertEqual(len(lines), 3)- self.assertEqual(lines[0], "off 160ms cosine")- self.assertIn("0:#00E5FF 760ms pulse 0ms", lines[1])- self.assertIn("5:#00E5FF 760ms pulse 475ms", lines[1])- self.assertIn("7:#00E5FF 760ms pulse 665ms", lines[1])- self.assertEqual(lines[-1], "repeat")-- def test_agent_led_controller_skips_unchanged_state(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- device = Path(tmp) / "SidePulse"- device.mkdir()- controller = AgentLedController(device_path=device)-- first = controller.sync_mode(AgentMode.COMPLETED)- second = controller.sync_mode(AgentMode.COMPLETED)- third = controller.sync_mode(AgentMode.WAITING_FOR_INPUT)-- self.assertTrue(first.changed)- self.assertFalse(second.changed)- self.assertTrue(third.changed)- self.assertIn("#FF3A00 1.6s pulse", (device / "LEDS.LED").read_text())-- def test_battery_parser_uses_adapter_watts_and_raw_capacity(self) -> None:- payload = plistlib.dumps(- [- {- "CurrentCapacity": 50,- "ExternalConnected": True,- "IsCharging": True,- "FullyCharged": False,- "Voltage": 12000,- "Amperage": 1000,- "AppleRawCurrentCapacity": 4000,- "AppleRawMaxCapacity": 8000,- "DesignCapacity": 10000,- "CycleCount": 12,- "AdapterDetails": {- "Watts": 96,- "AdapterVoltage": 20000,- "Current": 4800,- "UsbHvcMenu": [- {"MaxVoltage": 5000, "MaxCurrent": 3000},- {"MaxVoltage": 20000, "MaxCurrent": 4800},- ],- },- }- ]- )-- snapshot = parse_ioreg_battery_plist(payload)-- self.assertEqual(snapshot.percent, 50)- self.assertTrue(snapshot.is_plugged)- self.assertTrue(snapshot.is_charging)- self.assertEqual(snapshot.adapter_power, 96)- self.assertEqual(snapshot.health_percent, 80)- self.assertEqual(snapshot.current_capacity_mah, 4000)- self.assertEqual(len(snapshot.pd_profiles), 2)-- def test_battery_program_matches_simulator_frontier_pulse(self) -> None:- snapshot = BatterySnapshot(- percent=50,- is_plugged=True,- is_charging=True,- adapter_watts=70,- full_charge_watts=140,- )-- program = program_for_battery(snapshot, led_count=8)-- validate_led_text(program)- lines = program.splitlines()- self.assertIn(f"0:{BATTERY_CHARGING_MINT} 360ms ease", lines[0])- self.assertIn(f"3:{BATTERY_CHARGING_MINT} 360ms ease", lines[0])- self.assertIn("4:#000000 360ms ease", lines[0])- self.assertEqual(lines[1], f"4:{BATTERY_CHARGING_MINT} 790ms pulse")- self.assertEqual(len(lines), 2)- self.assertNotIn("repeat", program)- self.assertNotIn("\noff", program)-- def test_unplugged_battery_program_eases_to_static_level(self) -> None:- snapshot = BatterySnapshot(percent=50, is_plugged=False)-- program = program_for_battery(snapshot, led_count=8)-- validate_led_text(program)- self.assertEqual(len(program.splitlines()), 1)- self.assertIn("0:#FFB000 360ms ease", program)- self.assertIn("3:#FFB000 360ms ease", program)- self.assertIn("4:#000000 360ms ease", program)- self.assertNotIn("repeat", program)-- def test_battery_program_uses_partial_next_led(self) -> None:- snapshot = BatterySnapshot(percent=57, is_plugged=False)-- program = program_for_battery(snapshot, led_count=8)-- validate_led_text(program)- segments = program.split(";")- self.assertEqual(segments[0], "0:#00FF66 360ms ease")- self.assertEqual(segments[3], "3:#00FF66 360ms ease")- 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,- is_plugged=True,- is_charging=True,- adapter_watts=140,- full_charge_watts=140,- )-- program = program_for_battery(snapshot, led_count=8)-- validate_led_text(program)- self.assertIn(f"6:{BATTERY_CHARGING_MINT} 1400ms pulse", program)- self.assertNotIn("repeat", program)- self.assertNotIn("none", program)-- def test_battery_led_controller_animates_charging_on_cadence(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- device = Path(tmp) / "SidePulse"- device.mkdir()- controller = BatteryLedController(device_path=device)- snapshot = BatterySnapshot(- percent=50,- is_plugged=True,- is_charging=True,- adapter_watts=70,- full_charge_watts=140,- )-- with patch(- "agent_monitor.battery.time.monotonic",- side_effect=[0.0, 0.5, 2.0],- ):- first = controller.sync_snapshot(snapshot)- second = controller.sync_snapshot(snapshot)- third = controller.sync_snapshot(snapshot)-- self.assertTrue(first.changed)- self.assertFalse(second.changed)- self.assertTrue(third.changed)-- def test_battery_led_controller_skips_unchanged_static_level(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- device = Path(tmp) / "SidePulse"- device.mkdir()- controller = BatteryLedController(device_path=device)- snapshot = BatterySnapshot(percent=50, is_plugged=False)-- with patch(- "agent_monitor.battery.time.monotonic",- side_effect=[0.0, 10.0],- ):- first = controller.sync_snapshot(snapshot)- second = controller.sync_snapshot(snapshot)-- self.assertTrue(first.changed)- self.assertFalse(second.changed)-- def test_keep_awake_holds_working_then_graces_done(self) -> None:- processes: list[FakeProcess] = []-- def factory(*_args, **_kwargs):- process = FakeProcess()- processes.append(process)- return process-- controller = KeepAwakeController(- grace_seconds=300,- process_factory=factory,- )-- self.assertTrue(controller.update(AgentMode.WORKING, now=100))- self.assertEqual(len(processes), 1)- self.assertTrue(controller.process_running())-- self.assertTrue(controller.update(AgentMode.COMPLETED, now=110))- self.assertIn("grace", controller.detail(now=110))-- self.assertTrue(controller.update(AgentMode.IDLE_READY, now=200))- self.assertTrue(controller.process_running())-- self.assertFalse(controller.update(AgentMode.IDLE_READY, now=411))- self.assertFalse(controller.process_running())- self.assertTrue(processes[0].terminated)-- def test_keep_awake_ask_grace_expires_without_refresh_extension(self) -> None:- processes: list[FakeProcess] = []-- def factory(*_args, **_kwargs):- process = FakeProcess()- processes.append(process)- return process-- controller = KeepAwakeController(- grace_seconds=300,- process_factory=factory,- )-- self.assertTrue(controller.update(AgentMode.WAITING_FOR_INPUT, now=100))- self.assertTrue(controller.update(AgentMode.WAITING_FOR_INPUT, now=350))- self.assertFalse(controller.update(AgentMode.WAITING_FOR_INPUT, now=401))- self.assertEqual(len(processes), 1)- self.assertTrue(processes[0].terminated)-- def test_keep_awake_touches_keepalive_file_once_per_interval(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- device = Path(tmp) / "SidePulse"- device.mkdir()- status_path = device / "keepalive"- reads: list[Path] = []-- controller = KeepAwakeController(- status_read_seconds=60,- status_reader=lambda path: reads.append(path),- status_read_async=False,- )-- self.assertEqual(status_file_for_target(device / "LEDS.LED"), status_path)- self.assertEqual(status_file_for_target(device / "STATUS.TXT"), status_path)- self.assertEqual(- controller.poke_status_file(device / "LEDS.LED", now=0),- status_path,- )- self.assertIsNone(controller.poke_status_file(device / "LEDS.LED", now=30))- self.assertEqual(- controller.poke_status_file(device / "LEDS.LED", now=61),- status_path,- )- 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")-- self.assertEqual(- default_state_dir(home),- home / ".local" / "state" / "sidepulse" / "agent-monitor",- )- self.assertEqual(- default_log_path("codex", home),- home / ".local" / "state" / "sidepulse" / "agent-monitor" / "codex.jsonl",- )-- with patch.dict(os.environ, {"XDG_STATE_HOME": "/tmp/xdg-state"}):- self.assertEqual(- default_state_dir(),- Path("/tmp/xdg-state") / "sidepulse" / "agent-monitor",- )-- def test_install_defaults_to_standard_state_log_path(self) -> None:- parser = build_parser()- args = parser.parse_args(["install", "codex"])-- with patch.object(- cli_module,- "default_log_path",- return_value=Path("/tmp/state/sidepulse/agent-monitor/codex.jsonl"),- ):- self.assertEqual(- cli_module.install_log_path("codex", args),- Path("/tmp/state/sidepulse/agent-monitor/codex.jsonl"),- )-- def test_settings_use_xdg_config_dir_and_round_trip(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- config_home = Path(tmp) / "xdg-config"- settings_path = config_home / "sidepulse" / "agent-monitor" / "settings.json"-- with patch.dict(os.environ, {"XDG_CONFIG_HOME": str(config_home)}):- self.assertEqual(default_config_dir(), settings_path.parent)- self.assertEqual(default_settings_path(), settings_path)-- saved = AgentMonitorSettings(- codex_transcripts_enabled=False,- claude_transcripts_enabled=True,- )- self.assertEqual(save_settings(saved), settings_path)- self.assertEqual(load_settings(), saved)-- def test_default_sources_respect_transcript_settings(self) -> None:- settings = AgentMonitorSettings(- codex_transcripts_enabled=False,- claude_transcripts_enabled=True,- )-- providers = [source.provider for source in default_sources(settings)]-- self.assertNotIn("codex-transcripts", providers)- self.assertIn("claude-transcripts", providers)-- def test_default_sources_are_hook_only_by_default(self) -> None:- providers = [source.provider for source in default_sources(AgentMonitorSettings())]-- self.assertIn("codex", providers)- self.assertIn("claude", providers)- self.assertNotIn("codex-transcripts", providers)- self.assertNotIn("claude-transcripts", providers)-- def test_settings_round_trip_remembered_device_display_modes(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- settings_path = Path(tmp) / "settings.json"- 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",- brightness=128,- ),- )- )-- save_settings(settings, settings_path)- loaded = load_settings(settings_path)-- 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(- "/Volumes/PulseDot",- "battery",- name="PulseDot",- path="/Volumes/PulseDot",- )-- remembered = settings.with_remembered_device(- device_id="/Volumes/PulseDot",- name="PulseDot",- path="/Volumes/PulseDot",- )-- 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(- python_executable="/usr/bin/python3",- stdout_path=Path("/tmp/sidepulse.out.log"),- stderr_path=Path("/tmp/sidepulse.err.log"),- )-- self.assertEqual(plist["Label"], LAUNCH_AGENT_LABEL)- self.assertEqual(- plist["ProgramArguments"],- [- "/usr/bin/python3",- "-m",- "agent_monitor",- "status-bar",- "--foreground",- ],- )- self.assertTrue(plist["RunAtLoad"])- self.assertEqual(plist["StandardOutPath"], "/tmp/sidepulse.out.log")- 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(- provider="codex",- agent_id="recent",- display_name="Recent",- mode=AgentMode.WORKING,- updated_at=now - timedelta(seconds=20),- event_name="PostToolUse",- )- older = AgentStatus(- provider="claude",- agent_id="older",- display_name="Older",- mode=AgentMode.COMPLETED,- updated_at=now - timedelta(seconds=600),- event_name="Stop",- )- snapshot = MonitorSnapshot(- aggregate=AggregateStatus(AgentMode.WORKING, 2, 0, recent),- statuses=(recent, older),- stale_statuses=(),- sources=(),- collected_at=now,- )-- visible = visible_watch_statuses(snapshot, recent_seconds=120, include_stale=False)-- self.assertEqual([status.agent_id for status in visible], ["recent"])-- def test_orphaned_tool_running_expires_before_session_stale_timeout(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- old = datetime.now(timezone.utc) - timedelta(seconds=180)- log.write_text(- json.dumps(- {- "logged_at": old.strftime("%Y-%m-%dT%H:%M:%SZ"),- "event": {- "hook_event_name": "PreToolUse",- "session_id": "codex-session",- "tool_name": "Bash",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=300,- tool_running_timeout_seconds=120,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.IDLE_READY)- self.assertEqual(snapshot.statuses, ())- self.assertEqual(len(snapshot.stale_statuses), 1)- self.assertEqual(snapshot.stale_statuses[0].mode, AgentMode.TOOL_RUNNING)-- def test_completed_status_expires_before_session_stale_timeout(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- old = datetime.now(timezone.utc) - timedelta(seconds=60)- log.write_text(- json.dumps(- {- "logged_at": old.isoformat(),- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Done.",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- completed_visible_seconds=15,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.IDLE_READY)- self.assertEqual(snapshot.statuses, ())- self.assertEqual(len(snapshot.stale_statuses), 1)- self.assertEqual(snapshot.stale_statuses[0].mode, AgentMode.COMPLETED)-- def test_completed_status_stays_visible_for_twenty_minutes_by_default(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- recent_done = datetime.now(timezone.utc) - timedelta(minutes=19)- log.write_text(- json.dumps(- {- "logged_at": recent_done.isoformat(),- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Done.",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)- self.assertEqual(len(snapshot.statuses), 1)-- def test_completed_status_is_hidden_when_active_work_exists(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- "\n".join(- [- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "Stop",- "session_id": "done-session",- "last_assistant_message": "Done.",- },- }- ),- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "PreToolUse",- "session_id": "working-session",- "tool_name": "Bash",- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- completed_visible_seconds=15,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.active_count, 1)- self.assertEqual([status.session_id for status in snapshot.statuses], ["working-session"])- self.assertEqual(snapshot.stale_statuses[0].session_id, "done-session")-- def test_idle_notification_does_not_resurrect_completed_claude_session(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "claude.jsonl"- old = datetime.now(timezone.utc) - timedelta(minutes=25)- log.write_text(- "\n".join(- [- json.dumps(- {- "logged_at": old.isoformat(),- "hook_event_name": "Stop",- "session_id": "claude-session",- "cwd": "/tmp/project",- "last_assistant_message": "Done and verified.",- "background_tasks": [],- "session_crons": [],- }- ),- json.dumps(- {- "logged_at": (old + timedelta(seconds=60)).isoformat(),- "hook_event_name": "Notification",- "session_id": "claude-session",- "cwd": "/tmp/project",- "notification_type": "idle_prompt",- "message": "Claude is waiting for your input",- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("claude", log),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.IDLE_READY)- self.assertEqual(snapshot.statuses, ())- self.assertEqual(snapshot.stale_statuses[0].mode, AgentMode.COMPLETED)-- def test_codex_permission_request_stays_ask_during_unrelated_tool_activity(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc)- session_id = "019f179b-7fdc-7eb0-a3af-1ca3eb128eee"- server_command = ".venv/bin/bambucuts server --host 127.0.0.1 --port 5425"- curl_command = "curl -s http://127.0.0.1:5425/api/status | head -c 1000"- events = [- {- "logged_at": now.isoformat(),- "event": {- "hook_event_name": "PreToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": server_command},- },- },- {- "logged_at": (now + timedelta(seconds=1)).isoformat(),- "event": {- "hook_event_name": "PermissionRequest",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": server_command},- },- },- {- "logged_at": (now + timedelta(seconds=2)).isoformat(),- "event": {- "hook_event_name": "PreToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": curl_command},- },- },- {- "logged_at": (now + timedelta(seconds=3)).isoformat(),- "event": {- "hook_event_name": "PostToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": curl_command},- "tool_response": "{}",- },- },- ]- log.write_text("\n".join(json.dumps(event) for event in events) + "\n")-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)- self.assertEqual(snapshot.statuses[0].event_name, "PermissionRequest")-- def test_codex_permission_request_clears_when_matching_tool_finishes(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc)- session_id = "019f179b-7fdc-7eb0-a3af-1ca3eb128eee"- command = "curl -s http://127.0.0.1:5425/api/status | head -c 1000"- events = [- {- "logged_at": now.isoformat(),- "event": {- "hook_event_name": "PreToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": command},- },- },- {- "logged_at": (now + timedelta(seconds=1)).isoformat(),- "event": {- "hook_event_name": "PermissionRequest",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": command},- },- },- {- "logged_at": (now + timedelta(seconds=2)).isoformat(),- "event": {- "hook_event_name": "PostToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/a1plotter",- "tool_name": "Bash",- "tool_input": {"command": command},- "tool_response": "{}",- },- },- ]- log.write_text("\n".join(json.dumps(event) for event in events) + "\n")-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WORKING)- self.assertEqual(snapshot.statuses[0].event_name, "PostToolUse")-- def test_internal_codex_helper_sessions_are_ignored(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- "\n".join(- [- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "UserPromptSubmit",- "session_id": "codex-helper",- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- "prompt": "Overview\nGenerate 0 to 3 hyperpersonalized suggestions for what this user might do.",- },- }- ),- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "PostToolUse",- "session_id": "codex-helper",- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- "tool_name": "mcp__codex_apps__gmail__batch_read_email",- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.IDLE_READY)- self.assertEqual(snapshot.statuses, ())-- def test_codex_transcript_fallback_marks_recent_user_turn_active(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "aaaaaaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee"- path = root / "2026" / "06" / "29" / f"rollout-2026-06-29T08-27-42-{session_id}.jsonl"- path.parent.mkdir(parents=True)- now = datetime.now(timezone.utc).isoformat()- path.write_text(- "\n".join(- [- json.dumps(- {- "timestamp": now,- "type": "turn_context",- "payload": {- "turn_id": "turn-1",- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- },- }- ),- json.dumps(- {- "timestamp": now,- "type": "response_item",- "payload": {- "type": "message",- "role": "user",- "content": [- {- "type": "input_text",- "text": "it didnt catch this conversation",- }- ],- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex-transcripts", root),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WORKING)- self.assertEqual(snapshot.statuses[0].session_id, session_id)- self.assertIn("pixiepulse-bridge", snapshot.statuses[0].display_name)- self.assertIn("it didnt catch", snapshot.statuses[0].display_name)-- def test_transcript_records_are_cached_until_file_changes(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "019ee395-2f64-7cc3-b566-afcc1d626160"- path = root / f"rollout-2026-06-29T08-27-42-{session_id}.jsonl"- now = datetime.now(timezone.utc).isoformat()- path.write_text(- json.dumps(- {- "timestamp": now,- "type": "response_item",- "payload": {- "type": "function_call",- "name": "exec_command",- "call_id": "call-1",- "arguments": "{}",- },- }- )- + "\n"- )- monitor = AgentMonitor(- sources=(SourceSpec("codex-transcripts", root),),- stale_after_seconds=3600,- )- calls: list[Path] = []- original_read_recent_lines = collector_module.read_recent_lines-- def counting_read_recent_lines(read_path: Path, max_lines: int) -> list[str]:- if read_path == path:- calls.append(read_path)- return original_read_recent_lines(read_path, max_lines)-- with patch(- "agent_monitor.collector.read_recent_lines",- side_effect=counting_read_recent_lines,- ):- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(calls, [path])-- with path.open("a", encoding="utf-8") as handle:- handle.write(- json.dumps(- {- "timestamp": datetime.now(timezone.utc).isoformat(),- "type": "response_item",- "payload": {- "type": "function_call_output",- "call_id": "call-1",- "output": "{}",- },- }- )- + "\n"- )-- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.WORKING)- self.assertEqual(calls, [path, path])-- def test_hook_log_records_are_cached_until_file_changes(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "PreToolUse",- "session_id": "codex-session",- "tool_name": "Bash",- },- }- )- + "\n"- )- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- )- calls: list[Path] = []- original_read_recent_lines = collector_module.read_recent_lines-- def counting_read_recent_lines(read_path: Path, max_lines: int) -> list[str]:- if read_path == log:- calls.append(read_path)- return original_read_recent_lines(read_path, max_lines)-- with patch(- "agent_monitor.collector.read_recent_lines",- side_effect=counting_read_recent_lines,- ):- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(calls, [log])-- with log.open("a", encoding="utf-8") as handle:- handle.write(- json.dumps(- {- "logged_at": datetime.now(timezone.utc).isoformat(),- "event": {- "hook_event_name": "PostToolUse",- "session_id": "codex-session",- "tool_name": "Bash",- },- }- )- + "\n"- )-- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.WORKING)- self.assertEqual(calls, [log, log])-- def test_snapshot_reuses_latest_statuses_when_inputs_are_unchanged(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- log.write_text(- json.dumps(- {- "logged_at": datetime.now(timezone.utc).isoformat(),- "event": {- "hook_event_name": "PreToolUse",- "session_id": "codex-session",- "tool_name": "Bash",- },- }- )- + "\n"- )- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=3600,- )-- with patch(- "agent_monitor.collector.status_from_event",- wraps=collector_module.status_from_event,- ) as status_from_event:- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)- first_count = status_from_event.call_count- self.assertGreater(first_count, 0)-- self.assertEqual(monitor.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(status_from_event.call_count, first_count)-- def test_codex_transcript_fallback_marks_tool_calls_running(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "019ee395-2f64-7cc3-b566-afcc1d626160"- path = root / "rollout-2026-06-29T08-27-42-" / f"{session_id}.jsonl"- path.parent.mkdir(parents=True)- now = datetime.now(timezone.utc).isoformat()- path.write_text(- "\n".join(- [- json.dumps(- {- "timestamp": now,- "type": "turn_context",- "payload": {- "turn_id": "turn-1",- "cwd": "/tmp/project",- },- }- ),- json.dumps(- {- "timestamp": now,- "type": "response_item",- "payload": {- "type": "function_call",- "name": "exec_command",- "call_id": "call-1",- "arguments": "{}",- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex-transcripts", root),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(snapshot.statuses[0].tool_name, "exec_command")-- def test_codex_transcript_task_complete_overrides_last_tool_result(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "019f179b-7fdc-7eb0-a3af-1ca3eb128eee"- path = root / f"rollout-2026-06-30T01-18-14-{session_id}.jsonl"- now = datetime.now(timezone.utc).isoformat()- path.write_text(- "\n".join(- [- json.dumps(- {- "timestamp": now,- "type": "turn_context",- "payload": {"cwd": "/tmp/project"},- }- ),- json.dumps(- {- "timestamp": now,- "type": "response_item",- "payload": {- "type": "function_call_output",- "call_id": "call-1",- "output": "ok",- },- }- ),- json.dumps(- {- "timestamp": now,- "type": "event_msg",- "payload": {- "type": "task_complete",- "last_agent_message": "All set.",- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex-transcripts", root),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)- self.assertEqual(snapshot.statuses[0].event_name, "Stop")-- def test_claude_transcript_fallback_marks_tool_calls_running(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "e289f361-f64f-415e-8dd3-01ed835f7869"- path = root / "-Users-pero-pgit-sdrgb" / f"{session_id}.jsonl"- path.parent.mkdir(parents=True)- now = datetime.now(timezone.utc).isoformat()- path.write_text(- "\n".join(- [- json.dumps(- {- "timestamp": now,- "type": "user",- "sessionId": session_id,- "cwd": "/Users/pero/pgit/sdrgb",- "message": {- "role": "user",- "content": "make a pull request",- },- }- ),- json.dumps(- {- "timestamp": now,- "type": "assistant",- "sessionId": session_id,- "cwd": "/Users/pero/pgit/sdrgb",- "message": {- "role": "assistant",- "stop_reason": "tool_use",- "content": [- {- "type": "tool_use",- "id": "toolu_1",- "name": "Edit",- "input": {"file_path": "README.md"},- }- ],- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("claude-transcripts", root),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.TOOL_RUNNING)- self.assertEqual(snapshot.statuses[0].provider, "claude")- self.assertEqual(snapshot.statuses[0].tool_name, "Edit")-- def test_claude_transcript_mtime_extends_active_file_activity(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "e289f361-f64f-415e-8dd3-01ed835f7869"- path = root / f"{session_id}.jsonl"- old = datetime.now(timezone.utc) - timedelta(minutes=25)- now = datetime.now(timezone.utc)- path.write_text(- json.dumps(- {- "timestamp": old.isoformat(),- "type": "user",- "sessionId": session_id,- "cwd": "/Users/pero/pgit/sdrgb",- "message": {- "role": "user",- "content": "keep going",- },- }- )- + "\n"- )- os.utime(path, (now.timestamp(), now.timestamp()))-- monitor = AgentMonitor(- sources=(SourceSpec("claude-transcripts", root),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WORKING)- self.assertEqual(snapshot.statuses[0].event_name, "Notification")-- def test_claude_transcript_mtime_does_not_resurrect_completed_session(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- root = Path(tmp)- session_id = "e289f361-f64f-415e-8dd3-01ed835f7869"- path = root / f"{session_id}.jsonl"- old = datetime.now(timezone.utc) - timedelta(minutes=25)- now = datetime.now(timezone.utc)- path.write_text(- "\n".join(- [- json.dumps(- {- "timestamp": old.isoformat(),- "type": "user",- "sessionId": session_id,- "cwd": "/Users/pero/pgit/sdrgb",- "message": {- "role": "user",- "content": "it's ok, done",- },- }- ),- json.dumps(- {- "timestamp": (old + timedelta(seconds=10)).isoformat(),- "type": "assistant",- "sessionId": session_id,- "cwd": "/Users/pero/pgit/sdrgb",- "message": {- "role": "assistant",- "stop_reason": "end_turn",- "content": [{"type": "text", "text": "Great, thanks for handling it."}],- },- }- ),- ]- )- + "\n"- )- os.utime(path, (now.timestamp(), now.timestamp()))-- monitor = AgentMonitor(- sources=(SourceSpec("claude-transcripts", root),),- stale_after_seconds=3600,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.IDLE_READY)- self.assertEqual(snapshot.statuses, ())- self.assertEqual(snapshot.stale_statuses[0].mode, AgentMode.COMPLETED)-- def test_final_question_maps_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- log.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:00Z",- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Which mode do you see now?",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)-- def test_anything_else_prompt_maps_to_completed_before_recaps(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "\n".join(- [- "Anything else you want to tweak?",- "",- "* Cogitated for 40s - 1 shell still running",- "※ recap: We built and deployed the SidePulse/PulseDot product status.",- ]- ),- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)-- def test_concrete_followup_question_maps_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "claude.jsonl"- log.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:00Z",- "hook_event_name": "Stop",- "session_id": "claude-session",- "last_assistant_message": (- "Committed as `67b0208` but not pushed. "- "Want me to push?"- ),- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("claude", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)-- def test_question_examples_in_inline_code_do_not_map_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "\n".join(- [- "Now:",- "- `Committed but not pushed. Want me to push?` => `Ask`",- "- `Which mode do you see now?` => `Ask`",- "",- "Verified: `42` tests pass.",- ]- ),- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)-- def test_real_question_with_inline_code_maps_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- log.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:00Z",- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Want me to run `git push`?",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)-- def test_answer_heading_does_not_map_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "\n".join(- [- "No. Nothing in this payload exposes live XYZ.",- "",- "What we can infer from this:",- "",- "- MQTT print status is useful for uploaded jobs.",- ]- ),- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)-- def test_explicit_sidepulse_marker_maps_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- log.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:00Z",- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "I need your choice.\n<!-- sidepulse:ask -->",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)-- def test_explicit_sidepulse_marker_overrides_question_heuristic(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Anything else to tweak?\n<!-- sidepulse:done -->",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)-- def test_explicit_sidepulse_field_maps_to_waiting_for_input(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "claude.jsonl"- log.write_text(- json.dumps(- {- "logged_at": "2026-06-20T06:00:00Z",- "hook_event_name": "Stop",- "session_id": "claude-session",- "last_assistant_message": "Done-ish.",- "sidepulse_status": "ask",- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("claude", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.WAITING_FOR_INPUT)-- def test_explicit_marker_inside_code_block_is_ignored(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "Stop",- "session_id": "codex-session",- "last_assistant_message": "Use:\n```text\n<!-- sidepulse:ask -->\n```",- },- }- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()-- self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)-- def test_session_display_name_uses_prompt_context_after_later_events(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "codex.jsonl"- session_id = "dddddddd-eeee-7fff-8aaa-bbbbbbbbbbbb"- prompt = """-# Files mentioned by the user:--## codex-clipboard.png: /var/folders/tmp/codex-clipboard.png--## My request for Codex:-team id 5QJ7W2AQ8H, push key '/Users/pero/Dropbox/keys/PixieDotPushKey.p8'-"""- log.write_text(- "\n".join(- [- json.dumps(- {- "logged_at": "2026-06-22T19:50:58Z",- "event": {- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- "prompt": prompt,- },- }- ),- json.dumps(- {- "logged_at": "2026-06-22T19:51:09Z",- "event": {- "hook_event_name": "PreToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- "tool_name": "Bash",- },- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- tool_running_timeout_seconds=0,- )- snapshot = monitor.snapshot()- status = snapshot.statuses[0]-- self.assertIn("pixiepulse-bridge", status.display_name)- self.assertIn("team id 5QJ7W2AQ8H", status.display_name)- self.assertIn(session_id[:8], status.display_name)- self.assertNotIn("/Users/pero", status.display_name)-- def test_codex_display_name_uses_session_index_thread_name(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- home = base / "home"- codex_home = home / ".codex"- codex_home.mkdir(parents=True)- session_id = "bbbbbbbb-cccc-7ddd-8eee-ffffffffffff"- (codex_home / "session_index.jsonl").write_text(- json.dumps(- {- "id": session_id,- "thread_name": "Refine README agent status modes",- "updated_at": "2026-06-20T05:52:21.985091Z",- }- )- + "\n"- )- log = base / "codex.jsonl"- now = datetime.now(timezone.utc).isoformat()- log.write_text(- "\n".join(- [- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- "prompt": "Why are we burning so much CPU",- },- }- ),- json.dumps(- {- "logged_at": now,- "event": {- "hook_event_name": "PreToolUse",- "session_id": session_id,- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- "tool_name": "Bash",- },- }- ),- ]- )- + "\n"- )-- with patch("agent_monitor.collector.Path.home", return_value=home):- monitor = AgentMonitor(- sources=(SourceSpec("codex", log),),- stale_after_seconds=999999999,- )- snapshot = monitor.snapshot()-- name = snapshot.statuses[0].display_name- self.assertIn("pixiepulse-bridge", name)- self.assertIn("Refine README agent status modes", name)- self.assertNotIn("Why are we burning", name)-- def test_live_monitor_refreshes_loaded_codex_display_name_from_session_index(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- base = Path(tmp)- home = base / "home"- codex_home = home / ".codex"- codex_home.mkdir(parents=True)- session_id = "cccccccc-dddd-7eee-8fff-aaaaaaaaaaaa"- (codex_home / "session_index.jsonl").write_text(- json.dumps(- {- "id": session_id,- "thread_name": "Refine README agent status modes",- }- )- + "\n"- )- latest = base / "latest.json"- now = datetime.now(timezone.utc)- latest.write_text(- json.dumps(- {- "updated_at": now.isoformat(),- "statuses": [- {- "provider": "codex",- "agent_id": f"codex:session:{session_id}",- "display_name": (- "pixiepulse-bridge: Why are we burning so much CPU "- f"({session_id[:8]})"- ),- "mode": "working",- "updated_at": now.isoformat(),- "event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": "/Users/pero/pgit/pixiepulse-bridge",- }- ],- }- )- + "\n"- )-- with patch("agent_monitor.collector.Path.home", return_value=home):- monitor = LiveAgentMonitor(latest_state_path=latest)- snapshot = monitor.snapshot()-- name = snapshot.statuses[0].display_name- self.assertIn("Refine README agent status modes", name)- self.assertNotIn("Why are we burning", name)-- def test_task_notification_does_not_replace_session_display_name(self) -> None:- with tempfile.TemporaryDirectory() as tmp:- log = Path(tmp) / "claude.jsonl"- session_id = "1ca4348e-2aec-4147-9e81-d7d56364d257"- log.write_text(- "\n".join(- [- json.dumps(- {- "logged_at": "2026-06-22T07:20:00Z",- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": "/Users/pero/pgit/sdstatus_bitbang",- "prompt": "convert these videos to mp4",- }- ),- json.dumps(- {- "logged_at": "2026-06-22T07:24:05Z",- "hook_event_name": "UserPromptSubmit",- "session_id": session_id,- "cwd": "/Users/pero/pgit/sdstatus_bitbang",- "prompt": "<task-notification><status>completed</status></task-notification>",- }- ),- ]- )- + "\n"- )-- monitor = AgentMonitor(- sources=(SourceSpec("claude", log),),- stale_after_seconds=999999999,- )- snapshot = monitor.snapshot()-- self.assertIn("convert these videos", snapshot.statuses[0].display_name)- self.assertNotIn("task-notification", snapshot.statuses[0].display_name)-- def test_codex_session_actions_build_deeplink_and_resume_command(self) -> None:- status = AgentStatus(- provider="codex",- agent_id="codex:session:abc",- display_name="Codex abc",- mode=AgentMode.WORKING,- updated_at=datetime.now(timezone.utc),- event_name="PreToolUse",- session_id="019ee395-2f64-7cc3-b566-afcc1d626160",- cwd="/tmp/project with spaces",- )-- self.assertEqual(- session_deep_link(status),- "codex://threads/019ee395-2f64-7cc3-b566-afcc1d626160",- )- self.assertEqual(- session_resume_command(status),- "cd '/tmp/project with spaces' && codex resume 019ee395-2f64-7cc3-b566-afcc1d626160",- )-- def test_claude_session_actions_build_app_link_and_resume_command(self) -> None:- 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",- )-- self.assertEqual(session_deep_link(status), "claude://")- self.assertEqual(- 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__":- unittest.main()diff --git a/tests/test_audio_monitor_example.py b/tests/test_audio_monitor_example.pyindex e36f989..9316757 100644--- a/tests/test_audio_monitor_example.py+++ b/tests/test_audio_monitor_example.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport unittest-from agent_monitor.device_writer import MAX_LED_BYTES, validate_led_text+from sidepulse.device_writer import MAX_LED_BYTES, validate_led_textfrom examples.audio_monitor import (build_led_program,green_to_red_rgb,