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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370"""Mail and agent handles between two daemons after a move.
The source daemon's PATH holds a loopback ssh, as in move_test, whose host`vassago` runs commands with ALBEDO_HOME set to the peer daemon's home anda login shell that reads no profile. The `down` switch makes every ssh failas an unreachable host does (a laptop's peer asleep). There is no ssh theother way: the target never reaches the source, as with a laptop.
A child of a session moves to vassago; its parent stays here. Letters go toit through the source's pusher, and its letters to "parent" come backthrough the long-poll the source keeps open."""
import jsonimport shutilimport sqlite3import subprocessimport sysimport tempfileimport unittestfrom contextlib import closingfrom pathlib import Path
from _transfer_support import ( finish_move, idle, loopback_ssh, settled_move, start_move, wait_for,)from harness import ( Albedo, Provider, exclusive_class, fresh_prompt, operation_id, peer_daemon, python, text,)
ELSEWHERE = "which this daemon can't reach; ask from there"
def rows(home, sql, *args): with closing(sqlite3.connect(Path(home) / "albedo.sqlite", timeout=10)) as db: return db.execute(sql, args).fetchall()
class Forwarding(unittest.TestCase): """A parent here and its child moved to vassago, with what the tests need to drive both daemons. It has no tests of its own."""
remote_home: Path hosts: Path down: Path
def setUp(self): self.addCleanup(self.recover)
def prepare(app): loopback = loopback_ssh( app, Path(tempfile.mkdtemp(prefix="host-", dir=app.root)) ) self.remote_home = loopback.remote_home self.hosts = loopback.hosts self.down = loopback.down
self.provider = Provider(lambda _request: text("done")) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses", prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None)
def target_prepare(peer): # The source's profile, with its key: the moved child runs there. for name in ("config.json", "creds.json"): if (self.app.home / name).exists(): shutil.copy(self.app.home / name, peer.home / name)
self.target = peer_daemon("forward-target", prepare=target_prepare) (self.hosts / "vassago").write_text(str(self.target.home)) destination = Path(tempfile.mkdtemp(prefix="dest-", dir=self.remote_home))
self.parent = self.app.session() self.app.prompt(self.parent, "hello").close() self.app.idle(self.parent) self.child = operation_id() self.app.api( f"/sessions/{self.child}", { "kind": "child", "parent_id": self.parent, "address": "kid", "name": "kid", "initial_input_id": operation_id(), "task": "wait for letters", }, method="PUT", headers={"If-None-Match": "*"}, ).close() self.app.idle(self.child, timeout=60) self.app.idle(self.parent, timeout=60)
transfer = operation_id() start_move(self.app, self.child, transfer, f"vassago:{destination}") move = settled_move(self.app, transfer, 90) self.assertEqual(move["state"], "checklist", move) self.assertEqual(finish_move(self.app, transfer)["state"], "active")
def recover(self): self.down.unlink(missing_ok=True)
def execute(self, daemon, session, source): """Runs one python cell in `session` on `daemon` (the app or the target) and answers the cell's tool result as text.""" marker = "forward cell " + operation_id() answer = self.provider.script
def dispatch(request): if fresh_prompt(request) == marker: return python(source) return answer(request)
self.provider.script = dispatch try: daemon.api( f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": marker}, method="PUT", ).close() idle(daemon, session) finally: self.provider.script = answer with daemon.api(f"/sessions/{session}/history") as response: items = json.load(response)["items"] [cell] = [item for item in items if item["kind"] == "tool_result"][-1:] return json.dumps(cell)
def arrived(self, home, recipient, body): return rows( home, "SELECT id,sender,sender_name,created_at FROM mail WHERE recipient=? AND body=?", recipient, body, )
# exclusive: the daemon's PATH holds the loopback ssh, and a test kills its# relays@exclusive_classclass MoveForwardTests(Forwarding): def test_a_letter_to_a_moved_session_arrives_there_once(self): cell = self.execute( self.app, self.parent, f"r = await mail.submit({self.child!r}, 'hello over there')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(letter, sender, name, _)] = wait_for( lambda: self.arrived(self.target.home, self.child, "hello over there"), 30, "the letter never reached the target", ) # Its sender lives on the source: kept with where it lives. self.assertIsNone(sender) [(remote, host)] = rows( self.target.home, "SELECT sender,host FROM mail_remote WHERE letter=?", letter, ) self.assertEqual(remote, self.parent) self.assertTrue(host) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_outbox WHERE id=? AND delivered_at IS NOT NULL", letter, ), 30, "the source never settled the letter", ) # A resend (an ack the relay dropped) is taken again without a copy. with self.target.api( "/mail/forwarded", { "origin": "source", "host": host, "letters": [ { "id": letter, "recipient": self.child, "sender": self.parent, "sender_name": name, "kind": "message", "body": "hello over there", } ], }, ) as response: [ack] = json.load(response)["acks"] self.assertEqual(ack, {"id": letter, "error": None, "retry": False}) self.assertEqual( len(self.arrived(self.target.home, self.child, "hello over there")), 1 ) # And the moved child reads it there. idle(self.target, self.child) with self.target.api(f"/sessions/{self.child}/history") as response: self.assertIn("hello over there", response.read().decode())
def test_a_letter_waits_while_the_target_is_out_of_reach(self): self.down.touch() self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'while you were away')", ) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_peers WHERE unreachable_since IS NOT NULL", ), 60, "the source never found the target out of reach", ) cell = self.execute( self.app, self.parent, "print('AWAITING', [a['forwarding'] for a in (await mail.open())['awaiting']])", ) self.assertIn("AWAITING ['queued for vassago, unreachable since ", cell) self.assertEqual( self.arrived(self.target.home, self.child, "while you were away"), [] ) self.down.unlink() wait_for( lambda: self.arrived(self.target.home, self.child, "while you were away"), 60, "the letter never arrived once the target was back", )
def test_a_moved_child_writes_to_its_parent_here(self): self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'report back')" ) wait_for(lambda: self.arrived(self.target.home, self.child, "report back"), 30) idle(self.target, self.child) cell = self.execute( self.target, self.child, "import time\n" "sent = time.time()\n" "r = await mail.submit('parent', 'reporting from vassago')\n" "print('SENT', sent, r.status, r.forwarding)", ) self.assertIn("SENT", cell) sent = float(cell.split("SENT ", 1)[1].split(" ", 1)[0]) [(_, sender, _, created)] = wait_for( lambda: self.arrived(self.app.home, self.parent, "reporting from vassago"), 30, "the parent never got the letter", ) self.assertEqual(sender, self.child) latency = created / 1000 - sent print(f"collect latency {latency:.3f}s", file=sys.stderr) self.assertLess(latency, 5) # The answer closes the request on the side that opened it. idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell)
# The long-poll survives its connection dying: the source opens it # again and the next letter still comes. subprocess.run(["pkill", "-f", "albedo_transfer_relay"], check=False) self.execute( self.target, self.child, "await mail.submit('parent', 'after the drop')" ) wait_for( lambda: self.arrived(self.app.home, self.parent, "after the drop"), 60, "the parent never got the letter sent after the connection dropped", )
def test_handles_reach_a_moved_session_and_not_the_other_way(self): cell = self.execute( self.app, self.parent, f"h = await agents.get({self.child!r})\n" "page = await h.messages()\n" "print('READ', 'wait for letters' in str(page))\n" "print('CANCELLED', await h.cancel())", ) self.assertIn("READ True", cell) self.assertIn("CANCELLED", cell) self.assertNotIn("Error", cell)
cell = self.execute( self.target, self.child, "p = await agents.get('parent')\n" "try:\n" " await p.messages()\n" "except AgentsError as error:\n" " print('REFUSED', error)\n" "try:\n" " await p.cancel()\n" "except AgentsError as error:\n" " print('REFUSED', error)", ) self.assertEqual(cell.count(ELSEWHERE), 2, cell)
# exclusive: restarts the source daemon with its timers 3600 times faster@exclusive_classclass MoveForwardBounceTests(Forwarding): def test_a_letter_bounces_after_a_day_out_of_reach(self): self.down.touch() cell = self.execute( self.app, self.parent, f"r = await mail.request({self.child!r}, 'anyone there?')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(sent,)] = rows( self.app.home, "SELECT created_at FROM mail_outbox WHERE body='anyone there?'", )
# A day is 24 s from here; python's kernel does not live at that # speed, so the request went out first. def faster(app): app.daemon.env["ALBEDO_TEST_TIME_SCALE"] = "3600" app.daemon.env["ALBEDO_SCHEDULE_TICK_MS"] = "60000"
self.app.restart(prepare=faster) [(sender, body, bounced)] = wait_for( lambda: rows( self.app.home, "SELECT sender,body,created_at FROM mail WHERE recipient=? AND body LIKE 'not delivered:%'", self.parent, ), 90, lambda: ( "the letter never bounced: " + repr(rows(self.app.home, "SELECT * FROM mail_outbox")) ), ) self.assertGreaterEqual(bounced - sent, 24_000) self.assertEqual(sender, self.child) self.assertIn("vassago was out of reach for a day", body)
# The bounce answers the request: the sender awaits nothing. self.app.restart( prepare=lambda app: app.daemon.env.pop("ALBEDO_TEST_TIME_SCALE") ) idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell)
if __name__ == "__main__": unittest.main()