Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

macOS tray: drain autoreleased objects on every pass (#159)

Jarel Remickbcf045cf7ead
diff --git a/README.md b/README.md
index eeb70be..03f5217 100644
--- a/README.md
+++ b/README.md
@@ -139,8 +139,12 @@ With the Reason CLI: `reason network leave`, then `reason network setup --remove
cargo fmt && cargo clippy --all-targets -- -D warnings && cargo test
cargo build && python3 tests/e2e/two_machines.py # two machines over iroh (needs internet)
python3 tests/e2e/hooks.py && python3 tests/e2e/codex_busy.py && python3 tests/e2e/guided.py
+python3 tests/e2e/tray_memory.py --output /tmp/tray-memory.json # macOS desktop; keep the test menu closed
```
+The tray memory check uses synthetic local data and writes its measurements to JSON. Separately open a test submenu,
+close it, and reopen it after several updates to verify that the menu still works; see the script's instructions.
+
A `v*` tag builds the macOS, Linux and Windows archives and the install scripts; the Reason CLI pins the macOS and
Linux ones.
diff --git a/src/tray.rs b/src/tray.rs
index e0fd18e..4218da1 100644
--- a/src/tray.rs
+++ b/src/tray.rs
@@ -13,7 +13,7 @@ pub use mac::run;
mod mac {
use crate::{CLI, client::Link, config::Config, proto::*, util, wizard};
use anyhow::{Result, anyhow};
- use objc2::MainThreadMarker;
+ use objc2::{MainThreadMarker, rc::autoreleasepool};
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSCellImagePosition, NSEventMask, NSImage};
use objc2_foundation::{NSDate, NSDefaultRunLoopMode, NSString};
use std::{
@@ -49,81 +49,88 @@ mod mac {
pub fn run() -> Result<()> {
let mtm = MainThreadMarker::new().ok_or_else(|| anyhow!("the menu bar icon needs the main thread"))?;
- let app = NSApplication::sharedApplication(mtm);
- // A menu bar item only: no Dock icon, no app menu.
- app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
- app.finishLaunching();
+ let (app, tray) = autoreleasepool(|_| -> Result<_> {
+ let app = NSApplication::sharedApplication(mtm);
+ // A menu bar item only: no Dock icon, no app menu.
+ app.setActivationPolicy(NSApplicationActivationPolicy::Accessory);
+ app.finishLaunching();
+
+ let tray = TrayIconBuilder::new()
+ .with_tooltip("Reason")
+ .with_autosave_name("com.reasonmachines.network.tray")
+ .with_menu(Box::new(Menu::new()))
+ .build()?;
+ set_icon(&tray, false, None, mtm);
+ Ok((app, tray))
+ })?;
let (tx, updates) = mpsc::channel();
let (act, actions) = amsc::unbounded_channel();
tokio::spawn(poll(tx, actions));
- let tray = TrayIconBuilder::new()
- .with_tooltip("Reason")
- .with_autosave_name("com.reasonmachines.network.tray")
- .with_menu(Box::new(Menu::new()))
- .build()?;
- set_icon(&tray, false, None, mtm);
let parent = util::parent_pid();
let mut shown: Option<Box<View>> = None;
let mut flash: Option<(&str, Instant)> = None;
loop {
- let until = NSDate::dateWithTimeIntervalSinceNow(0.5);
- // SAFETY: the main thread's event loop, with AppKit's own run loop mode.
- let ev = unsafe {
- app.nextEventMatchingMask_untilDate_inMode_dequeue(
- NSEventMask::Any,
- Some(&until),
- NSDefaultRunLoopMode,
- true,
- )
- };
- if let Some(ev) = ev {
- app.sendEvent(&ev);
- }
- while let Ok(ev) = MenuEvent::receiver().try_recv() {
- match ev.id.as_ref() {
- "link" => {
- let _ = act.send(Action::CopyLink);
- }
- "hide" => hide(),
- id => {
- if let Some(addr) = id.strip_prefix("copy:") {
- let _ = act.send(Action::Copy(addr.to_string()));
+ // Our manual event loop must drain AppKit's temporary images and menus each time around.
+ autoreleasepool(|_| {
+ let until = NSDate::dateWithTimeIntervalSinceNow(0.5);
+ // SAFETY: the main thread's event loop, with AppKit's own run loop mode.
+ let ev = unsafe {
+ app.nextEventMatchingMask_untilDate_inMode_dequeue(
+ NSEventMask::Any,
+ Some(&until),
+ NSDefaultRunLoopMode,
+ true,
+ )
+ };
+ if let Some(ev) = ev {
+ app.sendEvent(&ev);
+ }
+ while let Ok(ev) = MenuEvent::receiver().try_recv() {
+ match ev.id.as_ref() {
+ "link" => {
+ let _ = act.send(Action::CopyLink);
+ }
+ "hide" => hide(),
+ id => {
+ if let Some(addr) = id.strip_prefix("copy:") {
+ let _ = act.send(Action::Copy(addr.to_string()));
+ }
}
}
}
- }
- let mut changed = false;
- while let Ok(u) = updates.try_recv() {
- match u {
- Update::View(v) if shown.as_ref().is_none_or(|s| s.key != v.key) => {
- tray.set_menu(Some(Box::new(menu(&v))));
- shown = Some(v);
- changed = true;
- }
- Update::View(_) => {}
- Update::Flash(text) => {
- flash = Some((text, Instant::now()));
- changed = true;
+ let mut changed = false;
+ while let Ok(u) = updates.try_recv() {
+ match u {
+ Update::View(v) if shown.as_ref().is_none_or(|s| s.key != v.key) => {
+ tray.set_menu(Some(Box::new(menu(&v))));
+ shown = Some(v);
+ changed = true;
+ }
+ Update::View(_) => {}
+ Update::Flash(text) => {
+ flash = Some((text, Instant::now()));
+ changed = true;
+ }
+ Update::Gone => std::process::exit(0),
}
- Update::Gone => std::process::exit(0),
}
- }
- if flash.is_some_and(|(_, at)| at.elapsed() > Duration::from_secs(2)) {
- flash = None;
- changed = true;
- }
- if changed {
- let v = shown.as_deref();
- let online = v.is_some_and(|v| v.machines.iter().any(|(m, ..)| m.online && !m.is_me));
- let title = flash.map(|(t, _)| t.to_string());
- set_icon(&tray, online, title.as_deref(), mtm);
- }
- // Our daemon exited (we were handed to launchd): go with it.
- if util::parent_pid() != parent {
- std::process::exit(0);
- }
+ if flash.is_some_and(|(_, at)| at.elapsed() > Duration::from_secs(2)) {
+ flash = None;
+ changed = true;
+ }
+ if changed {
+ let v = shown.as_deref();
+ let online = v.is_some_and(|v| v.machines.iter().any(|(m, ..)| m.online && !m.is_me));
+ let title = flash.map(|(t, _)| t.to_string());
+ set_icon(&tray, online, title.as_deref(), mtm);
+ }
+ // Our daemon exited (we were handed to launchd): go with it.
+ if util::parent_pid() != parent {
+ std::process::exit(0);
+ }
+ });
}
}
diff --git a/tests/e2e/tray_memory.py b/tests/e2e/tray_memory.py
new file mode 100644
index 0000000..ef56e7a
--- /dev/null
+++ b/tests/e2e/tray_memory.py
@@ -0,0 +1,159 @@
+"""macOS tray memory stays bounded while the directory and menus keep changing.
+
+ cargo build --locked
+ python3 tests/e2e/tray_memory.py --output /tmp/tray-memory.json
+
+Requires a logged-in macOS desktop and permission to inspect a child with vmmap.
+Runs the real tray for about two minutes against a synthetic local IPC server;
+no team, daemon, credentials or agent configuration is used. A temporary menu-bar
+icon appears during the check. The JSON output records every memory sample.
+
+Keep the menu closed during measurement. This checks memory growth, not UI
+progress: the background poller can run while AppKit is stalled. Separately open
+a populated submenu, close it, let updates pass, then reopen it and verify that
+the synthetic update number changed and that the items still work.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import re
+import socket
+import subprocess
+import tempfile
+import threading
+import time
+
+
+ROOT = Path(__file__).resolve().parents[2]
+MIB = 1024 * 1024
+
+
+def directory(tick):
+ machines, sessions = [], []
+ for m in range(8):
+ machine = f"box-{m}"
+ machines.append(dict(person="test", machine=machine, endpoint=str(m), is_me=m == 0,
+ online=m == 0 or tick % 6 != 0, link="direct", rtt_ms=tick,
+ last_seen=tick, verified=False, has_proof=False))
+ for s in range(7 + tick % 2):
+ sessions.append(dict(address=f"test/task-{m}-{s}@{machine}", name=f"task-{m}-{s}",
+ person="test", machine=machine, agent="codex", cwd="/synthetic",
+ repo="synthetic", branch="main", status="busy" if tick % 2 else "idle",
+ since=tick, doing=f"Synthetic update {tick}", tier="pull", unread=0,
+ is_me=False))
+ return dict(team="Tray memory test", person="test", machine="box-0", machines=machines, sessions=sessions)
+
+
+def footprint(pid):
+ result = subprocess.run(["/usr/bin/vmmap", "-summary", str(pid)], capture_output=True, text=True, timeout=30)
+ if result.returncode:
+ raise RuntimeError(result.stderr or result.stdout)
+ match = re.search(r"^Physical footprint:\s+([\d.]+)([KMGT]?)", result.stdout, re.M)
+ if not match:
+ raise RuntimeError("vmmap did not report the child's physical footprint")
+ scale = {"": 1, "K": 1024, "M": MIB, "G": 1024 * MIB, "T": 1024 * 1024 * MIB}
+ return round(float(match[1]) * scale[match[2]] / MIB, 3)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", type=Path, default=ROOT / "target/debug/reason-network")
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--seconds", type=int, default=120, help="measurement time after a 15-second warmup")
+ parser.add_argument("--max-growth-mib", type=float, default=4)
+ args = parser.parse_args()
+ if platform.system() != "Darwin":
+ parser.error("this check requires a macOS desktop")
+ if args.seconds < 60 or args.seconds % 30 or args.max_growth_mib <= 0:
+ parser.error("use at least 60 seconds in multiples of 30 and a positive memory-growth limit")
+ binary = args.binary.resolve(strict=True)
+ report = dict(binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),
+ macos=platform.mac_ver()[0], seconds=args.seconds,
+ max_growth_mib=args.max_growth_mib, samples=[], memory_check_passed=False,
+ ui_verification="requires a separate submenu interaction check")
+ polls, errors = [], []
+ stop = threading.Event()
+ process = None
+ # A short socket path avoids the production path-length fallback.
+ with tempfile.TemporaryDirectory(prefix="rn-tray-", dir="/tmp") as temporary:
+ with socket.socket(socket.AF_UNIX) as server, tempfile.TemporaryFile(mode="w+") as log:
+ socket_path = os.path.join(temporary, "network.sock")
+ server.bind(socket_path)
+ os.chmod(socket_path, 0o600)
+ server.listen(1)
+ server.settimeout(0.5)
+
+ def serve():
+ try:
+ while not stop.is_set():
+ try:
+ conn, _ = server.accept()
+ except socket.timeout:
+ continue
+ with conn, conn.makefile("rb") as stream:
+ for line in stream:
+ request = json.loads(line)
+ if request.get("op") != "who":
+ raise RuntimeError(f"unexpected request: {request.get('op')}")
+ tick = len(polls) + 1
+ reply = dict(id=request["id"], ok=True, result=directory(tick))
+ conn.sendall((json.dumps(reply) + "\n").encode())
+ polls.append(time.monotonic())
+ except (BrokenPipeError, ConnectionResetError):
+ if not stop.is_set():
+ errors.append("tray disconnected during the check")
+ except Exception as error:
+ errors.append(str(error))
+
+ worker = threading.Thread(target=serve, daemon=True)
+ worker.start()
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("REASON_NETWORK_", "TINCAN_"))}
+ env.update(REASON_NETWORK_HOME=temporary, REASON_NETWORK_NO_SERVICE="1",
+ REASON_NETWORK_NO_UPDATE="1", REASON_NETWORK_NO_MDNS="1")
+ try:
+ process = subprocess.Popen([str(binary), "tray"], env=env, cwd=temporary,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=log)
+ start = time.monotonic()
+ for offset in range(0, args.seconds + 1, 30):
+ deadline = start + 15 + offset
+ while time.monotonic() < deadline:
+ if process.poll() is not None or errors:
+ raise RuntimeError(f"tray exited early ({process.poll()}), server errors: {errors}")
+ time.sleep(min(0.2, max(0, deadline - time.monotonic())))
+ sample = dict(elapsed_seconds=round(time.monotonic() - start, 2),
+ footprint_mib=footprint(process.pid), polls=len(polls))
+ report["samples"].append(sample)
+ print(json.dumps(sample), flush=True)
+ samples = report["samples"]
+ report["growth_mib"] = round(max(s["footprint_mib"] for s in samples[1:])
+ - samples[0]["footprint_mib"], 3)
+ report["measured_polls"] = samples[-1]["polls"] - samples[0]["polls"]
+ report["memory_check_passed"] = (report["growth_mib"] <= args.max_growth_mib
+ and report["measured_polls"] >= args.seconds // 3
+ and process.poll() is None and not errors)
+ except Exception as error:
+ report["error"] = str(error)
+ finally:
+ stop.set()
+ if process is not None and process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ worker.join(timeout=2)
+ log.seek(0)
+ report["tray_log_tail"] = log.read()[-4000:]
+ report["server_errors"] = errors
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(report, indent=2) + "\n")
+ print(f"{'PASS' if report['memory_check_passed'] else 'FAIL'} (memory only): {args.output}")
+ return 0 if report["memory_check_passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())