CLI for SidePulse
Python
Add headless remote agent relay
Peter Kuhar776f7cd83610
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 9d8ae5c..f221438 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -31,6 +31,7 @@ jobs:sh scripts/setup.sh"$smoke_home/.local/bin/sidepulse" --helpprintf '%064d\n' 0 | "$smoke_home/.local/bin/sidepulse" link >/dev/null+ "$smoke_home/.local/bin/sidepulse" link AbCdEfGhIjKlMnOpQrStUv"$smoke_home/.local/bin/sidepulse" push "off" --dry-runmkdir -p "$smoke_home/media/SidePulseDot""$smoke_home/.local/bin/sidepulse" write "off" \diff --git a/README.md b/README.mdindex ef8a894..4638ff9 100644--- a/README.md+++ b/README.md@@ -36,9 +36,10 @@ installs the menu-bar app and hardware helpers. On Linux, it automaticallyuses CLI-only mode for mounted SidePulse devices and iPhone linking/push. Runthe same command again to upgrade to the newest version.-Linux setup installs the CLI and agent hooks, but not an always-running relay-service yet. Local writes and iPhone pushes work immediately. For continuous-local agent-status mirroring, keep `sidepulse agent-monitor leds` running.+Setup also installs a headless SidePulse service. It runs through a LaunchAgent+on macOS and a user systemd service on Linux. If a Linux session has no systemd+user manager, setup still installs the unit and prints that it could not start;+`sidepulse service run` remains available as a foreground fallback.### 2. Install into your own Python environment@@ -132,6 +133,30 @@ LED program and event metadata. Remote payloads also include the sendingcomputer's name and available battery state. Set `SIDEPULSE_SERVER` to useanother bridge origin.+### Link a remote VM or computer++The receiving Mac gets a persistent, random relay channel during setup. Run+`sidepulse link` on the Mac to see the short command for another computer, then+paste that command into the VM. It looks like this:++```sh+sidepulse link AbCdEfGhIjKlMnOpQrStUv+```++The VM stores that channel locally. Its agent hooks hand events to the+background SidePulse service, which publishes them to the Mac. The Mac records+the remote events alongside its local agent history and updates its connected+SidePulse hardware or linked iPhone. The VM is an event source, so it does not+appear in the Devices menu.++The channel is a 128-bit capability token: possession grants access, so treat+the command like a password. There is no separate one-time code. Check the+service on either computer with:++```sh+sidepulse service status+```+## Battery LEDsShow the current Mac battery state:diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.pyindex d3b78e8..7ded3fd 100644--- a/src/sidepulse/cli.py+++ b/src/sidepulse/cli.py@@ -56,6 +56,11 @@ from .links import (send_ios_program,store_ios_link,)+from .relay import (+ configure_outbound_channel,+ ensure_receiver_config,+ relay_link_command,+)from .lid_sleep import (install_sleep_helper,sleep_helper_install_command,@@ -155,10 +160,23 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:link = subparsers.add_parser("link",- help="Link an iPhone by scanning a QR code or pasting its push token.",+ help="Link an iPhone or connect this computer to a remote SidePulse receiver.",)+ link.add_argument("relay_code", nargs="?", help="Relay code printed by the receiving Mac.")link.set_defaults(func=cmd_sidepulse_link)+ service = subparsers.add_parser(+ "service",+ help="Manage the headless SidePulse background service.",+ )+ service.add_argument(+ "service_command",+ choices=("start", "stop", "status", "run"),+ nargs="?",+ default="status",+ )+ service.set_defaults(func=cmd_sidepulse_service)+add_sidepulse_status_bar_parser(subparsers)add_sidepulse_sdejectguard_parser(subparsers)add_sidepulse_battery_parser(subparsers)@@ -597,8 +615,23 @@ def _remote_event_data(event_id: str) -> dict[str, object]:}-def cmd_sidepulse_link(_args: argparse.Namespace) -> int:+def cmd_sidepulse_link(args: argparse.Namespace) -> int:+ relay_code = getattr(args, "relay_code", None)+ if relay_code:+ try:+ config = configure_outbound_channel(relay_code, server=bridge_server())+ except LinkError as exc:+ print(f"sidepulse link: {exc}", file=sys.stderr)+ return 1+ print(+ "Linked this computer to the remote SidePulse receiver "+ f"({config.outbound_channel[:12]})."+ )+ print("Agent events will be relayed by the SidePulse background service.")+ return 0+try:+ relay_config = ensure_receiver_config()server = bridge_server()channel = new_pairing_channel()url = pairing_url(server, channel)@@ -612,6 +645,13 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:print(f"sidepulse link: {exc}", file=sys.stderr)return 1+ print("Link a remote computer")+ print()+ print("Run this command on the VM or other computer:")+ print()+ print(f" {relay_link_command(relay_config)}")+ print()+results: queue.Queue[IOSLink] = queue.Queue()stop = threading.Event()deadline = time.monotonic() + PAIRING_TIMEOUT_SECONDS@@ -682,6 +722,9 @@ def cmd_sidepulse_link(_args: argparse.Namespace) -> int:else:print("\nPairing timed out. Run `sidepulse link` to try again.", file=sys.stderr)return 1+ except KeyboardInterrupt:+ print("\nLinking stopped.")+ return 130finally:stop.set()@@ -940,6 +983,23 @@ def cmd_sidepulse_setup(args: argparse.Namespace) -> int:results = install_hook_results(args)print_install_results(results, dry_run=args.dry_run)+ from .service_launch import install_service++ relay_config = None+ if sys.platform == "darwin" and not args.dry_run:+ relay_config = ensure_receiver_config()+ service_result = install_service(start=True, dry_run=args.dry_run)+ service_action = "would install" if args.dry_run else "installed"+ if service_result.started:+ service_action += " and started"+ elif service_result.detail and not args.dry_run:+ service_action += f"; not started ({service_result.detail})"+ print(f"background service: {service_action}")+ if str(service_result.path):+ print(f" config: {service_result.path}")+ if relay_config is not None:+ print(f"remote computer: {relay_link_command(relay_config)}")+if sys.platform != "darwin":print("macOS integrations: skipped (CLI-only setup on this platform)")print("sidepulse: ready for linked phones and mounted SidePulse devices")@@ -975,6 +1035,32 @@ def cmd_sidepulse_setup(args: argparse.Namespace) -> int:return 0+def cmd_sidepulse_service(args: argparse.Namespace) -> int:+ from .service_launch import install_service, service_is_running, stop_service++ command = args.service_command+ if command == "run":+ from .service import run_service++ return run_service()+ if command == "stop":+ stopped = stop_service()+ print(f"background service: {'stopped' if stopped else 'not running'}")+ return 0+ if command == "start":+ result = install_service(start=True)+ action = "started" if result.started else "installed but not started"+ print(f"background service: {action}")+ print(f" config: {result.path}")+ if result.detail:+ print(f" {result.detail}")+ return 0 if result.started else 1++ running = service_is_running()+ print(f"background service: {'running' if running else 'not running'}")+ return 0 if running else 1++def print_sd_eject_guard_result(result) -> None:from .sd_eject_guard_launch import SD_EJECT_GUARD_DISPLAY_NAMEdiff --git a/src/sidepulse/hook.py b/src/sidepulse/hook.pyindex ce8a914..ad4aeb9 100644--- a/src/sidepulse/hook.py+++ b/src/sidepulse/hook.py@@ -135,6 +135,15 @@ def hook_log_main(provider: str, log_path: Path, event: str | None = None) -> intry:if not hook_event_socket_disabled():send_hook_event(actual_provider, line)+ from .relay import candidate_relay_event_socket_paths++ for relay_socket in candidate_relay_event_socket_paths():+ if send_hook_event(+ actual_provider,+ line,+ socket_path=relay_socket,+ ):+ breakexcept Exception:passexcept Exception:diff --git a/src/sidepulse/relay.py b/src/sidepulse/relay.pynew file mode 100644index 0000000..c4f822e--- /dev/null+++ b/src/sidepulse/relay.py@@ -0,0 +1,258 @@+from __future__ import annotations++import json+import hashlib+import os+import secrets+import socket+import threading+import urllib.error+import urllib.parse+import urllib.request+import uuid+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Callable++from .links import (+ DEFAULT_BRIDGE_SERVER,+ LinkError,+ bridge_server,+ iter_sse_messages,+ normalize_server,+)+from .providers import HOOK_PROVIDERS, candidate_state_dirs, default_state_dir+from .settings import default_config_dir+++RELAY_CONFIG_VERSION = 1+RELAY_MESSAGE_VERSION = 1+RELAY_CHANNEL_BYTES = 16+++@dataclass(frozen=True)+class RelayConfig:+ server: str+ receiver_channel: str = ""+ outbound_channel: str = ""+ machine_name: str = ""++ @property+ def receives_events(self) -> bool:+ return bool(self.receiver_channel)++ @property+ def publishes_events(self) -> bool:+ return bool(self.outbound_channel)+++def default_relay_config_path() -> Path:+ return default_config_dir() / "relay.json"+++def default_relay_event_socket_path() -> Path:+ return relay_socket_path_for_state_dir(default_state_dir())+++def candidate_relay_event_socket_paths() -> tuple[Path, ...]:+ return tuple(relay_socket_path_for_state_dir(path) for path in candidate_state_dirs())+++def relay_socket_path_for_state_dir(state_dir: Path) -> Path:+ path = state_dir / "relay-events.sock"+ if len(str(path).encode("utf-8")) <= 96:+ return path+ digest = hashlib.sha256(str(path).encode("utf-8")).hexdigest()[:16]+ return Path("/tmp") / f"sidepulse-relay-{os.getuid()}-{digest}.sock"+++def new_relay_channel() -> str:+ return secrets.token_urlsafe(RELAY_CHANNEL_BYTES)+++def load_relay_config(path: Path | None = None) -> RelayConfig:+ target = (path or default_relay_config_path()).expanduser()+ try:+ data = json.loads(target.read_text(encoding="utf-8"))+ except (FileNotFoundError, OSError, json.JSONDecodeError):+ return RelayConfig(server=bridge_server(), machine_name=socket.gethostname())+ if not isinstance(data, dict) or data.get("version") != RELAY_CONFIG_VERSION:+ return RelayConfig(server=bridge_server(), machine_name=socket.gethostname())+ try:+ server = normalize_server(str(data.get("server") or bridge_server()))+ except LinkError:+ server = bridge_server()+ return RelayConfig(+ server=server,+ receiver_channel=clean_channel(data.get("receiver_channel")),+ outbound_channel=clean_channel(data.get("outbound_channel")),+ machine_name=str(data.get("machine_name") or socket.gethostname()).strip()[:80],+ )+++def save_relay_config(config: RelayConfig, path: Path | None = None) -> Path:+ target = (path or default_relay_config_path()).expanduser()+ target.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "version": RELAY_CONFIG_VERSION,+ "server": normalize_server(config.server),+ "receiver_channel": clean_channel(config.receiver_channel),+ "outbound_channel": clean_channel(config.outbound_channel),+ "machine_name": config.machine_name.strip()[:80] or socket.gethostname(),+ }+ temp = target.with_suffix(".json.tmp")+ temp.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ os.chmod(temp, 0o600)+ temp.replace(target)+ return target+++def ensure_receiver_config(path: Path | None = None) -> RelayConfig:+ config = load_relay_config(path)+ if config.receiver_channel:+ return config+ updated = replace(config, receiver_channel=new_relay_channel())+ save_relay_config(updated, path)+ return updated+++def configure_outbound_channel(+ channel: str,+ *,+ server: str | None = None,+ path: Path | None = None,+) -> RelayConfig:+ config = load_relay_config(path)+ updated = replace(+ config,+ server=normalize_server(server or config.server),+ outbound_channel=clean_channel(channel, required=True),+ )+ save_relay_config(updated, path)+ return updated+++def relay_link_command(config: RelayConfig) -> str:+ command = f"sidepulse link {config.receiver_channel}"+ if normalize_server(config.server) != normalize_server(DEFAULT_BRIDGE_SERVER):+ return f"SIDEPULSE_SERVER={config.server} {command}"+ return command+++def clean_channel(value: object, *, required: bool = False) -> str:+ channel = str(value or "").strip()+ if channel and (+ len(channel) < 11+ or len(channel) > 128+ or any(+ char not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"+ for char in channel+ )+ ):+ raise LinkError("Relay code must be 11-128 Base64URL characters.")+ if required and not channel:+ raise LinkError("Relay code is required.")+ return channel+++def relay_event_message(provider: str, line: dict) -> dict[str, object]:+ return {+ "v": RELAY_MESSAGE_VERSION,+ "type": "agent_event",+ "event_id": str(uuid.uuid4()),+ "source": {"name": socket.gethostname()},+ "provider": provider,+ "line": line,+ }+++def parse_relay_event(value: str) -> tuple[str, dict, str] | None:+ try:+ message = json.loads(value)+ except json.JSONDecodeError:+ return None+ if not isinstance(message, dict):+ return None+ if message.get("v") != RELAY_MESSAGE_VERSION or message.get("type") != "agent_event":+ return None+ provider = message.get("provider")+ line = message.get("line")+ event_id = message.get("event_id")+ source = message.get("source")+ if (+ provider not in HOOK_PROVIDERS+ or not isinstance(line, dict)+ or not isinstance(event_id, str)+ ):+ return None+ source_name = "Remote computer"+ if isinstance(source, dict):+ source_name = str(source.get("name") or source_name).strip()[:80] or source_name+ return provider, annotate_remote_line(provider, line, source_name), event_id+++def annotate_remote_line(provider: str, line: dict, source_name: str) -> dict:+ annotated = dict(line)+ if provider == "codex" and isinstance(line.get("event"), dict):+ raw = dict(line["event"])+ annotated["event"] = raw+ else:+ raw = annotated+ raw["sidepulse_relay_source"] = source_name+ origin = str(raw.get("agent_origin") or raw.get("agentOrigin") or "").strip()+ raw["agent_origin"] = f"{origin} · {source_name}" if origin else source_name+ identity = str(+ raw.get("agent_id")+ or raw.get("agentId")+ or raw.get("session_id")+ or raw.get("sessionId")+ or "default"+ )+ raw["agent_id"] = f"relay:{source_name}:{identity}"+ return annotated+++def publish_relay_event(config: RelayConfig, provider: str, line: dict) -> None:+ if not config.outbound_channel:+ return+ body = json.dumps(+ relay_event_message(provider, line),+ separators=(",", ":"),+ ensure_ascii=False,+ ).encode("utf-8")+ channel = urllib.parse.quote(clean_channel(config.outbound_channel, required=True), safe="")+ request = urllib.request.Request(+ f"{normalize_server(config.server)}/api/leds/{channel}",+ data=body,+ method="POST",+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(request, timeout=5.0):+ return+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode("utf-8", errors="replace").strip()+ raise LinkError(detail or f"Bridge returned HTTP {exc.code}.") from exc+ except (OSError, urllib.error.URLError) as exc:+ raise LinkError(f"Could not reach the bridge: {exc}") from exc+++def listen_for_relay_events(+ config: RelayConfig,+ stop: threading.Event,+ on_event: Callable[[str, dict, str], None],+) -> None:+ channel = urllib.parse.quote(clean_channel(config.receiver_channel, required=True), safe="")+ url = f"{normalize_server(config.server)}/api/leds/{channel}"+ while not stop.is_set():+ request = urllib.request.Request(url, headers={"Accept": "text/event-stream"})+ try:+ with urllib.request.urlopen(request, timeout=30.0) as response:+ for value in iter_sse_messages(response):+ if stop.is_set():+ return+ parsed = parse_relay_event(value)+ if parsed is not None:+ on_event(*parsed)+ except (OSError, urllib.error.URLError):+ stop.wait(1.0)diff --git a/src/sidepulse/service.py b/src/sidepulse/service.pynew file mode 100644index 0000000..91daab7--- /dev/null+++ b/src/sidepulse/service.py@@ -0,0 +1,235 @@+from __future__ import annotations++import json+import signal+import socket+import sys+import threading+import time++from .battery import program_for_battery, read_battery_snapshot+from .collector import LiveAgentMonitor, default_sources+from .device_writer import DeviceWriteError, discover_devices, write_led_program+from .hook import write_hook_line+from .ipc import (+ HookEventServer,+ candidate_event_socket_paths,+ default_latest_state_path,+ send_hook_event,+)+from .led_status import led_count_for_target, program_for_agent_mode+from .links import load_ios_links, send_ios_program+from .providers import detect_log_path, parse_log_line+from .relay import (+ RelayConfig,+ default_relay_event_socket_path,+ listen_for_relay_events,+ load_relay_config,+ publish_relay_event,+)+from .settings import LED_DISPLAY_BATTERY, LED_DISPLAY_CUSTOM, load_settings+++SERVICE_POLL_SECONDS = 1.0+LINKED_PHONE_DEVICE_PREFIX = "ios/"+++class SidePulseService:+ def __init__(self, *, poll_seconds: float = SERVICE_POLL_SECONDS) -> None:+ self.poll_seconds = poll_seconds+ self.stop_event = threading.Event()+ self.local_server = HookEventServer(+ self.handle_local_event,+ socket_path=default_relay_event_socket_path(),+ )+ self.monitor = LiveAgentMonitor(+ recovery_sources=default_sources(),+ latest_state_path=default_latest_state_path(),+ )+ self.receiver_stop: threading.Event | None = None+ self.receiver_thread: threading.Thread | None = None+ self.receiver_signature: tuple[str, str] | None = None+ self.seen_event_ids: set[str] = set()+ self.last_program_by_target: dict[str, str] = {}++ def run(self) -> int:+ self.install_signal_handlers()+ self.local_server.start()+ try:+ while not self.stop_event.is_set():+ config = load_relay_config()+ self.sync_receiver(config)+ self.sync_outputs()+ self.stop_event.wait(self.poll_seconds)+ finally:+ self.stop_receiver()+ self.local_server.stop()+ return 0++ def stop(self) -> None:+ self.stop_event.set()++ def install_signal_handlers(self) -> None:+ if threading.current_thread() is not threading.main_thread():+ return+ for signum in (signal.SIGINT, signal.SIGTERM):+ signal.signal(signum, lambda _signum, _frame: self.stop())++ def handle_local_event(self, provider: str, line: dict) -> None:+ self.ingest_event(provider, line)+ config = load_relay_config()+ if not config.publishes_events:+ return+ try:+ publish_relay_event(config, provider, line)+ except Exception as exc:+ print(f"sidepulse service: relay send failed: {exc}", file=sys.stderr)++ def sync_receiver(self, config: RelayConfig) -> None:+ signature = (+ config.server,+ config.receiver_channel,+ ) if config.receives_events else None+ if signature == self.receiver_signature:+ return+ self.stop_receiver()+ self.receiver_signature = signature+ if signature is None:+ return+ stop = threading.Event()+ thread = threading.Thread(+ target=listen_for_relay_events,+ args=(config, stop, self.handle_remote_event),+ daemon=True,+ )+ self.receiver_stop = stop+ self.receiver_thread = thread+ thread.start()++ def stop_receiver(self) -> None:+ if self.receiver_stop is not None:+ self.receiver_stop.set()+ self.receiver_stop = None+ self.receiver_thread = None+ self.receiver_signature = None++ def handle_remote_event(self, provider: str, line: dict, event_id: str) -> None:+ if event_id in self.seen_event_ids:+ return+ self.seen_event_ids.add(event_id)+ if len(self.seen_event_ids) > 2048:+ self.seen_event_ids = {event_id}+ try:+ write_hook_line(detect_log_path(provider), line)+ except Exception as exc:+ print(f"sidepulse service: relay receive failed: {exc}", file=sys.stderr)+ return+ self.ingest_event(provider, line)+ send_hook_event(provider, line)++ def ingest_event(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)+ except Exception:+ pass++ def sync_outputs(self) -> None:+ if status_bar_monitor_available():+ return+ settings = load_settings()+ snapshot = self.monitor.snapshot(include_stale=False)+ mode = snapshot.aggregate.mode+ battery = None+ try:+ battery = read_battery_snapshot(+ full_charge_watts=settings.battery_full_charge_watts,+ )+ except Exception:+ pass++ active_targets: set[str] = set()+ for candidate in discover_devices():+ device_id = str(candidate.root.expanduser())+ display = settings.display_for_device(device_id)+ if display == LED_DISPLAY_CUSTOM:+ continue+ if display == LED_DISPLAY_BATTERY and battery is not None:+ program = program_for_battery(+ battery,+ led_count=led_count_for_target(candidate.target),+ brightness=settings.brightness_for_device(device_id),+ )+ else:+ animation = settings.agent_animation(mode)+ try:+ program = program_for_agent_mode(+ mode,+ led_count=led_count_for_target(candidate.target),+ brightness=settings.brightness_for_device(device_id),+ animation_style=animation.style,+ custom_program=animation.custom_program,+ )+ except DeviceWriteError:+ continue+ key = f"file:{candidate.target}"+ active_targets.add(key)+ if self.last_program_by_target.get(key) == program:+ continue+ try:+ write_led_program(program, device_path=candidate.target)+ except Exception as exc:+ print(f"sidepulse service: device write failed: {exc}", file=sys.stderr)+ continue+ self.last_program_by_target[key] = program++ for link in load_ios_links():+ device_id = f"{LINKED_PHONE_DEVICE_PREFIX}{link.link_id}"+ if settings.display_for_device(device_id) == LED_DISPLAY_CUSTOM:+ continue+ animation = settings.agent_animation(mode)+ try:+ program = program_for_agent_mode(+ mode,+ led_count=8,+ animation_style=animation.style,+ custom_program=animation.custom_program,+ )+ except DeviceWriteError:+ continue+ key = f"phone:{link.link_id}"+ active_targets.add(key)+ if self.last_program_by_target.get(key) == program:+ continue+ data: dict[str, object] = {"source": {"name": socket.gethostname()}}+ try:+ send_ios_program(link, program, data=data)+ except Exception as exc:+ print(f"sidepulse service: phone push failed: {exc}", file=sys.stderr)+ continue+ self.last_program_by_target[key] = program++ for key in set(self.last_program_by_target) - active_targets:+ self.last_program_by_target.pop(key, None)+++def run_service() -> int:+ return SidePulseService().run()+++def status_bar_monitor_available() -> bool:+ for path in candidate_event_socket_paths():+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ client.settimeout(0.05)+ try:+ client.connect(str(path.expanduser()))+ return True+ except OSError:+ continue+ finally:+ client.close()+ return Falsediff --git a/src/sidepulse/service_launch.py b/src/sidepulse/service_launch.pynew file mode 100644index 0000000..76d3ca3--- /dev/null+++ b/src/sidepulse/service_launch.py@@ -0,0 +1,182 @@+from __future__ import annotations++import os+import plistlib+import shutil+import subprocess+import sys+from dataclasses import dataclass+from pathlib import Path++from .providers import default_state_dir+++SERVICE_LABEL = "io.sidepulse.service"+++@dataclass(frozen=True)+class ServiceInstallResult:+ path: Path+ changed: bool+ started: bool+ detail: str = ""+++def service_command() -> list[str]:+ return [sys.executable, "-m", "sidepulse", "service", "run"]+++def install_service(*, start: bool = True, dry_run: bool = False) -> ServiceInstallResult:+ if sys.platform == "darwin":+ return install_launch_agent(start=start, dry_run=dry_run)+ if sys.platform.startswith("linux"):+ return install_systemd_user_service(start=start, dry_run=dry_run)+ return ServiceInstallResult(Path(""), False, False, "unsupported platform")+++def install_launch_agent(*, start: bool, dry_run: bool) -> ServiceInstallResult:+ path = Path.home() / "Library" / "LaunchAgents" / f"{SERVICE_LABEL}.plist"+ state = default_state_dir()+ payload = {+ "Label": SERVICE_LABEL,+ "ProgramArguments": service_command(),+ "RunAtLoad": True,+ "KeepAlive": True,+ "StandardOutPath": str(state / "service.out.log"),+ "StandardErrorPath": str(state / "service.err.log"),+ "WorkingDirectory": str(Path.home()),+ "EnvironmentVariables": {+ "PATH": os.environ.get(+ "PATH",+ "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",+ ),+ },+ }+ data = plistlib.dumps(payload, sort_keys=False)+ existing = path.read_bytes() if path.exists() else None+ changed = existing != data+ if dry_run:+ return ServiceInstallResult(path, changed, False, "dry run")+ path.parent.mkdir(parents=True, exist_ok=True)+ state.mkdir(parents=True, exist_ok=True)+ if changed:+ path.write_bytes(data)+ started = False+ if start:+ domain = f"gui/{subprocess.check_output(['id', '-u'], text=True).strip()}"+ subprocess.run(+ ["launchctl", "bootout", domain, str(path)],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ result = subprocess.run(+ ["launchctl", "bootstrap", domain, str(path)],+ check=False,+ capture_output=True,+ text=True,+ )+ started = result.returncode == 0+ detail = result.stderr.strip() if not started else ""+ else:+ detail = ""+ return ServiceInstallResult(path, changed, started, detail)+++def install_systemd_user_service(*, start: bool, dry_run: bool) -> ServiceInstallResult:+ path = Path.home() / ".config" / "systemd" / "user" / "sidepulse.service"+ command = " ".join(systemd_quote(part) for part in service_command())+ text = (+ "[Unit]\n"+ "Description=SidePulse background agent\n"+ "After=network-online.target\n\n"+ "[Service]\n"+ f"ExecStart={command}\n"+ "Restart=on-failure\n"+ "RestartSec=2\n\n"+ "[Install]\n"+ "WantedBy=default.target\n"+ )+ existing = path.read_text(encoding="utf-8") if path.exists() else None+ changed = existing != text+ if dry_run:+ return ServiceInstallResult(path, changed, False, "dry run")+ path.parent.mkdir(parents=True, exist_ok=True)+ if changed:+ path.write_text(text, encoding="utf-8")+ systemctl = shutil.which("systemctl")+ if not start or systemctl is None:+ detail = "systemd user manager unavailable" if start else ""+ return ServiceInstallResult(path, changed, False, detail)+ reload_result = subprocess.run(+ [systemctl, "--user", "daemon-reload"],+ check=False,+ capture_output=True,+ text=True,+ )+ if reload_result.returncode != 0:+ return ServiceInstallResult(+ path,+ changed,+ False,+ reload_result.stderr.strip() or "systemd user manager unavailable",+ )+ result = subprocess.run(+ [systemctl, "--user", "enable", "--now", "sidepulse.service"],+ check=False,+ capture_output=True,+ text=True,+ )+ return ServiceInstallResult(+ path,+ changed,+ result.returncode == 0,+ result.stderr.strip() if result.returncode else "",+ )+++def stop_service() -> bool:+ if sys.platform == "darwin":+ path = Path.home() / "Library" / "LaunchAgents" / f"{SERVICE_LABEL}.plist"+ domain = f"gui/{subprocess.check_output(['id', '-u'], text=True).strip()}"+ result = subprocess.run(+ ["launchctl", "bootout", domain, str(path)],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ return result.returncode == 0+ systemctl = shutil.which("systemctl")+ if systemctl is None:+ return False+ result = subprocess.run(+ [systemctl, "--user", "stop", "sidepulse.service"],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ return result.returncode == 0+++def service_is_running() -> bool:+ if sys.platform == "darwin":+ domain = f"gui/{subprocess.check_output(['id', '-u'], text=True).strip()}"+ result = subprocess.run(+ ["launchctl", "print", f"{domain}/{SERVICE_LABEL}"],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ return result.returncode == 0+ systemctl = shutil.which("systemctl")+ if systemctl is None:+ return False+ result = subprocess.run(+ [systemctl, "--user", "is-active", "--quiet", "sidepulse.service"],+ check=False,+ )+ return result.returncode == 0+++def systemd_quote(value: str) -> str:+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'diff --git a/tests/test_relay.py b/tests/test_relay.pynew file mode 100644index 0000000..1cb86e0--- /dev/null+++ b/tests/test_relay.py@@ -0,0 +1,252 @@+from __future__ import annotations++import io+import json+import os+import tempfile+import threading+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++from sidepulse.cli import sidepulse_main+from sidepulse.device_writer import DeviceCandidate+from sidepulse.hook import hook_log_main+from sidepulse.models import AgentMode+from sidepulse.relay import (+ RelayConfig,+ configure_outbound_channel,+ ensure_receiver_config,+ load_relay_config,+ new_relay_channel,+ parse_relay_event,+ publish_relay_event,+ relay_socket_path_for_state_dir,+ relay_event_message,+ relay_link_command,+)+from sidepulse.service import SidePulseService+from sidepulse.service_launch import install_systemd_user_service+from sidepulse.settings import AgentMonitorSettings+++class RelayConfigTests(unittest.TestCase):+ def test_receiver_code_is_persistent_and_128_bit(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "relay.json"+ first = ensure_receiver_config(path)+ second = ensure_receiver_config(path)++ self.assertEqual(first.receiver_channel, second.receiver_channel)+ self.assertEqual(len(first.receiver_channel), 22)+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)++ def test_outbound_code_round_trips(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "relay.json"+ config = configure_outbound_channel("a" * 22, path=path)++ self.assertEqual(config.outbound_channel, "a" * 22)+ self.assertEqual(load_relay_config(path), config)++ def test_link_command_is_short_for_default_server(self) -> None:+ config = RelayConfig(+ server="https://bridge.sidepulse.io",+ receiver_channel="a" * 22,+ )+ self.assertEqual(relay_link_command(config), f"sidepulse link {'a' * 22}")++ def test_relay_codes_are_unique_base64url(self) -> None:+ codes = {new_relay_channel() for _ in range(100)}+ alphabet = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")+ self.assertEqual(len(codes), 100)+ self.assertTrue(all(len(code) == 22 for code in codes))+ self.assertTrue(all(set(code) <= alphabet for code in codes))++ def test_link_code_configures_this_computer_as_a_source(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ home = Path(tmp)+ environment = {+ "HOME": str(home),+ "XDG_CONFIG_HOME": str(home / ".config"),+ }+ with patch.dict(os.environ, environment):+ result = sidepulse_main(["link", "a" * 22])+ config = load_relay_config()++ self.assertEqual(result, 0)+ self.assertEqual(config.outbound_channel, "a" * 22)++ def test_long_state_paths_use_a_short_socket_path(self) -> None:+ path = relay_socket_path_for_state_dir(Path("/tmp") / ("very-long/" * 20))+ self.assertEqual(path.parent, Path("/tmp"))+ self.assertLessEqual(len(str(path).encode("utf-8")), 96)+++class RelayTransportTests(unittest.TestCase):+ def test_event_message_round_trips(self) -> None:+ line = {"hook_event_name": "Stop", "session_id": "vm-session"}+ message = relay_event_message("claude", line)+ parsed = parse_relay_event(json.dumps(message))++ self.assertIsNotNone(parsed)+ provider, parsed_line, event_id = parsed+ self.assertEqual(provider, "claude")+ self.assertEqual(parsed_line["hook_event_name"], "Stop")+ self.assertIn("sidepulse_relay_source", parsed_line)+ self.assertTrue(parsed_line["agent_id"].startswith("relay:"))+ self.assertTrue(event_id)++ def test_unknown_provider_is_rejected(self) -> None:+ message = relay_event_message("claude", {})+ message["provider"] = "../../escape"+ self.assertIsNone(parse_relay_event(json.dumps(message)))++ def test_publish_posts_to_receiver_channel(self) -> None:+ response = MagicMock()+ response.__enter__.return_value = response+ config = RelayConfig(+ server="https://bridge.sidepulse.io",+ outbound_channel="a" * 22,+ )+ with patch("sidepulse.relay.urllib.request.urlopen", return_value=response) as open_url:+ publish_relay_event(config, "codex", {"event": {"type": "task_complete"}})++ request = open_url.call_args.args[0]+ self.assertEqual(+ request.full_url,+ f"https://bridge.sidepulse.io/api/leds/{'a' * 22}",+ )+ self.assertEqual(json.loads(request.data)["type"], "agent_event")++ def test_hook_notifies_ui_and_background_service_sockets(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ relay_socket = Path(tmp) / "relay.sock"+ log = Path(tmp) / "claude.jsonl"+ with (+ patch("sys.stdin", io.StringIO('{"hook_event_name":"Stop"}')),+ patch("sidepulse.hook.hook_event_socket_disabled", return_value=False),+ patch("sidepulse.hook.send_hook_event", return_value=True) as send,+ patch(+ "sidepulse.relay.candidate_relay_event_socket_paths",+ return_value=(relay_socket,),+ ),+ ):+ result = hook_log_main("claude", log)++ self.assertEqual(result, 0)+ self.assertEqual(send.call_count, 2)+ self.assertEqual(send.call_args_list[1].kwargs["socket_path"], relay_socket)+++class SidePulseServiceTests(unittest.TestCase):+ def test_local_hook_is_published_when_source_is_linked(self) -> None:+ service = SidePulseService()+ config = RelayConfig(+ server="https://bridge.sidepulse.io",+ outbound_channel="a" * 22,+ )+ line = {"hook_event_name": "Stop"}+ with (+ patch.object(service, "ingest_event"),+ patch("sidepulse.service.load_relay_config", return_value=config),+ patch("sidepulse.service.publish_relay_event") as publish,+ ):+ service.handle_local_event("claude", line)++ publish.assert_called_once_with(config, "claude", line)++ def test_remote_event_is_logged_forwarded_and_deduplicated(self) -> None:+ service = SidePulseService()+ line = {"hook_event_name": "Stop"}+ with (+ patch("sidepulse.service.detect_log_path", return_value=Path("/tmp/claude.jsonl")),+ patch("sidepulse.service.write_hook_line") as write,+ patch("sidepulse.service.send_hook_event") as forward,+ ):+ service.handle_remote_event("claude", line, "event-1")+ service.handle_remote_event("claude", line, "event-1")++ write.assert_called_once_with(Path("/tmp/claude.jsonl"), line)+ forward.assert_called_once_with("claude", line)++ def test_manual_linked_phone_is_not_updated(self) -> None:+ service = SidePulseService()+ service.monitor = SimpleNamespace(+ snapshot=lambda include_stale=False: SimpleNamespace(+ aggregate=SimpleNamespace(mode=AgentMode.WORKING)+ )+ )+ link = SimpleNamespace(link_id="phone", name="iPhone")+ settings = MagicMock()+ settings.battery_full_charge_watts = None+ settings.display_for_device.return_value = "custom"+ with (+ patch("sidepulse.service.status_bar_monitor_available", return_value=False),+ patch("sidepulse.service.load_settings", return_value=settings),+ patch("sidepulse.service.read_battery_snapshot", side_effect=OSError),+ patch("sidepulse.service.discover_devices", return_value=[]),+ patch("sidepulse.service.load_ios_links", return_value=(link,)),+ patch("sidepulse.service.send_ios_program") as send,+ ):+ service.sync_outputs()++ send.assert_not_called()++ def test_headless_service_writes_agent_status_to_local_dot(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp) / "SidePulseDot"+ root.mkdir()+ target = root / "LEDS.LED"+ service = SidePulseService()+ service.monitor = SimpleNamespace(+ snapshot=lambda include_stale=False: SimpleNamespace(+ aggregate=SimpleNamespace(mode=AgentMode.WORKING)+ )+ )+ with (+ patch("sidepulse.service.status_bar_monitor_available", return_value=False),+ patch("sidepulse.service.load_settings", return_value=AgentMonitorSettings()),+ patch("sidepulse.service.read_battery_snapshot", side_effect=OSError),+ patch(+ "sidepulse.service.discover_devices",+ return_value=(DeviceCandidate(root, target, "test"),),+ ),+ patch("sidepulse.service.load_ios_links", return_value=()),+ ):+ service.sync_outputs()++ self.assertTrue(target.exists())+ self.assertIn("#", target.read_text(encoding="utf-8"))++ def test_status_bar_process_remains_output_owner_when_running(self) -> None:+ service = SidePulseService()+ with (+ patch("sidepulse.service.status_bar_monitor_available", return_value=True),+ patch.object(service.monitor, "snapshot") as snapshot,+ ):+ service.sync_outputs()++ snapshot.assert_not_called()+++class ServiceLaunchTests(unittest.TestCase):+ def test_linux_installs_systemd_user_unit_without_requiring_running_systemd(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ home = Path(tmp)+ with (+ patch.object(Path, "home", return_value=home),+ patch("sidepulse.service_launch.shutil.which", return_value=None),+ ):+ result = install_systemd_user_service(start=True, dry_run=False)++ text = result.path.read_text(encoding="utf-8")+ self.assertIn("SidePulse background agent", text)+ self.assertIn('"service" "run"', text)+ self.assertFalse(result.started)+ self.assertIn("unavailable", result.detail)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.pyindex 11e3323..3798891 100644--- a/tests/test_sidepulse.py+++ b/tests/test_sidepulse.py@@ -3747,7 +3747,6 @@ class AgentMonitorTests(unittest.TestCase):cleanup_removed=None,cleanup_skipped=None,)-with patch("sidepulse.sd_eject_guard_launch.install_sd_eject_guard",return_value=guard_result,@@ -3880,9 +3879,21 @@ class AgentMonitorTests(unittest.TestCase):cleanup_removed=None,cleanup_skipped=None,)+ service_result = SimpleNamespace(+ path=Path("/tmp/io.sidepulse.service.plist"),+ changed=True,+ started=True,+ detail="",+ )+ relay_config = SimpleNamespace(+ receiver_channel="receiver-code",+ server="https://bridge.sidepulse.io",+ )with (patch.object(cli_module.sys, "platform", "darwin"),+ patch.object(cli_module, "ensure_receiver_config", return_value=relay_config),+ patch("sidepulse.service_launch.install_service", return_value=service_result) as service,patch.object(cli_module, "install_codex_hooks", return_value=codex_result) as codex,patch.object(cli_module, "install_claude_hooks", return_value=claude_result) as claude,patch.object(@@ -3909,6 +3920,7 @@ class AgentMonitorTests(unittest.TestCase):grok.assert_called_once()guard.assert_called_once_with(scope="auto", dry_run=False)launch.assert_called_once_with(start=True)+ service.assert_called_once_with(start=True, dry_run=False)def test_sidepulse_setup_no_status_bar_still_installs_guard(self) -> None:parser = cli_module.build_sidepulse_parser()@@ -3930,9 +3942,21 @@ class AgentMonitorTests(unittest.TestCase):cleanup_removed=None,cleanup_skipped=None,)+ service_result = SimpleNamespace(+ path=Path("/tmp/io.sidepulse.service.plist"),+ changed=False,+ started=True,+ detail="",+ )+ relay_config = SimpleNamespace(+ receiver_channel="receiver-code",+ server="https://bridge.sidepulse.io",+ )with (patch.object(cli_module.sys, "platform", "darwin"),+ patch.object(cli_module, "ensure_receiver_config", return_value=relay_config),+ patch("sidepulse.service_launch.install_service", return_value=service_result),patch.object(cli_module, "install_hook_results", return_value=[hook_result]),patch("sidepulse.sd_eject_guard_launch.install_sd_eject_guard",@@ -3956,10 +3980,17 @@ class AgentMonitorTests(unittest.TestCase):changed=False,backup_path=None,)+ service_result = SimpleNamespace(+ path=Path("/tmp/sidepulse.service"),+ changed=True,+ started=False,+ detail="systemd user manager unavailable",+ )with (patch.object(cli_module.sys, "platform", "linux"),patch.object(cli_module, "install_hook_results", return_value=[hook_result]),+ patch("sidepulse.service_launch.install_service", return_value=service_result) as service,patch("sidepulse.sd_eject_guard_launch.install_sd_eject_guard") as guard,patch("sidepulse.status_bar_launch.install_launch_agent") as launch,patch("builtins.print") as output,@@ -3969,6 +4000,7 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(result, 0)guard.assert_not_called()launch.assert_not_called()+ service.assert_called_once_with(start=True, dry_run=False)rendered = "\n".join(" ".join(map(str, call.args)) for call in output.call_args_list)self.assertIn("CLI-only setup", rendered)self.assertIn("linked phones and mounted SidePulse devices", rendered)