Skip to content

CLI for SidePulse

Python

Reduce SidePulse memory and log churn

Peter Kuhar044508556934
diff --git a/src/sidepulse/audit.py b/src/sidepulse/audit.py
index 8e68b8a..c4fab92 100644
--- a/src/sidepulse/audit.py
+++ b/src/sidepulse/audit.py
@@ -5,7 +5,7 @@ import html
import json
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Iterable
+from typing import Any, Iterator
from .battery import BatterySnapshot
from .lid_sleep import MacSleepSnapshot
@@ -213,21 +213,24 @@ def truncate_preview(text: str, limit: int) -> str:
def read_status_audit_records(path: Path | None = None) -> list[dict[str, str]]:
+ return list(iter_status_audit_records(path))
+
+
+def iter_status_audit_records(path: Path | None = None) -> Iterator[dict[str, str]]:
source = path or default_status_audit_log_path()
try:
- lines = source.read_text(encoding="utf-8").splitlines()
+ handle = source.open(encoding="utf-8")
except OSError:
- return []
+ return
- records: list[dict[str, str]] = []
- for line in lines:
- try:
- obj = json.loads(line)
- except json.JSONDecodeError:
- continue
- if isinstance(obj, dict):
- records.append({column: str(obj.get(column, "")) for column in AUDIT_COLUMNS})
- return records
+ with handle:
+ for line in handle:
+ try:
+ obj = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(obj, dict):
+ yield {column: str(obj.get(column, "")) for column in AUDIT_COLUMNS}
def read_status_history_records(
@@ -237,13 +240,13 @@ def read_status_history_records(
) -> list[dict[str, object]]:
source = path or default_status_history_log_path()
try:
- lines = source.read_text(encoding="utf-8").splitlines()
+ if limit is not None and limit > 0:
+ lines = read_recent_lines(source, limit)
+ else:
+ lines = source.read_text(encoding="utf-8").splitlines()
except OSError:
return []
- if limit is not None and limit > 0:
- lines = lines[-limit:]
-
records: list[dict[str, object]] = []
for line in lines:
try:
@@ -255,18 +258,42 @@ def read_status_history_records(
return records
+def read_recent_lines(path: Path, max_lines: int) -> list[str]:
+ if max_lines <= 0:
+ return []
+
+ chunk_size = 8192
+ chunks: list[bytes] = []
+ newline_count = 0
+ with path.open("rb") as handle:
+ handle.seek(0, 2)
+ position = handle.tell()
+ while position > 0 and newline_count <= max_lines:
+ read_size = min(chunk_size, position)
+ position -= read_size
+ handle.seek(position)
+ chunk = handle.read(read_size)
+ chunks.append(chunk)
+ newline_count += chunk.count(b"\n")
+
+ data = b"".join(reversed(chunks))
+ return data.decode("utf-8", errors="replace").splitlines()[-max_lines:]
+
+
def export_status_audit_csv(
destination: Path,
*,
source: Path | None = None,
) -> int:
- records = read_status_audit_records(source)
destination.parent.mkdir(parents=True, exist_ok=True)
+ count = 0
with destination.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=AUDIT_COLUMNS)
writer.writeheader()
- writer.writerows(records)
- return len(records)
+ for record in iter_status_audit_records(source):
+ writer.writerow(record)
+ count += 1
+ return count
def export_status_audit_html(
@@ -274,39 +301,41 @@ def export_status_audit_html(
*,
source: Path | None = None,
) -> int:
- records = read_status_audit_records(source)
destination.parent.mkdir(parents=True, exist_ok=True)
- body = "\n".join(table_row(record) for record in records)
+ count = 0
generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
- destination.write_text(
- "\n".join(
- [
- "<!doctype html>",
- '<meta charset="utf-8">',
- "<title>SidePulse Agent Debug Log</title>",
- "<style>",
- "body{font:14px -apple-system,BlinkMacSystemFont,sans-serif;margin:24px;color:#1d1d1f}",
- "h1{font-size:22px;margin:0 0 4px}",
- "p{color:#6e6e73;margin:0 0 20px}",
- "table{border-collapse:collapse;width:100%;table-layout:fixed}",
- "th,td{border-bottom:1px solid #ddd;padding:7px 8px;text-align:left;vertical-align:top;word-wrap:break-word}",
- "th{position:sticky;top:0;background:#fff;font-weight:600}",
- "td.raw{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}",
- "</style>",
- "<h1>SidePulse Agent Debug Log</h1>",
- f"<p>{len(records)} events exported {html.escape(generated_at)}</p>",
- "<table>",
- "<thead><tr>",
- "".join(f"<th>{html.escape(column)}</th>" for column in AUDIT_COLUMNS),
- "</tr></thead>",
- f"<tbody>{body}</tbody>",
- "</table>",
- ]
+ with destination.open("w", encoding="utf-8") as handle:
+ handle.write(
+ "\n".join(
+ [
+ "<!doctype html>",
+ '<meta charset="utf-8">',
+ "<title>SidePulse Agent Debug Log</title>",
+ "<style>",
+ "body{font:14px -apple-system,BlinkMacSystemFont,sans-serif;margin:24px;color:#1d1d1f}",
+ "h1{font-size:22px;margin:0 0 4px}",
+ "p{color:#6e6e73;margin:0 0 20px}",
+ "table{border-collapse:collapse;width:100%;table-layout:fixed}",
+ "th,td{border-bottom:1px solid #ddd;padding:7px 8px;text-align:left;vertical-align:top;word-wrap:break-word}",
+ "th{position:sticky;top:0;background:#fff;font-weight:600}",
+ "td.raw{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}",
+ "</style>",
+ "<h1>SidePulse Agent Debug Log</h1>",
+ f"<p>Exported {html.escape(generated_at)}</p>",
+ "<table>",
+ "<thead><tr>",
+ "".join(f"<th>{html.escape(column)}</th>" for column in AUDIT_COLUMNS),
+ "</tr></thead><tbody>",
+ ]
+ )
+ + "\n"
)
- + "\n",
- encoding="utf-8",
- )
- return len(records)
+ for record in iter_status_audit_records(source):
+ handle.write(table_row(record))
+ handle.write("\n")
+ count += 1
+ handle.write(f"</tbody></table><p>{count} events</p>\n")
+ return count
def table_row(record: dict[str, str]) -> str:
diff --git a/src/sidepulse/battery.py b/src/sidepulse/battery.py
index 6c822bd..1663423 100644
--- a/src/sidepulse/battery.py
+++ b/src/sidepulse/battery.py
@@ -157,6 +157,7 @@ def read_battery_snapshot(
["ioreg", "-r", "-n", "AppleSmartBattery", "-a"],
check=True,
capture_output=True,
+ timeout=2,
)
data = result.stdout
if isinstance(data, str):
diff --git a/src/sidepulse/resources/sd_eject_guard.c b/src/sidepulse/resources/sd_eject_guard.c
index 34b5317..3161e59 100644
--- a/src/sidepulse/resources/sd_eject_guard.c
+++ b/src/sidepulse/resources/sd_eject_guard.c
@@ -16,12 +16,28 @@
#include <DiskArbitration/DiskArbitration.h>
#include <stdio.h>
#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
#define MOUNT_RETRY_SECONDS 5.0
+#define LOG_TRUNCATE_BYTES (10 * 1024 * 1024)
static DASessionRef g_session;
static bool g_no_mount = false;
+static void truncate_stdout_if_large(void) {
+ fflush(stdout);
+ int fd = fileno(stdout);
+ struct stat st;
+ if (fd < 0 || fstat(fd, &st) != 0 || !S_ISREG(st.st_mode))
+ return;
+ if (st.st_size <= LOG_TRUNCATE_BYTES)
+ return;
+ if (ftruncate(fd, 0) == 0)
+ lseek(fd, 0, SEEK_SET);
+ clearerr(stdout);
+}
+
static void log_msg(const char *fmt, CFStringRef s) {
char buf[256] = "?";
if (s) CFStringGetCString(s, buf, sizeof(buf), kCFStringEncodingUTF8);
@@ -54,8 +70,6 @@ static void mount_done(DADiskRef disk, DADissenterRef dissenter, void *ctx);
static void retry_mount(CFRunLoopTimerRef timer, void *info) {
DADiskRef disk = (DADiskRef)info;
if (is_mounted(disk)) {
- printf("mounted; stopping retries for %s\n", DADiskGetBSDName(disk));
- fflush(stdout);
CFRunLoopTimerInvalidate(timer);
CFRelease(disk);
return;
@@ -64,12 +78,9 @@ static void retry_mount(CFRunLoopTimerRef timer, void *info) {
}
static void mount_done(DADiskRef disk, DADissenterRef dissenter, void *ctx) {
- if (dissenter)
- printf("mount of %s dissented (0x%x), will retry\n",
- DADiskGetBSDName(disk), DADissenterGetStatus(dissenter));
- else
- printf("mount of %s succeeded\n", DADiskGetBSDName(disk));
- fflush(stdout);
+ (void)disk;
+ (void)dissenter;
+ (void)ctx;
}
static void start_mount_retries(DADiskRef disk) {
@@ -83,11 +94,15 @@ static void start_mount_retries(DADiskRef disk) {
}
static DADissenterRef eject_approval(DADiskRef disk, void *ctx) {
+ (void)ctx;
if (!is_builtin_sd(disk))
return NULL; // not ours, allow
+ const char *disk_name = DADiskGetBSDName(disk);
+ if (!disk_name) disk_name = "?";
CFDictionaryRef desc = DADiskCopyDescription(disk);
CFStringRef vol = desc ? CFDictionaryGetValue(desc, kDADiskDescriptionVolumeNameKey) : NULL;
- printf("vetoing eject of %s", DADiskGetBSDName(disk));
+ truncate_stdout_if_large();
+ printf("prevented eject of %s", disk_name);
log_msg(" (volume: %s)\n", vol);
if (desc) CFRelease(desc);
if (!g_no_mount)
@@ -96,12 +111,6 @@ static DADissenterRef eject_approval(DADiskRef disk, void *ctx) {
CFSTR("SidePulse Pro Eject Prevention: keeping SD card attached"));
}
-static void disk_appeared(DADiskRef disk, void *ctx) {
- if (!is_builtin_sd(disk)) return;
- printf("SD disk appeared: %s\n", DADiskGetBSDName(disk));
- fflush(stdout);
-}
-
int main(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--no-mount")) {
@@ -117,11 +126,7 @@ int main(int argc, char **argv) {
return 1;
}
DARegisterDiskEjectApprovalCallback(g_session, NULL, eject_approval, NULL);
- DARegisterDiskAppearedCallback(g_session, NULL, disk_appeared, NULL);
DASessionScheduleWithRunLoop(g_session, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
- printf("SidePulse Pro Eject Prevention: watching for ejects of the built-in SD reader%s...\n",
- g_no_mount ? " (mount retries disabled)" : "");
- fflush(stdout);
CFRunLoopRun();
return 0;
}
diff --git a/src/sidepulse/sd_eject_guard_launch.py b/src/sidepulse/sd_eject_guard_launch.py
index 40f7f1e..f9acea2 100644
--- a/src/sidepulse/sd_eject_guard_launch.py
+++ b/src/sidepulse/sd_eject_guard_launch.py
@@ -16,6 +16,7 @@ SD_EJECT_GUARD_DISPLAY_NAME = "SidePulse Pro Eject Prevention"
SD_EJECT_GUARD_BINARY_NAME = SD_EJECT_GUARD_DISPLAY_NAME
SD_EJECT_GUARD_LEGACY_BINARY_NAMES = ("sd_eject_guard",)
SD_EJECT_GUARD_SCOPES = ("auto", "system", "user")
+SD_EJECT_GUARD_LOG_MAX_BYTES = 10 * 1024 * 1024
SdEjectGuardScope = Literal["auto", "system", "user"]
ResolvedSdEjectGuardScope = Literal["system", "user"]
@@ -105,6 +106,7 @@ def install_sd_eject_guard(
paths.plist_path.parent.mkdir(parents=True, exist_ok=True)
paths.stdout_path.parent.mkdir(parents=True, exist_ok=True)
paths.stderr_path.parent.mkdir(parents=True, exist_ok=True)
+ truncate_log_if_large(paths.stdout_path)
if needs_compile:
compile_sd_eject_guard(resolved_source, paths.binary_path)
@@ -451,12 +453,46 @@ def read_log_tail(path: Path, line_count: int = 80) -> str:
if line_count <= 0:
return ""
try:
- lines = path.read_text(errors="replace").splitlines()
+ truncate_log_if_large(path)
+ lines = read_recent_lines(path, line_count)
except FileNotFoundError:
return ""
except OSError as exc:
return f"(unreadable: {exc})"
- return "\n".join(lines[-line_count:])
+ return "\n".join(lines)
+
+
+def truncate_log_if_large(
+ path: Path,
+ max_bytes: int = SD_EJECT_GUARD_LOG_MAX_BYTES,
+) -> bool:
+ try:
+ if path.stat().st_size <= max_bytes:
+ return False
+ with path.open("r+b") as handle:
+ handle.truncate(0)
+ return True
+ except (FileNotFoundError, OSError):
+ return False
+
+
+def read_recent_lines(path: Path, max_lines: int) -> list[str]:
+ chunk_size = 8192
+ chunks: list[bytes] = []
+ newline_count = 0
+ with path.open("rb") as handle:
+ handle.seek(0, 2)
+ position = handle.tell()
+ while position > 0 and newline_count <= max_lines:
+ read_size = min(chunk_size, position)
+ position -= read_size
+ handle.seek(position)
+ chunk = handle.read(read_size)
+ chunks.append(chunk)
+ newline_count += chunk.count(b"\n")
+
+ data = b"".join(reversed(chunks))
+ return data.decode("utf-8", errors="replace").splitlines()[-max_lines:]
def packaged_sd_eject_guard_source():
diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.py
index 0147e9f..6cb2b73 100644
--- a/src/sidepulse/status_bar.py
+++ b/src/sidepulse/status_bar.py
@@ -76,7 +76,7 @@ from .audit import (
read_status_history_records,
status_history_record,
)
-from .collector import LiveAgentMonitor, SourceSpec, read_recent_lines
+from .collector import LiveAgentMonitor, SourceSpec
from .device_writer import (
DEFAULT_FILE_NAME,
MOUNT_ROOT,
@@ -125,7 +125,6 @@ from .providers import (
detect_claude_config,
detect_codex_config,
detect_grok_config,
- detect_log_path,
default_state_dir,
parse_log_line,
)
@@ -234,10 +233,11 @@ STATUS_BAR_DEVICE_POLL_SECONDS = 2.0
STATUS_BAR_SESSION_HISTORY_LIMIT = 10
SCREEN_BAR_FEATURE_ENABLED = True
STATUS_BAR_MAX_LINES_PER_SOURCE = 500
-STATUS_BAR_STARTUP_REPLAY_LINES = 200
STATUS_BAR_HISTORY_CHART_RECORD_LIMIT = 2400
STATUS_BAR_HISTORY_CHART_RECORD_LIMIT_PADDING = 300
STATUS_BAR_HISTORY_CHART_RECORD_LIMIT_MULTIPLIER = 3.0
+MAC_SLEEP_POLL_SECONDS = 60.0
+SYSTEM_POLL_ERROR_BACKOFF_SECONDS = 30.0
LID_ANIMATION_RESTORE_FUDGE_SECONDS = 0.15
LID_ANIMATION_LABELS = {
LID_ANIMATION_CLOSED: "Lid Closed",
@@ -338,30 +338,6 @@ def format_percent_value(value: float | int) -> str:
return f"{number:.1f}%"
-def replay_recent_debug_logs(
- monitor: LiveAgentMonitor,
- *,
- providers: tuple[str, ...] = ("codex", "claude", "grok"),
- max_lines: int = STATUS_BAR_STARTUP_REPLAY_LINES,
-) -> int:
- replayed = 0
- for provider in providers:
- try:
- path = detect_log_path(provider)
- lines = read_recent_lines(path, max_lines) if path.exists() else []
- except Exception as exc:
- log_status_bar(f"startup_replay {provider} error: {exc}")
- continue
-
- for line in lines:
- record = parse_log_line(provider, line)
- if record is None:
- continue
- monitor.ingest_record(record)
- replayed += 1
- return replayed
-
-
class StatusBarController(NSObject):
def init(self):
self = objc.super(StatusBarController, self).init()
@@ -406,6 +382,10 @@ class StatusBarController(NSObject):
self.last_closed_lid_awake_error = None
self.last_mac_sleep_error = None
self.last_mac_sleep_snapshot = None
+ self.mac_sleep_poll_in_flight = False
+ self.last_mac_sleep_poll_monotonic = 0.0
+ self.mac_sleep_poll_backoff_until_monotonic = 0.0
+ self.pending_mac_sleep_snapshot = None
self.last_status_history_error = None
self.last_status_read_error = None
self.event_refresh_pending = False
@@ -416,6 +396,10 @@ class StatusBarController(NSObject):
self.battery_sleep_safeguard_reason = ""
self.last_lid_closed = None
self.last_lid_error = None
+ self.lid_poll_in_flight = False
+ self.lid_poll_backoff_until_monotonic = 0.0
+ self.pending_lid_closed = None
+ self.pending_lid_error = None
self.led_animation_until_monotonic = 0.0
self.led_animation_token = 0
self.virtual_status_device = VirtualStatusDevice.alloc().init()
@@ -425,7 +409,6 @@ class StatusBarController(NSObject):
NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)
log_status_bar("launching status item")
self.start_event_server()
- self.replay_debug_logs()
self.status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(
NSVariableStatusItemLength
@@ -854,11 +837,6 @@ class StatusBarController(NSObject):
self.event_refresh_pending = False
self.refresh_(None)
- def replay_debug_logs(self) -> None:
- replayed = replay_recent_debug_logs(self.monitor)
- if replayed:
- log_status_bar(f"startup_replay events={replayed}")
-
def show_settings_window(self) -> None:
if self.settings_window is None:
self.settings_window = build_settings_window(self)
@@ -1620,14 +1598,40 @@ class StatusBarController(NSObject):
self.last_power_connected = plugged
def read_mac_sleep_snapshot(self) -> MacSleepSnapshot | None:
- snapshot = read_mac_sleep_snapshot()
+ now = time.monotonic()
+ if (
+ not self.mac_sleep_poll_in_flight
+ and now >= self.mac_sleep_poll_backoff_until_monotonic
+ and now - self.last_mac_sleep_poll_monotonic >= MAC_SLEEP_POLL_SECONDS
+ ):
+ self.mac_sleep_poll_in_flight = True
+ self.last_mac_sleep_poll_monotonic = now
+ threading.Thread(target=self._read_mac_sleep_snapshot_async, daemon=True).start()
+ return self.last_mac_sleep_snapshot
+
+ def _read_mac_sleep_snapshot_async(self) -> None:
+ self.pending_mac_sleep_snapshot = read_mac_sleep_snapshot()
+ self.performSelectorOnMainThread_withObject_waitUntilDone_(
+ "handleMacSleepSnapshot:",
+ None,
+ False,
+ )
+
+ def handleMacSleepSnapshot_(self, _sender):
+ self.mac_sleep_poll_in_flight = False
+ snapshot = self.pending_mac_sleep_snapshot
+ self.pending_mac_sleep_snapshot = None
+ if not isinstance(snapshot, MacSleepSnapshot):
+ return
error = snapshot.error or None
if error != self.last_mac_sleep_error:
self.last_mac_sleep_error = error
if error:
log_status_bar(f"mac_sleep error: {error}")
+ self.mac_sleep_poll_backoff_until_monotonic = (
+ time.monotonic() + SYSTEM_POLL_ERROR_BACKOFF_SECONDS if error else 0.0
+ )
self.last_mac_sleep_snapshot = snapshot
- return snapshot
def record_status_history(
self,
@@ -2129,18 +2133,46 @@ class StatusBarController(NSObject):
@objc.IBAction
def pollLid_(self, _sender):
+ if self.lid_poll_in_flight:
+ return
+ if time.monotonic() < self.lid_poll_backoff_until_monotonic:
+ return
+ self.lid_poll_in_flight = True
+ threading.Thread(target=self._read_lid_closed_async, daemon=True).start()
+
+ def _read_lid_closed_async(self) -> None:
try:
- closed = read_lid_closed()
+ self.pending_lid_closed = read_lid_closed()
+ self.pending_lid_error = None
except Exception as exc:
- error = str(exc)
+ self.pending_lid_closed = None
+ self.pending_lid_error = str(exc)
+
+ self.performSelectorOnMainThread_withObject_waitUntilDone_(
+ "handleLidPollResult:",
+ None,
+ False,
+ )
+
+ def handleLidPollResult_(self, _sender):
+ self.lid_poll_in_flight = False
+ error = self.pending_lid_error
+ if error:
+ error = str(error)
if error != self.last_lid_error:
self.last_lid_error = error
log_status_bar(f"lid_state error: {error}")
+ self.lid_poll_backoff_until_monotonic = (
+ time.monotonic() + SYSTEM_POLL_ERROR_BACKOFF_SECONDS
+ )
return
+ closed = self.pending_lid_closed
if closed is None:
return
+ closed = bool(closed)
self.last_lid_error = None
+ self.lid_poll_backoff_until_monotonic = 0.0
if self.last_lid_closed is None:
self.last_lid_closed = closed
return
@@ -4009,13 +4041,24 @@ def session_open_action_title(status: AgentStatus, action: str, settings=None) -
def session_row_icon_for_status(status: AgentStatus):
+ cache_key = (
+ status.mode.value,
+ status.provider.lower(),
+ normalized_origin_text(status.origin),
+ )
+ if cache_key in _session_row_icon_cache:
+ return _session_row_icon_cache[cache_key]
+
status_icon = status_icon_for_status(status)
origin_icon = session_origin_icon_for_status(status)
if origin_icon is None:
- return status_icon
- if status_icon is None:
- return origin_icon
- return horizontal_icon_pair(status_icon, origin_icon)
+ image = status_icon
+ elif status_icon is None:
+ image = origin_icon
+ else:
+ image = horizontal_icon_pair(status_icon, origin_icon)
+ _session_row_icon_cache[cache_key] = image
+ return image
def status_icon_for_status(status: AgentStatus):
@@ -4037,57 +4080,63 @@ def provider_icon_for_status(status: AgentStatus):
def provider_icon_for_provider(provider: str):
provider = provider.lower()
+ if provider in _provider_icon_cache:
+ return _provider_icon_cache[provider]
+ image = None
if provider == "codex":
for path in ("/Applications/Codex.app", "/Applications/ChatGPT.app"):
image = app_icon(path)
if image is not None:
- return image
- return image_for_symbol("sparkles", "Codex")
- if provider == "claude":
+ break
+ image = image or image_for_symbol("sparkles", "Codex")
+ elif provider == "claude":
image = app_icon("/Applications/Claude.app")
- if image is not None:
- return image
- return image_for_symbol("brain.head.profile", "Claude")
- if provider == "grok":
+ image = image or image_for_symbol("brain.head.profile", "Claude")
+ elif provider == "grok":
image = app_icon("/Applications/Grok.app")
- if image is not None:
- return image
- return grok_badge_icon()
- return image_for_symbol("terminal", provider.title() or "Agent")
+ image = image or grok_badge_icon()
+ else:
+ image = image_for_symbol("terminal", provider.title() or "Agent")
+ _provider_icon_cache[provider] = image
+ return image
def host_icon_for_origin(origin: str | None):
normalized = normalized_origin_text(origin)
if not normalized:
return None
+ if normalized in _origin_icon_cache:
+ return _origin_icon_cache[normalized]
+ image = None
if "vs code" in normalized or "vscode" in normalized or "visual studio code" in normalized:
- return first_app_icon(
+ image = first_app_icon(
(
"/Applications/Visual Studio Code.app",
"/Applications/Visual Studio Code - Insiders.app",
)
) or image_for_symbol("chevron.left.forwardslash.chevron.right", "VS Code")
- if "cursor" in normalized:
- return first_app_icon(("/Applications/Cursor.app",)) or image_for_symbol(
+ elif "cursor" in normalized:
+ image = first_app_icon(("/Applications/Cursor.app",)) or image_for_symbol(
"cursorarrow",
"Cursor",
)
- if "windsurf" in normalized:
- return first_app_icon(("/Applications/Windsurf.app",)) or image_for_symbol(
+ elif "windsurf" in normalized:
+ image = first_app_icon(("/Applications/Windsurf.app",)) or image_for_symbol(
"wind",
"Windsurf",
)
- if any(token in normalized for token in ("cli", "terminal", "command line")):
- return first_app_icon(
+ elif any(token in normalized for token in ("cli", "terminal", "command line")):
+ image = first_app_icon(
(
"/System/Applications/Utilities/Terminal.app",
"/Applications/iTerm.app",
"/Applications/iTerm2.app",
)
) or image_for_symbol("terminal", "Terminal")
- if "transcript" in normalized:
- return image_for_symbol("doc.text", "Transcript")
- return None
+ elif "transcript" in normalized:
+ image = image_for_symbol("doc.text", "Transcript")
+ _origin_icon_cache[normalized] = image
+ return image
def first_app_icon(paths: tuple[str, ...]):
@@ -4161,6 +4210,11 @@ def normalized_origin_text(origin: str | None) -> str:
_grok_badge_icon = None
+_app_icon_cache = {}
+_provider_icon_cache = {}
+_origin_icon_cache = {}
+_session_row_icon_cache = {}
+_symbol_icon_cache = {}
def grok_badge_icon():
@@ -4195,11 +4249,15 @@ def grok_badge_icon():
def app_icon(path: str):
+ if path in _app_icon_cache:
+ return _app_icon_cache[path]
if not Path(path).exists():
+ _app_icon_cache[path] = None
return None
image = NSWorkspace.sharedWorkspace().iconForFile_(path)
if image is not None:
image.setSize_((18, 18))
+ _app_icon_cache[path] = image
return image
@@ -4390,6 +4448,9 @@ def project_name_from_cwd(cwd: str | None) -> str | None:
def image_for_symbol(symbol: str, description: str):
+ cache_key = (symbol, description)
+ if cache_key in _symbol_icon_cache:
+ return _symbol_icon_cache[cache_key]
try:
image = NSImage.imageWithSystemSymbolName_accessibilityDescription_(
symbol,
@@ -4399,6 +4460,7 @@ def image_for_symbol(symbol: str, description: str):
image.setTemplate_(True)
except Exception:
image = None
+ _symbol_icon_cache[cache_key] = image
return image
diff --git a/src/sidepulse/virtual_device.py b/src/sidepulse/virtual_device.py
index 019df7a..d58d132 100644
--- a/src/sidepulse/virtual_device.py
+++ b/src/sidepulse/virtual_device.py
@@ -32,13 +32,15 @@ LED_BAND_HEIGHT = 5.0
WINDOW_HEIGHT = FALLBACK_NOTCH_DEPTH + LED_BAND_HEIGHT
NOTCH_BOTTOM_RADIUS = 8.0
LED_BLEND_RADIUS_LEDS = 1.5
-BLEND_COLUMN_WIDTH = 2.0
+BLEND_COLUMN_WIDTH = 4.0
LED_GLOW_HEIGHT = 11.0
LED_CORE_BOOST = 1.22
LED_HOTLINE_BOOST = 1.46
LED_GAMMA = 0.86
FRAME_RATE = 60.0
FRAME_INTERVAL = 1.0 / FRAME_RATE
+IDLE_FRAME_RATE = 12.0
+IDLE_FRAME_INTERVAL = 1.0 / IDLE_FRAME_RATE
def monotonic_ms() -> int:
@@ -402,6 +404,7 @@ class VirtualStatusDevice(NSObject):
self.window = None
self.view = None
self.timer = None
+ self.frame_interval = None
return self
def show(self):
@@ -409,29 +412,46 @@ class VirtualStatusDevice(NSObject):
self._build_window()
self.reposition()
self.window.orderFrontRegardless()
- if self.timer is None:
- self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
- FRAME_INTERVAL, self, "redraw:", None, True
- )
def hide(self):
- if self.timer is not None:
- self.timer.invalidate()
- self.timer = None
+ self._stop_timer()
if self.window is not None:
self.window.orderOut_(None)
def set_state(self, state: LedDisplayState, brightness: int | float):
self.show()
self.view.setState_brightness_(state, brightness)
+ if state in {LedDisplayState.WORKING, LedDisplayState.ASK}:
+ self._ensure_timer(FRAME_INTERVAL)
+ elif state == LedDisplayState.IDLE:
+ self._ensure_timer(IDLE_FRAME_INTERVAL)
+ else:
+ self._stop_timer()
def set_battery(self, percent: int, brightness: int | float):
self.show()
self.view.setBatteryPercent_brightness_(percent, brightness)
+ self._stop_timer()
def set_program(self, program: str):
self.show()
self.view.setProgram_(program)
+ self._ensure_timer(FRAME_INTERVAL)
+
+ def _ensure_timer(self, interval: float):
+ if self.timer is not None and self.frame_interval == interval:
+ return
+ self._stop_timer()
+ self.frame_interval = interval
+ self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
+ interval, self, "redraw:", None, True
+ )
+
+ def _stop_timer(self):
+ if self.timer is not None:
+ self.timer.invalidate()
+ self.timer = None
+ self.frame_interval = None
def reposition(self):
screen = NSScreen.mainScreen()
diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.py
index 8981479..b960646 100644
--- a/tests/test_sidepulse.py
+++ b/tests/test_sidepulse.py
@@ -93,12 +93,15 @@ from sidepulse.sd_eject_guard_launch import (
SD_EJECT_GUARD_BINARY_NAME,
SD_EJECT_GUARD_DISPLAY_NAME,
SD_EJECT_GUARD_LABEL,
+ SD_EJECT_GUARD_LOG_MAX_BYTES,
SdEjectGuardInstallError,
SdEjectGuardPaths,
build_sd_eject_guard_plist,
install_sd_eject_guard,
+ read_log_tail,
sd_eject_guard_installed,
stop_sd_eject_guard,
+ truncate_log_if_large,
uninstall_sd_eject_guard,
)
from sidepulse.session_actions import (
@@ -606,47 +609,6 @@ class AgentMonitorTests(unittest.TestCase):
self.assertEqual(reloaded.snapshot().aggregate.mode, AgentMode.TOOL_RUNNING)
self.assertEqual(reloaded.snapshot().statuses[0].origin, "Codex UI")
- def test_status_bar_startup_replay_ingests_recent_debug_logs(self) -> None:
- try:
- from sidepulse import status_bar
- except SystemExit as exc:
- self.skipTest(str(exc))
-
- with tempfile.TemporaryDirectory() as tmp:
- base = Path(tmp)
- log = base / "codex.jsonl"
- session_id = "eeeeeeee-ffff-7aaa-8bbb-cccccccccccc"
- log.write_text(
- json.dumps(
- {
- "logged_at": datetime.now(timezone.utc).isoformat(),
- "event": {
- "hook_event_name": "UserPromptSubmit",
- "session_id": session_id,
- "cwd": "/tmp/project",
- "prompt": "startup replay should restore this",
- },
- }
- )
- + "\n"
- )
- monitor = LiveAgentMonitor()
-
- with patch(
- "sidepulse.status_bar.detect_log_path",
- return_value=log,
- ):
- replayed = status_bar.replay_recent_debug_logs(
- monitor,
- providers=("codex",),
- max_lines=20,
- )
-
- snapshot = monitor.snapshot()
- self.assertEqual(replayed, 1)
- self.assertEqual(snapshot.aggregate.mode, AgentMode.WORKING)
- self.assertIn("startup replay", snapshot.statuses[0].display_name)
-
def test_status_bar_session_menu_title_is_task_and_project(self) -> None:
try:
from sidepulse import status_bar
@@ -4742,6 +4704,21 @@ class AgentMonitorTests(unittest.TestCase):
def test_sd_eject_guard_default_binary_uses_background_item_name(self) -> None:
self.assertEqual(SD_EJECT_GUARD_BINARY_NAME, SD_EJECT_GUARD_DISPLAY_NAME)
+ def test_sd_eject_guard_log_cleaner_truncates_files_over_limit(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ log = Path(tmp) / "sd-eject-guard.out.log"
+ log.parent.mkdir(parents=True, exist_ok=True)
+ with log.open("wb") as handle:
+ handle.seek(SD_EJECT_GUARD_LOG_MAX_BYTES)
+ handle.write(b"x")
+
+ self.assertTrue(truncate_log_if_large(log))
+ self.assertEqual(log.stat().st_size, 0)
+
+ log.write_text("prevented eject of disk4s1\n", encoding="utf-8")
+ self.assertFalse(truncate_log_if_large(log))
+ self.assertEqual(read_log_tail(log, 5), "prevented eject of disk4s1")
+
def test_sd_eject_guard_installed_checks_user_and_system_plists(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)