Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280"""Exercise production launchd commands on a private macOS agent.
Run `nix develop --command python3 test/manual/service_darwin.py` after buildingcli/bin/albedo. The runner builds one sealed snapshot unless ALBEDO_TEST_DAEMONis supplied. The agent's HOME, LaunchAgents directory, ALBEDO_HOME and label areprivate to the run. Captures and logs stay in the printed evidence directory(ALBEDO_LAUNCHD_EVIDENCE, or a new temporary one), which the run never removes."""
import hashlibimport jsonimport osfrom pathlib import Pathimport shutilimport signalimport subprocessimport sysimport tempfileimport timeimport unittest
ROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT / "test/e2e"))from harness import Albedo, Provider, alive, exclusive, python, text, wait_until # noqa: E402
LAUNCHCTL = "/bin/launchctl"# Runner-only settings that must never reach the managed daemon.RUNNER_ONLY = ("ALBEDO_PRELOAD=", "ALBEDO_IDLE_SECONDS=", "ALBEDO_MCP_SECRET=")
def launchctl(*args: str, check: bool = False) -> subprocess.CompletedProcess[str]: return subprocess.run( [LAUNCHCTL, *args], capture_output=True, text=True, timeout=55, check=check )
def process_environment(pid: int) -> str: return subprocess.run( ["/bin/ps", "eww", "-o", "command=", "-p", str(pid)], capture_output=True, text=True, check=True, ).stdout
def processes_naming(fragment: str) -> list[str]: listing = subprocess.run( ["/bin/ps", "eww", "-axo", "pid=,command="], capture_output=True, text=True, check=True, ).stdout return [ line for line in listing.splitlines() if fragment in line and str(os.getpid()) != line.split()[0] ]
@exclusiveclass NativeLaunchdTests(unittest.TestCase): def test_production_lifecycle(self) -> None: if sys.platform != "darwin": self.skipTest("requires a macOS GUI domain") evidence = Path( os.environ.get("ALBEDO_LAUNCHD_EVIDENCE") or tempfile.mkdtemp(prefix="albedo-launchd-native-") ) evidence.mkdir(parents=True, exist_ok=True) print(f"native launchd evidence: {evidence}", flush=True) uid = os.getuid() disabled_before = launchctl("print-disabled", f"gui/{uid}", check=True).stdout cells: list[str] = []
def script(request: dict) -> list: if request["input"][-1].get("role") == "user" and cells: return python(cells.pop(0)) return text("done")
target: str | None = None
def prepare(app: Albedo) -> None: nonlocal target label = ( "systems.albedo.daemon-" + hashlib.sha256(str(app.home).encode()).hexdigest()[:16] ) target = f"gui/{uid}/{label}" app.env["ALBEDO_LAUNCHCTL"] = LAUNCHCTL app.env.pop("ALBEDO_PARENT_PID", None) app.daemon.boot_action = lambda daemon: daemon.cli("daemon", "install")
provider = Provider(script) app = Albedo(provider, protocol="responses", prepare=prepare) kernel_pid: int | None = None kernel_identity: str | None = None try: app.__enter__() assert target is not None path = ( Path(app.env["HOME"]) / "Library/LaunchAgents" / (target.split("/")[-1] + ".plist") ) shutil.copy(path, evidence / "generated.plist") (evidence / "identity.json").write_text( json.dumps({"home": str(app.home), "target": target}) )
def must(*args: str) -> str: result = subprocess.run( [str(ROOT / "cli/bin/albedo"), *args], env=app.env, capture_output=True, text=True, timeout=60, ) with (evidence / "commands.log").open("a") as log: log.write( f"{args}: exit {result.returncode}\n{result.stdout}{result.stderr}\n" ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) return result.stdout
def identity(name: str) -> int: app.daemon.connection = None app.daemon.await_ready() with app.api("/server") as response: server = json.load(response) output = launchctl("print", target, check=True).stdout (evidence / f"print-{name}.txt").write_text(output) self.assertIn(f"\tpid = {app.connection['pid']}\n", output) self.assertEqual(server["pid"], app.connection["pid"]) return server["pid"]
session = app.session()
def cell(code: str) -> str: cells.append(code) app.prompt(session, "run it").close() app.idle(session) return [ json.loads(part["value"])["value"] for entry in app.history(session)["items"] if entry["kind"] == "tool_result" and entry["tool"]["name"] == "python" for part in entry["content"] if part["kind"] == "json" and part["field"] == "result" ][-1]
original = identity("installed") process = process_environment(original) self.assertIn("beam", process.split()[0].lower()) for key in RUNNER_ONLY: self.assertNotIn(key, process) self.assertEqual( json.loads(must("daemon", "status", "--json"))["class"], "managed" ) kernel_pid = int(cell("import os\nsurvivor = 41\nos.getpid()")) kernel_identity = process_environment(kernel_pid) must("daemon", "--stop") self.assertTrue(alive(kernel_pid)) # The real OS timer is under test: clean exit must stay idle beyond throttle. deadline = time.monotonic() + 11 while time.monotonic() < deadline: self.assertIn( "\tstate = not running\n", launchctl("print", target, check=True).stdout, ) time.sleep(0.5) must("daemon") identity("restarted") self.assertEqual(cell("(survivor, os.getpid())"), f"(41, {kernel_pid})") crashed = app.connection["pid"] os.kill(crashed, signal.SIGKILL) wait_until(lambda: not alive(crashed), 20, "crashed daemon survived") self.assertNotEqual(identity("recovered"), crashed) self.assertEqual(cell("(survivor, os.getpid())"), f"(41, {kernel_pid})") must("daemon", "--stop", "--kernels") wait_until( lambda: not alive(kernel_pid), 10, "private kernel survived shutdown" ) kernel_pid = None must("daemon", "uninstall") self.assertFalse(path.exists()) finally: cleanup_errors: list[str] = [] try: if kernel_pid is not None and alive(kernel_pid): # An idle agent needs a daemon to adopt and end its kernels. result = subprocess.run( [str(ROOT / "cli/bin/albedo"), "daemon"], env=app.env, capture_output=True, text=True, timeout=60, ) (evidence / "cleanup-start.txt").write_text( f"exit {result.returncode}\n{result.stdout}{result.stderr}" ) if target is not None and launchctl("print", target).returncode != 113: subprocess.run( [str(ROOT / "cli/bin/albedo"), "daemon", "--stop", "--kernels"], env=app.env, capture_output=True, timeout=60, ) except (OSError, subprocess.SubprocessError) as error: cleanup_errors.append(str(error)) finally: # If adoption failed, signal only the original private kernel. try: if kernel_pid is not None and alive(kernel_pid): if ( kernel_identity is None or process_environment(kernel_pid) != kernel_identity or f"ALBEDO_HOME={app.home}" not in kernel_identity or os.getpgid(kernel_pid) != kernel_pid ): raise AssertionError("private kernel identity changed") os.kill(kernel_pid, signal.SIGTERM) wait_until( lambda: not alive(kernel_pid), 30, "private kernel survived" ) except (OSError, subprocess.SubprocessError, AssertionError) as error: cleanup_errors.append(str(error)) try: if ( target is not None and launchctl("print", target).returncode != 113 ): launchctl("bootout", target) except (OSError, subprocess.SubprocessError) as error: cleanup_errors.append(str(error)) cleanup: dict[str, object] = {"errors": cleanup_errors} try: cleanup = { "print": None if target is None else launchctl("print", target).returncode, "survivors": processes_naming(f"ALBEDO_HOME={app.home}"), "disabled_unchanged": launchctl( "print-disabled", f"gui/{uid}" ).stdout == disabled_before, } deadline = time.monotonic() + 30 while cleanup["survivors"] and time.monotonic() < deadline: time.sleep(0.5) cleanup["survivors"] = processes_naming(f"ALBEDO_HOME={app.home}") self.assertIn(cleanup["print"], (None, 113)) self.assertEqual(cleanup["survivors"], []) self.assertTrue(cleanup["disabled_unchanged"]) finally: try: cleanup["errors"] = cleanup_errors (evidence / "cleanup.json").write_text( json.dumps(cleanup, indent=2) ) if (app.home / "daemon.log").exists(): shutil.copy(app.home / "daemon.log", evidence / "daemon.log") finally: try: app.__exit__(None, None, None) finally: provider.close() self.assertEqual(cleanup_errors, [])
if __name__ == "__main__": raise SystemExit( subprocess.run( [ sys.executable, str(ROOT / "test/e2e/run.py"), str(Path(__file__).resolve()), ] ).returncode )