CLI for SidePulse
Python
Initial SidePulse agent monitor
Peter Kuharac7aa4458eaf
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..7597c33--- /dev/null+++ b/.gitignore@@ -0,0 +1,9 @@+.DS_Store+__pycache__/+*.py[cod]+*.egg-info/+.pytest_cache/+.mypy_cache/+.ruff_cache/+build/+dist/diff --git a/LEDS_FORMAT.txt b/LEDS_FORMAT.txtnew file mode 100644index 0000000..d091883--- /dev/null+++ b/LEDS_FORMAT.txt@@ -0,0 +1,209 @@+# LEDS.LED DSL++Write LED animation programs to `LEDS.LED`. Each non-empty, non-comment line is+one animation step. The embedded controller accepts at most 512 bytes and at+most 20 physical lines.++The controller keeps the current visible LED state across parses. A successful+parse starts the new program from line 1 using the current state as the+transition start colors. A parse error stops the current program and blinks all+LEDs red six times with 150 ms on/off phases.++## Comments++Blank lines are ignored. Comment lines may start with `;`, `//`, or `# `.++```text+# all LEDs white+#ffffff++; all LEDs off+off+```++## Colors++Set all LEDs to one color:++```text+#ffffff+```++Turn all LEDs off:++```text+off+```++Assign colors by position. LEDs past the list turn off. Extra colors past the+compiled LED count are checked for valid syntax, then ignored:++```text+#ff0000 #00ff00 #0000ff+```++Assign specific LEDs. Unmentioned LEDs hold their current state. Indexes past+the compiled LED count are checked for valid syntax, then ignored:++```text+0:#ffffff 2:#ff00ee 7:#0040ff+```++Multiple segments may appear on one line, separated by semicolons. If an LED is+assigned more than once on a line, the last assignment wins:++```text+0:#ff0000 1s; 0:#0000ff 1s+```++## 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`.++```text+brightness 128+#808080+```++## Timing++A color assignment may be followed by:++```text+duration+easing+duration easing+duration easing delay+duration delay+easing delay+```++Durations and delays accept integer milliseconds, integer seconds, or decimal+seconds, up to 65535 ms:++```text+#ff00ff 330ms+#ff00ff ease-in+#ff00ff 0.33s+#ff00ff 0.33s ease-in+#ff00ff 0.33s ease-in 1s+#ff00ff pulse 1s+```++An easing name without a duration uses the default 330 ms duration. Each line+finishes after the longest delay plus duration on that line. A line with no+duration, easing, or delay lasts one 60 Hz frame.++## Easing++Supported easing names:++```text+linear+ease+ease-in+ease-out+ease-in-out+cosine+pulse+none+```++`cosine` is a smooth half-cosine transition from the line's start color to the+target color. `pulse` is a full-cycle envelope: it moves from the line's start+color to the target color and back to the start color over one duration. The+target color is the peak, not the final hold.++```text+# fade to purple+#ff00ff 0.33s cosine++# pulse to purple and return to the current color+#ff00ff 1.4s pulse++# same pulse using the default 330 ms duration+#ff00ff pulse+```++`none` jumps to the target after any delay and holds until the line finishes:++```text+3:#ffffff 80ms none+```++## Delays And Staggering++Different LEDs can use independent timing on the same line:++```text+0:#ff00ff 0.33s ease-in 0s; 1:#00ff00 0.33s linear 250ms+```++Stagger all 8 LEDs:++```text+0:#ff0000 150ms ease 0ms; 1:#ff8000 150ms ease 50ms; 2:#ffff00 150ms ease 100ms; 3:#00ff00 150ms ease 150ms+4:#00ccff 150ms ease 0ms; 5:#004cff 150ms ease 50ms; 6:#8800ff 150ms ease 100ms; 7:#ff00cc 150ms ease 150ms+```++## Repeat++Loop forever from the first animation line:++```text+0:#ffffff 80ms none+1:#ffffff 80ms none+2:#ffffff 80ms none+repeat+```++Run the animation before the repeat marker 10 total times, then hold the final+state:++```text+#ff0000 200ms none+#00ff00 200ms none+repeat 10+```++Finite repeat can continue with more animation lines:++```text+off+#ff0000 200ms none+#00ff00 200ms none+repeat 2+off+```++## Examples++Soft breathing pulse:++```text+#404040 1.4s pulse+off 400ms none+repeat+```++One-line chase step. Only LED 3 changes; all others hold:++```text+3:#ffffff 80ms none+```++Indexed sparkle:++```text+0:#ffffff 90ms none+2:#ff00ee 90ms none+5:#00ccff 90ms none+off 120ms ease-out+repeat+```++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.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..658bf42--- /dev/null+++ b/README.md@@ -0,0 +1,409 @@+# SidePulse++SidePulse is the overall product for small LED status devices and the local+agent-monitoring tools that drive them.++The SidePulse device is the eight-LED SD card slot version for MacBook Pro.+PulseDot is the tiny two-LED USB-C version.++They can display the status of an AI agent, battery level, or other system+signals.++The device mounts as a flash drive. Control the LEDs by writing to `LEDS.LED`+on current firmware. Older PulseDot firmware exposes the same control as+`LEDS.TXT`, and the CLI keeps that fallback.++The LED control DSL is described in [`LEDS_FORMAT.txt`](LEDS_FORMAT.txt).++Write an LED program directly to a mounted SidePulse or PulseDot device:++```sh+sidepulse write "off\n#ff3a00 1.6s pulse\nrepeat"+```++The CLI auto-detects mounted devices under `/Volumes` by looking for a+SidePulse/PulseDot-style volume name, an existing `LEDS.LED`, or a legacy+`LEDS.TXT`. If more than one device is possible, pass the mounted folder or+file explicitly:++```sh+sidepulse write "off\n#ff3a00 1.6s pulse\nrepeat" --device /Volumes/SidePulse+sidepulse write "off" --device /Volumes/SidePulse/LEDS.LED+sidepulse write "off" --device /Volumes/PulseDot/LEDS.TXT+```++The writer decodes simple escapes such as `\n`, then enforces the controller's+512-byte and 20-line limits before writing the LED control file.++## Battery LEDs++Show the current Mac battery state:++```sh+sidepulse battery status+sidepulse battery status --json+```++Mirror battery level to a mounted SidePulse/PulseDot:++```sh+sidepulse battery leds+sidepulse battery leds --once --dry-run+sidepulse battery leds --device /Volumes/SidePulse --full-watts 140+```++SidePulse 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 whole+strip into its new base state, then trigger one frontier pulse. The app owns+the animation cadence by rewriting that one-shot pulse; the device does not run+a repeated charging loop. Pulse length and rewrite frequency are based on+charger wattage divided by the laptop's full-speed wattage baseline, so slow+chargers produce occasional short blinks and full-speed chargers produce a+steady pulse.++Save the status-bar LED display preference:++```sh+sidepulse battery configure --display battery+sidepulse battery configure --display agent+sidepulse battery configure --full-watts auto+sidepulse battery configure --show-on-power-change yes --power-change-preview-seconds 7+```++## SidePulse Bridge++SidePulse Bridge is a companion app for macOS that controls SidePulse devices.++### Main Functionality++#### AI Agent Monitoring++SidePulse can monitor AI agents such as Codex and Claude through hooks, then+translate the current agent state into a small, glanceable LED status.++Agent status modes:++| Mode | Meaning | LED pattern |+| --- | --- | --- |+| Idle / Ready | The agent is available and not currently running a task. | Very dim idle pulse. |+| Working | The agent is thinking, generating, or otherwise actively processing. | Cyan rolling animation. |+| Tool Running | A shell command, API call, or external tool is in progress. | Cyan rolling animation. |+| Waiting for Input | The agent needs a user decision, approval, or additional context. | Slow amber pulse. |+| Long Task Progress | A longer job has measurable progress. | Cyan rolling animation. |+| Blocked / Error | The agent cannot continue, a tool failed, or a recoverable error needs attention. | Slow amber pulse. |+| Completed | The agent finished successfully. | Solid green. |++When multiple states are active, SidePulse should show the most actionable+mode first: Blocked / Error, Waiting for Input, Tool Running, Long Task+Progress, Working, then Idle / Ready.++For multiple agents, SidePulse aggregates their statuses into one global+display state. Each agent reports its own mode, and SidePulse renders the+highest-priority active mode across all non-stale agents. This keeps the device+useful at a glance: if any agent is blocked or waiting, the LEDs show that+actionable state instead of trying to show every agent separately.++Aggregation priority:++| Priority | Mode | Aggregated behavior |+| --- | --- | --- |+| 1 | Blocked / Error | Show immediately if any agent is blocked or has errored. |+| 2 | Waiting for Input | Show if any agent needs user input and no agent is blocked. |+| 3 | Tool Running | Show if any agent is running a tool and no higher-priority state is active. |+| 4 | Long Task Progress | Show the most recent or furthest-progressing long task. |+| 5 | Working | Show while one or more agents are actively processing. |+| 6 | Completed | Show briefly when the latest active agent completes successfully. |+| 7 | Idle / Ready | Show only when all known agents are idle or no fresh agent status exists. |++Agent statuses should include a timestamp. SidePulse should ignore stale+statuses after a short timeout so disconnected or finished agents do not hold+the display indefinitely.++#### Agent Monitor Library++The `agent_monitor` Python package collects and normalizes local AI agent hook+events. The macOS status-bar app receives hook events through a lightweight+local 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.++The package can also mirror the aggregate state to a mounted SidePulse or+PulseDot by writing the current LED program to `LEDS.LED`, with `LEDS.TXT`+fallback for legacy firmware.++The monitor currently supports:++| Provider | Config | Detected log |+| --- | --- | --- |+| 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` |++For CLI snapshots, debugging, or recovery after missed hook events, the+file-based monitor can optionally read recent local transcripts as a fallback:++- Codex: `~/.codex/sessions/**/*.jsonl`+- Claude: `~/.claude/projects/**/*.jsonl`++Transcript monitoring is off by default and can be enabled in Settings. It can+catch active threads even when hook events are stale or missed. Claude+transcript files can be touched after their embedded event timestamps stop+moving, so a recent transcript mtime is treated as a Working heartbeat only+when the latest embedded event was already active. File mtimes never resurrect+a terminal `Stop` / `Completed` session. Internal Codex helper/suggestion+transcripts are ignored so app background work does not look like one of your+agents.++By default the monitor stores runtime logs under+`~/.local/state/sidepulse/agent-monitor/`, following the XDG state directory+convention. Set `XDG_STATE_HOME` to place them somewhere else.++Install locally for the `sidepulse` CLI:++```sh+python3 -m pip install -e .+```++On Homebrew Python, use the user-site install form:++```sh+python3 -m pip install --user --break-system-packages -e .+ln -sf "$(python3 -m site --user-base)/bin/sidepulse" ~/.local/bin/sidepulse+```++Check the current hook configuration:++```sh+sidepulse agent-monitor doctor+```++Install or refresh the monitor hooks:++```sh+sidepulse agent-monitor install+sidepulse agent-monitor install codex+sidepulse agent-monitor install claude+```++Show current aggregated status:++```sh+sidepulse agent-monitor status+```++Watch a live dashboard of recently active agents:++```sh+sidepulse agent-monitor live+```++The dashboard refreshes every second and shows agents updated in the last hour+by default. Use `--recent-seconds` to change that window, or `--all` to+include stale/older sessions:++```sh+sidepulse agent-monitor live --recent-seconds 120+sidepulse agent-monitor live --all+```++By default, `Tool Running` events are not time-limited, so genuinely long tools+remain visible. If a provider drops completion hooks and you want protection+against stale tool starts, set `--tool-running-timeout`.++`Completed` remains visible for 20 minutes so the status bar and LEDs can show+Done long enough to be noticed. After that it drops out instead of counting as+an active session for the full stale window, and the LEDs return to the very+dim Idle pattern. Idle/session-start records also do not count as active+sessions.++Status detection is strongest when the agent tells the monitor its intended+handoff state explicitly. A final assistant message can include a hidden marker+line:++```text+<!-- sidepulse:ask -->+<!-- sidepulse:done -->+<!-- sidepulse:working -->+<!-- sidepulse:blocked -->+<!-- sidepulse:idle -->+```++Explicit markers win over text heuristics. If no marker is present, the monitor+falls back to provider events and then to conservative question detection in the+final assistant message. Casual closing questions such as "Anything else?" are+treated as Done unless the agent emits `<!-- sidepulse:ask -->`; concrete+follow-ups such as "Want me to push?" still count as Ask. Questions inside+markdown code spans or fenced code examples are ignored.++Codex `PermissionRequest` events are treated as Ask and remain sticky until the+matching tool command finishes. This prevents unrelated same-session activity+from 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:++```text+When your final response needs user input, approval, or a decision, include+`<!-- sidepulse:ask -->` as a final hidden marker line. When the work is complete+and no user response is needed, include `<!-- sidepulse:done -->`.+```++Mirror the aggregate agent status to the LEDs in a foreground process:++```sh+sidepulse agent-monitor leds+```++The LED mirror writes only when the aggregate display state changes. Use+`--once` to write the current state and exit, or `--dry-run` to inspect the LED+program:++```sh+sidepulse agent-monitor leds --once --dry-run+sidepulse agent-monitor leds --device /Volumes/PulseDot+```++PulseDot programs are generated for two LEDs. SidePulse programs are generated+for 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.++Remove monitor hooks:++```sh+sidepulse agent-monitor uninstall+sidepulse agent-monitor uninstall codex+sidepulse agent-monitor uninstall claude+```++Install and start the macOS status-bar app:++```sh+sidepulse agent-monitor status-bar+```++This writes `~/Library/LaunchAgents/com.sidepulse.agentstatus.plist`, starts the+menu-bar app immediately, enables it at login, and mirrors the same aggregate+state to the LEDs. For debugging, run it in the foreground:++```sh+sidepulse agent-monitor status-bar --foreground+```++The status-bar item shows one of four collapsed states:++| Label | Meaning |+| --- | --- |+| Idle | No recent active agent work. |+| Working | One or more agents are thinking, running tools, or progressing. |+| Done | The most recent active agent completed successfully. |+| Ask | An agent needs input, permission, or attention. |++Click the status-bar item to expand the recent session list. Each session row+has two actions:++- `Deep Link` opens the provider app. Codex uses `codex://threads/<session-id>`.+- `Resume` opens Terminal in the session working directory and runs the+ provider CLI resume command.++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+reconnect.++The dropdown and Settings window can switch the LEDs between agent status and+battery status. When agent status is selected, `Show Battery on Plug/Unplug`+can briefly show the battery animation for seven seconds after the power source+changes.++Open `Settings...` from the dropdown to manage agent integrations. The settings+window can install or uninstall Codex and Claude hooks. The transcript+checkboxes control the file-based CLI/debug fallback; the status-bar app gets+live updates from the local hook event socket. Settings are stored at+`${XDG_CONFIG_HOME:-~/.config}/sidepulse/agent-monitor/settings.json`.++The checked `Keep Awake` item controls a macOS `caffeinate -dimsu` assertion.+When enabled, the status-bar app keeps the Mac awake while agents are Working /+Tool Running / Progressing. Done and Ask states keep the Mac awake for a+five-minute grace period, then release the assertion so normal sleep can resume.+While keep-awake is enabled and a device is connected, the app also touches a+`keepalive` file on each SidePulse/PulseDot volume at least once per minute to+keep the device volume active. Closed-lid sleep is still subject to macOS+clamshell rules.++The app is also installed as a user LaunchAgent at+`~/Library/LaunchAgents/com.sidepulse.agentstatus.plist`.++Stop and remove the LaunchAgent:++```sh+sidepulse agent-monitor status-bar --uninstall+```++Use it from another Python app:++```python+from agent_monitor import AgentMonitor, LiveAgentMonitor++snapshot = AgentMonitor.from_default_sources().snapshot()+print(snapshot.aggregate.mode.value)+for status in snapshot.statuses:+ print(status.provider, status.mode.value, status.cwd)++live = LiveAgentMonitor()+```++Publish a hook-shaped event to the status-bar app from another local process:++```python+from agent_monitor import send_hook_event++send_hook_event(+ "codex",+ {+ "logged_at": "2026-07-13T12:00:00Z",+ "event": {+ "hook_event_name": "Stop",+ "session_id": "example",+ "last_assistant_message": "Done.",+ },+ },+)+```++#### Audio Monitor Example++`examples/audio_monitor.py` turns microphone volume into a smooth LED level+bar. The LEDs stay dim at rest, run green through yellow to red, and brighten as+the audio level fills the bar.++Install the optional live-audio dependencies:++```sh+python3 -m pip install sounddevice numpy+```++Preview the meter in the terminal without touching a device:++```sh+python3 examples/audio_monitor.py --dry-run --terminal+```++Write to a mounted SidePulse or PulseDot:++```sh+python3 examples/audio_monitor.py --device /Volumes/SidePulse --terminal+python3 examples/audio_monitor.py --device /Volumes/PulseDot --terminal+```++List audio inputs or tune sensitivity:++```sh+python3 examples/audio_monitor.py --list-inputs+python3 examples/audio_monitor.py --device /Volumes/SidePulse --gain-db 8 --release 0.45+```++#### Battery Monitor++...++####diff --git a/examples/audio_monitor.py b/examples/audio_monitor.pynew file mode 100644index 0000000..02755d5--- /dev/null+++ b/examples/audio_monitor.py@@ -0,0 +1,467 @@+#!/usr/bin/env python3+from __future__ import annotations++import argparse+import math+import queue+import sys+import time+from pathlib import Path+from typing import Any+++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+ DEFAULT_FILE_NAME,+ DeviceWriteError,+ LEGACY_FILE_NAMES,+ validate_led_text,+ write_led_program,+)+from agent_monitor.led_status import led_count_for_target # noqa: E402+++DEFAULT_FPS = 25.0+DEFAULT_IDLE_BRIGHTNESS = 0.08+DEFAULT_MAX_BRIGHTNESS = 1.0+DEFAULT_NOISE_FLOOR_DB = -54.0+DEFAULT_PEAK_DB = -8.0+DEFAULT_CURVE = 0.72+DEFAULT_ATTACK_SECONDS = 0.045+DEFAULT_RELEASE_SECONDS = 0.32+DEFAULT_TRANSITION_MS = 90+MIN_RMS = 1e-9+++def clamp(value: float, low: float = 0.0, high: float = 1.0) -> float:+ return max(low, min(high, value))+++def normalize_led_count(led_count: int) -> int:+ return max(1, min(8, int(led_count)))+++def green_to_red_rgb(index: int, led_count: int) -> tuple[int, int, int]:+ count = normalize_led_count(led_count)+ if count == 1:+ return 0, 255, 0++ position = clamp(index / (count - 1))+ if position <= 0.5:+ red = int(round(255 * (position / 0.5)))+ green = 255+ else:+ red = 255+ green = int(round(255 * (1.0 - ((position - 0.5) / 0.5))))+ return red, green, 0+++def scale_rgb(rgb: tuple[int, int, int], brightness: float) -> tuple[int, int, int]:+ brightness = clamp(brightness)+ return tuple(int(round(channel * brightness)) for channel in rgb)+++def rgb_hex(rgb: tuple[int, int, int]) -> str:+ red, green, blue = rgb+ return f"#{red:02X}{green:02X}{blue:02X}"+++def build_led_program(+ level: float,+ *,+ led_count: int = 8,+ idle_brightness: float = DEFAULT_IDLE_BRIGHTNESS,+ max_brightness: float = DEFAULT_MAX_BRIGHTNESS,+ transition_ms: int = DEFAULT_TRANSITION_MS,+) -> str:+ count = normalize_led_count(led_count)+ level = clamp(level)+ idle = clamp(idle_brightness)+ peak = max(idle, clamp(max_brightness))+ fill = level * count+ duration = max(0, int(transition_ms))++ segments: list[str] = []+ for index in range(count):+ segment_level = clamp(fill - index)+ brightness = idle + ((peak - idle) * segment_level)+ color = rgb_hex(scale_rgb(green_to_red_rgb(index, count), brightness))+ token = f"{index}:{color}"+ if duration:+ token += f" {duration}ms cosine"+ segments.append(token)++ program = "; ".join(segments)+ validate_led_text(program)+ return program+++def rms_to_dbfs(rms: float, *, gain_db: float = 0.0) -> float:+ return 20.0 * math.log10(max(float(rms), MIN_RMS)) + gain_db+++def rms_to_level(+ rms: float,+ *,+ noise_floor_db: float = DEFAULT_NOISE_FLOOR_DB,+ peak_db: float = DEFAULT_PEAK_DB,+ gain_db: float = 0.0,+ curve: float = DEFAULT_CURVE,+) -> float:+ if peak_db <= noise_floor_db:+ raise ValueError("--peak-db must be greater than --noise-floor-db")++ db = rms_to_dbfs(rms, gain_db=gain_db)+ level = clamp((db - noise_floor_db) / (peak_db - noise_floor_db))+ return level ** max(0.05, float(curve))+++def smooth_level(+ previous: float,+ target: float,+ *,+ elapsed: float,+ attack_seconds: float = DEFAULT_ATTACK_SECONDS,+ release_seconds: float = DEFAULT_RELEASE_SECONDS,+) -> float:+ previous = clamp(previous)+ target = clamp(target)+ tau = attack_seconds if target > previous else release_seconds+ if tau <= 0:+ return target+ alpha = 1.0 - math.exp(-max(0.0, elapsed) / tau)+ return previous + ((target - previous) * alpha)+++def push_latest(samples: queue.Queue[float], value: float) -> None:+ try:+ samples.put_nowait(value)+ return+ except queue.Full:+ pass++ try:+ samples.get_nowait()+ except queue.Empty:+ pass+ samples.put_nowait(value)+++def drain_peak(samples: queue.Queue[float]) -> float:+ peak = 0.0+ while True:+ try:+ peak = max(peak, samples.get_nowait())+ except queue.Empty:+ return peak+++def terminal_meter(level: float, *, led_count: int) -> str:+ count = normalize_led_count(led_count)+ fill = clamp(level) * count+ cells: list[str] = []+ for index in range(count):+ segment_level = clamp(fill - index)+ if segment_level >= 0.66:+ char = "#"+ elif segment_level >= 0.33:+ char = "="+ elif segment_level > 0:+ char = "-"+ else:+ char = "."++ red, green, blue = green_to_red_rgb(index, count)+ cells.append(f"\033[38;2;{red};{green};{blue}m{char}\033[0m")+ return "".join(cells)+++def parse_input_device(value: str | None) -> int | str | None:+ if value is None:+ return None+ try:+ return int(value)+ except ValueError:+ return value+++def load_audio_modules() -> tuple[Any, Any]:+ try:+ import numpy as np+ import sounddevice as sd+ except ImportError as exc:+ raise SystemExit(+ "audio_monitor.py needs sounddevice and numpy for live audio.\n"+ "Install them with: python3 -m pip install sounddevice numpy"+ ) from exc+ return sd, np+++def list_input_devices() -> int:+ sd, _ = load_audio_modules()+ devices = sd.query_devices()+ default_input = None+ try:+ default_input = sd.default.device[0]+ except (AttributeError, IndexError, TypeError):+ pass++ for index, device in enumerate(devices):+ channels = int(device.get("max_input_channels", 0))+ if channels <= 0:+ continue+ marker = "*" if index == default_input else " "+ name = device.get("name", "Unnamed input")+ sample_rate = int(float(device.get("default_samplerate", 0)))+ print(f"{marker} {index:2d}: {name} ({channels} ch, {sample_rate} Hz)")+ return 0+++def resolve_target(args: argparse.Namespace) -> Path | None:+ if args.dry_run and args.device is None:+ return None+ return write_led_program(+ "off",+ device_path=args.device,+ file_name=args.file_name,+ dry_run=True,+ )+++def infer_led_count(args: argparse.Namespace, target: Path | None) -> int:+ if args.led_count is not None:+ return normalize_led_count(args.led_count)+ if target is not None:+ return led_count_for_target(target)+ return 8+++def print_preview(+ *,+ level: float,+ rms: float,+ led_count: int,+ target: Path | None,+ dry_run: bool,+) -> None:+ db = rms_to_dbfs(rms)+ destination = "dry-run" if dry_run else str(target)+ print(+ f"\r{terminal_meter(level, led_count=led_count)} "+ f"{level:5.1%} {db:6.1f} dBFS -> {destination}",+ end="",+ flush=True,+ )+++def run_monitor(args: argparse.Namespace) -> int:+ if args.list_inputs:+ return list_input_devices()++ sd, np = load_audio_modules()+ target = resolve_target(args)+ led_count = infer_led_count(args, target)+ audio_samples: queue.Queue[float] = queue.Queue(maxsize=8)+ stream_errors: queue.Queue[str] = queue.Queue(maxsize=4)+ preview = args.terminal or args.dry_run+ frame_seconds = 1.0 / max(1.0, float(args.fps))+ input_device = parse_input_device(args.input_device)+ sample_rate = int(args.sample_rate)+ block_size = max(0, int(args.block_size))++ def callback(indata: Any, frames: int, time_info: Any, status: Any) -> None:+ if status:+ try:+ stream_errors.put_nowait(str(status))+ except queue.Full:+ pass+ rms = math.sqrt(float(np.mean(np.square(indata))))+ push_latest(audio_samples, rms)++ if args.dry_run:+ print(f"audio monitor: dry-run preview with {led_count} LEDs")+ else:+ print(f"audio monitor: writing {led_count} LEDs to {target}")+ print("press Ctrl-C to stop")++ smoothed = 0.0+ latest_rms = 0.0+ last_program: str | None = None+ last_time = time.monotonic()+ printed_preview = False++ try:+ with sd.InputStream(+ channels=1,+ samplerate=sample_rate,+ blocksize=block_size,+ callback=callback,+ device=input_device,+ dtype="float32",+ ):+ while True:+ frame_start = time.monotonic()+ rms = drain_peak(audio_samples)+ if rms > 0.0:+ latest_rms = rms++ target_level = rms_to_level(+ rms,+ noise_floor_db=args.noise_floor_db,+ peak_db=args.peak_db,+ gain_db=args.gain_db,+ curve=args.curve,+ )+ now = time.monotonic()+ smoothed = smooth_level(+ smoothed,+ target_level,+ elapsed=now - last_time,+ attack_seconds=args.attack,+ release_seconds=args.release,+ )+ last_time = now++ program = build_led_program(+ smoothed,+ led_count=led_count,+ idle_brightness=args.idle_brightness,+ max_brightness=args.max_brightness,+ transition_ms=args.transition_ms,+ )+ if program != last_program:+ if not args.dry_run:+ write_led_program(program, device_path=target, file_name=args.file_name)+ last_program = program++ if preview:+ printed_preview = True+ print_preview(+ level=smoothed,+ rms=latest_rms,+ led_count=led_count,+ target=target,+ dry_run=args.dry_run,+ )++ try:+ error = stream_errors.get_nowait()+ except queue.Empty:+ error = None+ if error and not preview:+ print(f"audio stream: {error}", file=sys.stderr)++ sleep_for = frame_seconds - (time.monotonic() - frame_start)+ if sleep_for > 0:+ time.sleep(sleep_for)+ except KeyboardInterrupt:+ return 0+ finally:+ if printed_preview:+ print()+ if args.off_on_exit and target is not None and not args.dry_run:+ try:+ write_led_program("off", device_path=target, file_name=args.file_name)+ except (DeviceWriteError, OSError) as exc:+ print(f"audio monitor: could not turn LEDs off: {exc}", file=sys.stderr)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Show microphone volume as a smooth dim green-to-red SidePulse LED bar.",+ )+ parser.add_argument(+ "--device",+ type=Path,+ help="Mounted device folder or LED program file. Defaults to auto-detecting /Volumes.",+ )+ parser.add_argument(+ "--file-name",+ default=DEFAULT_FILE_NAME,+ help=(+ f"Target file name when --device is a folder. Default: {DEFAULT_FILE_NAME}; "+ f"legacy devices may use {', '.join(LEGACY_FILE_NAMES)}."+ ),+ )+ parser.add_argument("--led-count", type=int, help="LED count. Defaults to device name, then 8.")+ parser.add_argument("--fps", type=float, default=DEFAULT_FPS, help="LED update rate.")+ parser.add_argument(+ "--transition-ms",+ type=int,+ default=DEFAULT_TRANSITION_MS,+ help="Controller-side cosine fade per frame; set 0 for immediate updates.",+ )+ parser.add_argument(+ "--idle-brightness",+ type=float,+ default=DEFAULT_IDLE_BRIGHTNESS,+ help="Dim baseline brightness from 0.0 to 1.0.",+ )+ parser.add_argument(+ "--max-brightness",+ type=float,+ default=DEFAULT_MAX_BRIGHTNESS,+ help="Peak brightness from 0.0 to 1.0.",+ )+ parser.add_argument(+ "--noise-floor-db",+ type=float,+ default=DEFAULT_NOISE_FLOOR_DB,+ help="Input level that maps to an empty bar.",+ )+ parser.add_argument(+ "--peak-db",+ type=float,+ default=DEFAULT_PEAK_DB,+ help="Input level that maps to a full bar.",+ )+ parser.add_argument("--gain-db", type=float, default=0.0, help="Gain applied before level mapping.")+ parser.add_argument(+ "--curve",+ type=float,+ default=DEFAULT_CURVE,+ help="Response curve; lower values make quiet sounds more visible.",+ )+ parser.add_argument(+ "--attack",+ type=float,+ default=DEFAULT_ATTACK_SECONDS,+ help="Seconds for the meter to rise toward louder audio.",+ )+ parser.add_argument(+ "--release",+ type=float,+ default=DEFAULT_RELEASE_SECONDS,+ help="Seconds for the meter to fall after audio gets quieter.",+ )+ parser.add_argument("--sample-rate", type=float, default=44100.0, help="Audio sample rate.")+ parser.add_argument("--block-size", type=int, default=0, help="Audio callback block size; 0 lets PortAudio choose.")+ 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("--off-on-exit", action="store_true", help="Write 'off' when the monitor exits.")+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ return run_monitor(args)+ except ValueError as exc:+ print(f"audio monitor: {exc}", file=sys.stderr)+ return 2+ except DeviceWriteError as exc:+ print(f"audio monitor: {exc}", file=sys.stderr)+ return 2+ except OSError as exc:+ print(f"audio monitor: {exc}", file=sys.stderr)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter.xcodeproj/project.pbxproj b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter.xcodeproj/project.pbxprojnew file mode 100644index 0000000..28371ce--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter.xcodeproj/project.pbxproj@@ -0,0 +1,369 @@+// !$*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.swiftnew file mode 100644index 0000000..3591328--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppDelegate.swift@@ -0,0 +1,131 @@+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.swiftnew file mode 100644index 0000000..6c2da3f--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/AppModel.swift@@ -0,0 +1,215 @@+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.jsonnew file mode 100644index 0000000..eb87897--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AccentColor.colorset/Contents.json@@ -0,0 +1,11 @@+{+ "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.jsonnew file mode 100644index 0000000..374b093--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,116 @@+{+ "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]new file mode 100644index 0000000..acbb0e7Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..50e9661Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..e66f18cBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..e66f18cBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..518b435Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..888668eBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..b085ce1Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..b085ce1Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..43966c2Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..e66f18cBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..0ab6e63Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..0ab6e63Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..1b10f4cBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..1b10f4cBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected]new file mode 100644index 0000000..7d2ea8aBinary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/[email protected] 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.pngnew file mode 100644index 0000000..5737d59Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x~ipad.png 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.pngnew file mode 100644index 0000000..930b0e0Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x~ipad.png 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.pngnew file mode 100644index 0000000..9862c50Binary files /dev/null and b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x~ipad.png differdiff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/Contents.json b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/Contents.jsonnew file mode 100644index 0000000..73c0059--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/ContentView.swift b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/ContentView.swiftnew file mode 100644index 0000000..3cda74a--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/ContentView.swift@@ -0,0 +1,679 @@+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.swiftnew file mode 100644index 0000000..63c994e--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/DriveWriter.swift@@ -0,0 +1,125 @@+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.swiftnew file mode 100644index 0000000..5d3fcf3--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/EventLog.swift@@ -0,0 +1,30 @@+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.swiftnew file mode 100644index 0000000..242f91a--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/FolderPicker.swift@@ -0,0 +1,41 @@+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.plistnew file mode 100644index 0000000..8563d77--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/Info.plist@@ -0,0 +1,61 @@+<?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.entitlementsnew file mode 100644index 0000000..2cf0210--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriter.entitlements@@ -0,0 +1,8 @@+<?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.swiftnew file mode 100644index 0000000..4867e02--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PixiePulseUSBWriterApp.swift@@ -0,0 +1,12 @@+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.swiftnew file mode 100644index 0000000..3404ce4--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/PushPayload.swift@@ -0,0 +1,301 @@+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.swiftnew file mode 100644index 0000000..3ecdcc0--- /dev/null+++ b/ios/PixiePulseUSBWriter/PixiePulseUSBWriter/WriteLEDsIntent.swift@@ -0,0 +1,41 @@+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.mdnew file mode 100644index 0000000..9a4844f--- /dev/null+++ b/ios/PixiePulseUSBWriter/README.md@@ -0,0 +1,192 @@+# 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.pngnew file mode 100644index 0000000..acbb0e7Binary files /dev/null and b/ios/PixiePulseUSBWriter/SidePulseIconSource.png differdiff --git a/ios/PixiePulseUSBWriter/examples/LEDS.example.txt b/ios/PixiePulseUSBWriter/examples/LEDS.example.txtnew file mode 100644index 0000000..4ad13f5--- /dev/null+++ b/ios/PixiePulseUSBWriter/examples/LEDS.example.txt@@ -0,0 +1,3 @@+#404040 1.4s pulse+off 400ms none+repeatdiff --git a/ios/PixiePulseUSBWriter/tools/.gitignore b/ios/PixiePulseUSBWriter/tools/.gitignorenew file mode 100644index 0000000..bf5305e--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/.gitignore@@ -0,0 +1,5 @@+.venv/+__pycache__/+*.pyc+*.env+pixiedot.envdiff --git a/ios/PixiePulseUSBWriter/tools/apns_client.py b/ios/PixiePulseUSBWriter/tools/apns_client.pynew file mode 100644index 0000000..4057cfe--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/apns_client.py@@ -0,0 +1,239 @@+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.pynew file mode 100644index 0000000..41e05b1--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/patterns.py@@ -0,0 +1,70 @@+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.examplenew file mode 100644index 0000000..549c770--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/pixiedot.env.example@@ -0,0 +1,9 @@+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.txtnew file mode 100644index 0000000..ba1e45a--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/requirements.txt@@ -0,0 +1,4 @@+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.pynew file mode 100644index 0000000..17def73--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/send_push.py@@ -0,0 +1,70 @@+#!/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.pynew file mode 100644index 0000000..d314b4a--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/server.py@@ -0,0 +1,382 @@+#!/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.pynew file mode 100644index 0000000..8f58e3e--- /dev/null+++ b/ios/PixiePulseUSBWriter/tools/tests/test_server.py@@ -0,0 +1,175 @@+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/mac_menu_test.py b/mac_menu_test.pynew file mode 100644index 0000000..ffedccb--- /dev/null+++ b/mac_menu_test.py@@ -0,0 +1,128 @@+#!/usr/bin/env python3+"""Tiny native macOS status-bar UI smoke test.++If needed:+ python3 -m pip install pyobjc-framework-Cocoa+"""++try:+ import objc+ from AppKit import (+ NSApp,+ NSApplication,+ NSApplicationActivationPolicyAccessory,+ NSButton,+ NSFont,+ NSMakeRect,+ NSMinYEdge,+ NSPopover,+ NSPopoverBehaviorTransient,+ NSPopUpButton,+ NSStatusBar,+ NSTextField,+ NSVariableStatusItemLength,+ NSView,+ NSViewController,+ )+ from Foundation import NSObject+except ImportError as exc:+ raise SystemExit(+ "This status-bar test requires PyObjC:\n"+ " python3 -m pip install pyobjc-framework-Cocoa"+ ) from exc+++class PopoverController(NSViewController):+ def init(self):+ self = objc.super(PopoverController, self).init()+ if self is None:+ return None++ self.status_label = None+ return self++ def loadView(self):+ view = NSView.alloc().initWithFrame_(NSMakeRect(0, 0, 200, 200))++ title = NSTextField.labelWithString_("Status Bar UI")+ title.setFrame_(NSMakeRect(16, 162, 168, 24))+ title.setFont_(NSFont.boldSystemFontOfSize_(14))+ view.addSubview_(title)++ dropdown = NSPopUpButton.alloc().initWithFrame_pullsDown_(+ NSMakeRect(16, 120, 168, 28), False+ )+ dropdown.addItemsWithTitles_(["One", "Two", "Three"])+ dropdown.setTarget_(self)+ dropdown.setAction_("dropdownChanged:")+ view.addSubview_(dropdown)++ button_one = NSButton.alloc().initWithFrame_(NSMakeRect(16, 82, 168, 30))+ button_one.setTitle_("Button 1")+ button_one.setTarget_(self)+ button_one.setAction_("buttonOneClicked:")+ view.addSubview_(button_one)++ button_two = NSButton.alloc().initWithFrame_(NSMakeRect(16, 46, 168, 30))+ button_two.setTitle_("Button 2")+ button_two.setTarget_(self)+ button_two.setAction_("buttonTwoClicked:")+ view.addSubview_(button_two)++ self.status_label = NSTextField.labelWithString_("Pick an action")+ self.status_label.setFrame_(NSMakeRect(16, 14, 168, 20))+ view.addSubview_(self.status_label)++ self.setView_(view)++ @objc.IBAction+ def dropdownChanged_(self, sender):+ self.status_label.setStringValue_(f"Selected {sender.titleOfSelectedItem()}")++ @objc.IBAction+ def buttonOneClicked_(self, _sender):+ self.status_label.setStringValue_("Button 1 clicked")++ @objc.IBAction+ def buttonTwoClicked_(self, _sender):+ self.status_label.setStringValue_("Button 2 clicked")+++class AppDelegate(NSObject):+ def applicationDidFinishLaunching_(self, _notification):+ NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)++ self.popover_controller = PopoverController.alloc().init()+ self.popover = NSPopover.alloc().init()+ self.popover.setBehavior_(NSPopoverBehaviorTransient)+ self.popover.setContentViewController_(self.popover_controller)++ self.status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(+ NSVariableStatusItemLength+ )+ status_button = self.status_item.button()+ status_button.setTitle_("UI")+ status_button.setTarget_(self)+ status_button.setAction_("togglePopover:")++ @objc.IBAction+ def togglePopover_(self, sender):+ if self.popover.isShown():+ self.popover.performClose_(sender)+ return++ self.popover.showRelativeToRect_ofView_preferredEdge_(+ sender.bounds(), sender, NSMinYEdge+ )+ NSApp.activateIgnoringOtherApps_(True)+++def main() -> None:+ app = NSApplication.sharedApplication()+ delegate = AppDelegate.alloc().init()+ app.setDelegate_(delegate)+ app.run()+++if __name__ == "__main__":+ main()diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..0e708e3--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,19 @@+[build-system]+requires = ["setuptools>=68"]+build-backend = "setuptools.build_meta"++[project]+name = "sidepulse-agent-monitor"+version = "0.1.0"+description = "Provider-neutral agent status collection for Codex and Claude hooks."+readme = "README.md"+requires-python = ">=3.10"+dependencies = []++[project.scripts]+sidepulse = "agent_monitor.cli:sidepulse_main"+agent-monitor = "agent_monitor.cli:main"+agent-status-bar = "agent_monitor.status_bar:main"++[tool.setuptools.packages.find]+where = ["src"]diff --git a/src/agent_monitor/__init__.py b/src/agent_monitor/__init__.pynew file mode 100644index 0000000..32ceb0a--- /dev/null+++ b/src/agent_monitor/__init__.py@@ -0,0 +1,49 @@+"""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 .models import AgentMode, AgentStatus, AggregateStatus, HookEvent++__all__ = [+ "AgentLedController",+ "AgentMode",+ "AgentStatus",+ "AggregateStatus",+ "BatteryLedController",+ "BatterySnapshot",+ "AgentMonitor",+ "LiveAgentMonitor",+ "HookEvent",+ "HookEventServer",+ "LedDisplayState",+ "MonitorSnapshot",+ "SourceSpec",+ "default_event_socket_path",+ "default_latest_state_path",+ "display_state_for_mode",+ "program_for_battery",+ "read_battery_snapshot",+ "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__.pynew file mode 100644index 0000000..bfdcd0c--- /dev/null+++ b/src/agent_monitor/__main__.py@@ -0,0 +1,4 @@+from .cli import main++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/agent_monitor/battery.py b/src/agent_monitor/battery.pynew file mode 100644index 0000000..f918c90--- /dev/null+++ b/src/agent_monitor/battery.py@@ -0,0 +1,663 @@+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+++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,+) -> 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 ";".join(+ battery_segment(index, BATTERY_HIGH_GREEN, transition)+ for index in range(count)+ )+ return ";".join(+ battery_segment(index, battery_fill_color(index, fill, color), transition)+ for index in range(count)+ )++ 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 "\n".join(lines)+++@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,+) -> 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,+ )+ 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,+ ) -> None:+ self.device_path = device_path+ self.file_name = file_name+ self.dry_run = dry_run+ self.error_retry_seconds = error_retry_seconds+ 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))+ 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.pynew file mode 100644index 0000000..3546a06--- /dev/null+++ b/src/agent_monitor/cli.py@@ -0,0 +1,782 @@+from __future__ import annotations++import argparse+import json+import os+import shutil+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, LEGACY_FILE_NAMES, 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 .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.",+ )+ 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}; "+ f"auto-detect falls back to {', '.join(LEGACY_FILE_NAMES)} when present."+ ),+ )+ write.add_argument("--dry-run", action="store_true", help="Show the target without writing.")+ write.set_defaults(func=cmd_sidepulse_write)++ add_sidepulse_battery_parser(subparsers)+ return parser+++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}; "+ f"auto-detect falls back to {', '.join(LEGACY_FILE_NAMES)} when present."+ ),+ )+ 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 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}; "+ f"auto-detect falls back to {', '.join(LEGACY_FILE_NAMES)} when present."+ ),+ )+ 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:+ providers = ("codex", "claude") if args.provider == "all" else (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))++ for result in results:+ action = "would update" if args.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}")+ return 0+++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 = args.codex_log if provider == "codex" else args.claude_log+ if explicit:+ return explicit.expanduser()+ if args.log_dir:+ return args.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.pynew file mode 100644index 0000000..ec03fe3--- /dev/null+++ b/src/agent_monitor/collector.py@@ -0,0 +1,1622 @@+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.pynew file mode 100644index 0000000..d6424f5--- /dev/null+++ b/src/agent_monitor/device_writer.py@@ -0,0 +1,189 @@+from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Iterable++DEFAULT_FILE_NAME = "LEDS.LED"+LEGACY_FILE_NAMES = ("LEDS.TXT",)+LED_FILE_NAMES = (DEFAULT_FILE_NAME, *LEGACY_FILE_NAMES)+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+ if file_name == DEFAULT_FILE_NAME:+ existing = existing_led_file(path)+ if existing is not None:+ return existing+ 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 existing_led_file(volume: Path) -> Path | None:+ for name in LED_FILE_NAMES:+ target = volume / name+ if path_exists(target):+ return target+ return None+++def iter_mounts(mount_root: Path) -> Iterable[Path]:+ try:+ children = list(mount_root.iterdir())+ 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.pynew file mode 100644index 0000000..9879464--- /dev/null+++ b/src/agent_monitor/hook.py@@ -0,0 +1,56 @@+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/install.py b/src/agent_monitor/install.pynew file mode 100644index 0000000..094a4a7--- /dev/null+++ b/src/agent_monitor/install.py@@ -0,0 +1,532 @@+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"+ command = " ".join(+ [+ shlex.quote(executable),+ "-m",+ "agent_monitor",+ "hook-log",+ "--provider",+ shlex.quote(provider),+ "--log",+ shlex.quote(str(log_path.expanduser())),+ ]+ )+ return hook_pythonpath_assignment() + 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 "agent_monitor hook-log" 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/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:+ pattern = re.compile(+ rf"^[^\n]*{re.escape(MANAGED_START)}[^\n]*\n.*?"+ rf"^[^\n]*{re.escape(MANAGED_END)}[^\n]*\n?",+ re.MULTILINE | re.DOTALL,+ )+ return pattern.sub("", text)+++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:+ 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:+ 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.pynew file mode 100644index 0000000..f941a28--- /dev/null+++ b/src/agent_monitor/ipc.py@@ -0,0 +1,137 @@+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.pynew file mode 100644index 0000000..9b2662e--- /dev/null+++ b/src/agent_monitor/keep_awake.py@@ -0,0 +1,213 @@+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.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.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.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.pynew file mode 100644index 0000000..d6fe273--- /dev/null+++ b/src/agent_monitor/led_status.py@@ -0,0 +1,224 @@+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,+) -> str:+ if state == LedDisplayState.IDLE:+ return "\n".join(+ [+ "off",+ f"{IDLE_DIM} 6s pulse",+ "repeat",+ ]+ )+ if state == LedDisplayState.ASK:+ return "\n".join(+ [+ "off",+ f"{ASK_AMBER} 1.6s pulse",+ "repeat",+ ]+ )+ if state == LedDisplayState.DONE:+ return DONE_GREEN+ if state == LedDisplayState.WORKING:+ return rolling_program(WORKING_CYAN, led_count=led_count)+ 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,+) -> 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),+ )+ 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())+++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,+ ) -> None:+ self.device_path = device_path+ self.file_name = file_name+ self.dry_run = dry_run+ self.error_retry_seconds = error_retry_seconds+ self.last_state: LedDisplayState | 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_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)+ now = time.monotonic()+ if state == self.last_state and self.last_error is None:+ return LedStatusWrite(+ state=state,+ target=self.last_target,+ program="",+ changed=False,+ )+ if (+ state == self.last_state+ 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,+ )+ except (DeviceWriteError, OSError) as exc:+ self.last_state = state+ 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_error = None+ self.last_target = result.target+ return resultdiff --git a/src/agent_monitor/models.py b/src/agent_monitor/models.pynew file mode 100644index 0000000..c4b5dae--- /dev/null+++ b/src/agent_monitor/models.py@@ -0,0 +1,157 @@+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.pynew file mode 100644index 0000000..7c8ec47--- /dev/null+++ b/src/agent_monitor/providers.py@@ -0,0 +1,282 @@+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/session_actions.py b/src/agent_monitor/session_actions.pynew file mode 100644index 0000000..99949aa--- /dev/null+++ b/src/agent_monitor/session_actions.py@@ -0,0 +1,33 @@+from __future__ import annotations++import shlex+from pathlib import Path+from urllib.parse import quote++from .models import AgentStatus+++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_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 Nonediff --git a/src/agent_monitor/settings.py b/src/agent_monitor/settings.pynew file mode 100644index 0000000..3ef2a4e--- /dev/null+++ b/src/agent_monitor/settings.py@@ -0,0 +1,278 @@+from __future__ import annotations++import json+import os+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Any++from .battery import DEFAULT_POWER_CHANGE_PREVIEW_SECONDS+++LED_DISPLAY_AGENT = "agent"+LED_DISPLAY_BATTERY = "battery"+LED_DISPLAY_CHOICES = (LED_DISPLAY_AGENT, LED_DISPLAY_BATTERY)+++@dataclass(frozen=True)+class DeviceDisplaySetting:+ device_id: str+ name: str+ path: str+ led_display: str = LED_DISPLAY_AGENT++ def to_dict(self) -> dict[str, str]:+ return {+ "id": self.device_id,+ "name": self.name,+ "path": self.path,+ "led_display": self.led_display,+ }+++@dataclass(frozen=True)+class AgentMonitorSettings:+ codex_transcripts_enabled: bool = False+ claude_transcripts_enabled: bool = False+ led_display: str = LED_DISPLAY_AGENT+ devices: tuple[DeviceDisplaySetting, ...] = ()+ 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++ 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 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,+ )+ )+ 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,+ )+ )+ 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 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 to_dict(self) -> dict[str, Any]:+ return {+ "led_display": self.led_display,+ "devices": [device.to_dict() for device in self.devices],+ "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,+ },+ }+++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),+ 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,+ ),+ )+++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 _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)+ devices.append(+ DeviceDisplaySetting(+ device_id=device_id,+ name=name,+ path=path,+ led_display=display,+ )+ )+ seen.add(device_id)+ return tuple(devices)+++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 defaultdiff --git a/src/agent_monitor/status_bar.py b/src/agent_monitor/status_bar.pynew file mode 100644index 0000000..f1545b7--- /dev/null+++ b/src/agent_monitor/status_bar.py@@ -0,0 +1,1546 @@+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,+ NSImage,+ NSMenu,+ NSMenuItem,+ NSOffState,+ NSOnState,+ NSStatusBar,+ NSTextField,+ 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,+ battery_state_label,+ format_watts,+ read_battery_snapshot,+)+from .collector import LiveAgentMonitor, SourceSpec, read_recent_lines+from .device_writer import (+ DEFAULT_FILE_NAME,+ MOUNT_ROOT,+ DeviceCandidate,+ discover_devices,+ path_exists,+ target_from_device_path,+)+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, normalized_device_name, write_mode_to_leds+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 session_deep_link, session_resume_command+from .settings import (+ LED_DISPLAY_AGENT,+ LED_DISPLAY_BATTERY,+ default_settings_path,+ load_settings,+ 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+ 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+++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.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.last_keep_awake_error = None+ self.last_status_read_error = None+ self.event_refresh_pending = False+ 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,+ )++ @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+ ns_url = NSURL.URLWithString_(str(url))+ if ns_url is not None:+ NSWorkspace.sharedWorkspace().openURL_(ns_url)++ @objc.IBAction+ def resumeSession_(self, sender):+ command = sender.representedObject()+ if command:+ open_terminal_command(str(command))++ @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 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 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 quit_(self, _sender):+ self.keep_awake.release()+ NSApp.terminate_(self)++ def applicationWillTerminate_(self, _notification):+ self.stop_event_server()+ 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,+ )++ 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_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+ 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+ 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),+ 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,+ 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 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 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++ 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}")++ 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 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()++ title = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ f"Agent Status: {state.label}",+ None,+ "",+ )+ title.setEnabled_(False)+ menu.addItem_(title)++ updated = snapshot.collected_at.astimezone().strftime("%H:%M:%S")+ counts = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ f"{snapshot.aggregate.active_count} active, {snapshot.aggregate.stale_count} stale - {updated}",+ None,+ "",+ )+ counts.setEnabled_(False)+ menu.addItem_(counts)+ menu.addItem_(NSMenuItem.separatorItem())++ devices_title = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Devices",+ None,+ "",+ )+ devices_title.setEnabled_(False)+ menu.addItem_(devices_title)++ device_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "LED Output",+ "toggleDeviceConnection:",+ "",+ )+ device_item.setTarget_(target)+ device_item.setState_(1 if target.device_connected() else 0)+ menu.addItem_(device_item)++ detail = device_connection_detail(target)+ if detail:+ detail_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ detail,+ None,+ "",+ )+ detail_item.setEnabled_(False)+ menu.addItem_(detail_item)++ devices = target.status_bar_devices()+ if devices:+ connected_devices = [device for device in devices if device.connected]+ previous_devices = [device for device in devices if not device.connected]+ if connected_devices:+ menu.addItem_(disabled_menu_item("Connected"))+ for device in connected_devices:+ menu.addItem_(build_device_menu_item(device, target))+ if previous_devices:+ menu.addItem_(disabled_menu_item("Previously Connected"))+ for device in previous_devices:+ menu.addItem_(build_device_menu_item(device, target))+ else:+ no_devices = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "No SidePulse or PulseDot devices seen",+ None,+ "",+ )+ no_devices.setEnabled_(False)+ menu.addItem_(no_devices)++ menu.addItem_(NSMenuItem.separatorItem())++ keep_awake_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Keep Awake",+ "toggleKeepAwake:",+ "",+ )+ keep_awake_item.setTarget_(target)+ keep_awake_item.setState_(1 if target.keep_awake.enabled else 0)+ menu.addItem_(keep_awake_item)++ keep_awake_detail_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ target.keep_awake.detail(),+ None,+ "",+ )+ keep_awake_detail_item.setEnabled_(False)+ menu.addItem_(keep_awake_detail_item)++ battery_preview_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Show Battery on Plug/Unplug",+ "toggleBatteryPowerPreview:",+ "",+ )+ battery_preview_item.setTarget_(target)+ battery_preview_item.setState_(1 if target.settings.battery_show_on_power_change else 0)+ menu.addItem_(battery_preview_item)++ battery_detail = battery_status_detail(target)+ if battery_detail:+ battery_detail_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ battery_detail,+ None,+ "",+ )+ battery_detail_item.setEnabled_(False)+ menu.addItem_(battery_detail_item)++ menu.addItem_(NSMenuItem.separatorItem())++ statuses = recent_statuses(snapshot)+ if not statuses:+ empty = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "No recent sessions",+ None,+ "",+ )+ empty.setEnabled_(False)+ menu.addItem_(empty)+ else:+ for status in statuses:+ menu.addItem_(build_session_menu_item(status, snapshot.collected_at, target))++ menu.addItem_(NSMenuItem.separatorItem())+ sources_title = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Sources",+ None,+ "",+ )+ sources_title.setEnabled_(False)+ menu.addItem_(sources_title)+ for source in snapshot.sources:+ marker = "OK" if source.path.exists() else "Missing"+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ f"{marker} {source.provider}: {source.path}",+ None,+ "",+ )+ item.setEnabled_(False)+ menu.addItem_(item)++ menu.addItem_(NSMenuItem.separatorItem())+ settings = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Settings...",+ "openSettings:",+ ",",+ )+ settings.setTarget_(target)+ menu.addItem_(settings)++ refresh = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Refresh",+ "forceRefresh:",+ "r",+ )+ refresh.setTarget_(target)+ menu.addItem_(refresh)++ quit_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(+ "Quit Agent Status",+ "quit:",+ "q",+ )+ quit_item.setTarget_(target)+ menu.addItem_(quit_item)++ return menu+++def build_device_menu_item(device: StatusBarDevice, target: StatusBarController) -> NSMenuItem:+ title = f"{device.name} - {device_display_label(device.display)}"+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, None, "")+ item.setImage_(+ image_for_symbol(+ device_display_symbol(device.display),+ device_display_label(device.display),+ )+ )+ submenu = NSMenu.alloc().init()++ status_text = "Connected" if device.connected else "Not Connected"+ submenu.addItem_(disabled_menu_item(status_text))+ location_text = f"Mounted at {device.root}" if device.connected else f"Last seen at {device.root}"+ submenu.addItem_(disabled_menu_item(location_text))++ if device.connected and device.reason:+ submenu.addItem_(disabled_menu_item(f"Detected by {device.reason}"))++ submenu.addItem_(NSMenuItem.separatorItem())+ 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)++ item.setSubmenu_(submenu)+ return item+++def build_settings_window(target: StatusBarController) -> NSWindow:+ width = 600+ height = 460+ 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, 412, 200, 24)+ add_label(content, "Codex", 32, 370, 80, 22)+ codex_status = add_label(content, "", 112, 370, 230, 22)+ add_button(content, "Install", 352, 366, 90, 28, target, "installCodexHooks:")+ add_button(content, "Uninstall", 452, 366, 100, 28, target, "uninstallCodexHooks:")++ add_label(content, "Claude", 32, 328, 80, 22)+ claude_status = add_label(content, "", 112, 328, 230, 22)+ add_button(content, "Install", 352, 324, 90, 28, target, "installClaudeHooks:")+ add_button(content, "Uninstall", 452, 324, 100, 28, target, "uninstallClaudeHooks:")++ add_separator(content, 24, 296, width - 48)+ add_label(content, "Transcript Monitoring", 24, 262, 240, 24)+ codex_transcripts = add_checkbox(+ content,+ "CLI fallback: Codex transcripts",+ 32,+ 228,+ 260,+ 24,+ target,+ "toggleCodexTranscripts:",+ )+ claude_transcripts = add_checkbox(+ content,+ "CLI fallback: Claude transcripts",+ 32,+ 196,+ 260,+ 24,+ target,+ "toggleClaudeTranscripts:",+ )++ add_separator(content, 24, 176, width - 48)+ add_label(content, "LED Display", 24, 142, 240, 24)+ battery_leds = add_checkbox(+ content,+ "Show battery on LEDs",+ 32,+ 108,+ 260,+ 24,+ target,+ "setBatteryLedDisplayFromCheckbox:",+ )+ battery_power_preview = add_checkbox(+ content,+ "Show battery for 7s on plug/unplug",+ 32,+ 76,+ 320,+ 24,+ target,+ "setBatteryPowerPreviewFromCheckbox:",+ )++ add_separator(content, 24, 56, width - 48)+ message = add_label(content, "", 24, 30, width - 48, 22)+ settings_path = add_label(content, "", 24, 8, width - 48, 18)++ target.settings_fields = {+ "codex_hook_status": codex_status,+ "claude_hook_status": claude_status,+ "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,+ }+ 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_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_checkbox_state(button, enabled: bool) -> None:+ if button is not None:+ button.setState_(NSOnState if enabled else NSOffState)+++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 device_display_symbol(display: str) -> str:+ if display == LED_DISPLAY_BATTERY:+ return "battery.100"+ return "waveform.path.ecg"+++def disabled_menu_item(title: str) -> NSMenuItem:+ item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, None, "")+ item.setEnabled_(False)+ 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,+ 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 device_connection_detail(target: StatusBarController) -> str:+ if not target.leds_enabled:+ return "LED output disabled"+ if target.last_led_error:+ return f"Device error: {target.last_led_error}"+ if target.led_controller.last_error:+ return f"Device error: {target.led_controller.last_error}"+ if target.battery_led_controller.last_error:+ return f"Device error: {target.battery_led_controller.last_error}"+ devices = target.status_bar_devices(remember=False)+ connected = [device for device in devices if device.connected]+ previous_count = max(0, len(devices) - len(connected))+ if connected:+ suffix = "device" if len(connected) == 1 else "devices"+ if previous_count:+ return f"{len(connected)} connected {suffix}, {previous_count} remembered"+ return f"{len(connected)} connected {suffix}"+ if previous_count:+ suffix = "device" if previous_count == 1 else "devices"+ return f"No devices connected, {previous_count} remembered {suffix}"+ return "No devices connected"+++def battery_status_detail(target: StatusBarController) -> str:+ if target.last_battery_error:+ return f"Battery error: {target.last_battery_error}"+ snapshot = target.last_battery_snapshot+ if snapshot is None:+ return ""+ state = battery_state_label(snapshot)+ if snapshot.is_plugged:+ return (+ f"Battery: {snapshot.percent}% {state}, "+ f"adapter {format_watts(snapshot.adapter_power)}"+ )+ return f"Battery: {snapshot.percent}% {state}"+++def preferred_status_bar_device(candidates: list[DeviceCandidate]) -> DeviceCandidate:+ return sorted(candidates, key=status_bar_device_sort_key)[0]+++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.setEnabled_(True)++ submenu = NSMenu.alloc().init()+ add_action_item(+ submenu,+ "Deep Link",+ "openDeepLink:",+ session_deep_link(status),+ target,+ )+ add_action_item(+ submenu,+ "Resume",+ "resumeSession:",+ session_resume_command(status),+ target,+ )+ item.setSubmenu_(submenu)+ return item+++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)+ age = format_age(status.age_seconds(now))+ tool = f" - {status.tool_name}" if status.tool_name else ""+ cwd = compact_path(status.cwd) if status.cwd else "-"+ return f"{state.label:7} {status.display_name} {age} {status.event_name}{tool} {cwd}"+++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_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.pynew file mode 100644index 0000000..550f715--- /dev/null+++ b/src/agent_monitor/status_bar_launch.py@@ -0,0 +1,160 @@+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 = "com.sidepulse.agentstatus"+LAUNCH_AGENT_FILENAME = f"{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 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,+) -> LaunchAgentResult:+ target = plist_path or launch_agent_path()+ 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)++ 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 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.pynew file mode 100644index 0000000..e9c6f47--- /dev/null+++ b/tests/test_agent_monitor.py@@ -0,0 +1,2388 @@+from __future__ import annotations++import json+import os+import plistlib+import tempfile+import time+import unittest+from datetime import datetime, timedelta, timezone+from pathlib import Path+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.models import AgentMode, AgentStatus, AggregateStatus+from agent_monitor.providers import default_log_path, default_state_dir, parse_log_line+from agent_monitor.session_actions import session_deep_link, session_resume_command+from agent_monitor.settings import (+ AgentMonitorSettings,+ DeviceDisplaySetting,+ default_config_dir,+ default_settings_path,+ load_settings,+ save_settings,+)+from agent_monitor.status_bar_launch import LAUNCH_AGENT_LABEL, build_launch_agent_plist+++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_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("agent_monitor", text)+ self.assertIn("hook-log", 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("agent_monitor" 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_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_falls_back_to_existing_legacy_leds_txt(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.TXT")+ self.assertEqual(target.read_text(), "off\n#FF00FF pulse")++ def test_sidepulse_write_discovers_pulsedot_volume(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ mount_root = Path(tmp)+ device = mount_root / "PulseDot"+ device.mkdir()+ (device / "LEDS.TXT").write_text("off")++ candidates = discover_devices(mount_root=mount_root)++ self.assertEqual(len(candidates), 1)+ self.assertEqual(candidates[0].root, device)+ self.assertEqual(candidates[0].target, device / "LEDS.TXT")++ 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")+ (device / "LEDS.TXT").write_text("legacy")++ candidates = discover_devices(mount_root=mount_root)++ self.assertEqual(len(candidates), 1)+ self.assertEqual(candidates[0].target, device / "LEDS.LED")++ def test_device_discovery_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.TXT").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()+ (device / "LEDS.TXT").write_text("off")+ result = cli_module.sidepulse_main(+ ["write", r"off\n#FF00FF pulse", "--device", str(device)]+ )++ self.assertEqual(result, 0)+ self.assertEqual((device / "LEDS.TXT").read_text(), "off\n#FF00FF pulse")++ 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,+ )++ def test_write_mode_to_leds_uses_device_specific_program(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ device = Path(tmp) / "PulseDot"+ device.mkdir()+ (device / "LEDS.TXT").write_text("off")++ result = write_mode_to_leds(AgentMode.WORKING, device_path=device)++ self.assertEqual(result.state, LedDisplayState.WORKING)+ self.assertEqual(result.target, device / "LEDS.TXT")+ self.assertEqual(+ (device / "LEDS.TXT").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.TXT").read_text(),+ "off\n#020204 6s pulse\nrepeat",+ )++ def test_led_count_uses_product_name(self) -> None:+ self.assertEqual(led_count_for_target(Path("/Volumes/PulseDot/LEDS.TXT")), 2)+ self.assertEqual(led_count_for_target(Path("/Volumes/PulseDot/LEDS.LED")), 2)+ self.assertEqual(led_count_for_target(Path("/Volumes/SidePulse/LEDS.LED")), 8)++ 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_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 / "LEDS.TXT"), status_path)+ self.assertEqual(status_file_for_target(device / "STATUS.TXT"), status_path)+ self.assertEqual(+ controller.poke_status_file(device / "LEDS.LED", now=0),+ 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_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",+ ),+ )+ )++ 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")++ 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")++ 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_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",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_audio_monitor_example.py b/tests/test_audio_monitor_example.pynew file mode 100644index 0000000..c930fbd--- /dev/null+++ b/tests/test_audio_monitor_example.py@@ -0,0 +1,64 @@+from __future__ import annotations++import unittest++from agent_monitor.device_writer import MAX_LED_BYTES, validate_led_text+from examples.audio_monitor import (+ build_led_program,+ green_to_red_rgb,+ rms_to_level,+ smooth_level,+)+++class AudioMonitorExampleTests(unittest.TestCase):+ def test_dim_idle_gradient_stays_within_led_limits(self) -> None:+ program = build_led_program(0.0, led_count=8, idle_brightness=0.08)++ validate_led_text(program)+ self.assertLessEqual(len(program.encode("utf-8")), MAX_LED_BYTES)+ self.assertEqual(program.count("; "), 7)+ self.assertIn("0:#001400 90ms cosine", program)+ self.assertIn("7:#140000 90ms cosine", program)++ def test_full_level_brightens_green_to_red_bar(self) -> None:+ program = build_led_program(1.0, led_count=8, transition_ms=0)++ self.assertTrue(program.startswith("0:#00FF00; "))+ self.assertIn("3:#DBFF00", program)+ self.assertIn("4:#FFDB00", program)+ self.assertTrue(program.endswith("7:#FF0000"))++ def test_half_level_keeps_back_half_dim(self) -> None:+ program = build_led_program(0.5, led_count=8, idle_brightness=0.08, transition_ms=0)+ segments = program.split("; ")++ self.assertEqual(segments[0], "0:#00FF00")+ self.assertEqual(segments[3], "3:#DBFF00")+ self.assertEqual(segments[4], "4:#141200")+ self.assertEqual(segments[7], "7:#140000")++ def test_color_gradient_endpoints(self) -> None:+ self.assertEqual(green_to_red_rgb(0, 8), (0, 255, 0))+ self.assertEqual(green_to_red_rgb(7, 8), (255, 0, 0))++ def test_audio_mapping_uses_db_range(self) -> None:+ self.assertEqual(rms_to_level(0.0, noise_floor_db=-60, peak_db=0, curve=1), 0.0)+ self.assertAlmostEqual(+ rms_to_level(10 ** (-30 / 20), noise_floor_db=-60, peak_db=0, curve=1),+ 0.5,+ places=6,+ )+ self.assertEqual(rms_to_level(1.0, noise_floor_db=-60, peak_db=0, curve=1), 1.0)++ def test_attack_is_faster_than_release(self) -> None:+ rising = smooth_level(0.0, 1.0, elapsed=0.05, attack_seconds=0.05, release_seconds=0.3)+ falling = smooth_level(1.0, 0.0, elapsed=0.05, attack_seconds=0.05, release_seconds=0.3)++ self.assertGreater(rising, 0.6)+ self.assertGreater(falling, 0.8)+ self.assertGreater(rising, 1.0 - falling)+++if __name__ == "__main__":+ unittest.main()