CLI for SidePulse
Python
Simplify menu-bar settings and share the online update installer
Peter Kuhar441ed383f674
diff --git a/README.md b/README.mdindex a8264ff..13b4475 100644--- a/README.md+++ b/README.md@@ -34,7 +34,7 @@ The command works on macOS and Linux with Python 3.10 or newer. Theat `~/.local/bin/sidepulse`, and runs `sidepulse setup`. On macOS, setup alsoinstalls the menu-bar app and hardware helpers. On Linux, it automaticallyuses CLI-only mode for mounted SidePulse devices and iPhone linking/push. Run-the same command again to upgrade to the newest version.+`sidepulse update` to upgrade to the newest version from GitHub.Setup also installs a headless SidePulse service. It runs through a LaunchAgenton macOS and a user systemd service on Linux. Setup restarts the service, so an@@ -64,6 +64,29 @@ python3 -m pip install -e .sidepulse setup```+### Updating++```sh+sidepulse update+sidepulse update --dry-run+```++`update` runs the same installer as `curl -fsSL https://sidepulse.io/setup.sh | bash`.+It downloads the script completely before executing it, so curl failures do not+run a partial installer. The website script forwards to `scripts/setup.sh` on+GitHub, keeping both entry points on one implementation.++The installer updates `~/.local/share/sidepulse/venv` from GitHub, refreshes the+CLI links, and runs `sidepulse setup` to configure hooks and restart services.+It replaces the installed code even when the package version has not changed.+Settings and linked devices are retained. Downloads and builds finish before+the background service and menu-bar app are paused; if installation fails,+the installer attempts to restart them. Restart manually started processes yourself.++Both commands honor `PYTHON_BIN`, `SIDEPULSE_INSTALL_SPEC`,+`SIDEPULSE_INSTALL_ROOT`, and `SIDEPULSE_BIN_DIR`. They use the managed install+path above, even when invoked from a development checkout or bundled app.+Send an LED program to SidePulse:```sh@@ -554,7 +577,7 @@ On first launch, the status-bar app shows a SidePulse Setup window. It can:The Setup window can be reopened from the dropdown with `Setup...`.-The status-bar item shows one of four collapsed states:+The status-bar item uses a single icon, with the current state in its tooltip:| Label | Meaning || --- | --- |@@ -563,6 +586,13 @@ The status-bar item shows one of four collapsed states:| Done | The most recent active agent completed successfully. || Ask | An agent needs input, permission, or attention. |+To hide the icon, open **Settings → Advanced** and uncheck **Show menu bar icon**.+Monitoring and LEDs continue running. Reopen settings with `sidepulse settings`+in Terminal (it starts the app if needed), or open the installed SidePulse app+from Finder or Spotlight. Check **Show menu bar icon** to restore it.+Running `sidepulse status-bar` (or `sidepulse status-bar start`) also restores+the icon immediately. Automatic starts at login retain your visibility preference.+Click the status-bar item to expand the recent session list. Click a sessionrow to open that agent using the remembered choice for that provider. Use thesession's Open Options row to choose and remember another opener, such as the@@ -574,10 +604,10 @@ If both devices are mounted, the status-bar app prefers SidePulse Pro, thenSidePulse Dot. Click the item to disconnect and turn the LEDs off; click it again toreconnect.-The dropdown and Settings window can switch the LEDs between agent status and-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.+The menu-bar dropdown can switch the LEDs between agent status and battery+status. In **Settings → Advanced**, `Show battery for 7s on plug/unplug` can+briefly show the battery animation for seven seconds after the power source+changes when agent status is selected.The Devices section also offers **Add SidePulse Notch**, an optional virtualeight-LED device. It appears as a notch-shaped status-bar overlay that coversdiff --git a/packaging/sidepulse_entry.py b/packaging/sidepulse_entry.pyindex 6ab1434..cade3e0 100644--- a/packaging/sidepulse_entry.py+++ b/packaging/sidepulse_entry.py@@ -9,4 +9,6 @@ from sidepulse.status_bar import main as status_bar_mainif __name__ == "__main__":# Finder launches the app without arguments. The same executable is exposed# as /usr/local/bin/sidepulse by the installer for command-line use.- raise SystemExit(sidepulse_main() if len(sys.argv) > 1 else status_bar_main())+ raise SystemExit(+ sidepulse_main() if len(sys.argv) > 1 else status_bar_main(show_settings=True)+ )diff --git a/scripts/setup.sh b/scripts/setup.shindex 319fdd0..216ab26 100755--- a/scripts/setup.sh+++ b/scripts/setup.sh@@ -16,25 +16,76 @@ if ! "$PYTHON_BIN" -c 'import sys; raise SystemExit(sys.version_info < (3, 10))'exit 1fi-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+# Reuse a working environment on updates; recreating it can change the Python+# interpreter underneath an existing installation.+if [ ! -x "$VENV/bin/python" ]; then+ 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+fi++WHEEL_DIR=$(mktemp -d "${TMPDIR:-/tmp}/sidepulse-setup.XXXXXX")+SERVICE_STOPPED=0+STATUS_BAR_STOPPED=0+SETUP_COMPLETE=0+STATUS_BAR_PLIST="$HOME/Library/LaunchAgents/io.sidepulse.agentstatus.plist"+LAUNCH_DOMAIN="gui/$(id -u)"++cleanup() {+ result=$?+ trap - EXIT+ if [ "$SETUP_COMPLETE" -eq 0 ]; then+ if [ "$SERVICE_STOPPED" -eq 1 ]; then+ "$VENV/bin/sidepulse" service start || printf 'Could not restart the background service.\n' >&2+ fi+ if [ "$STATUS_BAR_STOPPED" -eq 1 ]; then+ if ! launchctl print "$LAUNCH_DOMAIN/io.sidepulse.agentstatus" >/dev/null 2>&1; then+ launchctl bootstrap "$LAUNCH_DOMAIN" "$STATUS_BAR_PLIST" || printf 'Could not restart the menu-bar app.\n' >&2+ fi+ fi+ fi+ rm -rf "$WHEEL_DIR"+ exit "$result"+}+trap cleanup EXIT+trap 'exit 130' INT+trap 'exit 143' TERM++# Fetch and build everything before pausing services. GitHub/network/build+# failures leave the installed code and running services alone.+"$VENV/bin/python" -m pip wheel --wheel-dir "$WHEEL_DIR" "$INSTALL_SPEC"+set -- "$WHEEL_DIR"/sidepulse-*.whl+if [ "$#" -ne 1 ] || [ ! -f "$1" ]; then+ printf 'The build did not produce exactly one SidePulse wheel.\n' >&2exit 1fi-# Stop a service still running from this venv before pip replaces the files-# underneath it. `sidepulse setup` starts the new build again below.-if [ -x "$VENV/bin/sidepulse" ]; then- "$VENV/bin/sidepulse" service stop >/dev/null 2>&1 || true+SIDEPULSE_WHEEL=$1++if [ -x "$VENV/bin/sidepulse" ] && "$VENV/bin/sidepulse" service status >/dev/null 2>&1; then+ "$VENV/bin/sidepulse" service stop+ SERVICE_STOPPED=1+fi+if [ "$(uname -s)" = "Darwin" ] && [ -f "$STATUS_BAR_PLIST" ]; then+ if launchctl print "$LAUNCH_DOMAIN/io.sidepulse.agentstatus" >/dev/null 2>&1; then+ launchctl bootout "$LAUNCH_DOMAIN" "$STATUS_BAR_PLIST"+ STATUS_BAR_STOPPED=1+ fifi-"$VENV/bin/python" -m pip install --upgrade \- "$INSTALL_SPEC"+# --upgrade alone can retain old code when GitHub commits share a version.+# Force replacement, using only the wheels already downloaded above.+"$VENV/bin/python" -m pip install --upgrade --force-reinstall \+ --no-index --find-links "$WHEEL_DIR" "$SIDEPULSE_WHEEL"mkdir -p "$BIN_DIR"ln -sf "$VENV/bin/sidepulse" "$BIN_DIR/sidepulse"ln -sf "$VENV/bin/agent-monitor" "$BIN_DIR/agent-monitor""$VENV/bin/sidepulse" setup+SETUP_COMPLETE=1+"$VENV/bin/sidepulse" --versionprintf '\nSidePulse is installed.\n'printf 'Command: %s\n' "$BIN_DIR/sidepulse"diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.pyindex 480fe6e..d89709b 100644--- a/src/sidepulse/cli.py+++ b/src/sidepulse/cli.py@@ -130,6 +130,12 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:subparsers = parser.add_subparsers(dest="command", required=True)version = subparsers.add_parser("version", help="Print the installed SidePulse version.")version.set_defaults(func=cmd_version)+ update = subparsers.add_parser("update", help="Update using the one-command setup installer.")+ update.add_argument(+ "--dry-run", action="store_true",+ help="Show the setup command without downloading or changing anything.",+ )+ update.set_defaults(func=cmd_sidepulse_update)subparsers.add_parser("agent-monitor",help="Install hooks and show live AI agent statuses.",@@ -199,6 +205,11 @@ def build_sidepulse_parser() -> argparse.ArgumentParser:service.set_defaults(func=cmd_sidepulse_service)add_sidepulse_status_bar_parser(subparsers)+ settings = subparsers.add_parser(+ "settings",+ help="Open SidePulse settings, even when the menu bar icon is hidden.",+ )+ settings.set_defaults(func=cmd_sidepulse_settings)add_sidepulse_sdejectguard_parser(subparsers)add_sidepulse_battery_parser(subparsers)# Agent configs written by older installs invoke `sidepulse hook-log`@@ -242,7 +253,7 @@ def add_hook_log_parser(subparsers: argparse._SubParsersAction) -> None:def add_sidepulse_status_bar_parser(subparsers: argparse._SubParsersAction) -> None:status_bar = subparsers.add_parser("status-bar",- help="Start or stop the macOS SidePulse menu-bar app.",+ help="Show and start the macOS SidePulse menu-bar app, or stop it.",)status_bar.add_argument("status_bar_command",@@ -1305,6 +1316,31 @@ def cmd_leds(args: argparse.Namespace) -> int:return 0+def cmd_sidepulse_update(args: argparse.Namespace) -> int:+ from .update import update_installation++ return update_installation(dry_run=args.dry_run)+++def cmd_sidepulse_settings(_args: argparse.Namespace) -> int:+ if sys.platform != "darwin":+ print("SidePulse settings requires macOS.", file=sys.stderr)+ return 1+ from .ipc import request_settings_window+ from .status_bar_launch import install_launch_agent++ if request_settings_window():+ return 0+ install_launch_agent(start=True)+ deadline = time.monotonic() + 10.0+ while time.monotonic() < deadline:+ if request_settings_window():+ return 0+ time.sleep(0.1)+ print("Could not open SidePulse settings. Check the status-bar logs.", file=sys.stderr)+ return 1++def cmd_status_bar(args: argparse.Namespace) -> int:if args.foreground:from .status_bar import main as status_bar_main@@ -1320,6 +1356,12 @@ def cmd_status_bar(args: argparse.Namespace) -> int:print(f" plist: {result.plist_path}")return 0+ # Explicit starts restore the icon. LaunchAgent starts use --foreground+ # above, so login and automatic restarts keep the saved visibility choice.+ if not args.no_start:+ settings = load_settings()+ if not settings.show_menu_bar_icon:+ save_settings(settings.with_menu_bar_icon(True))result = install_launch_agent(start=not args.no_start)action = "installed" if result.changed else "already installed"if result.started:diff --git a/src/sidepulse/ipc.py b/src/sidepulse/ipc.pyindex 7bb09ed..55baac4 100644--- a/src/sidepulse/ipc.py+++ b/src/sidepulse/ipc.py@@ -26,6 +26,23 @@ def default_latest_state_path() -> Path:return default_state_dir() / "latest.json"+def request_settings_window(*, socket_path: Path | None = None) -> bool:+ """Ask a running UI to open settings, requiring an acknowledgement."""+ targets = (socket_path,) if socket_path is not None else candidate_event_socket_paths()+ for target in targets:+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:+ client.settimeout(0.5)+ try:+ client.connect(str(target.expanduser()))+ client.sendall(b'{"command":"open-settings"}')+ client.shutdown(socket.SHUT_WR)+ if client.recv(2) == b"ok":+ return True+ except OSError:+ continue+ return False++def send_hook_event(provider: str,line: dict,@@ -70,8 +87,10 @@ class HookEventServer:on_event: Callable[[str, dict], None],*,socket_path: Path | None = None,+ on_open_settings: Callable[[], None] | None = None,) -> None:self.on_event = on_event+ self.on_open_settings = on_open_settingsself.socket_path = (socket_path or default_event_socket_path()).expanduser()self.socket: socket.socket | None = Noneself.thread: threading.Thread | None = None@@ -147,6 +166,14 @@ class HookEventServer:if not isinstance(message, dict):return+ if message.get("command") == "open-settings":+ if self.on_open_settings is not None:+ self.on_open_settings()+ try:+ connection.sendall(b"ok")+ except OSError:+ pass+ returnprovider = message.get("provider")line = message.get("line")if isinstance(provider, str) and isinstance(line, dict):diff --git a/src/sidepulse/settings.py b/src/sidepulse/settings.pyindex 426e89f..7d7092e 100644--- a/src/sidepulse/settings.py+++ b/src/sidepulse/settings.py@@ -331,6 +331,7 @@ class AgentMonitorSettings:sleep_prevention_min_battery_percent: float = DEFAULT_SLEEP_PREVENTION_MIN_BATTERY_PERCENThistory_timeframe_seconds: float = DEFAULT_HISTORY_TIMEFRAME_SECONDSsetup_screen_completed: bool = False+ show_menu_bar_icon: bool = Truedef transcript_enabled(self, provider: str) -> bool:if provider == "codex":@@ -767,6 +768,9 @@ class AgentMonitorSettings:def with_setup_screen_completed(self, completed: bool = True) -> "AgentMonitorSettings":return replace(self, setup_screen_completed=bool(completed))+ def with_menu_bar_icon(self, visible: bool) -> "AgentMonitorSettings":+ return replace(self, show_menu_bar_icon=bool(visible))+def with_virtual_status_device(self, enabled: bool) -> "AgentMonitorSettings":return replace(self, virtual_status_device_enabled=bool(enabled))@@ -800,6 +804,7 @@ class AgentMonitorSettings:def to_dict(self) -> dict[str, Any]:return {"led_display": self.led_display,+ "show_menu_bar_icon": self.show_menu_bar_icon,"devices": [device.to_dict() for device in self.devices],"sleep_prevention_policy": self.sleep_prevention_policy,"virtual_status_device_enabled": self.virtual_status_device_enabled,@@ -944,6 +949,7 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:})return AgentMonitorSettings(+ show_menu_bar_icon=_bool_setting(data.get("show_menu_bar_icon"), True),codex_transcripts_enabled=_bool_setting(transcript.get("codex"), False),claude_transcripts_enabled=_bool_setting(transcript.get("claude"), False),led_display=led_display,diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.pyindex 90b98aa..32d7b9c 100644--- a/src/sidepulse/status_bar.py+++ b/src/sidepulse/status_bar.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import mathimport shleximport socketimport subprocess@@ -28,6 +29,7 @@ try:NSEventTrackingRunLoopMode,NSFont,NSFontAttributeName,+ NSFontWeightBold,NSForegroundColorAttributeName,NSImage,NSMenu,@@ -53,9 +55,9 @@ try:NSWindowStyleMaskClosable,NSWindowStyleMaskMiniaturizable,NSWindowStyleMaskTitled,- NSVariableStatusItemLength,+ NSSquareStatusItemLength,)- from Foundation import NSRunLoop, NSRunLoopCommonModes, NSObject, NSString, NSTimer, NSURL+ from Foundation import NSMutableAttributedString, NSRunLoop, NSRunLoopCommonModes, NSObject, NSString, NSTimer, NSURLexcept ImportError as exc: # pragma: no cover - only exercised on non-macOS setups.raise SystemExit(f"The status-bar app requires PyObjC/AppKit ({exc}):\n"@@ -529,6 +531,7 @@ class StatusBarController(NSObject):return Noneself.settings = load_settings()+ self.open_settings_on_launch = Falseself.monitor = self.build_monitor()self.event_server = Noneself.status_item = None@@ -612,12 +615,14 @@ class StatusBarController(NSObject):self.start_event_server()self.status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(- NSVariableStatusItemLength+ NSSquareStatusItemLength)button = self.status_item.button()- button.setTitle_(" Idle")+ button.setTitle_("")button.setImage_(image_for_symbol(STATE_IDLE.symbol, STATE_IDLE.label))button.setToolTip_("SidePulse Agent Monitor: Idle")+ button.setAccessibilityLabel_("SidePulse Agent Monitor: Idle")+ self.status_item.setVisible_(self.settings.show_menu_bar_icon)log_status_bar("status item created")self.refresh_(None)@@ -648,6 +653,13 @@ class StatusBarController(NSObject):else:self.virtual_status_device.hide()+ if self.open_settings_on_launch:+ self.show_settings_window()++ def applicationShouldHandleReopen_hasVisibleWindows_(self, _application, _visible):+ self.show_settings_window()+ return True+@objc.IBActiondef refresh_(self, _sender):try:@@ -838,6 +850,15 @@ class StatusBarController(NSObject):def openSettings_(self, _sender):self.show_settings_window()+ @objc.IBAction+ def setMenuBarIconFromCheckbox_(self, sender):+ settings = self.settings.with_menu_bar_icon(sender.state() == NSOnState)+ save_settings(settings)+ self.settings = settings+ if self.status_item is not None:+ self.status_item.setVisible_(settings.show_menu_bar_icon)+ self.refresh_settings_window()+@objc.IBActiondef openSetup_(self, _sender):self.show_setup_window()@@ -906,10 +927,6 @@ class StatusBarController(NSObject):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.IBActiondef toggleBatteryPowerPreview_(self, _sender):self.set_battery_power_preview(not self.settings.battery_show_on_power_change)@@ -997,6 +1014,16 @@ class StatusBarController(NSObject):def saveAgentListTiming_(self, _sender):self.save_agent_list_timing_from_fields()+ def windowShouldClose_(self, window):+ if window == self.settings_window:+ window.makeFirstResponder_(None)+ return True++ def tabView_shouldSelectTabViewItem_(self, _tab_view, _tab_item):+ if self.settings_window is not None:+ self.settings_window.makeFirstResponder_(None)+ return True+@objc.IBActiondef setDeviceDisplayAgent_(self, sender):self.set_device_display(sender.representedObject(), LED_DISPLAY_AGENT)@@ -1075,9 +1102,10 @@ class StatusBarController(NSObject):button = self.status_item.button()if button is None:return- button.setTitle_(f" {state.label}")+ button.setTitle_("")button.setImage_(image_for_symbol(state.symbol, state.label))button.setToolTip_(f"SidePulse Agent Monitor: {state.label}")+ button.setAccessibilityLabel_(f"SidePulse Agent Monitor: {state.label}")if previous != state:log_status_bar(f"state={state.label}")@@ -1095,7 +1123,10 @@ class StatusBarController(NSObject):def start_event_server(self) -> None:self.stop_event_server()- self.event_server = HookEventServer(self.handle_hook_event_message)+ self.event_server = HookEventServer(+ self.handle_hook_event_message,+ on_open_settings=self.schedule_open_settings,+ )try:socket_path = self.event_server.start()log_status_bar(f"event_server listening={socket_path}")@@ -1108,6 +1139,11 @@ class StatusBarController(NSObject):self.event_server.stop()self.event_server = None+ def schedule_open_settings(self) -> None:+ self.performSelectorOnMainThread_withObject_waitUntilDone_(+ "openSettings:", None, False,+ )+def handle_hook_event_message(self, provider: str, line: dict) -> None:try:record = parse_log_line(@@ -1361,6 +1397,11 @@ class StatusBarController(NSObject):if self.settings_window is None:return+ set_checkbox_state(+ self.settings_buttons.get("show_menu_bar_icon"),+ self.settings.show_menu_bar_icon,+ )+codex = detect_codex_config()claude = detect_claude_config()grok = detect_grok_config()@@ -1402,10 +1443,6 @@ class StatusBarController(NSObject):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,@@ -1653,26 +1690,33 @@ class StatusBarController(NSObject):DEFAULT_SLEEP_PREVENTION_MIN_BATTERY_PERCENT)except ValueError:- self.set_settings_message("Behavior settings must be numeric.")+ self.set_settings_message("Advanced settings must be numeric.")+ return++ if not all(math.isfinite(value) for value in (retention_hours * 3600, idle_minutes * 60, min_battery_percent)):+ self.set_settings_message("Advanced settings must be finite numbers.")returntry:- self.settings = self.settings.with_agent_list_timing(+ settings = self.settings.with_agent_list_timing(recent_session_retention_seconds=retention_hours * 3600,idle_timeout_seconds=idle_minutes * 60,)- self.settings = self.settings.with_sleep_prevention_battery_safeguard(+ settings = settings.with_sleep_prevention_battery_safeguard(min_battery_percent)- save_settings(self.settings)+ if settings == self.settings:+ return+ save_settings(settings)+ self.settings = settingsexcept Exception as exc:- self.set_settings_message(f"Could not save behavior settings: {exc}")+ self.set_settings_message(f"Could not save advanced settings: {exc}")self.settings = load_settings()self.refresh_settings_window()returnself.reload_monitor()- self.set_settings_message("Behavior settings saved.")+ self.set_settings_message("Advanced settings saved.")self.refresh_settings_window()self.refresh_(None)@@ -4336,6 +4380,7 @@ def build_settings_window(target: StatusBarController) -> NSWindow:False,)window.setTitle_("SidePulse Settings")+ window.setDelegate_(target)window.setReleasedWhenClosed_(False)window.center()content = window.contentView()@@ -4347,13 +4392,6 @@ def build_settings_window(target: StatusBarController) -> NSWindow:)tab_view.setDelegate_(target)agents_tab = add_settings_tab(tab_view, "agents", "Agents", tab_width, tab_height)- devices_tab = add_settings_tab(- tab_view,- "devices",- "Devices",- tab_width,- tab_height,- )animations_tab = add_settings_tab(tab_view,"animations",@@ -4364,7 +4402,7 @@ def build_settings_window(target: StatusBarController) -> NSWindow:behavior_tab = add_settings_tab(tab_view,"behavior",- "Behavior",+ "Advanced",tab_width,tab_height,)@@ -4498,28 +4536,6 @@ def build_settings_window(target: StatusBarController) -> NSWindow:"toggleClaudeTranscripts:",)- add_label(devices_tab, "LED Display", 24, 398, 240, 24)- battery_leds = add_checkbox(- devices_tab,- "Show battery on LEDs",- 32,- 356,- 260,- 24,- target,- "setBatteryLedDisplayFromCheckbox:",- )- battery_power_preview = add_checkbox(- devices_tab,- "Show battery for 7s on plug/unplug",- 32,- 318,- 320,- 24,- target,- "setBatteryPowerPreviewFromCheckbox:",- )-add_label(agent_animations_tab, "Profile", 32, 360, 56, 24)animation_profile = add_agent_animation_profile_popup(agent_animations_tab,@@ -4651,7 +4667,47 @@ def build_settings_window(target: StatusBarController) -> NSWindow:add_label(behavior_tab, "Let Mac sleep on battery below", 32, 196, 210, 22)min_battery_percent = add_editable_field(behavior_tab, "", 260, 194, 58, 24)add_label(behavior_tab, "%", 328, 196, 24, 22)- add_button(behavior_tab, "Save", 32, 112, 90, 28, target, "saveAgentListTiming:")+ for field in (retention_hours, idle_minutes, min_battery_percent):+ field.setTarget_(target)+ field.setAction_("saveAgentListTiming:")+ field.cell().setSendsActionOnEndEditing_(True)+ add_separator(behavior_tab, 24, 140, tab_width - 48)+ battery_power_preview = add_checkbox(+ behavior_tab,+ "Show battery for 7s on plug/unplug",+ 32,+ 106,+ 320,+ 24,+ target,+ "setBatteryPowerPreviewFromCheckbox:",+ )+ add_separator(behavior_tab, 24, 96, tab_width - 48)+ show_menu_bar_icon = add_checkbox(+ behavior_tab, "Show menu bar icon", 32, 60, 280, 24,+ target, "setMenuBarIconFromCheckbox:",+ )+ settings_hint = add_label(+ behavior_tab, "Reopen settings anytime: run sidepulse settings in Terminal.",+ 32, 28, 588, 22,+ )+ hint_text = str(settings_hint.stringValue())+ hint = NSMutableAttributedString.alloc().initWithString_attributes_(+ hint_text,+ {+ NSFontAttributeName: settings_hint.font(),+ NSForegroundColorAttributeName: NSColor.labelColor(),+ },+ )+ hint.addAttribute_value_range_(+ NSFontAttributeName,+ NSFont.monospacedSystemFontOfSize_weight_(+ settings_hint.font().pointSize(), NSFontWeightBold,+ ),+ (hint_text.index("sidepulse settings"), len("sidepulse settings")),+ )+ settings_hint.setAttributedStringValue_(hint)+ settings_hint.setSelectable_(True)add_label(history_tab, "Status History", 24, 398, 240, 24)add_label(history_tab, "Timeframe", 430, 398, 76, 22)@@ -4710,9 +4766,9 @@ def build_settings_window(target: StatusBarController) -> NSWindow:},}target.settings_buttons = {+ "show_menu_bar_icon": show_menu_bar_icon,"codex_transcripts": codex_transcripts,"claude_transcripts": claude_transcripts,- "battery_leds": battery_leds,"battery_power_preview": battery_power_preview,"delete_agent_animation_profile": delete_animation_profile,}@@ -6710,15 +6766,21 @@ def applescript_quote(value: str) -> str:return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'-def run_status_bar() -> None:+def run_status_bar(*, show_settings: bool = False) -> None:app = NSApplication.sharedApplication()controller = StatusBarController.alloc().init()+ controller.open_settings_on_launch = show_settingsapp.setDelegate_(controller)app.run()-def main() -> int:- run_status_bar()+def main(*, show_settings: bool = False) -> int:+ if show_settings:+ from .ipc import request_settings_window++ if request_settings_window():+ return 0+ run_status_bar(show_settings=show_settings)return 0diff --git a/src/sidepulse/update.py b/src/sidepulse/update.pynew file mode 100644index 0000000..e32c99e--- /dev/null+++ b/src/sidepulse/update.py@@ -0,0 +1,30 @@+from __future__ import annotations++import subprocess+import sys+import tempfile+from pathlib import Path+++SETUP_URL = "https://sidepulse.io/setup.sh"+++def update_installation(*, dry_run: bool = False) -> int:+ print(f"Updating with: curl -fsSL {SETUP_URL} | bash", flush=True)+ if dry_run:+ print("Would run the same installer as one-command setup, using its install path and environment overrides.")+ return 0+ try:+ # Download completely before executing: a failed or interrupted curl+ # must not run a partial installer or appear to succeed via a pipe.+ with tempfile.TemporaryDirectory(prefix="sidepulse-update-") as directory:+ script = Path(directory) / "setup.sh"+ subprocess.run(+ ["curl", "-fsSL", "-H", "Cache-Control: no-cache", SETUP_URL,+ "-o", str(script)], check=True,+ )+ subprocess.run(["bash", str(script)], check=True)+ except (OSError, subprocess.CalledProcessError) as exc:+ print(f"SidePulse update failed: {exc}", file=sys.stderr)+ return 1+ return 0diff --git a/tests/test_settings_access.py b/tests/test_settings_access.pynew file mode 100644index 0000000..b3445b7--- /dev/null+++ b/tests/test_settings_access.py@@ -0,0 +1,110 @@+"""Settings remain reachable without a menu bar item."""++import tempfile+import sys+import unittest+from pathlib import Path+from unittest.mock import Mock, patch++from sidepulse.cli import sidepulse_main+from sidepulse.ipc import HookEventServer, request_settings_window+from sidepulse.settings import AgentMonitorSettings, load_settings, save_settings+++class SettingsAccessTests(unittest.TestCase):+ def test_explicit_status_bar_start_restores_hidden_icon_before_launch(self):+ for args in (["status-bar"], ["status-bar", "start"]):+ with self.subTest(args=args), tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "settings.json"+ hidden = AgentMonitorSettings().with_menu_bar_icon(False)+ save_settings(hidden, path)++ def launch(**kwargs):+ self.assertTrue(load_settings(path).show_menu_bar_icon)+ return Mock(changed=False, started=True, plist_path="test.plist")++ with (+ patch("sidepulse.settings.default_settings_path", return_value=path),+ patch("sidepulse.status_bar_launch.install_launch_agent", side_effect=launch) as install,+ ):+ self.assertEqual(sidepulse_main(args), 0)+ install.assert_called_once_with(start=True)+ self.assertEqual(load_settings(path), hidden.with_menu_bar_icon(True))++ def test_launch_agent_foreground_start_preserves_hidden_preference(self):+ app = Mock()+ app.main.return_value = 0+ with (+ patch.dict(sys.modules, {"sidepulse.status_bar": app}),+ patch("sidepulse.cli.save_settings") as save,+ ):+ self.assertEqual(sidepulse_main(["status-bar", "--foreground"]), 0)+ app.main.assert_called_once_with()+ save.assert_not_called()++ def test_stopping_status_bar_does_not_change_icon_preference(self):+ with (+ patch("sidepulse.status_bar_launch.uninstall_launch_agent"),+ patch("sidepulse.cli.save_settings") as save,+ ):+ self.assertEqual(sidepulse_main(["status-bar", "stop"]), 0)+ save.assert_not_called()++ def test_icon_visibility_defaults_visible_and_round_trips(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "settings.json"+ path.write_text("{}")+ self.assertTrue(load_settings(path).show_menu_bar_icon)+ for visible in (False, True):+ settings = AgentMonitorSettings().with_menu_bar_icon(visible)+ save_settings(settings, path)+ self.assertEqual(load_settings(path).show_menu_bar_icon, visible)++ def test_settings_request_is_acknowledged_only_by_a_ui_listener(self):+ with tempfile.TemporaryDirectory(dir="/tmp") as directory:+ path = Path(directory) / "events.sock"+ self.assertFalse(request_settings_window(socket_path=path))+ for has_ui in (False, True):+ open_settings = Mock()+ on_event = Mock()+ server = HookEventServer(+ on_event, socket_path=path,+ on_open_settings=open_settings if has_ui else None,+ )+ try:+ server.start()+ self.assertEqual(request_settings_window(socket_path=path), has_ui)+ self.assertEqual(open_settings.call_count, int(has_ui))+ on_event.assert_not_called()+ finally:+ server.stop()+ server.thread.join(timeout=2)++ @patch("sidepulse.cli.sys.platform", "darwin")+ def test_settings_command_reuses_running_app(self):+ with (+ patch("sidepulse.ipc.request_settings_window", return_value=True),+ patch("sidepulse.status_bar_launch.install_launch_agent") as install,+ ):+ self.assertEqual(sidepulse_main(["settings"]), 0)+ install.assert_not_called()++ @patch("sidepulse.cli.sys.platform", "darwin")+ def test_settings_command_starts_app_when_needed(self):+ with (+ patch("sidepulse.ipc.request_settings_window", side_effect=[False, False, True]),+ patch("sidepulse.status_bar_launch.install_launch_agent") as install,+ patch("sidepulse.cli.time.sleep"),+ ):+ self.assertEqual(sidepulse_main(["settings"]), 0)+ install.assert_called_once_with(start=True)++ @patch("sidepulse.cli.sys.platform", "darwin")+ def test_settings_command_reports_startup_timeout(self):+ with (+ patch("sidepulse.ipc.request_settings_window", return_value=False),+ patch("sidepulse.status_bar_launch.install_launch_agent"),+ patch("sidepulse.cli.time.monotonic", side_effect=[0, 11]),+ patch("sys.stderr"),+ ):+ self.assertEqual(sidepulse_main(["settings"]), 1)diff --git a/tests/test_setup_update.py b/tests/test_setup_update.pynew file mode 100644index 0000000..9de8ef1--- /dev/null+++ b/tests/test_setup_update.py@@ -0,0 +1,171 @@+"""Run the actual curl installer against offline package fixtures."""+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import textwrap+import unittest+import zipfile+from pathlib import Path+++SCRIPT = Path(__file__).resolve().parents[1] / 'scripts' / 'setup.sh'+++class SetupUpdateTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(prefix='sidepulse-setup-test-')+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)+ self.install_root = self.root / 'install with spaces'+ self.bin = self.root / 'bin'+ self.log = self.root / 'calls.jsonl'+ self.home = self.root / 'home'+ self.home.mkdir()+ self.env = {+ **os.environ,+ 'HOME': str(self.home),+ 'PYTHON_BIN': sys.executable,+ 'SIDEPULSE_INSTALL_ROOT': str(self.install_root),+ 'SIDEPULSE_BIN_DIR': str(self.bin),+ 'SIDEPULSE_TEST_LOG': str(self.log),+ 'PIP_NO_INDEX': '1',+ 'PIP_DISABLE_PIP_VERSION_CHECK': '1',+ }+ # The fixtures must import their installed wheels, even when the test+ # runner uses PYTHONPATH to exercise an isolated source snapshot.+ self.env.pop('PYTHONPATH', None)+ self.env.pop('PYTHONHOME', None)+ self.old = self.wheel('old')+ self.new = self.wheel('new', dependency=True)+ self.write_wheel(self.new.parent, 'sidepulse_fixture_dependency', {'sidepulse_fixture_dependency/__init__.py': ''})+ self.env['PIP_FIND_LINKS'] = str(self.new.parent)++ def wheel(self, marker, dependency=False):+ directory = self.root / marker+ directory.mkdir()+ cli = textwrap.dedent(f'''+ import json, os, sys+ MARKER = {marker!r}+ def main():+ args = sys.argv[1:]+ with open(os.environ['SIDEPULSE_TEST_LOG'], 'a') as log:+ log.write(json.dumps([MARKER, args]) + '\\n')+ if args == ['setup'] and os.environ.get('SIDEPULSE_TEST_SETUP_FAIL'):+ return 1+ if args == ['--version']:+ print('sidepulse 1.0 ' + MARKER)+ return 0+ ''')+ return self.write_wheel(directory, 'sidepulse', {+ 'sidepulse/__init__.py': f'MARKER = {marker!r}\n',+ 'sidepulse/cli.py': cli,+ }, dependency=dependency)++ @staticmethod+ def write_wheel(directory, name, files, dependency=False):+ info = f'{name}-1.0.dist-info'+ metadata = f'Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n'+ if dependency:+ metadata += 'Requires-Dist: sidepulse-fixture-dependency==1.0\n'+ files = dict(files)+ files[f'{info}/METADATA'] = metadata+ files[f'{info}/WHEEL'] = 'Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n'+ if name == 'sidepulse':+ files[f'{info}/entry_points.txt'] = '[console_scripts]\nsidepulse = sidepulse.cli:main\nagent-monitor = sidepulse.cli:main\n'+ files[f'{info}/RECORD'] = ''.join(f'{path},,\n' for path in files) + f'{info}/RECORD,,\n'+ wheel = directory / f'{name}-1.0-py3-none-any.whl'+ with zipfile.ZipFile(wheel, 'w') as archive:+ for path, content in files.items():+ archive.writestr(path, content)+ return wheel++ def install(self, spec, **env):+ return subprocess.run(+ ['bash', str(SCRIPT)],+ env={**self.env, 'SIDEPULSE_INSTALL_SPEC': str(spec), **env},+ capture_output=True, text=True, timeout=120,+ )++ def calls(self):+ return [json.loads(line) for line in self.log.read_text().splitlines()]++ def test_fresh_install_then_same_version_update_loads_new_code_and_dependency(self):+ result = self.install(self.old)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ config = self.home / 'settings.json'+ config.write_text('{"show_menu_bar_icon": false}')+ self.log.write_text('')+ result = self.install(self.new)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(self.calls(), [+ ['old', ['service', 'status']], ['old', ['service', 'stop']],+ ['new', ['setup']], ['new', ['--version']],+ ])+ self.assertEqual(config.read_text(), '{"show_menu_bar_icon": false}')+ self.assertEqual((self.bin / 'sidepulse').resolve(), (self.install_root / 'venv/bin/sidepulse').resolve())+ self.assertTrue((self.bin / 'agent-monitor').is_file())+ python = self.install_root / 'venv/bin/python'+ output = subprocess.check_output([+ str(python), '-c', 'import sidepulse_fixture_dependency, sidepulse; print(sidepulse.MARKER)',+ ], text=True, cwd=self.root, env=self.env)+ self.assertEqual(output.strip(), 'new')++ def test_download_or_build_failure_keeps_existing_installation_running(self):+ self.assertEqual(self.install(self.old).returncode, 0)+ self.log.write_text('')+ result = self.install(self.root / 'missing.whl')+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(self.calls(), [])+ result = subprocess.run([str(self.bin / 'sidepulse'), '--version'], env=self.env, capture_output=True, text=True)+ self.assertIn('old', result.stdout)++ def test_setup_failure_resumes_previously_stopped_service(self):+ self.assertEqual(self.install(self.old).returncode, 0)+ self.log.write_text('')+ result = self.install(self.new, SIDEPULSE_TEST_SETUP_FAIL='1')+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(self.calls()[-1], ['new', ['service', 'start']])+ self.assertNotIn('SidePulse is installed.', result.stdout)++ def test_macos_menu_bar_is_stopped_before_replacement_and_resumed_on_failure(self):+ self.assertEqual(self.install(self.old).returncode, 0)+ stubs = self.root / 'stubs'+ stubs.mkdir()+ (stubs / 'uname').write_text('#!/bin/sh\nprintf "Darwin\\n"\n')+ launchctl = stubs / 'launchctl'+ launchctl.write_text(f'#!{sys.executable}\n' + textwrap.dedent('''+ import json, os, sys+ from pathlib import Path+ state = Path(os.environ['SIDEPULSE_TEST_LAUNCH_STATE'])+ args = sys.argv[1:]+ with open(os.environ['SIDEPULSE_TEST_LOG'], 'a') as log:+ log.write(json.dumps(['launchctl', args]) + '\\n')+ if args[0] == 'print':+ sys.exit(0 if state.exists() else 1)+ if args[0] == 'bootout':+ state.unlink()+ if args[0] == 'bootstrap':+ state.touch()+ '''))+ for path in stubs.iterdir():+ path.chmod(0o755)+ plist = self.home / 'Library/LaunchAgents/io.sidepulse.agentstatus.plist'+ plist.parent.mkdir(parents=True)+ plist.touch()+ state = self.root / 'loaded'+ state.touch()+ self.log.write_text('')+ result = self.install(+ self.new, SIDEPULSE_TEST_SETUP_FAIL='1',+ SIDEPULSE_TEST_LAUNCH_STATE=str(state),+ PATH=f'{stubs}:{os.environ["PATH"]}',+ )+ self.assertNotEqual(result.returncode, 0)+ actions = [(who, args[0]) for who, args in self.calls()]+ self.assertLess(actions.index(('launchctl', 'bootout')), actions.index(('new', 'setup')))+ self.assertEqual(actions[-1], ('launchctl', 'bootstrap'))+ self.assertTrue(state.exists())diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.pyindex c017cb6..4d1b069 100644--- a/tests/test_sidepulse.py+++ b/tests/test_sidepulse.py@@ -2136,7 +2136,10 @@ class AgentMonitorTests(unittest.TestCase):if hasattr(view, "numberOfTabViewItems")]self.assertEqual(len(tab_views), 1)- self.assertEqual(tab_views[0].numberOfTabViewItems(), 6)+ self.assertEqual(+ [str(item.label()) for item in tab_views[0].tabViewItems()],+ ["Agents", "Animations", "Advanced", "History", "Diagnostics"],+ )animations_tab = next(tab_views[0].tabViewItemAtIndex_(index)for index in range(tab_views[0].numberOfTabViewItems())diff --git a/tests/test_status_bar_ui.py b/tests/test_status_bar_ui.pyindex 54a35ad..c94f1af 100644--- a/tests/test_status_bar_ui.py+++ b/tests/test_status_bar_ui.py@@ -190,6 +190,116 @@ class StatusBarTestCase(unittest.TestCase):raise unittest.SkipTest("StatusBarController could not be created")+class MenuBarVisibilityTests(StatusBarTestCase):+ def test_status_updates_keep_only_icon_with_accessible_state(self):+ controller = sb.StatusBarController.alloc().init()+ controller.status_item = Mock()+ button = controller.status_item.button.return_value+ for state in (sb.STATE_IDLE, sb.STATE_WORKING, sb.STATE_DONE, sb.STATE_ASK):+ controller.set_status(state)+ button.setTitle_.assert_called_with("")+ self.assertIsNotNone(button.setImage_.call_args.args[0])+ button.setToolTip_.assert_called_with(f"SidePulse Agent Monitor: {state.label}")+ button.setAccessibilityLabel_.assert_called_with(f"SidePulse Agent Monitor: {state.label}")++ def test_hide_and_restore_preserve_controller_and_settings_window(self):+ controller = sb.StatusBarController.alloc().init()+ controller.status_item = Mock()+ controller.settings_window = sb.build_settings_window(controller)+ checkbox = controller.settings_buttons["show_menu_bar_icon"]+ monitor = controller.monitor+ with (+ patch.object(sb, "save_settings") as save,+ patch.object(sb.StatusBarController, "refresh_settings_window"),+ ):+ for visible in (False, True):+ checkbox.setState_(sb.NSOnState if visible else sb.NSOffState)+ controller.setMenuBarIconFromCheckbox_(checkbox)+ controller.status_item.setVisible_.assert_called_with(visible)+ self.assertEqual(save.call_args.args[0].show_menu_bar_icon, visible)+ self.assertEqual(controller.settings.show_menu_bar_icon, visible)+ self.assertIs(controller.monitor, monitor)+ self.assertIsNotNone(controller.settings_window)++ def test_external_settings_request_is_dispatched_to_main_thread(self):+ controller = Mock()+ sb.StatusBarController.schedule_open_settings(controller)+ controller.performSelectorOnMainThread_withObject_waitUntilDone_.assert_called_once_with(+ "openSettings:", None, False,+ )++ def test_finder_reopen_opens_settings(self):+ controller = sb.StatusBarController.alloc().init()+ with patch.object(sb.StatusBarController, "show_settings_window") as show:+ self.assertTrue(controller.applicationShouldHandleReopen_hasVisibleWindows_(+ None, False,+ ))+ show.assert_called_once_with()+++class AdvancedAutosaveTests(StatusBarTestCase):+ def setUp(self):+ self.target = sb.StatusBarController.alloc().init()+ self.target.settings_window = sb.build_settings_window(self.target)+ self.window = self.target.settings_window+ self.tabs = next(+ view for view in self.window.contentView().subviews()+ if hasattr(view, "numberOfTabViewItems")+ )+ self.tabs.selectTabViewItemWithIdentifier_("behavior")+ for key, value in (+ ("recent_session_retention_hours", "48"),+ ("idle_timeout_minutes", "60"),+ ("sleep_prevention_min_battery_percent", "20"),+ ):+ self.target.settings_fields[key].setStringValue_(value)+ self.saved = []+ for context in (+ patch.object(sb, "save_settings", side_effect=self.saved.append),+ patch.object(sb.StatusBarController, "reload_monitor"),+ patch.object(sb.StatusBarController, "refresh_settings_window"),+ patch.object(sb.StatusBarController, "refresh_"),+ ):+ context.start()+ self.addCleanup(context.stop)++ def edit(self, key, value):+ field = self.target.settings_fields[key]+ field.selectText_(None)+ editor = field.currentEditor()+ self.assertIsNotNone(editor)+ editor.setString_(value)++ def test_leaving_each_numeric_field_saves_without_a_button(self):+ for key, value, attribute, expected in (+ ("recent_session_retention_hours", "24", "recent_session_retention_seconds", 86400),+ ("idle_timeout_minutes", "15", "idle_timeout_seconds", 900),+ ("sleep_prevention_min_battery_percent", "30", "sleep_prevention_min_battery_percent", 30),+ ):+ self.edit(key, value)+ self.window.makeFirstResponder_(None)+ self.assertEqual(getattr(self.saved[-1], attribute), expected)+ self.assertEqual(len(self.saved), 3)++ def test_switching_tabs_commits_the_active_field(self):+ self.edit("idle_timeout_minutes", "10")+ self.tabs.selectTabViewItemWithIdentifier_("agents")+ self.assertEqual(self.saved[-1].idle_timeout_seconds, 600)++ def test_closing_window_commits_the_active_field(self):+ self.edit("idle_timeout_minutes", "5")+ self.assertTrue(self.target.windowShouldClose_(self.window))+ self.assertEqual(self.saved[-1].idle_timeout_seconds, 300)++ def test_invalid_input_keeps_last_saved_setting(self):+ original = self.target.settings+ for value in ("oops", "nan", "inf"):+ self.edit("idle_timeout_minutes", value)+ self.window.makeFirstResponder_(None)+ self.assertEqual(self.target.settings, original)+ self.assertEqual(self.saved, [])++class SelectorWiringTests(StatusBarTestCase):"""Menu and button actions are strings; a rename must not go unnoticed."""diff --git a/tests/test_update.py b/tests/test_update.pynew file mode 100644index 0000000..95e0c20--- /dev/null+++ b/tests/test_update.py@@ -0,0 +1,80 @@+from __future__ import annotations++import io+import subprocess+import unittest+from pathlib import Path+from unittest.mock import patch++from sidepulse.cli import sidepulse_main+from sidepulse.update import SETUP_URL, update_installation+++class UpdateTests(unittest.TestCase):+ def test_every_update_downloads_and_executes_the_internet_script(self):+ downloads = []+ executed = []++ def run(command, **kwargs):+ self.assertTrue(kwargs['check'])+ if command[0] == 'curl':+ self.assertIn(SETUP_URL, command)+ self.assertIn('Cache-Control: no-cache', command)+ script = Path(command[command.index('-o') + 1])+ downloads.append(script)+ script.write_text(f'echo latest-script-{len(downloads)}\n')+ elif command[0] == 'bash':+ executed.append(Path(command[1]).read_text())+ else:+ self.fail(f'Unexpected command: {command}')+ return subprocess.CompletedProcess(command, 0)++ with patch('sidepulse.update.subprocess.run', side_effect=run):+ self.assertEqual(update_installation(), 0)+ self.assertEqual(update_installation(), 0)+ self.assertEqual(executed, ['echo latest-script-1\n', 'echo latest-script-2\n'])+ self.assertTrue(all(not script.exists() for script in downloads))++ def test_partial_download_failure_never_executes_bash(self):+ commands = []++ def run(command, **kwargs):+ commands.append(command)+ Path(command[command.index('-o') + 1]).write_text('partial script')+ raise subprocess.CalledProcessError(22, command)++ with (+ patch('sidepulse.update.subprocess.run', side_effect=run),+ patch('sys.stderr', new_callable=io.StringIO),+ ):+ self.assertEqual(update_installation(), 1)+ self.assertEqual(len(commands), 1)+ self.assertEqual(commands[0][0], 'curl')++ def test_installer_failure_is_reported(self):+ with (+ patch('sidepulse.update.subprocess.run', side_effect=[+ subprocess.CompletedProcess([], 0),+ subprocess.CalledProcessError(1, ['bash', 'setup.sh']),+ ]),+ patch('sys.stderr', new_callable=io.StringIO) as stderr,+ ):+ self.assertEqual(update_installation(), 1)+ self.assertIn('update failed', stderr.getvalue())++ def test_missing_curl_is_reported(self):+ with (+ patch('sidepulse.update.subprocess.run', side_effect=FileNotFoundError('curl')),+ patch('sys.stderr', new_callable=io.StringIO),+ ):+ self.assertEqual(update_installation(), 1)++ def test_dry_run_does_not_download_or_execute_anything(self):+ with patch('sidepulse.update.subprocess.run') as run:+ self.assertEqual(sidepulse_main(['update', '--dry-run']), 0)+ run.assert_not_called()++ def test_cli_dispatches_update(self):+ with patch('sidepulse.update.update_installation', return_value=7) as update:+ self.assertEqual(sidepulse_main(['update']), 7)+ update.assert_called_once_with(dry_run=False)