Skip to content

CLI for SidePulse

Python

Find the event socket across state dirs, and resolve provider icons by app name (#37)

ben49827c2e0960
diff --git a/src/sidepulse/ipc.py b/src/sidepulse/ipc.py
index a9cb7e4..7bb09ed 100644
--- a/src/sidepulse/ipc.py
+++ b/src/sidepulse/ipc.py
@@ -6,7 +6,7 @@ import threading
from pathlib import Path
from typing import Callable
-from .providers import default_state_dir
+from .providers import candidate_state_dirs, default_state_dir
MAX_EVENT_BYTES = 1024 * 1024
@@ -17,6 +17,11 @@ def default_event_socket_path() -> Path:
return default_state_dir() / "events.sock"
+def candidate_event_socket_paths() -> tuple[Path, ...]:
+ """Socket paths a listening app may have bound, most likely first."""
+ return tuple(directory / "events.sock" for directory in candidate_state_dirs())
+
+
def default_latest_state_path() -> Path:
return default_state_dir() / "latest.json"
@@ -28,7 +33,6 @@ def send_hook_event(
socket_path: Path | None = None,
timeout: float = HOOK_EVENT_SEND_TIMEOUT_SECONDS,
) -> bool:
- target = (socket_path or default_event_socket_path()).expanduser()
payload = json.dumps(
{"provider": provider, "line": line},
separators=(",", ":"),
@@ -37,6 +41,17 @@ def send_hook_event(
if len(payload) > MAX_EVENT_BYTES:
return False
+ if socket_path is not None:
+ return _send_payload(socket_path.expanduser(), payload, timeout)
+
+ # The caller and the app can resolve different state dirs, so try each candidate.
+ for target in candidate_event_socket_paths():
+ if _send_payload(target.expanduser(), payload, timeout):
+ return True
+ return False
+
+
+def _send_payload(target: Path, payload: bytes, timeout: float) -> bool:
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.settimeout(timeout)
try:
diff --git a/src/sidepulse/models.py b/src/sidepulse/models.py
index 1628d3a..1cc71c2 100644
--- a/src/sidepulse/models.py
+++ b/src/sidepulse/models.py
@@ -158,4 +158,6 @@ def provider_label(provider: str) -> str:
"codex": "Codex",
"claude": "Claude",
"grok": "Grok",
+ # Lowercase is the product's own spelling, and provider.title() would break it.
+ "opencode": "opencode",
}.get(provider, provider.title())
diff --git a/src/sidepulse/providers.py b/src/sidepulse/providers.py
index 97c715d..60942c3 100644
--- a/src/sidepulse/providers.py
+++ b/src/sidepulse/providers.py
@@ -95,6 +95,21 @@ def default_state_dir(home: Path | None = None) -> Path:
return base / ".local" / "state" / "sidepulse" / "agent-monitor"
+def candidate_state_dirs(home: Path | None = None) -> tuple[Path, ...]:
+ """Every state dir a peer process may have resolved, most likely first.
+
+ ``default_state_dir`` reads ``XDG_STATE_HOME`` from the calling process. Hooks run in
+ the user's shell, while the status bar app runs from a LaunchAgent whose plist forwards
+ only ``PATH`` and ``PYTHONUNBUFFERED``. Whenever the user exports ``XDG_STATE_HOME``,
+ the two processes resolve different directories and never meet.
+ """
+ dirs = [default_state_dir(home)]
+ fallback = (home or Path.home()) / ".local" / "state" / "sidepulse" / "agent-monitor"
+ if fallback not in dirs:
+ dirs.append(fallback)
+ return tuple(dirs)
+
+
def default_log_path(provider: str, home: Path | None = None) -> Path:
suffix = "jsonl"
return default_state_dir(home) / f"{provider}.{suffix}"
diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.py
index 6cb2b73..eb3853b 100644
--- a/src/sidepulse/status_bar.py
+++ b/src/sidepulse/status_bar.py
@@ -4095,8 +4095,16 @@ def provider_icon_for_provider(provider: str):
elif provider == "grok":
image = app_icon("/Applications/Grok.app")
image = image or grok_badge_icon()
+ elif provider == "opencode":
+ image = app_icon("/Applications/OpenCode.app")
+ image = image or image_for_symbol(
+ "chevron.left.forwardslash.chevron.right", "opencode"
+ )
else:
- image = image_for_symbol("terminal", provider.title() or "Agent")
+ # Any other provider resolves its own app by name, so a new agent needs no branch
+ # here. Only providers with an alias or a custom glyph need one.
+ image = provider_app_icon(provider)
+ image = image or image_for_symbol("terminal", provider_label(provider) or "Agent")
_provider_icon_cache[provider] = image
return image
@@ -4248,6 +4256,21 @@ def grok_badge_icon():
return image
+def provider_app_icon(provider: str):
+ """Resolve a provider's own application icon by name.
+
+ LaunchServices matches an application name case-insensitively, so a provider named
+ "opencode" finds OpenCode.app and "ghostty" finds Ghostty.app. This keeps new
+ providers from needing a branch in provider_icon_for_provider. Returns None when no
+ application matches, which includes every provider that is not an installed app.
+ """
+ try:
+ path = NSWorkspace.sharedWorkspace().fullPathForApplication_(provider)
+ except Exception:
+ return None
+ return app_icon(path) if path else None
+
+
def app_icon(path: str):
if path in _app_icon_cache:
return _app_icon_cache[path]
diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.py
index b960646..424b910 100644
--- a/tests/test_sidepulse.py
+++ b/tests/test_sidepulse.py
@@ -570,6 +570,49 @@ class AgentMonitorTests(unittest.TestCase):
finally:
server.stop()
+ def test_hook_event_reaches_app_when_xdg_state_home_differs(self) -> None:
+ """A shell hook must still find an app that resolved another state dir.
+
+ The LaunchAgent plist forwards only PATH and PYTHONUNBUFFERED, so the app never
+ sees XDG_STATE_HOME and binds under ~/.local/state. A hook started from the user's
+ shell does see it. Before candidate probing the send failed silently.
+ """
+ # An AF_UNIX path is capped near 104 bytes and the macOS default temp dir is long,
+ # so root this fixture somewhere short.
+ with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
+ home = Path(tmp) / "home"
+ app_dir = home / ".local" / "state" / "sidepulse" / "agent-monitor"
+ app_dir.mkdir(parents=True)
+
+ received: list[tuple[str, dict]] = []
+ server = HookEventServer(
+ lambda provider, line: received.append((provider, line)),
+ socket_path=app_dir / "events.sock",
+ )
+ try:
+ server.start()
+ environment = {
+ "HOME": str(home),
+ "XDG_STATE_HOME": str(Path(tmp) / "xdg"),
+ }
+ with patch.dict(os.environ, environment):
+ sent = send_hook_event(
+ "claude",
+ {"hook_event_name": "Stop", "session_id": "claude-session"},
+ timeout=0.5,
+ )
+
+ deadline = time.time() + 1
+ while sent and not received and time.time() < deadline:
+ time.sleep(0.01)
+
+ self.assertTrue(sent)
+ self.assertTrue(received)
+ self.assertEqual(received[0][0], "claude")
+ self.assertEqual(received[0][1]["hook_event_name"], "Stop")
+ finally:
+ server.stop()
+
def test_live_sidepulse_ingests_events_and_persists_latest_state(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
diff --git a/tests/test_status_bar_ui.py b/tests/test_status_bar_ui.py
index e1258a9..0e7a19f 100644
--- a/tests/test_status_bar_ui.py
+++ b/tests/test_status_bar_ui.py
@@ -392,10 +392,66 @@ class IconTests(StatusBarTestCase):
self.assertIsInstance(sb.session_row_icon_for_status(status), NSImage)
def test_provider_icons_do_not_raise(self):
- for provider in ("claude", "codex", "grok", "nonsense"):
+ for provider in ("claude", "codex", "grok", "opencode", "nonsense"):
with self.subTest(provider=provider):
sb.provider_icon_for_provider(provider)
+ def test_mapped_providers_look_up_their_own_bundle(self):
+ """The generic fallback would absorb a deleted branch without failing.
+
+ provider_app_icon("codex") resolves ChatGPT.app by name on its own, so removing
+ the codex branch still yields an icon and no test notices. Pin the bundle that
+ each explicit branch reads.
+ """
+ wanted = {
+ "codex": "/Applications/Codex.app",
+ "claude": "/Applications/Claude.app",
+ "grok": "/Applications/Grok.app",
+ }
+ for provider, bundle in wanted.items():
+ with self.subTest(provider=provider):
+ looked_up: list[str] = []
+ sb._provider_icon_cache.pop(provider, None)
+ self.addCleanup(sb._provider_icon_cache.pop, provider, None)
+ with patch.object(
+ sb, "app_icon", lambda path: looked_up.append(path) and None
+ ):
+ sb.provider_icon_for_provider(provider)
+ self.assertIn(bundle, looked_up)
+
+ def test_unmapped_provider_tries_its_own_app_before_the_glyph(self):
+ """The terminal glyph always returns an image, so it hides a missing lookup.
+
+ Assert that an unmapped provider consults its own application first. Without that
+ step a new agent silently renders as a bare terminal icon.
+ """
+ looked_up: list[str] = []
+ sb._provider_icon_cache.pop("someagent", None)
+ self.addCleanup(sb._provider_icon_cache.pop, "someagent", None)
+ with patch.object(sb, "provider_app_icon", lambda p: looked_up.append(p) and None):
+ image = sb.provider_icon_for_provider("someagent")
+ self.assertEqual(looked_up, ["someagent"])
+ self.assertIsInstance(image, NSImage)
+
+ def test_provider_app_icon_resolves_an_installed_app_by_name(self):
+ """Pin the name matching itself, which is what makes the generic path work."""
+ installed = next(
+ (
+ name
+ for name, path in (
+ ("opencode", "/Applications/OpenCode.app"),
+ ("claude", "/Applications/Claude.app"),
+ ("grok", "/Applications/Grok.app"),
+ )
+ if Path(path).exists()
+ ),
+ None,
+ )
+ if installed is None: # pragma: no cover
+ self.skipTest("no known agent application installed")
+ self.assertIsInstance(sb.provider_app_icon(installed), NSImage)
+ self.assertIsNone(sb.provider_app_icon("definitely-not-an-installed-app"))
+
def test_state_symbols_render(self):
for state in (sb.STATE_IDLE, sb.STATE_WORKING, sb.STATE_DONE, sb.STATE_ASK):
with self.subTest(state=state.label):