CLI for SidePulse
Python
Add test suites for dependencies, agent hooks, and status-bar UI
Peter Kuhar609ed11d1e18
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 058ed02..a71049a 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -8,8 +8,13 @@ on:- "v*"jobs:+ # A tagged release must not ship code the test suite rejects.+ tests:+ uses: ./.github/workflows/tests.yml+build:name: Build distribution+ needs: testsruns-on: ubuntu-lateststeps:- uses: actions/checkout@v4diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlnew file mode 100644index 0000000..d200e64--- /dev/null+++ b/.github/workflows/tests.yml@@ -0,0 +1,68 @@+name: Tests++on:+ push:+ branches: ["**"]+ pull_request:+ workflow_call: # so the release pipeline can gate on this++jobs:+ macos:+ name: macOS / Python ${{ matrix.python-version }}+ runs-on: macos-latest+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.12"]+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: ${{ matrix.python-version }}++ # Install from pyproject alone. If a dependency is missing from the+ # declared list, it is missing here too, and the import contract tests+ # in tests/test_packaging.py fail -- which is the whole point.+ - name: Install package+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e '.[test]'++ - name: Import contract+ run: python -m pytest tests/test_packaging.py -v++ - name: Agent hook stability+ run: python -m pytest tests/test_hook_stability.py -v++ # Fails rather than skips if AppKit is unavailable: macOS runners have a+ # window server, so a skip here would mean the UI coverage vanished.+ - name: Status-bar UI+ env:+ SIDEPULSE_REQUIRE_UI_TESTS: "1"+ run: python -m pytest tests/test_status_bar_ui.py -v++ - name: Full suite+ run: python -m pytest tests -q++ linux:+ name: Linux / Python ${{ matrix.python-version }}+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.12"]+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: ${{ matrix.python-version }}++ - name: Install package+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e '.[test]'++ # The macOS-only modules are darwin-gated, so this catches a top-level+ # AppKit import creeping into a cross-platform module.+ - name: Platform-independent suite+ run: python -m pytest tests -qdiff --git a/.gitignore b/.gitignoreindex 7597c33..4614643 100644--- a/.gitignore+++ b/.gitignore@@ -7,3 +7,5 @@ __pycache__/.ruff_cache/build/dist/+.venv/+venv/diff --git a/README.md b/README.mdindex 94ad686..2586b40 100644--- a/README.md+++ b/README.md@@ -554,3 +554,23 @@ python3 examples/audio_monitor.py --device /Volumes/SidePulsePro --gain-db 8 --r...####++## Tests++```sh+python3 -m pip install -e '.[test]'+python3 -m pytest tests -q+```++CI runs the suite on macOS and Linux, and a tagged release will not publish+unless it passes. Four files, each guarding a different failure mode:++| File | Guards against |+| --- | --- |+| `tests/test_packaging.py` | Importing a module no dependency declares. Every module-level import must resolve to a declared distribution, so a new `import` without a matching `pyproject.toml` entry fails at commit time rather than on a user's machine. |+| `tests/test_hook_stability.py` | Breaking somebody's agent session. Hooks must exit 0 and stay silent on stdout for every input and internal failure — and must still work with PyObjC entirely unavailable. |+| `tests/test_status_bar_ui.py` | Menus and windows that build but crash when clicked. Runs headlessly against a real `StatusBarController`; verifies every selector string resolves to a real method. |+| `tests/test_sidepulse.py` | Collector, settings, install, and provider logic. |++The UI tests skip if AppKit is unavailable. Set `SIDEPULSE_REQUIRE_UI_TESTS=1`+to turn that skip into a failure, which is how CI runs them.diff --git a/pyproject.toml b/pyproject.tomlindex c6a5af3..ff56e56 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -44,6 +44,11 @@ Issues = "https://github.com/inteliwear/sidepulse/issues"# default now, so this extra is a no-op alias.status-bar = []reply-classifier = ["mlx-lm>=0.24,<1"]+test = [+ "pytest>=7",+ # tests/test_packaging.py reads pyproject.toml; tomllib is 3.11+.+ "tomli>=2; python_version < '3.11'",+][project.scripts]sidepulse = "sidepulse.cli:sidepulse_main"diff --git a/tests/test_hook_stability.py b/tests/test_hook_stability.pynew file mode 100644index 0000000..19d7126--- /dev/null+++ b/tests/test_hook_stability.py@@ -0,0 +1,485 @@+"""Agent hook stability tests.++SidePulse installs itself into the hook configuration of Claude Code, Codex,+and Grok. Those hooks run inside somebody else's agent session on every tool+call. The contract is therefore narrow and absolute:++1. **Never non-zero.** A failing hook can abort or degrade the agent turn.+ ``hook_log_main`` must return 0 for every input and every internal failure.+2. **Never noisy on stdout.** Hook stdout is interpreted by the agent runtime;+ stray output corrupts it.+3. **Never hang.** A blocking hook stalls every tool call.+4. **Still actually work.** Fail-open is only acceptable if the happy path+ genuinely logs -- otherwise "return 0" would pass these tests while+ silently recording nothing. ``HappyPathTests`` pins that down.+"""++from __future__ import annotations++import io+import json+import os+import subprocess+import sys+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path+from unittest.mock import patch++from sidepulse import hook as hook_module+from sidepulse.hook import format_hook_payload, hook_log_main, routed_hook_payload+from sidepulse.install import fail_open_command, hook_command++REPO_ROOT = Path(__file__).resolve().parents[1]+SRC_ROOT = REPO_ROOT / "src"++PROVIDERS = ("claude", "codex", "grok")++# Payloads a hook can plausibly be handed, including the ones nobody plans for.+HOSTILE_PAYLOADS = {+ "empty": "",+ "whitespace": " \n\t ",+ "not_json": "this is not json at all",+ "truncated_json": '{"hook_event_name": "PreToo',+ "json_null": "null",+ "json_list": "[1, 2, 3]",+ "json_string": '"just a string"',+ "json_number": "42",+ "empty_object": "{}",+ "nested_deep": json.dumps({"a": {"b": {"c": {"d": {"e": "f"}}}}}),+ "unicode": json.dumps({"hook_event_name": "Stop", "message": "emoji 🚀 ünïcode"}),+ "null_bytes": '{"hook_event_name": "Stop", "message": "a\\u0000b"}',+ "huge": json.dumps({"hook_event_name": "Stop", "message": "x" * 500_000}),+ "wrong_types": json.dumps({"hook_event_name": 12345, "session_id": []}),+ "missing_event": json.dumps({"session_id": "abc"}),+}+++class HookIsolationMixin:+ """Run hooks against a scratch HOME with the event socket disabled."""++ def setUp(self):+ super().setUp()+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.home = Path(self.tmp.name)+ self.log_path = self.home / "logs" / "hook.jsonl"++ env = patch.dict(+ os.environ,+ {+ "HOME": str(self.home),+ "XDG_CONFIG_HOME": str(self.home / ".config"),+ "SIDEPULSE_DISABLE_EVENT_SOCKET": "1",+ },+ )+ env.start()+ self.addCleanup(env.stop)+++def run_hook(provider: str, log_path: Path, payload: str) -> tuple[int, str]:+ """Drive hook_log_main with the given stdin, capturing stdout."""+ buffer = io.StringIO()+ with patch.object(sys, "stdin", io.StringIO(payload)), redirect_stdout(buffer):+ code = hook_log_main(provider, log_path)+ return code, buffer.getvalue()+++class FailOpenTests(HookIsolationMixin, unittest.TestCase):+ """No input and no internal failure may produce a non-zero exit."""++ def test_hostile_payloads_exit_zero(self):+ for provider in PROVIDERS:+ for name, payload in HOSTILE_PAYLOADS.items():+ with self.subTest(provider=provider, payload=name):+ code, _ = run_hook(provider, self.log_path, payload)+ self.assertEqual(0, code)++ def test_unknown_provider_exits_zero(self):+ code, _ = run_hook("not-a-provider", self.log_path, '{"hook_event_name": "Stop"}')+ self.assertEqual(0, code)++ def test_unwritable_log_path_exits_zero(self):+ """A read-only or impossible log destination must not break the agent."""+ blocked = self.home / "blocked"+ blocked.mkdir()+ blocked.chmod(0o500)+ self.addCleanup(blocked.chmod, 0o700)+ code, _ = run_hook("claude", blocked / "sub" / "hook.jsonl", '{"hook_event_name": "Stop"}')+ self.assertEqual(0, code)++ def test_log_path_is_a_directory_exits_zero(self):+ directory = self.home / "iam-a-directory"+ directory.mkdir()+ code, _ = run_hook("claude", directory, '{"hook_event_name": "Stop"}')+ self.assertEqual(0, code)++ def test_every_internal_failure_exits_zero(self):+ """Whatever blows up downstream, the hook still reports success.++ Each collaborator is replaced with one that raises, one at a time, so+ a future refactor that lets an exception escape gets caught here.+ """+ collaborators = [+ "routed_hook_payload",+ "send_hook_event",+ "write_hook_line",+ "write_hook_status_audit",+ "hook_event_socket_disabled",+ ]+ for name in collaborators:+ with self.subTest(raises=name):+ with patch.object(+ hook_module, name, side_effect=RuntimeError(f"boom in {name}")+ ):+ code, _ = run_hook(+ "claude", self.log_path, '{"hook_event_name": "Stop"}'+ )+ self.assertEqual(0, code, f"{name} raising must not fail the hook")++ def test_interrupts_are_not_swallowed(self):+ """Fail-open covers errors, not Ctrl-C.++ ``hook_log_main`` catches ``Exception``, deliberately not+ ``BaseException``: swallowing an interrupt would make the hook+ unkillable. The shell wrapper (``; true``) is what keeps an+ interrupted hook from failing the agent turn -- see+ ``InstalledCommandTests``.+ """+ with patch.object(+ hook_module, "routed_hook_payload", side_effect=KeyboardInterrupt+ ):+ with self.assertRaises(KeyboardInterrupt):+ run_hook("claude", self.log_path, "{}")++ def test_socket_send_failure_still_writes_log(self):+ """The log is the durable record; a dead status bar must not lose it."""+ with patch.dict(os.environ, {"SIDEPULSE_DISABLE_EVENT_SOCKET": "0"}):+ with patch.object(+ hook_module, "send_hook_event", side_effect=OSError("no listener")+ ):+ code, _ = run_hook(+ "claude", self.log_path, '{"hook_event_name": "Stop"}'+ )+ self.assertEqual(0, code)+++class StdoutPurityTests(HookIsolationMixin, unittest.TestCase):+ """Hook stdout belongs to the agent runtime, not to us."""++ def test_hooks_write_nothing_to_stdout(self):+ for provider in PROVIDERS:+ for name, payload in HOSTILE_PAYLOADS.items():+ with self.subTest(provider=provider, payload=name):+ _, out = run_hook(provider, self.log_path, payload)+ self.assertEqual("", out, f"hook printed to stdout: {out!r}")++ def test_hooks_write_nothing_to_stdout_on_internal_error(self):+ with patch.object(hook_module, "write_hook_line", side_effect=RuntimeError("boom")):+ _, out = run_hook("claude", self.log_path, '{"hook_event_name": "Stop"}')+ self.assertEqual("", out)+++class HappyPathTests(HookIsolationMixin, unittest.TestCase):+ """Fail-open is worthless if the hook never succeeds at anything."""++ def test_valid_payload_is_appended_as_jsonl(self):+ payload = json.dumps({"hook_event_name": "Stop", "session_id": "s1"})+ code, _ = run_hook("claude", self.log_path, payload)+ self.assertEqual(0, code)+ self.assertTrue(self.log_path.exists(), "hook wrote no log file")+ lines = self.log_path.read_text(encoding="utf-8").splitlines()+ self.assertEqual(1, len(lines))+ record = json.loads(lines[0])+ self.assertEqual("Stop", record["hook_event_name"])+ self.assertIn("logged_at", record)++ def test_repeated_calls_append_rather_than_truncate(self):+ for index in range(5):+ payload = json.dumps({"hook_event_name": "Stop", "session_id": f"s{index}"})+ run_hook("claude", self.log_path, payload)+ lines = self.log_path.read_text(encoding="utf-8").splitlines()+ self.assertEqual(5, len(lines))+ for line in lines:+ json.loads(line) # every line must be independently parseable++ def test_each_record_is_one_physical_line(self):+ """Multi-line content must not break the JSONL reader downstream."""+ payload = json.dumps({"hook_event_name": "Stop", "message": "one\ntwo\nthree"})+ run_hook("claude", self.log_path, payload)+ lines = self.log_path.read_text(encoding="utf-8").splitlines()+ self.assertEqual(1, len(lines))+ self.assertEqual("one\ntwo\nthree", json.loads(lines[0])["message"])++ def test_malformed_payload_is_recorded_as_parse_error(self):+ """Garbage in must still leave a breadcrumb rather than vanishing."""+ run_hook("claude", self.log_path, "definitely not json")+ record = json.loads(self.log_path.read_text(encoding="utf-8").splitlines()[0])+ self.assertEqual("ParseError", record["hook_event_name"])+ self.assertIn("definitely not json", record["raw"])++ def test_format_hook_payload_always_timestamps(self):+ for name, payload in HOSTILE_PAYLOADS.items():+ for provider in PROVIDERS:+ with self.subTest(provider=provider, payload=name):+ line = format_hook_payload(provider, payload)+ self.assertIsInstance(line, dict)+ self.assertTrue(line.get("logged_at"))++ def test_routed_payload_returns_usable_triple(self):+ for name, payload in HOSTILE_PAYLOADS.items():+ with self.subTest(payload=name):+ provider, path, line = routed_hook_payload(+ "claude", self.log_path, payload+ )+ self.assertIsInstance(provider, str)+ self.assertTrue(provider)+ self.assertIsInstance(path, Path)+ self.assertIsInstance(line, dict)+++class EntryPointSubprocessTests(unittest.TestCase):+ """The hook runs as a fresh process from a shell command, so test it that way.++ This is what catches packaging and sys.path regressions that in-process+ tests cannot see -- including the legacy module names still referenced by+ hook configs installed before the SidePulse rename.+ """++ ENTRY_POINTS = (+ "sidepulse/hook_entry.py",+ "sidepulse_cli/hook_entry.py",+ "agent_monitor/hook_entry.py",+ )++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.home = Path(self.tmp.name)++ def run_entry(self, relative: str, args: list[str], payload: str = "{}"):+ env = {+ **os.environ,+ "HOME": str(self.home),+ "XDG_CONFIG_HOME": str(self.home / ".config"),+ "SIDEPULSE_DISABLE_EVENT_SOCKET": "1",+ }+ # Deliberately no PYTHONPATH: the entry points must bootstrap their+ # own sys.path exactly as they do when a hook config invokes them.+ env.pop("PYTHONPATH", None)+ return subprocess.run(+ [sys.executable, str(SRC_ROOT / relative), *args],+ input=payload,+ capture_output=True,+ text=True,+ timeout=30,+ env=env,+ cwd=str(self.home),+ )++ def test_entry_points_log_and_exit_zero(self):+ for relative in self.ENTRY_POINTS:+ with self.subTest(entry_point=relative):+ log_path = self.home / f"{relative.replace('/', '_')}.jsonl"+ result = self.run_entry(+ relative,+ ["--provider", "claude", "--log", str(log_path)],+ json.dumps({"hook_event_name": "Stop", "session_id": "s1"}),+ )+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual("", result.stdout)+ self.assertTrue(log_path.exists(), f"{relative} wrote no log")++ def test_entry_points_survive_bad_arguments(self):+ bad_arguments = [+ [],+ ["--provider"],+ ["--provider", "claude"],+ ["--log", "/tmp/x.jsonl"],+ ["--provider", "claude", "--log"],+ ["--unknown-flag", "value"],+ ]+ for relative in self.ENTRY_POINTS:+ for args in bad_arguments:+ with self.subTest(entry_point=relative, args=args):+ result = self.run_entry(relative, args)+ self.assertEqual(0, result.returncode, result.stderr)++ def test_entry_points_survive_hostile_payloads(self):+ for name, payload in HOSTILE_PAYLOADS.items():+ with self.subTest(payload=name):+ result = self.run_entry(+ "sidepulse/hook_entry.py",+ ["--provider", "claude", "--log", str(self.home / "h.jsonl")],+ payload,+ )+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertEqual("", result.stdout)++ def test_entry_point_exits_promptly(self):+ """A hook that hangs stalls every tool call in the agent session."""+ result = self.run_entry(+ "sidepulse/hook_entry.py",+ ["--provider", "claude", "--log", str(self.home / "h.jsonl")],+ json.dumps({"hook_event_name": "Stop"}),+ )+ # subprocess.run raises TimeoutExpired past 30s; reaching here is the+ # assertion. Keep the explicit check so the intent is not lost.+ self.assertEqual(0, result.returncode)++ def test_hook_works_without_the_gui_stack(self):+ """Hooks must not depend on PyObjC.++ The hook path runs in the user's agent session, which may have no+ working AppKit at all -- a broken PyObjC install, a non-macOS host, or+ exactly the missing-framework situation that motivated these tests.+ Logging must keep working regardless.+ """+ log_path = self.home / "no-gui.jsonl"+ blocker = self.home / "run_with_gui_blocked.py"+ blocker.write_text(+ "import sys, runpy\n"+ "BLOCKED = {'AppKit', 'Foundation', 'objc', 'Quartz',\n"+ " 'ScriptingBridge', 'WebKit', 'JavaScriptCore'}\n"+ "class Blocker:\n"+ " def find_module(self, name, path=None):\n"+ " return self if name.split('.')[0] in BLOCKED else None\n"+ " def find_spec(self, name, path=None, target=None):\n"+ " if name.split('.')[0] in BLOCKED:\n"+ " raise ImportError(f'{name} blocked for test')\n"+ " return None\n"+ "sys.meta_path.insert(0, Blocker())\n"+ "for name in list(sys.modules):\n"+ " if name.split('.')[0] in BLOCKED:\n"+ " del sys.modules[name]\n"+ "sys.argv = sys.argv[1:]\n"+ "runpy.run_path(sys.argv[0], run_name='__main__')\n",+ encoding="utf-8",+ )+ env = {+ **os.environ,+ "HOME": str(self.home),+ "SIDEPULSE_DISABLE_EVENT_SOCKET": "1",+ }+ env.pop("PYTHONPATH", None)+ result = subprocess.run(+ [+ sys.executable,+ str(blocker),+ str(SRC_ROOT / "sidepulse/hook_entry.py"),+ "--provider", "claude",+ "--log", str(log_path),+ ],+ input=json.dumps({"hook_event_name": "Stop", "session_id": "s1"}),+ capture_output=True,+ text=True,+ timeout=30,+ env=env,+ cwd=str(self.home),+ )+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertTrue(+ log_path.exists(),+ f"hook logged nothing with PyObjC blocked; stderr={result.stderr}",+ )+ record = json.loads(log_path.read_text(encoding="utf-8").splitlines()[0])+ self.assertEqual("Stop", record["hook_event_name"])++ def test_cli_hook_log_subcommand_matches_entry_point(self):+ log_path = self.home / "cli.jsonl"+ env = {+ **os.environ,+ "HOME": str(self.home),+ "SIDEPULSE_DISABLE_EVENT_SOCKET": "1",+ }+ result = subprocess.run(+ [+ sys.executable, "-m", "sidepulse", "hook-log",+ "--provider", "claude", "--log", str(log_path),+ ],+ input=json.dumps({"hook_event_name": "Stop"}),+ capture_output=True,+ text=True,+ timeout=30,+ env=env,+ cwd=str(REPO_ROOT),+ )+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertTrue(log_path.exists())+++class InstalledCommandTests(unittest.TestCase):+ """The string we write into somebody's agent config must be safe."""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.home = Path(self.tmp.name)++ def test_command_is_shell_fail_open(self):+ for provider in PROVIDERS:+ with self.subTest(provider=provider):+ command = hook_command(provider, self.home / "log.jsonl")+ self.assertTrue(+ command.rstrip().endswith("; true"),+ f"hook command is not fail-open: {command}",+ )++ def test_command_quotes_paths_with_spaces(self):+ import shlex++ weird = self.home / "path with spaces" / "log's file.jsonl"+ command = hook_command("claude", weird)+ parts = shlex.split(command)+ self.assertIn(str(weird), parts, "log path was not quoted intact")++ def test_command_exits_zero_when_python_is_missing(self):+ """Config survives a deleted virtualenv; the agent must keep working."""+ command = hook_command(+ "claude", self.home / "log.jsonl", python_executable="/nonexistent/python"+ )+ result = subprocess.run(+ command, shell=True, capture_output=True, text=True, timeout=30,+ input="{}",+ )+ self.assertEqual(+ 0, result.returncode, f"stale hook command failed the turn: {command}"+ )++ def test_installed_command_actually_logs(self):+ log_path = self.home / "installed.jsonl"+ command = hook_command("claude", log_path)+ result = subprocess.run(+ command,+ shell=True,+ input=json.dumps({"hook_event_name": "Stop"}),+ capture_output=True,+ text=True,+ timeout=30,+ env={**os.environ, "SIDEPULSE_DISABLE_EVENT_SOCKET": "1"},+ )+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertTrue(log_path.exists(), "installed hook command wrote nothing")++ def test_fail_open_wrapper_neutralizes_failure(self):+ # Note: a bare `exit 7` would terminate the shell before `; true` runs.+ # Hooks invoke a real program, which is what these cases model.+ failing_commands = (+ "/usr/bin/false",+ "/nonexistent/program --flag",+ "/bin/sh -c 'exit 7'",+ )+ for command in failing_commands:+ with self.subTest(command=command):+ result = subprocess.run(+ fail_open_command(command),+ shell=True,+ capture_output=True,+ timeout=30,+ )+ self.assertEqual(0, result.returncode)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_packaging.py b/tests/test_packaging.pynew file mode 100644index 0000000..85b427a--- /dev/null+++ b/tests/test_packaging.py@@ -0,0 +1,398 @@+"""Packaging and import-contract tests.++These guard the class of bug where the code imports a module that nothing+declares as a dependency, so the package installs cleanly and then explodes+at runtime on a user's machine.++The concrete instance that motivated this file: ``status_bar.py`` grew a+``from ScriptingBridge import SBApplication`` for the Ghostty integration.+``ScriptingBridge`` ships in ``pyobjc-framework-ScriptingBridge``, which was+never added to ``pyproject.toml``. Because the import shared a ``try`` block+with AppKit, the failure surfaced as a misleading "requires PyObjC/AppKit"+message and killed the whole status bar.++``test_hard_third_party_imports_are_declared`` fails on exactly that mistake.+"""++from __future__ import annotations++import ast+import importlib+import re+import subprocess+import sys+import unittest+from importlib.metadata import PackageNotFoundError, distribution, packages_distributions+from pathlib import Path++try: # Python 3.11++ import tomllib+except ModuleNotFoundError: # pragma: no cover - Python 3.10+ try:+ import tomli as tomllib # type: ignore[no-redef]+ except ModuleNotFoundError: # pragma: no cover+ tomllib = None # type: ignore[assignment]+++REPO_ROOT = Path(__file__).resolve().parents[1]+SRC_ROOT = REPO_ROOT / "src"+PYPROJECT = REPO_ROOT / "pyproject.toml"++# Top-level packages that live in this repo.+FIRST_PARTY = {"sidepulse", "sidepulse_cli", "agent_monitor"}++# Modules that are stdlib on some supported interpreters and not others, so+# they are legitimately imported without being declared.+CONDITIONAL_STDLIB = {"tomllib"}+++def normalize_dist_name(name: str) -> str:+ """PEP 503 normalization, so Foo_Bar and foo-bar compare equal."""+ return re.sub(r"[-_.]+", "-", name).lower()+++def load_pyproject() -> dict:+ if tomllib is None: # pragma: no cover+ raise unittest.SkipTest("need tomllib (3.11+) or tomli to parse pyproject.toml")+ return tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))+++def requirement_name(spec: str) -> str:+ """Pull the distribution name out of a requirement string.++ ``"pyobjc-framework-Cocoa>=10; sys_platform == 'darwin'"`` -> ``pyobjc-framework-cocoa``+ """+ head = spec.split(";", 1)[0].strip()+ head = re.split(r"[<>=!~\[\s]", head, 1)[0]+ return normalize_dist_name(head)+++def declared_dependencies() -> set[str]:+ """Distribution names declared in ``[project] dependencies``."""+ data = load_pyproject()+ return {requirement_name(dep) for dep in data["project"].get("dependencies", [])}+++def dependency_closure(roots: set[str]) -> set[str]:+ """Every distribution reachable from ``roots`` through installed metadata.++ A direct import satisfied only transitively (``objc`` via ``pyobjc-core``,+ which ``pyobjc-framework-Cocoa`` pulls in) is accepted. An import satisfied+ by nothing in the closure is the bug this module exists to catch.+ """+ seen: set[str] = set()+ queue = list(roots)+ while queue:+ name = queue.pop()+ if name in seen:+ continue+ seen.add(name)+ try:+ reqs = distribution(name).requires or []+ except PackageNotFoundError:+ continue+ for req in reqs:+ # Skip requirements gated behind an extra we do not install.+ if "extra ==" in req:+ continue+ child = requirement_name(req)+ if child and child not in seen:+ queue.append(child)+ return seen+++class ImportRecord:+ def __init__(self, module: str, path: Path, lineno: int, optional: bool):+ self.module = module+ self.top = module.split(".")[0]+ self.path = path+ self.lineno = lineno+ self.optional = optional++ @property+ def where(self) -> str:+ rel = self.path.relative_to(REPO_ROOT)+ return f"{rel}:{self.lineno}"+++def handlers_swallow_failure(node: ast.Try) -> bool:+ """True when a failed import in this ``try`` leaves the module usable.++ A handler that re-raises anything -- including ``raise SystemExit(...)``,+ which is how the ScriptingBridge bug manifested -- does not make the+ import optional. It makes it mandatory with a nicer error message, so the+ dependency still has to be declared.+ """+ if not node.handlers:+ return False+ for handler in node.handlers:+ for child in ast.walk(handler):+ if isinstance(child, ast.Raise):+ return False+ return True+++def scan_imports(root: Path) -> list[ImportRecord]:+ """Every import in the tree, tagged with whether the code can live without it.++ An import is optional when either:++ * it sits inside a function or method body, so it only runs when that+ feature is actually used and the caller can handle the failure; or+ * it sits inside a module-level ``try`` whose handlers swallow the error+ (assigning ``None``, setting a flag) rather than re-raising.++ Everything else runs unconditionally at import time and must be+ satisfiable from the declared dependencies.+ """+ records: list[ImportRecord] = []++ def visit(node: ast.AST, path: Path, in_function: bool, in_safe_try: bool) -> None:+ if isinstance(node, ast.Import):+ modules = [alias.name for alias in node.names]+ elif isinstance(node, ast.ImportFrom):+ # Relative imports are first-party by definition.+ modules = [node.module] if node.level == 0 and node.module else []+ else:+ modules = []+ for module in modules:+ records.append(+ ImportRecord(+ module, path, node.lineno, optional=in_function or in_safe_try+ )+ )++ if isinstance(node, ast.Try):+ # Only the protected body benefits from the handler.+ safe = in_safe_try or handlers_swallow_failure(node)+ for child in node.body:+ visit(child, path, in_function, safe)+ for child in (*node.handlers, *node.orelse, *node.finalbody):+ visit(child, path, in_function, in_safe_try)+ return++ entering_function = isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ for child in ast.iter_child_nodes(node):+ visit(child, path, in_function or entering_function, in_safe_try)++ for path in sorted(root.rglob("*.py")):+ visit(ast.parse(path.read_text(encoding="utf-8"), str(path)), path, False, False)+ return records+++def third_party(records: list[ImportRecord]) -> list[ImportRecord]:+ return [+ record+ for record in records+ if record.top not in sys.stdlib_module_names+ and record.top not in FIRST_PARTY+ and record.top not in CONDITIONAL_STDLIB+ ]+++class ImportContractTests(unittest.TestCase):+ """The dependency declaration must cover what the code actually imports."""++ def test_source_tree_is_parseable(self):+ # Cheap canary: a syntax error anywhere makes every other scan lie.+ for path in sorted(SRC_ROOT.rglob("*.py")):+ with self.subTest(path=path.relative_to(REPO_ROOT)):+ ast.parse(path.read_text(encoding="utf-8"), str(path))++ @unittest.skipUnless(+ sys.platform == "darwin",+ "every declared dependency is darwin-gated, so the contract can only "+ "be checked where they are installed",+ )+ def test_hard_third_party_imports_are_declared(self):+ """A module-level import of an undeclared distribution is a release bug.++ This is the regression test for the missing ScriptingBridge dependency.+ """+ closure = dependency_closure(declared_dependencies())+ module_to_dists = packages_distributions()++ missing: list[str] = []+ for record in third_party(scan_imports(SRC_ROOT)):+ if record.optional:+ continue+ providers = module_to_dists.get(record.top)+ if providers is None:+ missing.append(+ f"{record.where}: imports {record.top!r}, which is not "+ f"installed and not declared in pyproject.toml"+ )+ continue+ if not any(normalize_dist_name(p) in closure for p in providers):+ missing.append(+ f"{record.where}: imports {record.top!r} from "+ f"{providers}, which no declared dependency pulls in. "+ f"Add it to [project] dependencies, or make the import "+ f"guarded if the feature is optional."+ )++ self.assertEqual(+ [],+ missing,+ "Undeclared hard dependencies:\n " + "\n ".join(missing),+ )++ @unittest.skipUnless(sys.platform == "darwin", "optional deps are darwin-gated")+ def test_guarded_optional_imports_are_reachable_or_optional(self):+ """Guarded imports may be absent, but must name a real distribution.++ Catches typo'd optional imports (``ScriptingBrige``) that would+ silently disable a feature forever instead of failing loudly.+ """+ module_to_dists = packages_distributions()+ unknown: list[str] = []+ for record in third_party(scan_imports(SRC_ROOT)):+ if not record.optional:+ continue+ if record.top in module_to_dists:+ continue+ # Not installed here; accept only if some extra declares it.+ data = load_pyproject()+ extras = data["project"].get("optional-dependencies", {})+ declared_anywhere = {+ requirement_name(dep)+ for deps in extras.values()+ for dep in deps+ } | declared_dependencies()+ if normalize_dist_name(record.top) not in declared_anywhere:+ unknown.append(f"{record.where}: optional import {record.top!r}")++ # mlx_lm is the reply-classifier extra; it maps to distribution "mlx-lm".+ unknown = [u for u in unknown if "mlx_lm" not in u]+ self.assertEqual([], unknown, "Unrecognized optional imports:\n " + "\n ".join(unknown))++ def test_declared_dependencies_are_installed(self):+ """The test environment matches what we ship, or the suite proves nothing."""+ if sys.platform != "darwin":+ self.skipTest("declared dependencies are darwin-gated")+ for name in sorted(declared_dependencies()):+ with self.subTest(dependency=name):+ try:+ distribution(name)+ except PackageNotFoundError:+ self.fail(+ f"{name} is declared in pyproject.toml but not installed. "+ f"Run: pip install -e ."+ )+++class ModuleImportSmokeTests(unittest.TestCase):+ """Every shipped module must import. Nothing here is clever; that is the point."""++ def module_names(self) -> list[str]:+ names = []+ for path in sorted(SRC_ROOT.rglob("*.py")):+ rel = path.relative_to(SRC_ROOT)+ if rel.name == "__main__.py":+ continue # executes on import by design+ parts = list(rel.parts)+ parts[-1] = rel.stem+ if parts[-1] == "__init__":+ parts.pop()+ if parts:+ names.append(".".join(parts))+ return names++ def test_every_module_imports(self):+ darwin_only = {+ "sidepulse.status_bar",+ "sidepulse.virtual_device",+ "sidepulse.led_wasm",+ }+ for name in self.module_names():+ if name in darwin_only and sys.platform != "darwin":+ continue+ with self.subTest(module=name):+ try:+ importlib.import_module(name)+ except SystemExit as exc:+ # status_bar raises SystemExit with an install hint when+ # PyObjC is missing. On a machine with deps installed that+ # is always a bug -- most likely an undeclared dependency.+ self.fail(f"{name} raised SystemExit on import: {exc}")++ def test_main_module_does_not_import_eagerly(self):+ # __main__.py runs the CLI; it must be importable via runpy without+ # side effects beyond argument parsing.+ result = subprocess.run(+ [sys.executable, "-m", "sidepulse", "--help"],+ capture_output=True,+ text=True,+ timeout=60,+ cwd=REPO_ROOT,+ )+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertIn("usage", result.stdout.lower())+++class EntryPointTests(unittest.TestCase):+ """Every console script in pyproject must resolve to a real callable."""++ def test_console_scripts_resolve(self):+ scripts = load_pyproject()["project"].get("scripts", {})+ self.assertTrue(scripts, "expected console scripts in pyproject.toml")+ for name, target in sorted(scripts.items()):+ with self.subTest(script=name):+ module_name, _, attr = target.partition(":")+ if module_name == "sidepulse.status_bar" and sys.platform != "darwin":+ continue+ module = importlib.import_module(module_name)+ self.assertTrue(+ callable(getattr(module, attr, None)),+ f"{target} is not callable",+ )++ def test_console_scripts_respond_to_help(self):+ """An entry point that cannot even print --help is broken for users."""+ scripts = load_pyproject()["project"].get("scripts", {})+ for name, target in sorted(scripts.items()):+ module_name, _, _ = target.partition(":")+ if module_name == "sidepulse.status_bar":+ continue # launching the GUI is not a --help operation+ with self.subTest(script=name):+ result = subprocess.run(+ [sys.executable, "-c", f"import sys; sys.argv=['{name}','--help']; "+ f"import {module_name} as m; "+ f"sys.exit(m.{target.split(':')[1]}())"],+ capture_output=True,+ text=True,+ timeout=60,+ cwd=REPO_ROOT,+ )+ self.assertIn(+ result.returncode,+ (0, 2),+ f"{name} --help failed: {result.stderr}",+ )+++class PackageDataTests(unittest.TestCase):+ def test_declared_package_data_exists(self):+ data = load_pyproject()+ package_data = (+ data.get("tool", {})+ .get("setuptools", {})+ .get("package-data", {})+ )+ for package, patterns in package_data.items():+ package_dir = SRC_ROOT / package.replace(".", "/")+ with self.subTest(package=package):+ self.assertTrue(+ package_dir.is_dir(),+ f"package-data references missing package {package}",+ )+ for pattern in patterns:+ with self.subTest(package=package, pattern=pattern):+ self.assertTrue(+ list(package_dir.glob(pattern)),+ f"package-data pattern {pattern!r} matches nothing in {package}",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_status_bar_ui.py b/tests/test_status_bar_ui.pynew file mode 100644index 0000000..e1258a9--- /dev/null+++ b/tests/test_status_bar_ui.py@@ -0,0 +1,471 @@+"""Status-bar UI tests.++The status bar is 4k lines of AppKit that no other test touches, because+importing it needs PyObjC and CI historically ran nothing. That is how a+missing ``ScriptingBridge`` dependency shipped.++Everything here runs headlessly against real AppKit objects -- a real+``StatusBarController``, a real ``NSMenu``, real ``NSWindow`` hierarchies.+No ``NSApplication.run()``, so nothing appears on screen and nothing blocks.++The highest-value test in this file is ``test_every_selector_literal_resolves``:+menu items and buttons refer to their handlers by *string*, so renaming a+controller method leaves a menu entry that crashes when clicked and that no+type checker or import test would notice.+"""++from __future__ import annotations++import ast+import os+import re+import tempfile+import unittest+from datetime import datetime, timedelta, timezone+from pathlib import Path+from unittest.mock import patch++if os.uname().sysname != "Darwin": # pragma: no cover+ raise unittest.SkipTest("status-bar UI tests require macOS")++REPO_ROOT = Path(__file__).resolve().parents[1]++_ENV_PATCH = None+++def setUpModule():+ """Point config lookups at a scratch home for the duration of this module.++ Settings are read when the controller is constructed (in setUpClass), not+ at import time, so scoping the patch here keeps it from leaking into other+ test modules while still landing before anything reads configuration.+ """+ global _ENV_PATCH+ scratch = tempfile.mkdtemp(prefix="sidepulse-ui-tests-")+ _ENV_PATCH = patch.dict(+ os.environ,+ {"HOME": scratch, "XDG_CONFIG_HOME": str(Path(scratch) / ".config")},+ )+ _ENV_PATCH.start()+++def tearDownModule():+ if _ENV_PATCH is not None:+ _ENV_PATCH.stop()+++from AppKit import ( # noqa: E402+ NSApplication,+ NSControl,+ NSImage,+ NSMenu,+ NSView,+ NSWindow,+)++from sidepulse import status_bar as sb # noqa: E402+from sidepulse import virtual_device as vd # noqa: E402+from sidepulse.collector import MonitorSnapshot, SourceSpec # noqa: E402+from sidepulse.models import AgentMode, AgentStatus, AggregateStatus # noqa: E402+++# A selector literal: camelCase identifier ending in a single colon.+SELECTOR_LITERAL = re.compile(r"^[a-z][A-Za-z0-9_]*:$")++# Classes that can legally be the target of a selector in this codebase.+def target_classes():+ return (sb.StatusBarController, vd.VirtualStatusDevice)+++def make_status(+ *,+ provider: str = "claude",+ agent_id: str = "agent-1",+ display_name: str = "sidepulse",+ mode: AgentMode = AgentMode.WORKING,+ age_seconds: float = 5.0,+ cwd: str | None = "/Users/test/project",+ origin: str | None = None,+ stale: bool = False,+ now: datetime | None = None,+) -> AgentStatus:+ now = now or datetime.now(timezone.utc)+ return AgentStatus(+ provider=provider,+ agent_id=agent_id,+ display_name=display_name,+ mode=mode,+ updated_at=now - timedelta(seconds=age_seconds),+ event_name="PostToolUse",+ session_id=f"session-{agent_id}",+ cwd=cwd,+ tool_name="Bash",+ message="doing a thing",+ origin=origin,+ stale=stale,+ )+++def make_snapshot(statuses=(), stale_statuses=()) -> MonitorSnapshot:+ now = datetime.now(timezone.utc)+ statuses = tuple(statuses)+ representative = statuses[0] if statuses else None+ return MonitorSnapshot(+ aggregate=AggregateStatus(+ mode=representative.mode if representative else AgentMode.IDLE_READY,+ active_count=len(statuses),+ stale_count=len(stale_statuses),+ representative=representative,+ ),+ statuses=statuses,+ stale_statuses=tuple(stale_statuses),+ sources=(SourceSpec("event-bus", Path("/tmp/does-not-exist.sock")),),+ collected_at=now,+ )+++def walk_menu(menu: NSMenu):+ """Yield every item in a menu tree, descending into submenus."""+ for index in range(menu.numberOfItems()):+ item = menu.itemAtIndex_(index)+ yield item+ submenu = item.submenu()+ if submenu is not None:+ yield from walk_menu(submenu)+++def make_device(+ name: str = "PULSEDOT",+ *,+ device_id: str | None = None,+ connected: bool = True,+) -> sb.StatusBarDevice:+ root = Path("/Volumes") / name+ return sb.StatusBarDevice(+ device_id=device_id or name.lower(),+ name=name,+ root=root,+ target=root / "leds.txt",+ connected=connected,+ display=sb.LED_DISPLAY_AGENT,+ brightness=255,+ reason="test",+ )+++def walk_views(view: NSView):+ """Yield every view in a view tree."""+ yield view+ for subview in view.subviews():+ yield subview+ yield from walk_views(subview)+++class StatusBarTestCase(unittest.TestCase):+ """Shared headless AppKit setup."""++ @classmethod+ def setUpClass(cls):+ # A shared application instance must exist before AppKit objects are+ # created. We never call run(), so this stays headless.+ #+ # Some CI runners have no window server. Skipping there beats a red+ # build, but set SIDEPULSE_REQUIRE_UI_TESTS=1 on any machine that is+ # supposed to have one, so the coverage cannot silently disappear.+ try:+ cls.app = NSApplication.sharedApplication()+ cls.controller = sb.StatusBarController.alloc().init()+ except Exception as exc: # pragma: no cover - environment dependent+ if os.environ.get("SIDEPULSE_REQUIRE_UI_TESTS") == "1":+ raise+ raise unittest.SkipTest(f"AppKit unavailable in this session: {exc}")+ if cls.controller is None:+ raise unittest.SkipTest("StatusBarController could not be created")+++class SelectorWiringTests(StatusBarTestCase):+ """Menu and button actions are strings; a rename must not go unnoticed."""++ def selector_literals(self, path: Path) -> set[str]:+ tree = ast.parse(path.read_text(encoding="utf-8"), str(path))+ return {+ node.value+ for node in ast.walk(tree)+ if isinstance(node, ast.Constant)+ and isinstance(node.value, str)+ and SELECTOR_LITERAL.match(node.value)+ }++ def test_every_selector_literal_resolves(self):+ """Every selector-shaped string in the UI must exist on a real class.++ Catches the "renamed the handler, forgot the menu entry" bug, which+ only surfaces when a user clicks the item and the app dies.+ """+ sources = [+ REPO_ROOT / "src/sidepulse/status_bar.py",+ REPO_ROOT / "src/sidepulse/virtual_device.py",+ ]+ classes = target_classes()+ unresolved = []+ for path in sources:+ for selector in sorted(self.selector_literals(path)):+ if not any(c.instancesRespondToSelector_(selector) for c in classes):+ unresolved.append(f"{path.relative_to(REPO_ROOT)}: {selector}")+ self.assertEqual(+ [],+ unresolved,+ "Selectors with no implementation:\n " + "\n ".join(unresolved),+ )++ def test_scan_finds_the_selectors_we_expect(self):+ """Guard the guard: a regex that matches nothing would pass silently."""+ found = self.selector_literals(REPO_ROOT / "src/sidepulse/status_bar.py")+ for expected in ("openSettings:", "openSetup:", "quit:", "refresh:"):+ self.assertIn(expected, found)++ def test_controller_implements_application_delegate_hook(self):+ self.assertTrue(+ sb.StatusBarController.instancesRespondToSelector_(+ "applicationDidFinishLaunching:"+ )+ )+++class MenuBuildTests(StatusBarTestCase):+ """build_menu must produce a wired, clickable menu for any snapshot."""++ def setUp(self):+ # Real device discovery would make these tests depend on whatever+ # hardware happens to be plugged in.+ patcher = patch.object(sb, "discover_devices", return_value=[])+ self.discover_devices = patcher.start()+ self.addCleanup(patcher.stop)++ def assert_menu_is_wired(self, menu: NSMenu):+ for item in walk_menu(menu):+ if item.submenu() is not None:+ continue # AppKit owns submenuAction: on parent items+ action = item.action()+ if action is None:+ continue+ selector = action if isinstance(action, str) else action.decode()+ target = item.target()+ if target is None:+ # Nil-targeted items go up the responder chain; the controller+ # is the app delegate, so it must still implement the action.+ self.assertTrue(+ any(c.instancesRespondToSelector_(selector) for c in target_classes()),+ f"menu item {item.title()!r} has unroutable action {selector}",+ )+ continue+ self.assertTrue(+ target.respondsToSelector_(selector),+ f"menu item {item.title()!r} targets {target} "+ f"which does not implement {selector}",+ )++ def test_empty_snapshot_builds_menu(self):+ menu = sb.build_menu(make_snapshot(), sb.STATE_IDLE, self.controller)+ self.assertGreater(menu.numberOfItems(), 0)+ titles = [item.title() for item in walk_menu(menu)]+ self.assertIn("No recent sessions", titles)+ self.assert_menu_is_wired(menu)++ def test_populated_snapshot_builds_menu(self):+ snapshot = make_snapshot(+ statuses=[+ make_status(agent_id="a", display_name="alpha"),+ make_status(agent_id="b", display_name="beta", provider="codex"),+ ]+ )+ menu = sb.build_menu(snapshot, sb.STATE_WORKING, self.controller)+ titles = " ".join(item.title() for item in walk_menu(menu))+ self.assertNotIn("No recent sessions", titles)+ self.assert_menu_is_wired(menu)++ def test_menu_builds_for_every_agent_mode(self):+ for mode in AgentMode:+ with self.subTest(mode=mode.value):+ snapshot = make_snapshot(statuses=[make_status(mode=mode)])+ menu = sb.build_menu(snapshot, sb.STATE_WORKING, self.controller)+ self.assertGreater(menu.numberOfItems(), 0)+ self.assert_menu_is_wired(menu)++ def test_menu_builds_for_every_provider(self):+ for provider in ("claude", "codex", "grok", "unknown-provider"):+ with self.subTest(provider=provider):+ snapshot = make_snapshot(statuses=[make_status(provider=provider)])+ menu = sb.build_menu(snapshot, sb.STATE_IDLE, self.controller)+ self.assert_menu_is_wired(menu)++ def test_menu_handles_colliding_session_titles(self):+ """Two sessions with the same name must still produce distinct rows."""+ snapshot = make_snapshot(+ statuses=[+ make_status(agent_id="a", display_name="same", cwd="/one"),+ make_status(agent_id="b", display_name="same", cwd="/two"),+ ]+ )+ menu = sb.build_menu(snapshot, sb.STATE_WORKING, self.controller)+ self.assert_menu_is_wired(menu)++ def test_menu_handles_hostile_session_names(self):+ """Session titles come from user directories and must not break layout."""+ for name in ("", " ", "a" * 500, "emoji 🚀 name", "with\nnewline", "%s %d {}"):+ with self.subTest(name=repr(name)):+ snapshot = make_snapshot(statuses=[make_status(display_name=name)])+ menu = sb.build_menu(snapshot, sb.STATE_WORKING, self.controller)+ self.assertGreater(menu.numberOfItems(), 0)++ def test_menu_includes_core_actions(self):+ menu = sb.build_menu(make_snapshot(), sb.STATE_IDLE, self.controller)+ titles = [item.title() for item in walk_menu(menu)]+ for expected in ("Setup...", "Settings...", "Quit"):+ self.assertIn(expected, titles)++ def test_recent_statuses_are_capped(self):+ """The menu must not grow unbounded with session count."""+ snapshot = make_snapshot(+ statuses=[make_status(agent_id=f"a{i}") for i in range(50)]+ )+ self.assertLessEqual(len(sb.recent_statuses(snapshot)), 12)+++class WindowBuildTests(StatusBarTestCase):+ """Settings and setup windows construct hundreds of views; a crash is a crash."""++ def assert_controls_are_wired(self, window: NSWindow):+ content = window.contentView()+ self.assertIsNotNone(content)+ for view in walk_views(content):+ if not isinstance(view, NSControl):+ continue+ action = view.action()+ if action is None:+ continue+ selector = action if isinstance(action, str) else action.decode()+ target = view.target()+ if target is None:+ self.assertTrue(+ any(c.instancesRespondToSelector_(selector) for c in target_classes()),+ f"control has unroutable action {selector}",+ )+ continue+ self.assertTrue(+ target.respondsToSelector_(selector),+ f"control targets {target} which does not implement {selector}",+ )++ def test_settings_window_builds(self):+ window = sb.build_settings_window(self.controller)+ self.assertIsNotNone(window)+ self.assertTrue(window.title())+ self.assert_controls_are_wired(window)++ def test_setup_window_builds(self):+ window = sb.build_setup_window(self.controller)+ self.assertIsNotNone(window)+ self.assert_controls_are_wired(window)++ def test_settings_window_registers_its_fields(self):+ """The controller reads values back out of this dict when saving."""+ self.controller.settings_fields = {}+ sb.build_settings_window(self.controller)+ self.assertTrue(+ self.controller.settings_fields,+ "settings window built no addressable fields; saving would be a no-op",+ )++ def test_settings_window_is_not_visible(self):+ window = sb.build_settings_window(self.controller)+ self.assertFalse(window.isVisible(), "building a window must not show it")+++class IconTests(StatusBarTestCase):+ """Icon builders return real images rather than None."""++ def test_status_icons_exist_for_every_mode(self):+ for mode in AgentMode:+ with self.subTest(mode=mode.value):+ status = make_status(mode=mode)+ 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"):+ with self.subTest(provider=provider):+ sb.provider_icon_for_provider(provider)++ 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):+ self.assertIsInstance(+ sb.image_for_symbol(state.symbol, state.label), NSImage+ )+++class PureUiLogicTests(unittest.TestCase):+ """Label and formatting helpers -- no AppKit objects, fast and exhaustive."""++ def test_format_byte_count_is_monotonic_and_labelled(self):+ for size in (0, 1, 1023, 1024, 1024**2, 1024**3, 1024**4):+ with self.subTest(size=size):+ text = sb.format_byte_count(size)+ self.assertTrue(text)+ self.assertRegex(text, r"\d")++ def test_terminal_app_labels_exist_for_every_choice(self):+ for app in sb.TERMINAL_APP_CHOICES:+ with self.subTest(app=app):+ self.assertTrue(sb.terminal_app_label(app))+ self.assertTrue(sb.terminal_app_menu_label(app))++ def test_provider_open_actions_have_labels(self):+ for provider in ("claude", "codex", "grok"):+ actions = sb.provider_open_actions(provider)+ self.assertTrue(actions, f"{provider} has no open actions")+ self.assertIn(sb.default_provider_open_action(provider), actions)+ for action in actions:+ with self.subTest(provider=provider, action=action):+ self.assertTrue(sb.provider_open_action_label(provider, action))++ def test_device_name_disambiguation(self):+ # macOS mounts a second volume of the same name as "NAME 1", so both+ # devices report display name "SIDEPULSE" but differ by mount root.+ first = make_device("SIDEPULSE", device_id="one")+ second = make_device("SIDEPULSE", device_id="two")+ second = sb.StatusBarDevice(+ **{+ **second.__dict__,+ "root": Path("/Volumes/SIDEPULSE 1"),+ "target": Path("/Volumes/SIDEPULSE 1/leds.txt"),+ }+ )+ result = sb.disambiguate_device_names([first, second])+ self.assertEqual(2, len(result))+ self.assertEqual(+ 2,+ len({device.name for device in result}),+ "duplicate device names must be made distinct in the menu",+ )++ def test_distinct_device_names_are_left_alone(self):+ devices = [make_device("ALPHA"), make_device("BETA")]+ result = sb.disambiguate_device_names(devices)+ self.assertEqual(["ALPHA", "BETA"], [device.name for device in result])++ def test_applescript_quote_escapes_injection(self):+ """Session titles reach AppleScript; quoting must not let them break out."""+ quoted = sb.applescript_quote('evil" & do shell script "rm -rf /')+ self.assertTrue(quoted.startswith('"') and quoted.endswith('"'))+ self.assertNotIn('" & do shell script "', quoted)++ def test_normalize_match_text_is_stable(self):+ self.assertEqual(+ sb.normalize_match_text(" Mixed CASE "),+ sb.normalize_match_text("mixed case"),+ )+++if __name__ == "__main__":+ unittest.main()