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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246"""Long cells detach without losing output, deadlines, or completion wakes."""
import jsonimport timeimport unittest
from harness import ( Albedo, cell_result, exclusive_class, has_note, is_note, latest_user, Provider, python, text, wait_until,)
def wait_for(predicate, timeout=40): return wait_until(predicate, timeout, "background cell did not wake session")
@exclusive_classclass CellBackgroundTests(unittest.TestCase): def setUp(self): self.results = [] self.read_before_idle = False self.with_job = False self.stop_job_on_release = False self.cell_title = "" self.cell_code = None self.cell_id = None
def script(request): # A note the kernel's arrival left follows the cell's result. last = next(m for m in reversed(request["messages"]) if not is_note(m)) user = latest_user(request) if last.get("role") == "tool": result = cell_result(last["content"]) self.results.append(result) if result.get("status") == "backgrounded": self.cell_id = result["cell_id"] return text("waiting for the background cell") if "background python cells finished" in user: return text("completion received") if "start cell" in user: code = ( "import asyncio\n" "cell_gate = asyncio.Event()\n" "cell_done = asyncio.Event()\n" "print('before detach')\n" "await cell_gate.wait()\n" "print('after detach')\n" "cell_done.set()\n" "{'answer': 42}" ) if self.stop_job_on_release: code = code.replace( "cell_done.set()", "await held.stop()\ncell_done.set()" ) if self.with_job: code = "held = run('sleep', '30')\n" + code if self.cell_title: code = f"# {self.cell_title}\n" + code self.cell_code = code return python(code) if "release cell" in user: code = "print('other cell output')\ncell_gate.set()" if self.read_before_idle: code += f"\nawait cell_done.wait()\nprint(output.read({self.cell_id!r}))" return python(code) if "cancel cell" in user: return python(f"print(await cells.cancel({self.cell_id!r}))") if "inspect cell" in user: return python( f"print(await cells.info({self.cell_id!r}))\nprint(output.read({self.cell_id!r}))" ) return text("done")
def prepare(app): # Every cell still running past this answers as backgrounded, the # quick ones too. Those read the journal through the daemon, which # took over half a second on a loaded gate; a started cell waits on # its gate, so it detaches whatever this is. app.env["ALBEDO_CELL_BACKGROUND_SECONDS"] = "2" app.env["ALBEDO_IDLE_SECONDS"] = "2"
self.provider = Provider(script) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None)
def prompt(self, session, message): self.app.prompt(session, message).close() self.app.idle(session)
def wakes(self): return [ record for record in self.provider.requests if "background python cells finished" in latest_user(record["request"]) ]
def start(self): session = self.app.session() self.prompt(session, "start cell") result = self.results[0] self.assertEqual(result["status"], "backgrounded") self.assertIn("before detach", result["output"]) self.assertIn("instead of polling or sleeping", result["output"]) self.assertIn("wake automatically", result["output"]) return session
def test_a_background_cell_wakes_once_unless_read_or_cancelled(self): # The first cell starts a job, wakes its session once when it ends, # and is listed with that job nested under it meanwhile. self.with_job = True self.stop_job_on_release = True self.cell_title = "watch CI pipelines" session = self.start() first = self.cell_id self.prompt(session, "inspect cell") self.assertIn("'status': 'started'", self.results[-1]["output"]) self.assertIn("before detach", self.results[-1]["output"]) child = self.check_listed_while_running(session, first) self.prompt(session, "release cell") self.assertEqual(self.results[-1]["output"].strip(), "other cell output") wait_for(lambda: self.wakes()) self.app.idle(session) self.assertEqual(len(self.wakes()), 1) notes = [ entry for entry in self.app.history(session)["items"] if entry["kind"] == "note" and any( part["kind"] == "text" and "cell finished" in part["text"] for part in entry["content"] ) ] self.assertEqual(len(notes), 1) shown = next( part["text"] for part in notes[0]["content"] if part["kind"] == "text" ) self.assertTrue(shown.startswith("cell finished (status=ok"), shown) # The transcript names the code's first line, the model's notice the # cell id. self.assertTrue(shown.endswith("held = run('sleep', '30')"), shown) self.assertFalse(has_note(shown), shown) self.assertIn(first, latest_user(self.wakes()[0]["request"])) self.prompt(session, "inspect cell") self.assertIn("'status': 'ok'", self.results[-1]["output"]) self.assertIn("after detach", self.results[-1]["output"]) self.assertIn("{'answer': 42}", self.results[-1]["output"]) self.assertNotIn("other cell output", self.results[-1]["output"]) self.check_listed_after(session, first, child)
# A second cell whose finished output is read before the turn ends # owes no wake. self.with_job = self.stop_job_on_release = False self.read_before_idle = True self.prompt(session, "start cell") self.assertEqual(self.results[-1]["status"], "backgrounded") self.prompt(session, "release cell") self.assertIn("after detach", self.results[-1]["output"]) self.read_before_idle = False
# A third, cancelled, owes none either. self.prompt(session, "start cell") self.assertEqual(self.results[-1]["status"], "backgrounded") self.prompt(session, "cancel cell") self.assertEqual(self.results[-1]["output"].strip(), "True") self.prompt(session, "inspect cell") self.assertIn("'status': 'interrupted'", self.results[-1]["output"]) time.sleep(2.5) self.assertEqual(len(self.wakes()), 1)
def check_listed_while_running(self, session, cell): kernel = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())[ "kernel" ] self.assertEqual(kernel["live_job_count"], 1, kernel) running = {job["id"]: job for job in kernel["running_jobs"]} self.assertEqual(running[cell]["kind"], "cell") self.assertEqual(running[cell]["command"], "watch CI pipelines") self.assertIsNone(running[cell]["parent_id"]) children = [j for j in running.values() if j["parent_id"] == cell] self.assertEqual(len(children), 1, running) child = children[0] self.assertEqual((child["kind"], child["command"]), ("command", "sleep 30")) jobs_page = json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs").read() ) self.assertEqual(jobs_page["page"]["summary"], "1 background job running") rows = jobs_page["page"]["rows"] self.assertEqual([row["id"] for row in rows], [cell, child["id"]]) self.assertTrue(rows[1]["text"].startswith(" └ ")) recent = json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs/recent").read() )["items"] by_id = {item["id"]: item for item in recent} self.assertEqual( (by_id[cell]["kind"], by_id[cell]["state"]), ("cell", "running") ) self.assertNotIn("source", by_id[cell]) self.assertEqual(by_id[child["id"]]["parent_id"], cell) # Reading output through the jobs route does not suppress the wake. page = self.output_page(session, cell) self.assertIn("before detach", page["text"]) self.assertEqual(page["job"]["kind"], "cell") self.assertEqual(page["source"], self.cell_code) self.assertIsNone(self.output_page(session, child["id"])["source"]) return child
def check_listed_after(self, session, cell, child): after = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())["kernel"] self.assertEqual((after["live_job_count"], after["running_jobs"]), (0, [])) finished = { item["id"]: item for item in json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs/recent").read() )["items"] } self.assertEqual( (finished[cell]["state"], finished[cell]["exit_code"]), ("exited", 0) ) self.assertEqual(finished[child["id"]]["parent_id"], cell) self.assertEqual(self.output_page(session, cell)["source"], self.cell_code)
def output_page(self, session, job): return json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs/{job}/output").read() )
def test_background_cell_survives_idle_reaping_and_daemon_restart(self): session = self.start() time.sleep(4) self.app.restart() self.prompt(session, "release cell") wait_for(lambda: self.wakes()) self.app.idle(session) self.assertEqual(len(self.wakes()), 1) self.assertIn("status=ok", latest_user(self.wakes()[0]["request"]))