"""Human shell execution stays durable across restarts and crashes. The daemon keeps what only the assembled system shows: the login shell's environment, a model reading output through its kernel binding, process reaping on stop and on session deletion, and restart, crash, and fork durability. Receipt delivery, retries, paging, capture bounds, and capture failure are in-process tests in apps/albedo/test/albedo/session/shell_delivery_test.gleam. """ import json import os from pathlib import Path import shlex import shutil import sys import unittest import urllib.error from harness import ( Albedo, Provider, exclusive, operation_id, python, text, wait_until, conversation, ) def python_command(source): return shlex.join([sys.executable, "-c", source]) def publish_pid_marker(name: str, value: str) -> str: """Build child Python source that publishes a complete PID marker.""" temporary = name + ".tmp" return ( f"Path({temporary!r}).write_text({value}); " f"Path({temporary!r}).replace({name!r}); " ) def process_running(pid): try: os.kill(pid, 0) stat = Path(f"/proc/{pid}/stat") return not stat.exists() or stat.read_text().rsplit(")", 1)[1].split()[0] != "Z" except (ProcessLookupError, FileNotFoundError): return False @exclusive class ShellCommandTests(unittest.TestCase): # Shell startup reads HOME and SHELL: every daemon needs a private environment. def setUp(self): self.script = lambda _: text("reported") self.provider = Provider(lambda request: self.script(request)) self.addCleanup(self.provider.close) def prepare(app): app.daemon.env["HOME"] = str(app.home) app.daemon.env["SHELL"] = shutil.which("bash") for key in ("BASH_ENV", "ENV", "ZDOTDIR"): app.daemon.env.pop(key, None) (app.home / ".bash_profile").write_text( "export BANG_LOGIN_PROFILE=loaded\n" ) self.app = Albedo(self.provider, protocol="responses", prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.session = self.app.session() def url(self, command_id): return f"/sessions/{self.session}/shell-commands/{command_id}" def put(self, command_id, command): with self.app.api( self.url(command_id), {"command": command}, method="PUT" ) as response: return json.load(response)["shell_command"] def read(self, command_id): with self.app.api(self.url(command_id)) as response: return json.load(response)["shell_command"] def done(self, command_id, *, committed=True, seconds=15): observed = [] def ready(): observed[:] = [self.read(command_id)] command = observed[0] return command["status"] != "running" and ( not committed or command["history_seq"] is not None ) wait_until(ready, seconds, f"shell command {command_id} did not finish") return observed[0] def shell_history(self): return [ item for item in self.app.history(self.session)["items"] if item["kind"] == "shell_command" ] def capture(self, command_id, session=None): return self.app.home / "shell-output" / (session or self.session) / command_id def output_page(self, command_id, offset=0, limit=65536): with self.app.api( self.url(command_id) + f"/output?offset={offset}&limit={limit}" ) as response: return json.load(response) def test_login_shell_cwd_stdin_and_exit_status_without_model_generation(self): command_id = operation_id() command = ( 'printf "%s\\n" "$PWD" "$BANG_LOGIN_PROFILE"; ' + python_command( 'import os,sys; print("tty",os.isatty(0)); ' 'print("stdin",len(sys.stdin.buffer.read()))' ) + '; printf "stderr-marker\\n" >&2; exit 7' ) self.put(command_id, command) result = self.done(command_id) self.assertEqual(result["status"], "completed") self.assertEqual(result["exit_code"], 7) self.assertIn(str(self.app.workspace), result["output"]) self.assertIn("loaded", result["output"]) self.assertIn("tty False", result["output"]) self.assertIn("stdin 0", result["output"]) self.assertIn("stderr-marker", result["output"]) self.assertEqual(self.provider.requests, []) self.assertEqual(len(self.shell_history()), 1) self.assertEqual(self.app.idle(self.session)["status"]["phase"], "idle") def test_model_reads_output_beyond_its_context_excerpt_through_read_only_binding( self, ): command_id = operation_id() self.put( command_id, python_command( 'import sys; sys.stdout.write("h"*65536+"read-through-daemon")' ), ) self.done(command_id) def script(request): if any( item.get("type") == "function_call_output" for item in request["input"] ): return text("read") return python( f"page = await output.read_shell({command_id!r}, offset=65536); " "assert page.next_offset is None; print(page.text)" ) self.script = script self.app.prompt(self.session, "Read the rest of that command output.").close() self.app.idle(self.session) sent = json.dumps(conversation(self.provider.requests[-1]["request"])) self.assertIn("read-through-daemon", sent) self.assertEqual(len(self.provider.requests), 2) def test_second_running_command_is_refused_and_stop_reaps_descendants(self): command_id = operation_id() source = ( "import os,subprocess,sys,time; from pathlib import Path; " 'child=subprocess.Popen([sys.executable,"-c","import time;time.sleep(120)"]); ' + publish_pid_marker("pids", 'f"{os.getpid()} {child.pid}"') + 'print("started",flush=True); time.sleep(120)' ) self.put(command_id, python_command(source)) marker = self.app.workspace / "pids" wait_until(marker.exists, 10, "shell process did not start") parent, child = map(int, marker.read_text().split()) with self.assertRaises(urllib.error.HTTPError) as failure: self.put(operation_id(), "printf should-not-run") self.assertEqual(failure.exception.code, 409) with self.app.api(self.url(command_id) + "/stop", {}) as response: json.load(response) result = self.done(command_id) self.assertEqual(result["status"], "cancelled") wait_until( lambda: not any(map(process_running, (parent, child))), 10, "shell descendants survived stop", ) self.assertEqual(self.provider.requests, []) def test_fork_preserves_capture_and_rewind_keeps_retry_receipt_without_reexecution( self, ): self.app.prompt(self.session, "before shell").close() self.app.idle(self.session) first = next( item for item in self.app.history(self.session)["items"] if item["kind"] == "user" ) command_id = operation_id() command = "printf x >> fork-effect; printf forked-shell-output" self.put(command_id, command) self.done(command_id) self.app.prompt(self.session, "after shell").close() self.app.idle(self.session) last = next( item for item in reversed(self.app.history(self.session)["items"]) if item["kind"] == "user" ) branch = operation_id() with self.app.api( f"/sessions/{branch}", { "kind": "fork", "source_session_id": self.session, "checkpoint_id": last["checkpoint_id"], }, method="PUT", headers={"If-None-Match": "*"}, ) as response: json.load(response) copied = [ item for item in self.app.history(branch)["items"] if item["kind"] == "shell_command" ] self.assertEqual(len(copied), 1) with self.app.api( f"/sessions/{branch}/shell-commands/{command_id}/output" ) as response: self.assertEqual(json.load(response)["text"], "forked-shell-output") # A committed capture is immutable: the fork names the same file. self.assertTrue( self.capture(command_id).samefile(self.capture(command_id, branch)) ) with self.app.api("/storage") as response: totals = json.load(response)["files"]["totals"] self.assertEqual(totals["shell_output_bytes"], len("forked-shell-output")) self.app.prompt(branch, "What did the shell print?").close() self.app.idle(branch) self.assertIn( "forked-shell-output", json.dumps(conversation(self.provider.requests[-1]["request"])), ) with self.app.api( f"/sessions/{self.session}/rewind", { "checkpoint_id": first["checkpoint_id"], }, ) as response: json.load(response) self.assertEqual(self.shell_history(), []) recovered = self.put(command_id, command) self.assertEqual(recovered["status"], "completed") self.assertIsNone(recovered["history_seq"]) self.assertEqual(recovered["delivery"], "detached") self.assertEqual(self.shell_history(), []) self.assertEqual((self.app.workspace / "fork-effect").read_text(), "x") self.assertEqual(len(self.provider.requests), 3) def test_session_deletion_reaps_command_and_removes_output(self): command_id = operation_id() self.put( command_id, python_command( "import os,time; from pathlib import Path; " + publish_pid_marker("pid", "str(os.getpid())") + 'print("retained",flush=True); time.sleep(120)' ), ) marker = self.app.workspace / "pid" wait_until(marker.exists, 10, "shell process did not start") pid = int(marker.read_text()) wait_until( lambda: self.capture(command_id).exists(), 10, "capture never started" ) resource = f"/sessions/{self.session}/configuration" with self.app.api(resource) as response: validator = response.getheader("ETag") response.read() with self.app.api( resource.removesuffix("/configuration"), method="DELETE", headers={"If-Match": validator}, ) as response: self.assertEqual(json.load(response)["state"], "complete") wait_until( lambda: not process_running(pid), 10, "shell process survived session deletion", ) with self.assertRaises(urllib.error.HTTPError) as failure: self.read(command_id) self.assertEqual(failure.exception.code, 404) self.assertFalse(self.capture(command_id).parent.exists()) def test_crash_mid_capture_keeps_a_whole_readable_prefix(self): command_id = operation_id() self.put( command_id, python_command( 'import sys,time; sys.stdout.write("é"*4000); sys.stdout.flush(); ' "time.sleep(120)" ), ) wait_until( lambda: self.read(command_id)["output_bytes"] == 8000, 10, "capture did not reach its row", ) def lose_tail(_app): # A power loss kept the row but not the file's last page cache # write, ending it inside a two-byte character. with self.capture(command_id).open("r+b") as capture: capture.truncate(5001) self.app.restart(crash=True, prepare=lose_tail) result = self.done(command_id, committed=False) self.assertEqual(result["status"], "interrupted") self.assertEqual(result["output_bytes"], 5000) self.assertEqual(self.capture(command_id).stat().st_size, 5000) self.assertEqual(len(result["output"].encode()), 5000) pieces, offset = [], 0 while offset is not None: page = self.output_page(command_id, offset, 4000) pieces.append(page["text"]) offset = page["next_offset"] self.assertEqual("".join(pieces), "é" * 2500) def test_graceful_restart_stops_command_without_rerunning_it(self): command_id = operation_id() command = python_command( "import os,time; from pathlib import Path; " 'Path("effect").open("a").write("x"); ' + publish_pid_marker("pid", "str(os.getpid())") + "time.sleep(120)" ) self.put(command_id, command) marker = self.app.workspace / "pid" wait_until(marker.exists, 10, "shell process did not start") pid = int(marker.read_text()) self.app.restart() recovered = self.done(command_id, committed=False) self.assertIn(recovered["status"], ("cancelled", "interrupted")) self.app.idle(self.session) # reconnect materializes the idle actor result = self.done(command_id) self.assertIn(result["status"], ("cancelled", "interrupted")) self.assertEqual(self.put(command_id, command)["status"], result["status"]) self.assertEqual((self.app.workspace / "effect").read_text(), "x") wait_until( lambda: not process_running(pid), 10, "shell process survived daemon shutdown", ) self.assertEqual(self.provider.requests, []) def test_daemon_crash_interrupts_command_without_replaying_its_effect(self): command_id = operation_id() command = python_command( "import os,time; from pathlib import Path; " 'Path("effect").open("a").write("x"); ' + publish_pid_marker("pid", "str(os.getpid())") + "time.sleep(120)" ) self.put(command_id, command) marker = self.app.workspace / "pid" wait_until(marker.exists, 10, "shell process did not start") pid = int(marker.read_text()) self.app.restart(crash=True) self.assertEqual( self.done(command_id, committed=False)["status"], "interrupted" ) self.app.idle(self.session) # reconnect materializes the idle actor result = self.done(command_id) self.assertEqual(result["status"], "interrupted") self.assertEqual(self.put(command_id, command)["status"], "interrupted") self.assertEqual((self.app.workspace / "effect").read_text(), "x") wait_until( lambda: not process_running(pid), 10, "shell process survived daemon crash" ) self.assertEqual(len(self.shell_history()), 1) self.assertEqual(self.provider.requests, []) def test_pending_receipt_survives_restart_then_delivers_without_rerunning(self): command_id = operation_id() command = "printf x >> receipt-effect; printf '%s%s' restart-receipt- 416" self.put(command_id, command) self.assertEqual(self.done(command_id)["delivery"], "pending") self.app.restart(crash=True) self.app.idle(self.session) self.assertEqual(self.read(command_id)["delivery"], "pending") self.assertEqual(self.provider.requests, []) self.app.prompt(self.session, "Read the recovered shell receipt.").close() self.app.idle(self.session) self.assertEqual(self.read(command_id)["delivery"], "delivered") sent = json.dumps(conversation(self.provider.requests[-1]["request"])) self.assertEqual(sent.count("restart-receipt-416"), 1) self.app.restart(crash=True) self.app.idle(self.session) self.assertEqual(self.put(command_id, command)["delivery"], "delivered") self.assertEqual((self.app.workspace / "receipt-effect").read_text(), "x") self.assertEqual(len(self.shell_history()), 1) self.assertEqual(len(self.provider.requests), 1)