CLI for SidePulse
Python
Support CLI installation on Linux
Peter Kuhard09f42b08d69
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 8b7ec43..9d8ae5c 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -7,6 +7,36 @@ on:workflow_call: # so the release pipeline can gate on thisjobs:+ linux:+ name: Linux CLI / Python 3.12+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"++ - name: Install and test package+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e '.[test]'+ python -m pytest tests -q++ - name: TLDR installer and SidePulse Dot smoke test+ run: |+ smoke_home="$(mktemp -d)"+ export HOME="$smoke_home"+ SIDEPULSE_INSTALL_SPEC="$GITHUB_WORKSPACE" \+ PYTHON_BIN=python \+ sh scripts/setup.sh+ "$smoke_home/.local/bin/sidepulse" --help+ printf '%064d\n' 0 | "$smoke_home/.local/bin/sidepulse" link >/dev/null+ "$smoke_home/.local/bin/sidepulse" push "off" --dry-run+ mkdir -p "$smoke_home/media/SidePulseDot"+ "$smoke_home/.local/bin/sidepulse" write "off" \+ --device "$smoke_home/media/SidePulseDot"+ test "$(cat "$smoke_home/media/SidePulseDot/LEDS.LED")" = "off"+macos:name: macOS / Python ${{ matrix.python-version }}runs-on: macos-latestdiff --git a/README.md b/README.mdindex 620b19a..ef8a894 100644--- a/README.md+++ b/README.md@@ -28,10 +28,17 @@ Choose the level that fits how you want to use SidePulse.curl -fsSL https://sidepulse.io/setup.sh | bash```-The [setup script](scripts/setup.sh) creates an isolated environment under+The command works on macOS and Linux with Python 3.10 or newer. The+[setup script](scripts/setup.sh) creates an isolated environment under`~/.local/share/sidepulse/venv`, installs SidePulse from GitHub, links the CLI-at `~/.local/bin/sidepulse`, and runs `sidepulse setup`. Run the same command-again to upgrade to the newest version.+at `~/.local/bin/sidepulse`, and runs `sidepulse setup`. On macOS, setup also+installs the menu-bar app and hardware helpers. On Linux, it automatically+uses CLI-only mode for mounted SidePulse devices and iPhone linking/push. Run+the 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.### 2. Install into your own Python environment@@ -94,13 +101,17 @@ printf 'off\n#ff3a00 pulse\nrepeat' | sidepulse writesidepulse push - --title "Deploying" < deploy.LED```-The CLI auto-detects mounted devices under `/Volumes` by looking for a-SidePulse Pro/SidePulse Dot-style volume name or an existing `LEDS.LED`. For a-specific local path, the existing `--device` option remains available:+The CLI auto-detects mounted devices by looking for a SidePulse Pro/SidePulse+Dot-style volume name or an existing `LEDS.LED`. It checks `/Volumes` on macOS+and common removable-media locations such as `/media/$USER`,+`/run/media/$USER`, and `/mnt` on Linux. For a specific local path, the+existing `--device` option remains available:```shsidepulse write "off\n#ff3a00 1.6s pulse\nrepeat" --device /Volumes/SidePulseProsidepulse write "off" --device /Volumes/SidePulsePro/LEDS.LED+# Linux example:+sidepulse write "off" --device /media/$USER/SidePulseDot```The writer decodes simple escapes such as `\n`, then enforces the controller's@@ -156,7 +167,7 @@ sidepulse battery configure --full-watts autosidepulse battery configure --show-on-power-change yes --power-change-preview-seconds 7```-## sidepulse+## macOS companion app`sidepulse` includes a companion menu-bar app for macOS that controlsSidePulse Pro and SidePulse Dot.diff --git a/pyproject.toml b/pyproject.tomlindex 46aa7cf..6af2a1b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -18,6 +18,7 @@ classifiers = ["Environment :: MacOS X","Intended Audience :: Developers","Operating System :: MacOS :: MacOS X",+ "Operating System :: POSIX :: Linux","Programming Language :: Python :: 3","Programming Language :: Python :: 3.10","Programming Language :: Python :: 3.11",diff --git a/scripts/setup.sh b/scripts/setup.shindex 5ffc605..653a81f 100755--- a/scripts/setup.sh+++ b/scripts/setup.sh@@ -1,12 +1,28 @@#!/bin/shset -eu-VENV="$HOME/.local/share/sidepulse/venv"-BIN_DIR="$HOME/.local/bin"+PYTHON_BIN=${PYTHON_BIN:-python3}+INSTALL_SPEC=${SIDEPULSE_INSTALL_SPEC:-"git+https://github.com/inteliwear/sidepulse.git"}+VENV=${SIDEPULSE_INSTALL_ROOT:-"$HOME/.local/share/sidepulse"}/venv+BIN_DIR=${SIDEPULSE_BIN_DIR:-"$HOME/.local/bin"}-python3 -m venv "$VENV"+if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then+ printf 'SidePulse requires Python 3.10 or newer. Could not find %s.\n' "$PYTHON_BIN" >&2+ exit 1+fi++if ! "$PYTHON_BIN" -c 'import sys; raise SystemExit(sys.version_info < (3, 10))'; then+ printf 'SidePulse requires Python 3.10 or newer.\n' >&2+ exit 1+fi++if ! "$PYTHON_BIN" -m venv "$VENV"; then+ printf 'Could not create a Python virtual environment.\n' >&2+ printf 'On Debian or Ubuntu, install python3-venv and run this command again.\n' >&2+ exit 1+fi"$VENV/bin/python" -m pip install --upgrade \- "git+https://github.com/inteliwear/sidepulse.git"+ "$INSTALL_SPEC"mkdir -p "$BIN_DIR"ln -sf "$VENV/bin/sidepulse" "$BIN_DIR/sidepulse"@@ -16,3 +32,7 @@ ln -sf "$VENV/bin/agent-monitor" "$BIN_DIR/agent-monitor"printf '\nSidePulse is installed.\n'printf 'Command: %s\n' "$BIN_DIR/sidepulse"+case ":${PATH:-}:" in+ *":$BIN_DIR:"*) ;;+ *) printf 'Add %s to PATH to run sidepulse directly.\n' "$BIN_DIR" ;;+esacdiff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.pyindex e7ba4da..d3b78e8 100644--- a/src/sidepulse/cli.py+++ b/src/sidepulse/cli.py@@ -112,7 +112,7 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:)setup = subparsers.add_parser("setup",- help="Install agent hooks and start the macOS status-bar app.",+ help="Install agent hooks and, on macOS, start the status-bar app.",)setup.add_argument("provider",@@ -295,7 +295,7 @@ def add_sidepulse_battery_parser(subparsers: argparse._SubParsersAction) -> Noneleds.add_argument("--device",type=Path,- help="Mounted device folder or LED program file path. Defaults to auto-detecting /Volumes.",+ help="Mounted device folder or LED program file path. Defaults to auto-detection.",)leds.add_argument("--file-name",@@ -940,6 +940,11 @@ def cmd_sidepulse_setup(args: argparse.Namespace) -> int:results = install_hook_results(args)print_install_results(results, dry_run=args.dry_run)+ if sys.platform != "darwin":+ print("macOS integrations: skipped (CLI-only setup on this platform)")+ print("sidepulse: ready for linked phones and mounted SidePulse devices")+ return 0+from .sd_eject_guard_launch import SD_EJECT_GUARD_DISPLAY_NAME, SdEjectGuardInstallError, install_sd_eject_guardtry:diff --git a/src/sidepulse/device_writer.py b/src/sidepulse/device_writer.pyindex feba484..397ddd0 100644--- a/src/sidepulse/device_writer.py+++ b/src/sidepulse/device_writer.py@@ -1,5 +1,7 @@from __future__ import annotations+import os+import sysfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Iterable@@ -124,7 +126,7 @@ def resolve_target_path(if not candidates:raise DeviceWriteError("No SidePulse Pro or SidePulse Dot device found. "- "Mount the device, or pass --device /Volumes/SidePulseDot."+ "Mount the device, or pass --device /path/to/SidePulseDot.")if len(candidates) > 1:lines = "\n".join(f" {candidate.root}" for candidate in candidates)@@ -142,23 +144,69 @@ def target_from_device_path(path: Path, file_name: str) -> Path:def discover_devices(*,- mount_root: Path = MOUNT_ROOT,+ mount_root: Path | None = None,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"))+ seen: set[Path] = set()+ roots = (mount_root,) if mount_root is not None else default_mount_roots()+ for root in roots:+ if not root.exists():+ continue+ for volume in sorted(iter_mounts(root), key=lambda path: path.name.lower()):+ if volume in seen:+ continue+ seen.add(volume)+ 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 default_mount_roots(+ *,+ platform: str | None = None,+ home: Path | None = None,+) -> tuple[Path, ...]:+ configured = os.environ.get("SIDEPULSE_MOUNT_ROOTS")+ if configured is not None:+ return tuple(+ Path(value).expanduser()+ for value in configured.split(os.pathsep)+ if value.strip()+ )++ current_platform = platform or sys.platform+ if current_platform == "darwin":+ return (MOUNT_ROOT,)+ if current_platform.startswith("linux"):+ username = (home or Path.home()).name+ return unique_paths(+ (+ Path("/media") / username,+ Path("/run/media") / username,+ Path("/media"),+ Path("/run/media"),+ Path("/mnt"),+ )+ )+ return (MOUNT_ROOT,)+++def unique_paths(paths: Iterable[Path]) -> tuple[Path, ...]:+ result: list[Path] = []+ for path in paths:+ if path not in result:+ result.append(path)+ return tuple(result)++def iter_mounts(mount_root: Path) -> Iterable[Path]:try:children = list(mount_root.iterdir())diff --git a/tests/test_environment.py b/tests/test_environment.pyindex 5106e29..b50ece2 100644--- a/tests/test_environment.py+++ b/tests/test_environment.py@@ -281,6 +281,13 @@ class CleanInstallTests(unittest.TestCase):self.assertIn(result.returncode, (0, 2), result.stderr)self.assertNotIn(DEPENDENCY_ERROR_MARKER, result.stderr)+ @unittest.skipIf(sys.platform == "darwin", "Linux CLI-only setup check")+ def test_setup_completes_without_macos_services(self):+ result = self.run_script("sidepulse", ["setup", "--dry-run"])+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertIn("CLI-only setup", result.stdout)+ self.assertIn("linked phones and mounted SidePulse devices", result.stdout)+def test_packaged_resources_are_installed(self):"""Package data declared in pyproject must survive the wheel build."""result = self.run_python(diff --git a/tests/test_install_user.py b/tests/test_install_user.pyindex 7ecc983..26e3c0f 100644--- a/tests/test_install_user.py+++ b/tests/test_install_user.py@@ -30,8 +30,10 @@ class UserInstallerTests(unittest.TestCase):root = Path(__file__).resolve().parents[1]script = root / "scripts" / "setup.sh"text = script.read_text()- self.assertIn('$HOME/.local/share/sidepulse/venv', text)+ self.assertIn('$HOME/.local/share/sidepulse', text)self.assertIn('git+https://github.com/inteliwear/sidepulse.git', text)+ self.assertIn('SIDEPULSE_INSTALL_SPEC', text)+ self.assertIn("sys.version_info < (3, 10)", text)self.assertIn('"$VENV/bin/sidepulse" setup', text)self.assertNotIn("sudo", text)diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.pyindex b7e1bb6..11e3323 100644--- a/tests/test_sidepulse.py+++ b/tests/test_sidepulse.py@@ -43,6 +43,7 @@ from sidepulse.collector import (from sidepulse.cli import build_parser, visible_watch_statusesfrom sidepulse.device_writer import (DeviceWriteError,+ default_mount_roots,discover_devices,normalize_led_text,validate_led_text,@@ -3881,6 +3882,7 @@ class AgentMonitorTests(unittest.TestCase):)with (+ patch.object(cli_module.sys, "platform", "darwin"),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(@@ -3930,6 +3932,7 @@ class AgentMonitorTests(unittest.TestCase):)with (+ patch.object(cli_module.sys, "platform", "darwin"),patch.object(cli_module, "install_hook_results", return_value=[hook_result]),patch("sidepulse.sd_eject_guard_launch.install_sd_eject_guard",@@ -3943,6 +3946,33 @@ class AgentMonitorTests(unittest.TestCase):guard.assert_called_once_with(scope="user", dry_run=False)launch.assert_not_called()+ def test_sidepulse_setup_is_cli_only_on_linux(self) -> None:+ parser = cli_module.build_sidepulse_parser()+ args = parser.parse_args(["setup"])+ hook_result = SimpleNamespace(+ provider="codex",+ config_path=Path("/tmp/codex.toml"),+ log_path=Path("/tmp/codex.jsonl"),+ changed=False,+ backup_path=None,+ )++ with (+ patch.object(cli_module.sys, "platform", "linux"),+ patch.object(cli_module, "install_hook_results", return_value=[hook_result]),+ 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,+ ):+ result = cli_module.cmd_sidepulse_setup(args)++ self.assertEqual(result, 0)+ guard.assert_not_called()+ launch.assert_not_called()+ 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)+def test_sidepulse_write_decodes_escaped_newlines_and_writes_leds_file(self) -> None:with tempfile.TemporaryDirectory() as tmp:device = Path(tmp) / "SidePulsePro"@@ -3983,6 +4013,36 @@ class AgentMonitorTests(unittest.TestCase):self.assertEqual(candidates[0].root, device)self.assertEqual(candidates[0].target, device / "LEDS.LED")+ def test_linux_mount_roots_cover_common_desktop_locations(self) -> None:+ with patch.dict(os.environ, {}, clear=False):+ os.environ.pop("SIDEPULSE_MOUNT_ROOTS", None)+ roots = default_mount_roots(+ platform="linux",+ home=Path("/home/alice"),+ )++ self.assertIn(Path("/media/alice"), roots)+ self.assertIn(Path("/run/media/alice"), roots)+ self.assertIn(Path("/mnt"), roots)++ def test_sidepulse_discovers_dot_across_default_mount_roots(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ base = Path(tmp)+ first = base / "media"+ second = base / "run-media"+ first.mkdir()+ second.mkdir()+ device = second / "SidePulseDot"+ device.mkdir()++ with patch(+ "sidepulse.device_writer.default_mount_roots",+ return_value=(first, second),+ ):+ candidates = discover_devices()++ self.assertEqual([candidate.root for candidate in candidates], [device])+def test_sidepulse_write_prefers_leds_led_when_available(self) -> None:with tempfile.TemporaryDirectory() as tmp:mount_root = Path(tmp)