Skip to content

CLI for SidePulse

Python

Open session in existing terminal

Peter Kuhar4721a6c9101d
diff --git a/pyproject.toml b/pyproject.toml
index 77351ef..333470a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -52,7 +52,7 @@ sidepulse-reply = "sidepulse.reply_classifier:main"
[tool.setuptools.packages.find]
where = ["src"]
-include = ["sidepulse*"]
+include = ["sidepulse*", "agent_monitor*", "sidepulse_cli*"]
[tool.setuptools.package-data]
"sidepulse.resources" = ["sd_eject_guard.c", "sdled.wasm"]
diff --git a/src/agent_monitor/__init__.py b/src/agent_monitor/__init__.py
new file mode 100644
index 0000000..51c75fa
--- /dev/null
+++ b/src/agent_monitor/__init__.py
@@ -0,0 +1 @@
+"""Compatibility package for old agent-monitor hook paths."""
diff --git a/src/agent_monitor/hook_entry.py b/src/agent_monitor/hook_entry.py
index a13eada..c5d6da3 100644
--- a/src/agent_monitor/hook_entry.py
+++ b/src/agent_monitor/hook_entry.py
@@ -1,4 +1,4 @@
-"""Compatibility launcher for installations that predate the sidepulse rename."""
+"""Compatibility launcher for installations that predate the SidePulse rename."""
from __future__ import annotations
@@ -10,11 +10,8 @@ SOURCE_ROOT = Path(__file__).resolve().parents[1]
if str(SOURCE_ROOT) not in sys.path:
sys.path.insert(0, str(SOURCE_ROOT))
-try:
- from sidepulse.hook import hook_log_main
-except ImportError:
- from sidepulse.hook import hook_log_main
+from sidepulse.hook_entry import main
if __name__ == "__main__":
- raise SystemExit(hook_log_main())
+ raise SystemExit(main())
diff --git a/src/sidepulse/collector.py b/src/sidepulse/collector.py
index 27a6c13..267d42e 100644
--- a/src/sidepulse/collector.py
+++ b/src/sidepulse/collector.py
@@ -979,7 +979,7 @@ def update_metadata(metadata: StatusMetadata, record: HookEvent) -> None:
metadata.cwd = record.cwd
title = title_from_event(record)
- if title:
+ if title and (metadata.title is None or is_provider_session_title(record, title)):
metadata.title = title
origin = record.origin or origin_label_from_payload(record.provider, record.raw)
@@ -987,6 +987,12 @@ def update_metadata(metadata: StatusMetadata, record: HookEvent) -> None:
metadata.origin = origin
+def is_provider_session_title(record: HookEvent, title: str) -> bool:
+ if record.provider == "codex":
+ return title == codex_session_title(record.session_id)
+ return False
+
+
def status_from_event(record: HookEvent, metadata: StatusMetadata | None = None) -> AgentStatus | None:
mode = mode_for_event(record)
if mode is None:
diff --git a/src/sidepulse/hook.py b/src/sidepulse/hook.py
index 60155fa..aa7120c 100644
--- a/src/sidepulse/hook.py
+++ b/src/sidepulse/hook.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import os
import sys
from datetime import datetime, timezone
from pathlib import Path
@@ -96,6 +97,14 @@ def write_hook_status_audit(provider: str, line: dict[str, Any]) -> None:
pass
+def hook_event_socket_disabled() -> bool:
+ return os.environ.get("SIDEPULSE_DISABLE_EVENT_SOCKET", "").lower() in {
+ "1",
+ "true",
+ "yes",
+ }
+
+
def hook_log_main(provider: str, log_path: Path) -> int:
try:
actual_provider, actual_log_path, line = routed_hook_payload(
@@ -103,7 +112,8 @@ def hook_log_main(provider: str, log_path: Path) -> int:
log_path,
sys.stdin.read(),
)
- send_hook_event(actual_provider, line)
+ if not hook_event_socket_disabled():
+ send_hook_event(actual_provider, line)
write_hook_line(actual_log_path, line)
write_hook_status_audit(actual_provider, line)
except Exception:
diff --git a/src/sidepulse/install.py b/src/sidepulse/install.py
index 9cb1172..cafbbe8 100644
--- a/src/sidepulse/install.py
+++ b/src/sidepulse/install.py
@@ -148,12 +148,19 @@ def install_grok_hooks(
cleaned.append(grok_hook_entry(event_name, command))
hooks[event_name] = cleaned
- changed = json.dumps(data, sort_keys=True) != original
+ legacy_changed = any(
+ grok_legacy_hook_file_would_change(path, target_log)
+ for path in grok_legacy_hook_config_paths(config)
+ )
+ backup_changed = grok_live_backup_hook_files_would_change(config)
+ changed = json.dumps(data, sort_keys=True) != original or legacy_changed or backup_changed
backup = None
if changed and not dry_run:
config.parent.mkdir(parents=True, exist_ok=True)
- backup = backup_file(config)
+ backup = backup_file(config, grok_hook_backup_dir(config)) if config.exists() else None
config.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")
+ clean_grok_legacy_hook_files(config, target_log)
+ clean_grok_live_backup_hook_files(config)
target_log.parent.mkdir(parents=True, exist_ok=True)
target_log.touch(exist_ok=True)
@@ -250,10 +257,16 @@ def uninstall_grok_hooks(
data.pop("hooks", None)
changed = json.dumps(data, sort_keys=True) != original
+ legacy_changed = any(
+ grok_legacy_hook_file_would_change(path, target_log)
+ for path in grok_legacy_hook_config_paths(config)
+ )
+ backup_changed = grok_live_backup_hook_files_would_change(config)
+ changed = changed or legacy_changed or backup_changed
backup = None
if changed and not dry_run:
config.parent.mkdir(parents=True, exist_ok=True)
- backup = backup_file(config)
+ backup = backup_file(config, grok_hook_backup_dir(config)) if config.exists() else None
if data:
config.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")
else:
@@ -261,6 +274,8 @@ def uninstall_grok_hooks(
config.unlink()
except FileNotFoundError:
pass
+ clean_grok_legacy_hook_files(config, target_log)
+ clean_grok_live_backup_hook_files(config)
return InstallResult("grok", config, target_log, changed, backup, dry_run)
@@ -272,7 +287,7 @@ def hook_command(
) -> str:
executable = python_executable or sys.executable or "python3"
if getattr(sys, "frozen", False) and python_executable is None:
- return " ".join(
+ command = " ".join(
[
shlex.quote(executable),
"agent-monitor",
@@ -283,6 +298,7 @@ def hook_command(
shlex.quote(str(log_path.expanduser())),
]
)
+ return fail_open_command(command)
entry_point = Path(__file__).with_name("hook_entry.py")
command = " ".join(
[
@@ -294,7 +310,109 @@ def hook_command(
shlex.quote(str(log_path.expanduser())),
]
)
- return command
+ return fail_open_command(command)
+
+
+def fail_open_command(command: str) -> str:
+ return f"{command} ; true"
+
+
+def grok_legacy_hook_config_paths(config: Path) -> tuple[Path, ...]:
+ return (
+ config.parent / "sidepulse-agent-monitor.json",
+ config.parent / "sidepulse-cli.json",
+ )
+
+
+def grok_hook_backup_dir(config: Path) -> Path:
+ return config.parent.parent / "sidepulse-hook-backups"
+
+
+def grok_live_backup_hook_paths(config: Path) -> tuple[Path, ...]:
+ hooks_dir = config.parent
+ if not hooks_dir.exists():
+ return ()
+ return tuple(
+ sorted(
+ path
+ for path in hooks_dir.iterdir()
+ if path.is_file()
+ and path.name.startswith("sidepulse")
+ and ".json.bak." in path.name
+ )
+ )
+
+
+def grok_live_backup_hook_files_would_change(config: Path) -> bool:
+ return bool(grok_live_backup_hook_paths(config))
+
+
+def clean_grok_live_backup_hook_files(config: Path) -> None:
+ backup_dir = grok_hook_backup_dir(config)
+ for path in grok_live_backup_hook_paths(config):
+ backup_dir.mkdir(parents=True, exist_ok=True)
+ destination = backup_dir / path.name
+ if destination.exists():
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ destination = backup_dir / f"{path.name}.{stamp}"
+ path.replace(destination)
+
+
+def grok_legacy_hook_file_would_change(path: Path, log_path: Path) -> bool:
+ if not path.exists():
+ return False
+ try:
+ data = read_json_config(path)
+ except Exception:
+ return False
+ cleaned = clean_json_hook_data(data, log_path, GROK_EVENTS)
+ return json.dumps(cleaned, sort_keys=True) != json.dumps(data, sort_keys=True)
+
+
+def clean_grok_legacy_hook_files(config: Path, log_path: Path) -> None:
+ for path in grok_legacy_hook_config_paths(config):
+ if not path.exists():
+ continue
+ try:
+ data = read_json_config(path)
+ except Exception:
+ continue
+ cleaned = clean_json_hook_data(data, log_path, GROK_EVENTS)
+ if json.dumps(cleaned, sort_keys=True) == json.dumps(data, sort_keys=True):
+ continue
+ backup_file(path, grok_hook_backup_dir(config))
+ if cleaned:
+ path.write_text(json.dumps(cleaned, indent=2, sort_keys=False) + "\n")
+ else:
+ path.unlink()
+
+
+def clean_json_hook_data(
+ data: dict[str, Any],
+ log_path: Path,
+ event_names: tuple[str, ...],
+) -> dict[str, Any]:
+ cleaned_data = dict(data)
+ hooks = cleaned_data.get("hooks")
+ if not isinstance(hooks, dict):
+ return cleaned_data
+
+ cleaned_hooks = dict(hooks)
+ for event_name in list(cleaned_hooks):
+ entries = cleaned_hooks.get(event_name)
+ if event_name not in event_names or not isinstance(entries, list):
+ continue
+ cleaned = remove_json_command_hooks_for_log(entries, log_path)
+ if cleaned:
+ cleaned_hooks[event_name] = cleaned
+ else:
+ cleaned_hooks.pop(event_name, None)
+
+ if cleaned_hooks:
+ cleaned_data["hooks"] = cleaned_hooks
+ else:
+ cleaned_data.pop("hooks", None)
+ return cleaned_data
def read_json_config(config: Path) -> dict[str, Any]:
@@ -623,11 +741,13 @@ def ensure_codex_hooks_feature(text: str) -> str:
return "".join(lines)
-def backup_file(path: Path) -> Path | None:
+def backup_file(path: Path, backup_dir: Path | None = None) -> Path | None:
if not path.exists():
return None
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- backup = path.with_name(f"{path.name}.bak.{stamp}")
+ target_dir = backup_dir or path.parent
+ target_dir.mkdir(parents=True, exist_ok=True)
+ backup = target_dir / f"{path.name}.bak.{stamp}"
backup.write_bytes(path.read_bytes())
return backup
diff --git a/src/sidepulse/settings.py b/src/sidepulse/settings.py
index b3cf2f0..919f903 100644
--- a/src/sidepulse/settings.py
+++ b/src/sidepulse/settings.py
@@ -8,7 +8,7 @@ from pathlib import Path
from typing import Any
from .battery import DEFAULT_POWER_CHANGE_PREVIEW_SECONDS
-from .session_actions import SESSION_OPEN_CHOICES
+from .session_actions import SESSION_OPEN_CHOICES, SESSION_OPEN_TERMINAL
TERMINAL_APP_TERMINAL = "terminal"
@@ -126,6 +126,7 @@ class AgentMonitorSettings:
battery_show_on_power_change: bool = True
battery_power_change_preview_seconds: float = DEFAULT_POWER_CHANGE_PREVIEW_SECONDS
session_open_preferences: dict[str, str] = field(default_factory=dict)
+ grok_session_open_action: str = SESSION_OPEN_TERMINAL
session_terminal_app: str = TERMINAL_APP_TERMINAL
custom_terminal_path: str = ""
setup_screen_completed: bool = False
@@ -258,9 +259,10 @@ class AgentMonitorSettings:
return replace(self, devices=devices)
def session_open_action(self, provider: str, origin: str | None = None) -> str | None:
+ provider_key = provider.lower()
if origin:
action = self.session_open_preferences.get(
- session_open_preference_key(provider, origin)
+ session_open_preference_key(provider_key, origin)
)
if action in SESSION_OPEN_CHOICES:
return action
@@ -270,7 +272,12 @@ class AgentMonitorSettings:
if action in SESSION_OPEN_CHOICES:
return action
- action = self.session_open_preferences.get(provider.lower())
+ if provider_key == "grok":
+ action = self.grok_session_open_action
+ if action in SESSION_OPEN_CHOICES:
+ return action
+
+ action = self.session_open_preferences.get(provider_key)
if action in SESSION_OPEN_CHOICES:
return action
return None
@@ -283,6 +290,8 @@ class AgentMonitorSettings:
) -> "AgentMonitorSettings":
if action not in SESSION_OPEN_CHOICES:
raise ValueError(f"Unknown session open action: {action}")
+ if provider.lower() == "grok" and not origin:
+ return self.with_provider_session_open_action(provider, action)
key = session_open_preference_key(provider, origin)
preferences = dict(self.session_open_preferences)
preferences[key] = action
@@ -299,8 +308,14 @@ class AgentMonitorSettings:
preferences = {
key: value
for key, value in self.session_open_preferences.items()
- if not key.startswith(prefix)
+ if key != provider_key and not key.startswith(prefix)
}
+ if provider_key == "grok":
+ return replace(
+ self,
+ session_open_preferences=preferences,
+ grok_session_open_action=action,
+ )
preferences[provider_key] = action
return replace(self, session_open_preferences=preferences)
@@ -400,6 +415,7 @@ class AgentMonitorSettings:
"power_change_preview_seconds": self.battery_power_change_preview_seconds,
},
"session_open_preferences": dict(sorted(self.session_open_preferences.items())),
+ "grok_session_open_action": self.grok_session_open_action,
"session_terminal": {
"app": self.session_terminal_app,
"custom_path": self.custom_terminal_path,
@@ -448,6 +464,18 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:
terminal = {}
led_display = _led_display_setting(data.get("led_display"), LED_DISPLAY_AGENT)
+ session_open_preferences = _session_open_preferences(
+ data.get("session_open_preferences")
+ )
+ grok_session_open_action = _session_open_action_setting(
+ data.get("grok_session_open_action")
+ )
+ if grok_session_open_action is None:
+ grok_session_open_action = session_open_preferences.get(
+ "grok",
+ SESSION_OPEN_TERMINAL,
+ )
+ session_open_preferences.pop("grok", None)
return AgentMonitorSettings(
codex_transcripts_enabled=_bool_setting(transcript.get("codex"), False),
claude_transcripts_enabled=_bool_setting(transcript.get("claude"), False),
@@ -482,7 +510,8 @@ def load_settings(path: Path | None = None) -> AgentMonitorSettings:
battery.get("power_change_preview_seconds"),
DEFAULT_POWER_CHANGE_PREVIEW_SECONDS,
),
- session_open_preferences=_session_open_preferences(data.get("session_open_preferences")),
+ session_open_preferences=session_open_preferences,
+ grok_session_open_action=grok_session_open_action,
session_terminal_app=normalize_terminal_app(terminal.get("app")),
custom_terminal_path=_string_setting(terminal.get("custom_path")),
setup_screen_completed=_bool_setting(data.get("setup_screen_completed"), False),
@@ -575,6 +604,12 @@ def _session_open_preferences(value: object) -> dict[str, str]:
return result
+def _session_open_action_setting(value: object) -> str | None:
+ if isinstance(value, str) and value in SESSION_OPEN_CHOICES:
+ return value
+ return None
+
+
def session_open_preference_key(provider: str, origin: str | None = None) -> str:
if origin:
return f"origin:{provider.lower()}:{normalize_session_origin_key(origin)}"
diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.py
index 846dc6a..25fc54d 100644
--- a/src/sidepulse/status_bar.py
+++ b/src/sidepulse/status_bar.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import shlex
import subprocess
import threading
import time
@@ -35,6 +36,8 @@ try:
NSSavePanel,
NSSlider,
NSStatusBar,
+ NSTabView,
+ NSTabViewItem,
NSTextField,
NSTextView,
NSView,
@@ -46,6 +49,7 @@ try:
NSVariableStatusItemLength,
)
from Foundation import NSObject, NSString, NSTimer, NSURL
+ from ScriptingBridge import SBApplication
except ImportError as exc: # pragma: no cover - only exercised on non-macOS setups.
raise SystemExit(
"The status-bar app requires PyObjC/AppKit:\n"
@@ -187,6 +191,15 @@ class TerminalAppSpec:
system_paths: tuple[str, ...] = ()
+@dataclass(frozen=True)
+class TerminalSessionHints:
+ provider: str
+ session_id: str
+ cwd: str
+ title: str
+ match_title: str = ""
+
+
STATE_IDLE = StatusBarState("Idle", "circle", 4)
STATE_WORKING = StatusBarState("Working", "arrow.triangle.2.circlepath", 2)
STATE_DONE = StatusBarState("Done", "checkmark.circle", 3)
@@ -198,6 +211,7 @@ STATUS_BAR_KEEPALIVE_VOLUME_NAMES = (
)
STATUS_BAR_REFRESH_SECONDS = 15.0
STATUS_BAR_DEVICE_POLL_SECONDS = 2.0
+STATUS_BAR_RECENT_COMPLETED_SECONDS = 20 * 60.0
SCREEN_BAR_FEATURE_ENABLED = True
STATUS_BAR_MAX_LINES_PER_SOURCE = 500
STATUS_BAR_STARTUP_REPLAY_LINES = 200
@@ -478,7 +492,8 @@ class StatusBarController(NSObject):
self.refresh_settings_window()
return
self.set_settings_message(
- f"{provider.title()} sessions: {provider_open_action_label(provider, action)}."
+ f"{provider.title()} sessions: "
+ f"{provider_open_action_label(provider, action, self.settings)}."
)
@objc.IBAction
@@ -904,10 +919,12 @@ class StatusBarController(NSObject):
for provider in ("codex", "claude", "grok"):
popup = self.settings_fields.get(f"{provider}_session_opener")
if popup is not None:
- select_popup_action(
+ refresh_provider_opener_popup(
popup,
+ provider,
self.settings.session_open_action(provider)
or default_provider_open_action(provider),
+ self.settings,
)
terminal_popup = self.settings_fields.get("session_terminal")
if terminal_popup is not None:
@@ -1318,6 +1335,7 @@ class StatusBarController(NSObject):
value,
terminal_app=self.settings.session_terminal_app,
custom_terminal_path=self.settings.custom_terminal_path,
+ session_hints=terminal_session_hints(status),
)
else:
self.set_settings_message(f"Unknown open action for {status.display_name}.")
@@ -1958,8 +1976,16 @@ def build_menu(snapshot, state: StatusBarState, target: StatusBarController) ->
if not statuses:
menu.addItem_(disabled_menu_item("No recent sessions"))
else:
+ collision_keys = session_title_collision_keys(statuses)
for status in statuses:
- menu.addItem_(build_session_menu_item(status, snapshot.collected_at, target))
+ menu.addItem_(
+ build_session_menu_item(
+ status,
+ snapshot.collected_at,
+ target,
+ disambiguate_title=session_title_collision_key(status) in collision_keys,
+ )
+ )
menu.addItem_(NSMenuItem.separatorItem())
menu.addItem_(disabled_menu_item("Devices"))
@@ -2060,9 +2086,10 @@ def build_device_menu_item(device: StatusBarDevice, target: StatusBarController)
custom.setState_(1 if device.display == LED_DISPLAY_CUSTOM else 0)
submenu.addItem_(custom)
- submenu.addItem_(NSMenuItem.separatorItem())
- submenu.addItem_(disabled_menu_item(f"Brightness {brightness_percent(device.brightness)}%"))
- submenu.addItem_(build_brightness_slider_item(device, target))
+ if device.device_id != VIRTUAL_DEVICE_ID:
+ submenu.addItem_(NSMenuItem.separatorItem())
+ submenu.addItem_(disabled_menu_item(f"Brightness {brightness_percent(device.brightness)}%"))
+ submenu.addItem_(build_brightness_slider_item(device, target))
if device.device_id == VIRTUAL_DEVICE_ID:
submenu.addItem_(NSMenuItem.separatorItem())
@@ -2244,7 +2271,7 @@ def format_byte_count(size: int) -> str:
def build_settings_window(target: StatusBarController) -> NSWindow:
width = 680
- height = 1060
+ height = 560
style = (
NSWindowStyleMaskTitled
| NSWindowStyleMaskClosable
@@ -2256,109 +2283,138 @@ def build_settings_window(target: StatusBarController) -> NSWindow:
NSBackingStoreBuffered,
False,
)
- window.setTitle_("SidePulse Agent Monitor Settings")
+ window.setTitle_("SidePulse Settings")
window.setReleasedWhenClosed_(False)
window.center()
content = window.contentView()
- add_label(content, "Agent Hooks", 24, 1012, 200, 24)
- add_label(content, "Codex", 32, 970, 80, 22)
- codex_status = add_label(content, "", 112, 970, 270, 22)
- add_button(content, "Install", 432, 966, 90, 28, target, "installCodexHooks:")
- add_button(content, "Uninstall", 532, 966, 100, 28, target, "uninstallCodexHooks:")
-
- add_label(content, "Claude", 32, 928, 80, 22)
- claude_status = add_label(content, "", 112, 928, 270, 22)
- add_button(content, "Install", 432, 924, 90, 28, target, "installClaudeHooks:")
- add_button(content, "Uninstall", 532, 924, 100, 28, target, "uninstallClaudeHooks:")
-
- add_label(content, "Grok", 32, 886, 80, 22)
- grok_status = add_label(content, "", 112, 886, 270, 22)
- add_button(content, "Install", 432, 882, 90, 28, target, "installGrokHooks:")
- add_button(content, "Uninstall", 532, 882, 100, 28, target, "uninstallGrokHooks:")
-
- add_separator(content, 24, 856, width - 48)
- add_label(content, "Transcript Monitoring", 24, 822, 240, 24)
- add_label(content, "Open Sessions With", 352, 822, 240, 24)
+ tab_width = width - 40
+ tab_height = height - 84
+ tab_view = NSTabView.alloc().initWithFrame_(((20, 54), (tab_width, tab_height)))
+ agents_tab = add_settings_tab(tab_view, "agents", "Agents", tab_width, tab_height)
+ devices_tab = add_settings_tab(
+ tab_view,
+ "devices",
+ "Devices & LEDs",
+ tab_width,
+ tab_height,
+ )
+ sleep_tab = add_settings_tab(
+ tab_view,
+ "lid",
+ "Lid & Sleep",
+ tab_width,
+ tab_height,
+ )
+ diagnostics_tab = add_settings_tab(
+ tab_view,
+ "diagnostics",
+ "Diagnostics",
+ tab_width,
+ tab_height,
+ )
+ content.addSubview_(tab_view)
+
+ add_label(agents_tab, "Agent Hooks", 24, 398, 200, 24)
+ add_label(agents_tab, "Codex", 32, 360, 80, 22)
+ codex_status = add_label(agents_tab, "", 130, 360, 240, 22)
+ add_button(agents_tab, "Install", 400, 356, 90, 28, target, "installCodexHooks:")
+ add_button(agents_tab, "Uninstall", 500, 356, 100, 28, target, "uninstallCodexHooks:")
+
+ add_label(agents_tab, "Claude", 32, 326, 80, 22)
+ claude_status = add_label(agents_tab, "", 130, 326, 240, 22)
+ add_button(agents_tab, "Install", 400, 322, 90, 28, target, "installClaudeHooks:")
+ add_button(agents_tab, "Uninstall", 500, 322, 100, 28, target, "uninstallClaudeHooks:")
+
+ add_label(agents_tab, "Grok", 32, 292, 80, 22)
+ grok_status = add_label(agents_tab, "", 130, 292, 240, 22)
+ add_button(agents_tab, "Install", 400, 288, 90, 28, target, "installGrokHooks:")
+ add_button(agents_tab, "Uninstall", 500, 288, 100, 28, target, "uninstallGrokHooks:")
+
+ add_separator(agents_tab, 24, 258, tab_width - 48)
+ add_label(agents_tab, "Session Opening", 24, 224, 240, 24)
+ add_label(agents_tab, "Codex", 32, 188, 100, 22)
+ codex_opener = add_provider_opener_popup(agents_tab, "codex", 160, 186, target)
+ add_label(agents_tab, "Claude", 32, 154, 100, 22)
+ claude_opener = add_provider_opener_popup(agents_tab, "claude", 160, 152, target)
+ add_label(agents_tab, "Grok Sessions", 32, 120, 120, 22)
+ grok_opener = add_provider_opener_popup(agents_tab, "grok", 160, 118, target)
+
+ add_label(agents_tab, "Terminal App", 376, 188, 120, 22)
+ terminal_popup = add_terminal_popup(agents_tab, 376, 156, target)
+ custom_terminal_path = add_label(agents_tab, "", 376, 128, 170, 22)
+ add_button(agents_tab, "Choose...", 500, 92, 100, 28, target, "chooseSessionTerminal:")
+
+ add_separator(agents_tab, 24, 80, tab_width - 48)
+ add_label(agents_tab, "Transcript Monitoring", 24, 46, 240, 24)
codex_transcripts = add_checkbox(
- content,
+ agents_tab,
"CLI fallback: Codex transcripts",
32,
- 788,
+ 14,
260,
24,
target,
"toggleCodexTranscripts:",
)
claude_transcripts = add_checkbox(
- content,
+ agents_tab,
"CLI fallback: Claude transcripts",
- 32,
- 756,
+ 312,
+ 14,
260,
24,
target,
"toggleClaudeTranscripts:",
)
- add_label(content, "Codex", 360, 794, 62, 22)
- codex_opener = add_provider_opener_popup(content, "codex", 424, 792, target)
- add_label(content, "Claude", 360, 766, 62, 22)
- claude_opener = add_provider_opener_popup(content, "claude", 424, 764, target)
- add_label(content, "Grok", 360, 738, 62, 22)
- grok_opener = add_provider_opener_popup(content, "grok", 424, 736, target)
- add_label(content, "Resume Terminal", 360, 710, 100, 22)
- terminal_popup = add_terminal_popup(content, 464, 708, target)
- custom_terminal_path = add_label(content, "", 360, 682, 170, 22)
- add_button(content, "Choose...", 542, 678, 90, 28, target, "chooseSessionTerminal:")
-
- add_separator(content, 24, 656, width - 48)
- add_label(content, "Debug Log", 24, 622, 240, 24)
- debug_log_status = add_label(content, "", 32, 592, 606, 22)
- add_button(content, "Export CSV", 32, 554, 110, 28, target, "exportDebugCsv:")
- add_button(content, "Export HTML", 152, 554, 120, 28, target, "exportDebugHtml:")
-
- add_separator(content, 24, 534, width - 48)
- add_label(content, "LED Display", 24, 500, 240, 24)
+
+ add_label(devices_tab, "LED Display", 24, 398, 240, 24)
battery_leds = add_checkbox(
- content,
+ devices_tab,
"Show battery on LEDs",
32,
- 466,
+ 356,
260,
24,
target,
"setBatteryLedDisplayFromCheckbox:",
)
battery_power_preview = add_checkbox(
- content,
+ devices_tab,
"Show battery for 7s on plug/unplug",
32,
- 434,
+ 318,
320,
24,
target,
"setBatteryPowerPreviewFromCheckbox:",
)
- add_separator(content, 24, 414, width - 48)
- add_label(content, "Lid & Sleep", 24, 380, 240, 24)
- add_label(content, "Lid Closed", 32, 346, 120, 22)
- add_label(content, "Duration", 520, 346, 70, 22)
- closed_duration = add_editable_field(content, "", 590, 344, 48, 24)
- closed_program = add_text_view(content, "", 32, 254, 606, 82)
- add_button(content, "Preview", 32, 216, 90, 28, target, "previewLidClosedAnimation:")
- add_button(content, "Reset", 132, 216, 90, 28, target, "resetLidClosedAnimation:")
-
- add_label(content, "Lid Open", 32, 180, 120, 22)
- add_label(content, "Duration", 520, 180, 70, 22)
- open_duration = add_editable_field(content, "", 590, 178, 48, 24)
- open_program = add_text_view(content, "", 32, 88, 606, 82)
- add_button(content, "Preview", 32, 50, 90, 28, target, "previewLidOpenAnimation:")
- add_button(content, "Reset", 132, 50, 90, 28, target, "resetLidOpenAnimation:")
- add_button(content, "Save Animations", 492, 50, 146, 28, target, "saveLidAnimations:")
+ add_label(sleep_tab, "Lid Closed", 24, 398, 120, 22)
+ add_label(sleep_tab, "Duration", 516, 398, 70, 22)
+ closed_duration = add_editable_field(sleep_tab, "", 588, 396, 48, 24)
+ closed_program = add_text_view(sleep_tab, "", 24, 276, 612, 110)
+ add_button(sleep_tab, "Preview", 24, 236, 90, 28, target, "previewLidClosedAnimation:")
+ add_button(sleep_tab, "Reset", 124, 236, 90, 28, target, "resetLidClosedAnimation:")
+
+ add_separator(sleep_tab, 24, 210, tab_width - 48)
+ add_label(sleep_tab, "Lid Open", 24, 176, 120, 22)
+ add_label(sleep_tab, "Duration", 516, 176, 70, 22)
+ open_duration = add_editable_field(sleep_tab, "", 588, 174, 48, 24)
+ open_program = add_text_view(sleep_tab, "", 24, 54, 612, 110)
+ add_button(sleep_tab, "Preview", 24, 14, 90, 28, target, "previewLidOpenAnimation:")
+ add_button(sleep_tab, "Reset", 124, 14, 90, 28, target, "resetLidOpenAnimation:")
+ add_button(sleep_tab, "Save Animations", 490, 14, 146, 28, target, "saveLidAnimations:")
+
+ add_label(diagnostics_tab, "Debug Log", 24, 398, 240, 24)
+ debug_log_status = add_label(diagnostics_tab, "", 32, 360, 588, 22)
+ add_button(diagnostics_tab, "Export CSV", 32, 318, 110, 28, target, "exportDebugCsv:")
+ add_button(diagnostics_tab, "Export HTML", 152, 318, 120, 28, target, "exportDebugHtml:")
+ add_separator(diagnostics_tab, 24, 280, tab_width - 48)
+ add_label(diagnostics_tab, "Settings File", 24, 246, 240, 24)
+ settings_path = add_label(diagnostics_tab, "", 32, 208, 588, 22)
message = add_label(content, "", 24, 22, width - 48, 22)
- settings_path = add_label(content, "", 24, 4, width - 48, 18)
target.settings_fields = {
"codex_hook_status": codex_status,
@@ -2386,6 +2442,15 @@ def build_settings_window(target: StatusBarController) -> NSWindow:
return window
+def add_settings_tab(tab_view, identifier: str, title: str, width: int, height: int):
+ item = NSTabViewItem.alloc().initWithIdentifier_(identifier)
+ item.setLabel_(title)
+ view = NSView.alloc().initWithFrame_(((0, 0), (width, height - 34)))
+ item.setView_(view)
+ tab_view.addTabViewItem_(item)
+ return view
+
+
def add_label(parent, text: str, x: int, y: int, width: int, height: int):
label = NSTextField.alloc().initWithFrame_(((x, y), (width, height)))
label.setStringValue_(text)
@@ -2483,20 +2548,31 @@ def default_provider_open_action(provider: str) -> str:
return SESSION_OPEN_TERMINAL
-def provider_open_action_label(provider: str, action: str) -> str:
+def provider_open_action_label(provider: str, action: str, settings=None) -> str:
if action == SESSION_OPEN_VSCODE:
return "VS Code"
if action == SESSION_OPEN_TERMINAL:
- return "Terminal"
+ return "Resume in Terminal"
return {"codex": "Codex", "claude": "Claude"}.get(provider, "App")
-def select_popup_action(popup, action: str) -> None:
+def refresh_provider_opener_popup(popup, provider: str, action: str, settings) -> None:
for index in range(popup.numberOfItems()):
- payload = popup.itemAtIndex_(index).representedObject()
+ item = popup.itemAtIndex_(index)
+ payload = item.representedObject()
if isinstance(payload, dict) and payload.get("action") == action:
+ item.setTitle_(
+ provider_open_action_label(provider, str(payload.get("action")), settings)
+ )
popup.selectItemAtIndex_(index)
- return
+ elif isinstance(payload, dict):
+ item.setTitle_(
+ provider_open_action_label(
+ provider,
+ str(payload.get("action")),
+ settings,
+ )
+ )
def refresh_terminal_popup(popup, terminal_app: str) -> None:
@@ -2516,6 +2592,29 @@ def terminal_app_label(terminal_app: str) -> str:
return TERMINAL_APP_LABELS.get(normalize_terminal_app(terminal_app), "Terminal")
+def resume_terminal_label(settings=None) -> str:
+ return f"Resume in {resume_terminal_app_label(settings)}"
+
+
+def resume_terminal_app_label(settings=None) -> str:
+ if settings is None:
+ return "Terminal"
+ terminal = normalize_terminal_app(getattr(settings, "session_terminal_app", None))
+ if terminal == TERMINAL_APP_CUSTOM:
+ path = str(getattr(settings, "custom_terminal_path", "") or "").strip()
+ if path:
+ return custom_terminal_app_label(path)
+ return "Custom Terminal"
+ return terminal_app_label(terminal)
+
+
+def custom_terminal_app_label(path: str) -> str:
+ name = Path(path).name
+ if name.endswith(".app"):
+ return name[:-4] or "Custom Terminal"
+ return name or "Custom Terminal"
+
+
def terminal_app_menu_label(terminal_app: str) -> str:
terminal = normalize_terminal_app(terminal_app)
label = terminal_app_label(terminal)
@@ -2845,9 +2944,10 @@ def build_session_menu_item(
target: StatusBarController,
*,
width: float | None = None,
+ disambiguate_title: bool = False,
) -> NSMenuItem:
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
- native_session_menu_title(status),
+ native_session_menu_title(status, disambiguate=disambiguate_title),
"openSessionPrimary:",
"",
)
@@ -2859,8 +2959,10 @@ def build_session_menu_item(
return item
-def native_session_menu_title(status: AgentStatus) -> str:
+def native_session_menu_title(status: AgentStatus, *, disambiguate: bool = False) -> str:
title, project = session_title_parts(status)
+ if disambiguate and status.session_id:
+ title = f"{title} ({status.session_id[:8]})"
parts = [title]
if project:
parts.append(project)
@@ -2885,7 +2987,7 @@ def build_session_options_menu(
for action in available_session_open_actions(status):
add_session_open_action_item(
menu,
- session_open_action_label(status, action),
+ session_open_action_title(status, action, getattr(target, "settings", None)),
status,
action,
target,
@@ -2914,6 +3016,12 @@ def add_session_open_action_item(
menu.addItem_(item)
+def session_open_action_title(status: AgentStatus, action: str, settings=None) -> str:
+ if action == SESSION_OPEN_TERMINAL:
+ return resume_terminal_label(settings)
+ return session_open_action_label(status, action)
+
+
def session_row_icon_for_status(status: AgentStatus):
status_icon = status_icon_for_status(status)
origin_icon = session_origin_icon_for_status(status)
@@ -3145,11 +3253,67 @@ def build_error_menu(exc: Exception) -> NSMenu:
def recent_statuses(snapshot) -> list[AgentStatus]:
- statuses = list(snapshot.statuses)
+ statuses = coalesced_menu_statuses(menu_statuses(snapshot))
statuses.sort(key=lambda status: (status.priority, -status.updated_at.timestamp()))
return statuses[:12]
+def menu_statuses(snapshot) -> tuple[AgentStatus, ...]:
+ statuses = list(snapshot.statuses)
+ now = snapshot.collected_at
+ statuses.extend(
+ status
+ for status in getattr(snapshot, "stale_statuses", ())
+ if status.mode == AgentMode.COMPLETED
+ and status.age_seconds(now) <= STATUS_BAR_RECENT_COMPLETED_SECONDS
+ )
+ return tuple(statuses)
+
+
+def session_title_collision_keys(statuses: list[AgentStatus]) -> set[tuple[str, str]]:
+ counts: dict[tuple[str, str], int] = {}
+ for status in statuses:
+ key = session_title_collision_key(status)
+ counts[key] = counts.get(key, 0) + 1
+ return {key for key, count in counts.items() if count > 1}
+
+
+def session_title_collision_key(status: AgentStatus) -> tuple[str, str]:
+ return (
+ status.provider.lower(),
+ normalized_menu_part(native_session_menu_title(status)),
+ )
+
+
+def coalesced_menu_statuses(statuses) -> list[AgentStatus]:
+ return coalesce_statuses_by_key(statuses, menu_session_coalesce_key)
+
+
+def coalesce_statuses_by_key(statuses, key_fn) -> list[AgentStatus]:
+ by_key: dict[tuple[str, ...], AgentStatus] = {}
+ passthrough: list[AgentStatus] = []
+ for status in statuses:
+ key = key_fn(status)
+ if key is None:
+ passthrough.append(status)
+ continue
+ previous = by_key.get(key)
+ if previous is None or menu_status_sort_key(status) < menu_status_sort_key(previous):
+ by_key[key] = status
+ return [*by_key.values(), *passthrough]
+
+
+def menu_session_coalesce_key(status: AgentStatus) -> tuple[str, ...] | None:
+ if not status.session_id:
+ return None
+ return ("session", status.provider.lower(), status.session_id)
+
+
+def menu_status_sort_key(status: AgentStatus) -> tuple[int, int, float]:
+ subagent_penalty = 1 if ":agent:" in status.agent_id else 0
+ return (status.priority, subagent_penalty, -status.updated_at.timestamp())
+
+
def menu_title_for_status(status: AgentStatus, now: datetime) -> str:
state = state_for_mode(status.mode)
title, project = session_title_parts(status)
@@ -3276,36 +3440,303 @@ def open_terminal_command(
*,
terminal_app: str = TERMINAL_APP_TERMINAL,
custom_terminal_path: str = "",
+ session_hints: TerminalSessionHints | None = None,
) -> None:
terminal = normalize_terminal_app(terminal_app)
+ if session_hints is not None and focus_existing_terminal_session(
+ terminal,
+ custom_terminal_path,
+ session_hints,
+ ):
+ return
+
+ launch_command = command_for_terminal_session(command, session_hints)
if (
terminal not in {TERMINAL_APP_TERMINAL, TERMINAL_APP_CUSTOM}
and not terminal_app_installed(terminal)
):
- open_macos_terminal_command(command)
+ open_macos_terminal_command(launch_command)
return
if terminal == TERMINAL_APP_ITERM:
- open_iterm_command(command)
+ open_iterm_command(launch_command)
return
if terminal == TERMINAL_APP_GHOSTTY:
- open_exec_terminal_command(command, terminal_open_target(terminal))
+ open_ghostty_command(launch_command, session_hints)
return
if terminal == TERMINAL_APP_WARP:
- open_command_script_in_terminal_app(command, terminal_open_target(terminal))
+ open_command_script_in_terminal_app(launch_command, terminal_open_target(terminal))
return
if terminal == TERMINAL_APP_KITTY:
- open_exec_terminal_command(command, terminal_open_target(terminal))
+ open_exec_terminal_command(launch_command, terminal_open_target(terminal))
return
if terminal == TERMINAL_APP_WEZTERM:
- open_wezterm_command(command, terminal_open_target(terminal))
+ open_wezterm_command(launch_command, terminal_open_target(terminal))
return
if terminal == TERMINAL_APP_ALACRITTY:
- open_exec_terminal_command(command, terminal_open_target(terminal))
+ open_exec_terminal_command(launch_command, terminal_open_target(terminal))
return
if terminal == TERMINAL_APP_CUSTOM:
- open_custom_terminal_command(command, custom_terminal_path)
+ open_custom_terminal_command(launch_command, custom_terminal_path)
return
- open_macos_terminal_command(command)
+ open_macos_terminal_command(launch_command)
+
+
+def terminal_session_hints(status: AgentStatus) -> TerminalSessionHints:
+ title, project = session_title_parts(status)
+ label_parts = [provider_label(status.provider)]
+ if title:
+ label_parts.append(title)
+ if project:
+ label_parts.append(project)
+ return TerminalSessionHints(
+ provider=status.provider.lower(),
+ session_id=status.session_id or "",
+ cwd=status.cwd or "",
+ title=" ".join(part for part in label_parts if part).strip(),
+ match_title=title,
+ )
+
+
+def command_for_terminal_session(
+ command: str,
+ hints: TerminalSessionHints | None,
+) -> str:
+ if hints is None:
+ return command
+ title = terminal_session_title(hints)
+ if not title:
+ return command
+ return f"{terminal_title_command(title)}; {command}"
+
+
+def terminal_session_title(hints: TerminalSessionHints) -> str:
+ parts = ["SidePulse"]
+ if hints.title:
+ parts.append(hints.title)
+ if hints.session_id:
+ parts.append(f"({hints.session_id[:8]})")
+ return " ".join(parts)
+
+
+def terminal_title_command(title: str) -> str:
+ return "printf '\\033]0;%s\\007' " + shlex.quote(title)
+
+
+def terminal_session_match_terms(hints: TerminalSessionHints) -> tuple[str, ...]:
+ terms: list[str] = []
+ for term in (
+ hints.session_id,
+ hints.cwd,
+ hints.title,
+ terminal_session_title(hints),
+ ):
+ term = str(term or "").strip()
+ if term and term not in terms:
+ terms.append(term)
+ return tuple(terms)
+
+
+def focus_existing_terminal_session(
+ terminal_app: str,
+ custom_terminal_path: str,
+ hints: TerminalSessionHints,
+) -> bool:
+ terminal = normalize_terminal_app(terminal_app)
+ if terminal == TERMINAL_APP_CUSTOM:
+ terminal = terminal_app_from_custom_path(custom_terminal_path)
+ terms = terminal_session_match_terms(hints)
+ if not terms:
+ return False
+ if terminal == TERMINAL_APP_TERMINAL:
+ return focus_macos_terminal_session(terms)
+ if terminal == TERMINAL_APP_ITERM:
+ return focus_iterm_session(terms)
+ if terminal == TERMINAL_APP_GHOSTTY:
+ return focus_ghostty_session(hints)
+ return False
+
+
+def terminal_app_from_custom_path(path: str) -> str:
+ app_name = Path(path.strip()).name.casefold()
+ if app_name == "terminal.app":
+ return TERMINAL_APP_TERMINAL
+ if app_name in {"iterm.app", "iterm2.app"} or "iterm" in app_name:
+ return TERMINAL_APP_ITERM
+ if "ghost" in app_name:
+ return TERMINAL_APP_GHOSTTY
+ if "warp" in app_name:
+ return TERMINAL_APP_WARP
+ if "kitty" in app_name:
+ return TERMINAL_APP_KITTY
+ if "wezterm" in app_name:
+ return TERMINAL_APP_WEZTERM
+ if "alacritty" in app_name:
+ return TERMINAL_APP_ALACRITTY
+ return TERMINAL_APP_CUSTOM
+
+
+def focus_macos_terminal_session(terms: tuple[str, ...]) -> bool:
+ condition = applescript_contains_any(("tabTitle", "tabText"), terms)
+ script = "\n".join(
+ [
+ 'tell application "Terminal"',
+ " repeat with windowRef in windows",
+ " repeat with tabRef in tabs of windowRef",
+ ' set tabTitle to ""',
+ ' set tabText to ""',
+ " try",
+ " set tabTitle to custom title of tabRef",
+ " end try",
+ " try",
+ " set tabText to contents of tabRef",
+ " end try",
+ f" if {condition} then",
+ " set selected tab of windowRef to tabRef",
+ " set index of windowRef to 1",
+ " activate",
+ ' return "1"',
+ " end if",
+ " end repeat",
+ " end repeat",
+ "end tell",
+ 'return "0"',
+ ]
+ )
+ return run_osascript_bool(script)
+
+
+def focus_iterm_session(terms: tuple[str, ...]) -> bool:
+ condition = applescript_contains_any(("sessionName", "sessionText"), terms)
+ script = "\n".join(
+ [
+ 'tell application "iTerm"',
+ " repeat with windowRef in windows",
+ " repeat with tabRef in tabs of windowRef",
+ " repeat with sessionRef in sessions of tabRef",
+ ' set sessionName to ""',
+ ' set sessionText to ""',
+ " try",
+ " set sessionName to name of sessionRef",
+ " end try",
+ " try",
+ " set sessionText to contents of sessionRef",
+ " end try",
+ f" if {condition} then",
+ " tell windowRef to select tabRef",
+ " select sessionRef",
+ " set index of windowRef to 1",
+ " activate",
+ ' return "1"',
+ " end if",
+ " end repeat",
+ " end repeat",
+ " end repeat",
+ "end tell",
+ 'return "0"',
+ ]
+ )
+ return run_osascript_bool(script)
+
+
+def focus_ghostty_session(hints: TerminalSessionHints) -> bool:
+ app = ghostty_application()
+ if app is None or not sb_bool(app, "isRunning"):
+ return False
+ marker_terms = terminal_session_marker_match_terms(hints)
+ if marker_terms and focus_matching_ghostty_terminal(
+ app,
+ marker_terms,
+ include_working_directory=False,
+ ):
+ return True
+ title_terms = terminal_session_title_match_terms(hints)
+ return bool(
+ title_terms
+ and focus_matching_ghostty_terminal(
+ app,
+ title_terms,
+ include_working_directory=False,
+ require_unique=True,
+ )
+ )
+
+
+def terminal_session_marker_match_terms(hints: TerminalSessionHints) -> tuple[str, ...]:
+ terms: list[str] = []
+ for term in (
+ hints.session_id,
+ hints.session_id[:8] if hints.session_id else "",
+ terminal_session_title(hints),
+ hints.title,
+ ):
+ term = str(term or "").strip()
+ if term and term not in terms:
+ terms.append(term)
+ return tuple(terms)
+
+
+def terminal_session_title_match_terms(hints: TerminalSessionHints) -> tuple[str, ...]:
+ title = str(hints.match_title or "").strip()
+ return (title,) if title else ()
+
+
+def focus_matching_ghostty_terminal(
+ app,
+ terms: tuple[str, ...],
+ *,
+ include_working_directory: bool,
+ require_unique: bool = False,
+) -> bool:
+ normalized_terms = tuple(normalize_match_text(term) for term in terms if term)
+ if not normalized_terms:
+ return False
+ matches: list[tuple[object, object, object]] = []
+ for window in sb_elements(sb_call(app, "windows")):
+ window_name = sb_text(window, "name")
+ for tab in sb_elements(sb_call(window, "tabs")):
+ tab_name = sb_text(tab, "name")
+ for terminal in sb_elements(sb_call(tab, "terminals")):
+ values = [window_name, tab_name, sb_text(terminal, "name")]
+ if include_working_directory:
+ values.append(sb_text(terminal, "workingDirectory"))
+ if values_match_terms(values, normalized_terms):
+ matches.append((window, tab, terminal))
+ if require_unique and len(matches) != 1:
+ return False
+ if not matches:
+ return False
+ window, tab, terminal = matches[0]
+ focus_ghostty_terminal(window, tab, terminal, app)
+ return True
+
+
+def focus_ghostty_terminal(window, tab, terminal, app) -> None:
+ sb_call(tab, "selectTab")
+ sb_call(terminal, "focus")
+ sb_call(window, "activateWindow")
+ sb_call(app, "activate")
+
+
+def values_match_terms(values: list[str], normalized_terms: tuple[str, ...]) -> bool:
+ normalized_values = [normalize_match_text(value) for value in values if value]
+ return any(
+ term in value
+ for term in normalized_terms
+ for value in normalized_values
+ )
+
+
+def normalize_match_text(value: str) -> str:
+ return str(value or "").strip().casefold()
+
+
+def applescript_contains_any(variable_names: tuple[str, ...], terms: tuple[str, ...]) -> str:
+ clauses = [
+ f"{variable_name} contains {applescript_quote(term)}"
+ for variable_name in variable_names
+ for term in terms
+ ]
+ return " or ".join(clauses) if clauses else "false"
def open_macos_terminal_command(command: str) -> None:
@@ -3338,6 +3769,91 @@ def open_iterm_command(command: str) -> None:
run_osascript(script)
+def open_ghostty_command(
+ command: str,
+ hints: TerminalSessionHints | None = None,
+) -> None:
+ if open_ghostty_command_with_scripting_bridge(command, hints):
+ return
+ open_exec_terminal_command(command, terminal_open_target(TERMINAL_APP_GHOSTTY))
+
+
+def open_ghostty_command_with_scripting_bridge(
+ command: str,
+ hints: TerminalSessionHints | None = None,
+) -> bool:
+ app = ghostty_application()
+ if app is None:
+ return False
+ try:
+ config = {
+ "command": f"/bin/zsh -lc {shlex.quote(command)}",
+ "waitAfterCommand": True,
+ }
+ if hints is not None and hints.cwd:
+ config["workingDirectory"] = hints.cwd
+ surface_config = app.newSurfaceConfigurationFrom_(config)
+ if sb_bool(app, "isRunning"):
+ if hints is not None:
+ app.newWindowWithConfiguration_(surface_config)
+ else:
+ window = sb_call(app, "frontWindow")
+ if window is None:
+ app.newWindowWithConfiguration_(surface_config)
+ else:
+ app.newTabIn_withConfiguration_(window, surface_config)
+ else:
+ app.newWindowWithConfiguration_(surface_config)
+ sb_call(app, "activate")
+ except Exception:
+ return False
+ return True
+
+
+def ghostty_application():
+ app_path = installed_terminal_app_path(TERMINAL_APP_GHOSTTY)
+ if app_path is not None:
+ try:
+ return SBApplication.applicationWithURL_(
+ NSURL.fileURLWithPath_(str(app_path))
+ )
+ except Exception:
+ pass
+ try:
+ return SBApplication.applicationWithBundleIdentifier_("com.mitchellh.ghostty")
+ except Exception:
+ return None
+
+
+def sb_elements(collection) -> tuple[object, ...]:
+ if collection is None:
+ return ()
+ try:
+ return tuple(collection)
+ except TypeError:
+ pass
+ try:
+ return tuple(collection.objectAtIndex_(index) for index in range(collection.count()))
+ except Exception:
+ return ()
+
+
+def sb_call(obj, method: str):
+ try:
+ return getattr(obj, method)()
+ except Exception:
+ return None
+
+
+def sb_text(obj, method: str) -> str:
+ value = sb_call(obj, method)
+ return str(value or "")
+
+
+def sb_bool(obj, method: str) -> bool:
+ return bool(sb_call(obj, method))
+
+
def open_custom_terminal_command(command: str, custom_terminal_path: str) -> None:
path = custom_terminal_path.strip()
if not path:
@@ -3434,6 +3950,21 @@ def run_osascript(script: str) -> None:
)
+def run_osascript_bool(script: str) -> bool:
+ try:
+ result = subprocess.run(
+ ["/usr/bin/osascript", "-e", script],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ timeout=1.5,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return result.returncode == 0 and result.stdout.strip() == "1"
+
+
def applescript_quote(value: str) -> str:
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
diff --git a/src/sidepulse_cli/__init__.py b/src/sidepulse_cli/__init__.py
new file mode 100644
index 0000000..b0e9c9a
--- /dev/null
+++ b/src/sidepulse_cli/__init__.py
@@ -0,0 +1 @@
+"""Compatibility package for old sidepulse-cli hook paths."""
diff --git a/src/sidepulse_cli/hook_entry.py b/src/sidepulse_cli/hook_entry.py
new file mode 100644
index 0000000..658fcd7
--- /dev/null
+++ b/src/sidepulse_cli/hook_entry.py
@@ -0,0 +1,17 @@
+"""Compatibility launcher for installations that used the old sidepulse_cli name."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+
+SOURCE_ROOT = Path(__file__).resolve().parents[1]
+if str(SOURCE_ROOT) not in sys.path:
+ sys.path.insert(0, str(SOURCE_ROOT))
+
+from sidepulse.hook_entry import main
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.py
index be09d61..971181e 100644
--- a/tests/test_sidepulse.py
+++ b/tests/test_sidepulse.py
@@ -907,6 +907,213 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(by_title["Resume in Terminal"].state(), 1)
self.assertEqual(by_title["Open in VS Code"].state(), 0)
+ def test_status_bar_recent_statuses_keeps_distinct_sessions_with_same_title(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ older = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:019ffd2e-2060-7ff2-842f-761cb458ccf4",
+ display_name="msdosfs: What is here (019ffd2e)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=20),
+ event_name="Stop",
+ session_id="019ffd2e-2060-7ff2-842f-761cb458ccf4",
+ cwd="/Users/pero/temp/msdosfs",
+ origin="Grok CLI",
+ )
+ newer = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:019ffd37-1458-7d92-b077-3d0f92aedde4",
+ display_name="msdosfs: What is here (019ffd37)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=4),
+ event_name="Stop",
+ session_id="019ffd37-1458-7d92-b077-3d0f92aedde4",
+ cwd="/Users/pero/temp/msdosfs",
+ origin="Grok CLI",
+ )
+ different_folder = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:other",
+ display_name="other: What is here (019ffd99)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=2),
+ event_name="Stop",
+ session_id="019ffd99-0000-0000-0000-000000000000",
+ cwd="/Users/pero/temp/other",
+ origin="Grok CLI",
+ )
+ snapshot = MonitorSnapshot(
+ aggregate=AggregateStatus(AgentMode.COMPLETED, 0, 0, newer),
+ statuses=(older, newer, different_folder),
+ stale_statuses=(),
+ sources=(),
+ collected_at=now,
+ )
+
+ statuses = status_bar.recent_statuses(snapshot)
+
+ self.assertEqual(
+ [status.agent_id for status in statuses],
+ [
+ "grok:session:other",
+ "grok:session:019ffd37-1458-7d92-b077-3d0f92aedde4",
+ "grok:session:019ffd2e-2060-7ff2-842f-761cb458ccf4",
+ ],
+ )
+
+ def test_status_bar_disambiguates_same_visible_session_titles(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ older = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:019ffd2e-2060-7ff2-842f-761cb458ccf4",
+ display_name="msdosfs: What is here (019ffd2e)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=20),
+ event_name="Stop",
+ session_id="019ffd2e-2060-7ff2-842f-761cb458ccf4",
+ cwd="/Users/pero/temp/msdosfs",
+ origin="Grok CLI",
+ )
+ newer = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:019ffd37-1458-7d92-b077-3d0f92aedde4",
+ display_name="msdosfs: What is here (019ffd37)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=4),
+ event_name="Stop",
+ session_id="019ffd37-1458-7d92-b077-3d0f92aedde4",
+ cwd="/Users/pero/temp/msdosfs",
+ origin="Grok CLI",
+ )
+ snapshot = MonitorSnapshot(
+ aggregate=AggregateStatus(AgentMode.COMPLETED, 0, 0, newer),
+ statuses=(older, newer),
+ stale_statuses=(),
+ sources=(),
+ collected_at=now,
+ )
+ target = SimpleNamespace(
+ settings=AgentMonitorSettings(),
+ closed_lid_awake=SimpleNamespace(last_error=None),
+ status_bar_devices=lambda: [],
+ )
+
+ menu = status_bar.build_menu(snapshot, status_bar.STATE_DONE, target)
+ titles = [
+ menu.itemAtIndex_(index).title()
+ for index in range(menu.numberOfItems())
+ if menu.itemAtIndex_(index).title()
+ ]
+
+ self.assertIn("What is here (019ffd37) msdosfs", titles)
+ self.assertIn("What is here (019ffd2e) msdosfs", titles)
+
+ def test_status_bar_recent_statuses_coalesce_subagents_by_session(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ session_id = "f9ccc24e-3dad-4607-95e6-4142428a93cc"
+ main = AgentStatus(
+ provider="claude",
+ agent_id=f"claude:session:{session_id}",
+ display_name=f"peterkuhar.com: so all good? ({session_id[:8]})",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=40),
+ event_name="SessionEnd",
+ session_id=session_id,
+ cwd="/Users/pero/pgit/peterkuhar.com",
+ origin="Claude Code CLI",
+ )
+ subagent = AgentStatus(
+ provider="claude",
+ agent_id="claude:agent:ac7f1721ec697b403",
+ display_name="peterkuhar.com: what is this repo about? (agent ac7f1721)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(seconds=4),
+ event_name="SubagentStop",
+ session_id=session_id,
+ cwd="/Users/pero/pgit/peterkuhar.com",
+ origin="Claude Code CLI",
+ )
+ snapshot = MonitorSnapshot(
+ aggregate=AggregateStatus(AgentMode.COMPLETED, 0, 0, subagent),
+ statuses=(main, subagent),
+ stale_statuses=(),
+ sources=(),
+ collected_at=now,
+ )
+
+ statuses = status_bar.recent_statuses(snapshot)
+
+ self.assertEqual([status.agent_id for status in statuses], [main.agent_id])
+
+ def test_status_bar_recent_statuses_include_recent_done_while_active(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ working = AgentStatus(
+ provider="codex",
+ agent_id="codex:session:working",
+ display_name="project: Working session (working)",
+ mode=AgentMode.TOOL_RUNNING,
+ updated_at=now,
+ event_name="PreToolUse",
+ session_id="working",
+ cwd="/Users/pero/pgit/project",
+ )
+ recent_done = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:recent-done",
+ display_name="other: Recent done (recent-d)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(minutes=8),
+ event_name="Stop",
+ session_id="recent-done",
+ cwd="/Users/pero/pgit/other",
+ stale=True,
+ )
+ old_done = AgentStatus(
+ provider="claude",
+ agent_id="claude:session:old-done",
+ display_name="old: Old done (old-done)",
+ mode=AgentMode.COMPLETED,
+ updated_at=now - timedelta(minutes=25),
+ event_name="Stop",
+ session_id="old-done",
+ cwd="/Users/pero/pgit/old",
+ stale=True,
+ )
+ snapshot = MonitorSnapshot(
+ aggregate=AggregateStatus(AgentMode.TOOL_RUNNING, 1, 2, working),
+ statuses=(working,),
+ stale_statuses=(recent_done, old_done),
+ sources=(),
+ collected_at=now,
+ )
+
+ statuses = status_bar.recent_statuses(snapshot)
+
+ self.assertEqual(
+ [status.session_id for status in statuses],
+ ["working", "recent-done"],
+ )
+
def test_codex_session_options_are_codex_specific(self) -> None:
try:
from sidepulse import status_bar
@@ -943,6 +1150,62 @@ class AgentMonitorTests(unittest.TestCase):
self.assertNotIn("Open in VS Code", titles)
self.assertNotIn("Open Claude App", titles)
+ def test_grok_default_terminal_opener_uses_resume_terminal_setting(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ now = datetime.now(timezone.utc)
+ status = AgentStatus(
+ provider="grok",
+ agent_id="grok:session:abc",
+ display_name="Grok abc",
+ mode=AgentMode.WORKING,
+ updated_at=now,
+ event_name="PreToolUse",
+ session_id="grok-session",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ )
+ settings = AgentMonitorSettings().with_session_terminal(TERMINAL_APP_GHOSTTY)
+ target = SimpleNamespace(settings=settings)
+
+ self.assertEqual(
+ status_bar.provider_open_action_label("grok", SESSION_OPEN_TERMINAL, settings),
+ "Resume in Terminal",
+ )
+ self.assertEqual(
+ status_bar.session_open_action_title(status, SESSION_OPEN_TERMINAL, settings),
+ "Resume in Ghostty",
+ )
+ options = status_bar.build_session_options_menu(status, now, target)
+ titles = [
+ options.itemAtIndex_(index).title()
+ for index in range(options.numberOfItems())
+ if options.itemAtIndex_(index).title()
+ ]
+
+ self.assertIn("Resume in Ghostty", titles)
+
+ fake = SimpleNamespace(
+ settings=settings,
+ set_settings_message=lambda message: None,
+ )
+ with patch("sidepulse.status_bar.open_terminal_command") as open_terminal:
+ status_bar.StatusBarController.open_session(
+ fake,
+ status,
+ None,
+ remember=False,
+ )
+
+ open_terminal.assert_called_once_with(
+ "cd /Users/pero/pgit/sdstatus_bitbang && grok --resume grok-session",
+ terminal_app=TERMINAL_APP_GHOSTTY,
+ custom_terminal_path="",
+ session_hints=status_bar.terminal_session_hints(status),
+ )
+
def test_status_bar_device_submenu_has_brightness_slider(self) -> None:
try:
from sidepulse import status_bar
@@ -1039,9 +1302,16 @@ class AgentMonitorTests(unittest.TestCase):
for index in range(submenu.numberOfItems())
if submenu.itemAtIndex_(index).title()
]
+ submenu_view_count = sum(
+ 1
+ for index in range(submenu.numberOfItems())
+ if submenu.itemAtIndex_(index).view() is not None
+ )
self.assertNotIn("Remove Screen Bar", titles)
self.assertIn("Remove Screen Bar", submenu_titles)
+ self.assertNotIn("Brightness 100%", submenu_titles)
+ self.assertEqual(submenu_view_count, 0)
target.settings = AgentMonitorSettings(virtual_status_device_enabled=False)
target.status_bar_devices = lambda: []
@@ -1279,7 +1549,14 @@ class AgentMonitorTests(unittest.TestCase):
window = status_bar.build_settings_window(target)
- self.assertEqual(window.title(), "SidePulse Agent Monitor Settings")
+ self.assertEqual(window.title(), "SidePulse Settings")
+ tab_views = [
+ view
+ for view in window.contentView().subviews()
+ if hasattr(view, "numberOfTabViewItems")
+ ]
+ self.assertEqual(len(tab_views), 1)
+ self.assertEqual(tab_views[0].numberOfTabViewItems(), 4)
self.assertIn("debug_log_status", target.settings_fields)
self.assertIn("session_terminal", target.settings_fields)
self.assertIn("custom_terminal_path", target.settings_fields)
@@ -1370,25 +1647,13 @@ class AgentMonitorTests(unittest.TestCase):
"sidepulse.status_bar.installed_terminal_app_path",
return_value=Path("/Applications/Ghostty.app"),
),
- patch("sidepulse.status_bar.subprocess.Popen") as popen,
+ patch("sidepulse.status_bar.open_ghostty_command") as open_ghostty,
):
status_bar.open_terminal_command(
"echo hello",
terminal_app=TERMINAL_APP_GHOSTTY,
)
- self.assertEqual(
- popen.call_args.args[0],
- [
- "/usr/bin/open",
- "-n",
- "/Applications/Ghostty.app",
- "--args",
- "-e",
- "/bin/zsh",
- "-lc",
- "echo hello",
- ],
- )
+ open_ghostty.assert_called_once_with("echo hello", None)
with (
patch("sidepulse.status_bar.terminal_app_installed", return_value=False),
@@ -1536,6 +1801,441 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(args[:2], ["/usr/bin/osascript", "-e"])
self.assertIn('tell application "Terminal"', args[2])
+ def test_status_bar_resume_terminal_focuses_existing_terminal_session(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ hints = status_bar.TerminalSessionHints(
+ provider="codex",
+ session_id="019ee395-2f64-7cc3-b566-afcc1d626160",
+ cwd="/Users/pero/pgit/pixiepulse-bridge",
+ title="Codex Refine README agent status modes pixiepulse-bridge",
+ )
+
+ with (
+ patch(
+ "sidepulse.status_bar.subprocess.run",
+ return_value=subprocess.CompletedProcess(
+ ["/usr/bin/osascript"],
+ 0,
+ stdout="1\n",
+ ),
+ ) as run,
+ patch("sidepulse.status_bar.subprocess.Popen") as popen,
+ ):
+ status_bar.open_terminal_command(
+ "cd /Users/pero/pgit/pixiepulse-bridge && codex resume 019ee395-2f64-7cc3-b566-afcc1d626160",
+ session_hints=hints,
+ )
+
+ script = run.call_args.args[0][2]
+ self.assertIn('tell application "Terminal"', script)
+ self.assertIn("019ee395-2f64-7cc3-b566-afcc1d626160", script)
+ self.assertIn("selected tab of windowRef", script)
+ popen.assert_not_called()
+
+ def test_status_bar_resume_terminal_falls_back_with_session_title(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ hints = status_bar.TerminalSessionHints(
+ provider="grok",
+ session_id="grok-session",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ title="Grok all good sdstatus_bitbang",
+ )
+
+ with (
+ patch(
+ "sidepulse.status_bar.subprocess.run",
+ return_value=subprocess.CompletedProcess(
+ ["/usr/bin/osascript"],
+ 0,
+ stdout="0\n",
+ ),
+ ) as run,
+ patch("sidepulse.status_bar.subprocess.Popen") as popen,
+ ):
+ status_bar.open_terminal_command(
+ "cd /Users/pero/pgit/sdstatus_bitbang && grok --resume grok-session",
+ session_hints=hints,
+ )
+
+ script = run.call_args.args[0][2]
+ self.assertIn("grok-session", script)
+ launch_script = popen.call_args.args[0][2]
+ self.assertIn("SidePulse Grok all good sdstatus_bitbang (grok-ses)", launch_script)
+ self.assertIn("grok --resume grok-session", launch_script)
+
+ def test_status_bar_resume_iterm_focuses_existing_session(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ hints = status_bar.TerminalSessionHints(
+ provider="claude",
+ session_id="claude-session",
+ cwd="/Users/pero/pgit/app",
+ title="Claude app",
+ )
+
+ with (
+ patch(
+ "sidepulse.status_bar.subprocess.run",
+ return_value=subprocess.CompletedProcess(
+ ["/usr/bin/osascript"],
+ 0,
+ stdout="1\n",
+ ),
+ ) as run,
+ patch("sidepulse.status_bar.subprocess.Popen") as popen,
+ ):
+ status_bar.open_terminal_command(
+ "cd /Users/pero/pgit/app && claude --resume claude-session",
+ terminal_app=TERMINAL_APP_ITERM,
+ session_hints=hints,
+ )
+
+ script = run.call_args.args[0][2]
+ self.assertIn('tell application "iTerm"', script)
+ self.assertIn("select tabRef", script)
+ popen.assert_not_called()
+
+ def test_status_bar_resume_ghostty_focuses_existing_surface(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ class FakeTerminal:
+ def __init__(self) -> None:
+ self.focused = False
+
+ def name(self):
+ return "SidePulse Grok all good sdstatus_bitbang (grok-ses)"
+
+ def workingDirectory(self):
+ return "/Users/pero/pgit/sdstatus_bitbang"
+
+ def focus(self):
+ self.focused = True
+
+ class FakeTab:
+ def __init__(self, terminal) -> None:
+ self.terminal = terminal
+ self.selected = False
+
+ def name(self):
+ return "grok"
+
+ def terminals(self):
+ return [self.terminal]
+
+ def selectTab(self):
+ self.selected = True
+
+ class FakeWindow:
+ def __init__(self, tab) -> None:
+ self.tab = tab
+ self.activated = False
+
+ def name(self):
+ return "Ghostty"
+
+ def tabs(self):
+ return [self.tab]
+
+ def activateWindow(self):
+ self.activated = True
+
+ class FakeGhostty:
+ def __init__(self, window) -> None:
+ self.window = window
+ self.activated = False
+
+ def isRunning(self):
+ return True
+
+ def windows(self):
+ return [self.window]
+
+ def activate(self):
+ self.activated = True
+
+ terminal = FakeTerminal()
+ tab = FakeTab(terminal)
+ window = FakeWindow(tab)
+ app = FakeGhostty(window)
+ hints = status_bar.TerminalSessionHints(
+ provider="grok",
+ session_id="grok-session",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ title="Grok all good sdstatus_bitbang",
+ )
+
+ with patch("sidepulse.status_bar.ghostty_application", return_value=app):
+ self.assertTrue(status_bar.focus_ghostty_session(hints))
+
+ self.assertTrue(tab.selected)
+ self.assertTrue(terminal.focused)
+ self.assertTrue(window.activated)
+ self.assertTrue(app.activated)
+
+ def test_status_bar_resume_ghostty_focuses_unique_bare_grok_title(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ class FakeTerminal:
+ def __init__(self, name: str) -> None:
+ self._name = name
+ self.focused = False
+
+ def name(self):
+ return self._name
+
+ def workingDirectory(self):
+ return "/Users/pero/temp/msdosfs"
+
+ def focus(self):
+ self.focused = True
+
+ class FakeTab:
+ def __init__(self, terminal) -> None:
+ self.terminal = terminal
+ self.selected = False
+
+ def name(self):
+ return self.terminal.name()
+
+ def terminals(self):
+ return [self.terminal]
+
+ def selectTab(self):
+ self.selected = True
+
+ class FakeWindow:
+ def __init__(self, tab) -> None:
+ self.tab = tab
+ self.activated = False
+
+ def name(self):
+ return "Ghostty"
+
+ def tabs(self):
+ return [self.tab]
+
+ def activateWindow(self):
+ self.activated = True
+
+ class FakeGhostty:
+ def __init__(self, windows) -> None:
+ self._windows = windows
+ self.activated = False
+
+ def isRunning(self):
+ return True
+
+ def windows(self):
+ return self._windows
+
+ def activate(self):
+ self.activated = True
+
+ wrong_terminal = FakeTerminal("plain shell")
+ right_terminal = FakeTerminal("✳ Identify unknown code or concept")
+ wrong_window = FakeWindow(FakeTab(wrong_terminal))
+ right_window = FakeWindow(FakeTab(right_terminal))
+ app = FakeGhostty([wrong_window, right_window])
+ hints = status_bar.TerminalSessionHints(
+ provider="grok",
+ session_id="grok-session",
+ cwd="/Users/pero/temp/msdosfs",
+ title="Grok Identify unknown code or concept msdosfs",
+ match_title="Identify unknown code or concept",
+ )
+
+ with patch("sidepulse.status_bar.ghostty_application", return_value=app):
+ self.assertTrue(status_bar.focus_ghostty_session(hints))
+
+ self.assertFalse(wrong_terminal.focused)
+ self.assertFalse(wrong_window.activated)
+ self.assertTrue(right_terminal.focused)
+ self.assertTrue(right_window.activated)
+
+ def test_status_bar_resume_ghostty_ignores_same_cwd_without_session_marker(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ class FakeTerminal:
+ def __init__(self, name: str) -> None:
+ self._name = name
+ self.focused = False
+
+ def name(self):
+ return self._name
+
+ def workingDirectory(self):
+ return "/Users/pero/pgit/sdstatus_bitbang"
+
+ def focus(self):
+ self.focused = True
+
+ class FakeTab:
+ def __init__(self, terminal) -> None:
+ self.terminal = terminal
+ self.selected = False
+
+ def name(self):
+ return self.terminal.name()
+
+ def terminals(self):
+ return [self.terminal]
+
+ def selectTab(self):
+ self.selected = True
+
+ class FakeWindow:
+ def __init__(self, tab) -> None:
+ self.tab = tab
+ self.activated = False
+
+ def name(self):
+ return "Ghostty"
+
+ def tabs(self):
+ return [self.tab]
+
+ def activateWindow(self):
+ self.activated = True
+
+ class FakeGhostty:
+ def __init__(self, windows) -> None:
+ self._windows = windows
+ self.activated = False
+
+ def isRunning(self):
+ return True
+
+ def windows(self):
+ return self._windows
+
+ def activate(self):
+ self.activated = True
+
+ wrong_terminal = FakeTerminal("plain shell")
+ right_terminal = FakeTerminal("SidePulse Grok all good sdstatus_bitbang (grok-ses)")
+ wrong_window = FakeWindow(FakeTab(wrong_terminal))
+ right_window = FakeWindow(FakeTab(right_terminal))
+ app = FakeGhostty([wrong_window, right_window])
+ hints = status_bar.TerminalSessionHints(
+ provider="grok",
+ session_id="grok-session",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ title="Grok all good sdstatus_bitbang",
+ )
+
+ with patch("sidepulse.status_bar.ghostty_application", return_value=app):
+ self.assertTrue(status_bar.focus_ghostty_session(hints))
+
+ self.assertFalse(wrong_terminal.focused)
+ self.assertFalse(wrong_window.activated)
+ self.assertTrue(right_terminal.focused)
+ self.assertTrue(right_window.activated)
+
+ def test_status_bar_resume_ghostty_falls_back_to_new_window(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ class FakeWindow:
+ pass
+
+ class FakeGhostty:
+ def __init__(self) -> None:
+ self.window = FakeWindow()
+ self.config = None
+ self.new_tab_window = None
+ self.new_window_config = None
+ self.activated = False
+
+ def isRunning(self):
+ return True
+
+ def frontWindow(self):
+ return self.window
+
+ def newSurfaceConfigurationFrom_(self, config):
+ self.config = config
+ return config
+
+ def newTabIn_withConfiguration_(self, window, config):
+ self.new_tab_window = window
+ self.config = config
+
+ def newWindowWithConfiguration_(self, config):
+ self.new_window_config = config
+ self.config = config
+
+ def activate(self):
+ self.activated = True
+
+ app = FakeGhostty()
+ hints = status_bar.TerminalSessionHints(
+ provider="grok",
+ session_id="grok-session",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ title="Grok all good sdstatus_bitbang",
+ )
+
+ with patch("sidepulse.status_bar.ghostty_application", return_value=app):
+ self.assertTrue(
+ status_bar.open_ghostty_command_with_scripting_bridge(
+ "cd /Users/pero/pgit/sdstatus_bitbang && grok --resume grok-session",
+ hints,
+ )
+ )
+
+ self.assertIsNone(app.new_tab_window)
+ self.assertIs(app.new_window_config, app.config)
+ self.assertTrue(app.activated)
+ self.assertEqual(app.config["workingDirectory"], "/Users/pero/pgit/sdstatus_bitbang")
+ self.assertIn("grok --resume grok-session", app.config["command"])
+
+ def test_status_bar_resume_ghostty_uses_focus_before_new_tab(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ hints = status_bar.TerminalSessionHints(
+ provider="grok",
+ session_id="grok-session",
+ cwd="/Users/pero/pgit/sdstatus_bitbang",
+ title="Grok all good sdstatus_bitbang",
+ )
+
+ with (
+ patch("sidepulse.status_bar.focus_ghostty_session", return_value=True),
+ patch("sidepulse.status_bar.open_ghostty_command") as open_ghostty,
+ ):
+ status_bar.open_terminal_command(
+ "cd /Users/pero/pgit/sdstatus_bitbang && grok --resume grok-session",
+ terminal_app=TERMINAL_APP_GHOSTTY,
+ session_hints=hints,
+ )
+
+ open_ghostty.assert_not_called()
+
def test_status_bar_detects_installed_terminal_apps(self) -> None:
try:
from sidepulse import status_bar
@@ -1605,6 +2305,7 @@ class AgentMonitorTests(unittest.TestCase):
"cd /Users/pero/pgit/sdstatus_bitbang && claude --resume 1ca4348e-2aec-4147-9e81-d7d56364d257",
terminal_app=TERMINAL_APP_ITERM,
custom_terminal_path="",
+ session_hints=status_bar.terminal_session_hints(status),
)
self.assertEqual(
fake.settings.session_open_action("claude", "Claude in VS Code"),
@@ -1828,6 +2529,83 @@ class AgentMonitorTests(unittest.TestCase):
self.assertIn("matcher", data["hooks"]["PreToolUse"][-1])
self.assertNotIn("matcher", data["hooks"]["SessionStart"][-1])
+ def test_grok_installer_removes_legacy_sidepulse_hook_files(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ config = base / "hooks" / "sidepulse.json"
+ log = base / "grok.jsonl"
+ config.parent.mkdir()
+ old_backup = config.parent / "sidepulse.json.bak.20260813T214318Z"
+ old_backup.write_text('{"hooks": {"Stop": [{"hooks": []}]}}\n')
+ stale = config.parent / "sidepulse-cli.json"
+ stale.write_text(
+ json.dumps(
+ {
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": (
+ "python3 /missing/sidepulse_cli/hook_entry.py "
+ f"--provider grok --log {log}"
+ ),
+ }
+ ],
+ }
+ ]
+ }
+ }
+ )
+ )
+ mixed = config.parent / "sidepulse-agent-monitor.json"
+ mixed.write_text(
+ json.dumps(
+ {
+ "hooks": {
+ "Notification": [
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": (
+ "python3 /missing/agent_monitor/hook_entry.py "
+ f"--provider grok --log {log}"
+ ),
+ },
+ {
+ "type": "command",
+ "command": "echo keep >> /tmp/other.log",
+ },
+ ],
+ }
+ ]
+ }
+ }
+ )
+ )
+
+ result = install_grok_hooks(
+ log_path=log,
+ config_path=config,
+ python_executable="python3",
+ )
+
+ self.assertTrue(result.changed)
+ self.assertFalse(stale.exists())
+ self.assertFalse(old_backup.exists())
+ self.assertTrue((base / "sidepulse-hook-backups" / old_backup.name).exists())
+ data = json.loads(mixed.read_text())
+ commands = [
+ hook["command"]
+ for entry in data["hooks"]["Notification"]
+ for hook in entry["hooks"]
+ ]
+ self.assertEqual(commands, ["echo keep >> /tmp/other.log"])
+
def test_codex_uninstaller_removes_monitor_hooks_and_preserves_config(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
@@ -1935,6 +2713,40 @@ class AgentMonitorTests(unittest.TestCase):
]
self.assertEqual(commands, ["echo keep >> /tmp/other.log"])
+ def test_grok_uninstaller_removes_legacy_sidepulse_hook_files(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ config = base / "hooks" / "sidepulse.json"
+ log = base / "grok.jsonl"
+ config.parent.mkdir()
+ stale = config.parent / "sidepulse-cli.json"
+ stale.write_text(
+ json.dumps(
+ {
+ "hooks": {
+ "Stop": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": (
+ "python3 /missing/sidepulse_cli/hook_entry.py "
+ f"--provider grok --log {log}"
+ ),
+ }
+ ]
+ }
+ ]
+ }
+ }
+ )
+ )
+
+ result = uninstall_grok_hooks(log_path=log, config_path=config)
+
+ self.assertTrue(result.changed)
+ self.assertFalse(stale.exists())
+
def test_detect_grok_config_reads_managed_hook_file(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
@@ -2954,6 +3766,41 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(reloaded.session_terminal_app, TERMINAL_APP_ITERM)
self.assertEqual(reloaded.custom_terminal_path, "/Applications/WezTerm.app")
+ def test_settings_round_trip_grok_session_opening_is_split_from_terminal(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ settings_path = Path(tmp) / "settings.json"
+ settings = (
+ AgentMonitorSettings()
+ .with_provider_session_open_action("grok", SESSION_OPEN_TERMINAL)
+ .with_session_terminal(TERMINAL_APP_GHOSTTY)
+ )
+
+ save_settings(settings, settings_path)
+ loaded = load_settings(settings_path)
+
+ self.assertEqual(loaded.grok_session_open_action, SESSION_OPEN_TERMINAL)
+ self.assertEqual(loaded.session_open_action("grok"), SESSION_OPEN_TERMINAL)
+ self.assertEqual(loaded.session_terminal_app, TERMINAL_APP_GHOSTTY)
+ self.assertNotIn("grok", loaded.session_open_preferences)
+
+ def test_settings_migrates_legacy_grok_session_open_preference(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ settings_path = Path(tmp) / "settings.json"
+ settings_path.write_text(
+ json.dumps(
+ {
+ "session_open_preferences": {"grok": SESSION_OPEN_TERMINAL},
+ "session_terminal": {"app": TERMINAL_APP_ITERM},
+ }
+ )
+ )
+
+ loaded = load_settings(settings_path)
+
+ self.assertEqual(loaded.grok_session_open_action, SESSION_OPEN_TERMINAL)
+ self.assertEqual(loaded.session_terminal_app, TERMINAL_APP_ITERM)
+ self.assertNotIn("grok", loaded.session_open_preferences)
+
def test_settings_round_trip_closed_lid_policy_and_animations(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
settings_path = Path(tmp) / "settings.json"
@@ -3124,9 +3971,45 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(
command,
f"{sys.executable} agent-monitor hook-log --provider codex "
- "--log '/tmp/codex events.jsonl'",
+ "--log '/tmp/codex events.jsonl' ; true",
)
+ def test_hook_command_is_fail_open(self) -> None:
+ command = hook_command("grok", Path("/tmp/grok.jsonl"), python_executable="python3")
+
+ self.assertTrue(command.endswith("; true"))
+
+ def test_legacy_hook_entry_points_still_log_events(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ log = base / "grok.jsonl"
+ payload = b'{"hookEventName":"pre_tool_use","sessionId":"legacy"}'
+ root = Path(__file__).resolve().parents[1]
+ for script in (
+ root / "src" / "agent_monitor" / "hook_entry.py",
+ root / "src" / "sidepulse_cli" / "hook_entry.py",
+ ):
+ result = subprocess.run(
+ [
+ sys.executable,
+ str(script),
+ "--provider",
+ "grok",
+ "--log",
+ str(log),
+ ],
+ input=payload,
+ env={**os.environ, "SIDEPULSE_DISABLE_EVENT_SOCKET": "1"},
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ check=False,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr.decode())
+
+ lines = log.read_text().splitlines()
+ self.assertEqual(len(lines), 2)
+ self.assertTrue(all(json.loads(line)["sessionId"] == "legacy" for line in lines))
+
def test_status_bar_install_removes_legacy_com_sidepulse_plist(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
@@ -4737,6 +5620,56 @@ team id YOUR_TEAM_ID, push key '/path/to/AuthKey_YOUR_KEY_ID.p8'
self.assertIn("Refine README agent status modes", name)
self.assertNotIn("Why are we burning", name)
+ def test_session_display_name_keeps_initial_prompt_title(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ log = base / "grok.jsonl"
+ now = datetime.now(timezone.utc)
+ session_id = "019ffd37-1458-7d92-b077-3d0f92aedde4"
+ log.write_text(
+ "\n".join(
+ [
+ json.dumps(
+ {
+ "logged_at": now.isoformat(),
+ "hookEventName": "user_prompt_submit",
+ "sessionId": session_id,
+ "workspaceRoot": "/Users/pero/temp/msdosfs",
+ "prompt": "<user_query>\nWhat is here\n</user_query>",
+ }
+ ),
+ json.dumps(
+ {
+ "logged_at": (now + timedelta(seconds=30)).isoformat(),
+ "hookEventName": "user_prompt_submit",
+ "sessionId": session_id,
+ "workspaceRoot": "/Users/pero/temp/msdosfs",
+ "prompt": "<user_query>\nNow check permissions\n</user_query>",
+ }
+ ),
+ json.dumps(
+ {
+ "logged_at": (now + timedelta(seconds=60)).isoformat(),
+ "hookEventName": "stop",
+ "sessionId": session_id,
+ "workspaceRoot": "/Users/pero/temp/msdosfs",
+ }
+ ),
+ ]
+ )
+ + "\n"
+ )
+
+ monitor = AgentMonitor(
+ sources=(SourceSpec("grok", log),),
+ stale_after_seconds=999999999,
+ )
+ snapshot = monitor.snapshot()
+
+ name = snapshot.statuses[0].display_name
+ self.assertIn("What is here", name)
+ self.assertNotIn("Now check permissions", name)
+
def test_live_monitor_refreshes_loaded_codex_display_name_from_session_index(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)