import contextlib import dataclasses import io import json import pathlib import shutil import subprocess import sys import tempfile import unittest import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, Typed from loop_claude.hand_over import ClaudeCommand from failure import Failure from loop_inbox import inbox, main from loop_claude.paths import paths_from from loop_claude import session_lock from loop_claude.effects import system_effects from loop_claude import waiting ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {})) # The pid of this loop-inbox. INBOX = 4343 ANSWERED_ON_TERMINAL = object() def asked(session, root, question="Which one?", at=100.0, state=ASKING): return Ask(f"ask-{session}", session, root, question, at, state) def loops_hold(test, folder, *sessions): """Holds each session's lock until the test ends, as the loop that lists its ask does.""" for session in sessions: test.enterContext(session_lock.locked(folder, session)) def asks_and_answers(folder): return sorted(path.name for path in folder.iterdir() if path.suffix != ".lock") def keyed(screen, *keys): for key in keys: screen = inbox.pressed(screen, key) return screen class OutOfKeys(Exception): pass class Window: """A curses window that records the lines drawn on it, and hands out keys in turn, running each callable among them as it comes.""" def __init__(self, keys=(), height=24, width=80): self.keys, self.height, self.width = list(keys), height, width self.lines = {} def getmaxyx(self): return self.height, self.width def timeout(self, milliseconds): pass def get_wch(self): while self.keys and callable(self.keys[0]): self.keys.pop(0)() if not self.keys: raise OutOfKeys return self.keys.pop(0) def drop_typed(self): """Drops the keys not yet read, as curses.flushinp does.""" self.keys.clear() def erase(self): self.lines = {} def addnstr(self, row, column, text, count): self.lines[row] = text[:count] def refresh(self): pass class Answers(unittest.TestCase): def setUp(self): self.folder = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.folder) loops_hold(self, self.folder, "s1", "s2") def answer(self, number, text): """Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox.""" action = keyed(Listing(tuple(waiting.waiting(self.folder))), *number, ENTER, *text, ENTER) self.assertIsInstance(action, Send) return main.sent(self.folder, action.ask, action.text) def test_two_waiting_loops_each_get_their_own_answer(self): log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) for ask in (bender, log): waiting.publish(self.folder, ask) self.assertEqual(self.answer("2", "Use B."), "Sent to /code/bender.") self.assertEqual(self.answer("1", "Use A."), "Sent to /code/log.") self.assertEqual((waiting.answered(self.folder, log), waiting.answered(self.folder, bender)), (Typed("Use A."), Typed("Use B."))) def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self): log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) for ask in (log, bender): waiting.publish(self.folder, ask) picked = keyed(Listing(tuple(waiting.waiting(self.folder))), "1", ENTER, "A", ENTER) # log is answered on its terminal before the answer typed here is sent; bender is now first. waiting.withdraw(self.folder, "s1") self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.") self.assertEqual(asks_and_answers(self.folder), ["s2.json"]) def test_the_list_shows_the_loops_still_waiting_and_keeps_its_note(self): log = asked("s1", "/code/log") for ask in (log, asked("s3", "/code/bender")): waiting.publish(self.folder, ask) self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder), Listing((log,), "", "Sent to /a.")) def test_a_number_picks_the_loop_it_had_when_the_human_began_typing_it(self): log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) typing = keyed(Listing((log, bender)), "2") waiting.publish(self.folder, bender) self.assertEqual(main.refreshed(typing, self.folder), typing) self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender)) def test_a_loop_whose_claude_is_open_takes_no_answer_here(self): for state, where in ((OpenOnTerminal(), "on its terminal"), (OpenInInbox(7), "in loop-inbox")): with self.subTest(where=where): self.assertEqual(keyed(Listing((asked("s1", "/code/log", state=state),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there.")) def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self): ask = asked("s1", "/code/log") waiting.publish(self.folder, ask) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us")) waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask")) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")) def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self): ask = asked("s3", "/code/bender") waiting.publish(self.folder, ask) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped.")) def claim(self, ask, loop_does): """claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait.""" tenths = [0] def sleep(seconds): if not tenths[0]: loop_does() tenths[0] += round(seconds * 10) return waiting.claim_talk(self.folder, ask, INBOX, lambda: tenths[0] / 10, sleep), tenths[0] / 10 def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self): ask = asked("s1", "/code/log") def made_way_for_the_claim(): claim = waiting.answered(self.folder, ask) if isinstance(claim, waiting.ClaudeOpening): waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid))) for loop_does, claimed in ( (made_way_for_the_claim, (True, 0.1)), (lambda: waiting.withdraw(self.folder, "s1"), (False, 0.1)), (lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)), (lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)), (lambda: None, (False, waiting.MAKE_WAY_SECONDS)), ): with self.subTest(claimed=claimed): waiting.publish(self.folder, ask) self.assertEqual(self.claim(ask, loop_does), claimed) def test_a_claim_the_loop_did_not_make_way_for_in_time_is_taken_back(self): ask = asked("s1", "/code/log") waiting.publish(self.folder, ask) self.claim(ask, lambda: None) # A loop that reads it late ends its wait at once, as for a claude that has ended. self.assertEqual((waiting.answered(self.folder, ask), waiting.claude_ended(self.folder, ask)), (None, True)) def never_opens(args, cwd, env): raise AssertionError("claude opened") class Opens(unittest.TestCase): def setUp(self): home = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, home) self.paths = paths_from(home) self.ask = asked("s1", "/code/log") loops_hold(self, self.paths.waiting, "s1") waiting.publish(self.paths.waiting, self.ask) def open(self, claude, loop_shows=OpenInInbox(INBOX)): """What /talk in loop-inbox says for self.ask, whose loop shows loop_shows once claim_talk has asked it to make way; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended.""" def loop_looks(_): waiting.publish(self.paths.waiting, dataclasses.replace(self.ask, state=loop_shows)) effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=loop_looks) try: with contextlib.redirect_stderr(io.StringIO()): return main.opened(contextlib.nullcontext, self.paths, self.ask, effects) finally: self.ended = waiting.claude_ended(self.paths.waiting, self.ask) def test_tells_the_loop_once_claude_ends_or_cannot_start_and_says_what_the_loop_does(self): def unstarted(args, cwd, env): raise OSError(2, "No such file or directory") for claude, said in ( (lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't."), (unstarted, "Could not start claude for /code/log: No such file or directory. The loop stops."), ): with self.subTest(said=said): waiting.publish(self.paths.waiting, self.ask) self.assertEqual(self.open(claude), said) self.assertTrue(self.ended) def test_says_the_loop_waits_for_loop_inbox_to_quit_where_it_cannot_tell_it_that_claude_ended(self): def folder_lost(args, cwd, env): shutil.rmtree(self.paths.waiting) self.paths.waiting.write_text("") said = "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't. Could not tell the loop that claude ended: Not a directory; it waits until you quit loop-inbox." self.assertEqual(self.open(folder_lost), said) def test_opens_no_claude_for_a_loop_that_takes_talk_on_its_terminal_first(self): said = "Could not open claude for /code/log: the loop was answered elsewhere or stopped, or didn't respond within 5 s. If it is still listed, pick it again." self.assertEqual(self.open(never_opens, loop_shows=OpenOnTerminal()), said) def test_opens_no_claude_and_sends_nothing_to_a_loop_that_no_longer_waits(self): waiting.withdraw(self.paths.waiting, "s1") self.assertEqual(self.open(never_opens), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.") self.assertEqual(asks_and_answers(self.paths.waiting), []) def test_tells_the_loop_when_claude_is_interrupted(self): def interrupted(args, cwd, env): raise KeyboardInterrupt with self.assertRaises(KeyboardInterrupt): self.open(interrupted) self.assertTrue(self.ended) class Typing(unittest.TestCase): def typed(self, *keys): """What the log and bender loops get once keys are typed into loop-inbox, which lists log first. ANSWERED_ON_TERMINAL among the keys stands for log being answered on its terminal. Fails where loop-inbox quits before the keys run out.""" with tempfile.TemporaryDirectory() as home: paths = paths_from(pathlib.Path(home)) log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) loops_hold(self, paths.waiting, "s1", "s2") for ask in (log, bender): waiting.publish(paths.waiting, ask) def answered_on_terminal(): waiting.withdraw(paths.waiting, "s1") window = Window(answered_on_terminal if key is ANSWERED_ON_TERMINAL else key for key in keys) def made_way(seconds): waiting.publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX))) effects = dataclasses.replace(system_effects(), claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way) with self.assertRaises(OutOfKeys), contextlib.redirect_stderr(io.StringIO()): main.run(window, contextlib.nullcontext, paths, effects) return waiting.answered(paths.waiting, log), waiting.answered(paths.waiting, bender) def test_keys_typed_ahead_are_dropped_once_the_answer_screen_is_left(self): # Each case types, after leaving log's answer screen, a line that would pick bender and one that would answer it, or a line that would quit. for case, keys, got in ( ("a pasted answer", "1\nYes.\nSee item 2.\nThen release.\n", (Typed("Yes."), None)), ("a pasted answer with a line that would quit", "1\nOk.\nquick check first\n", (Typed("Ok."), None)), ("/talk", "1\n/talk\n2\nUse B.\n", (None, None)), ("a paste that opens with an empty line", "1\n\nSee item 2.\nThen release.\n", (None, None)), ("an answer typed as log is answered on its terminal", ["1", "\n", "U", "s", "e", ANSWERED_ON_TERMINAL, *" option 1.\nThen release.\n"], (None, None)), ): with self.subTest(case): self.assertEqual(self.typed(*keys), got) class Keys(unittest.TestCase): def test_the_list_takes_a_number_and_quits_on_q(self): ask = asked("s1", "/code/log") for keys, after in ( (("q",), Quit()), (("1", "q"), Listing((ask,), "1")), (("1", "2", "3", BACKSPACE), Listing((ask,), "12")), (("x",), Listing((ask,))), (("²",), Listing((ask,))), ((ENTER,), Listing()), (("2", ENTER), Listing(note="No loop has the number 2.")), (("1", ENTER), Answering(ask)), ): with self.subTest(keys=keys): self.assertEqual(keyed(Listing((ask,)), *keys), after) def test_an_answer_is_sent_stripped_talk_opens_claude_and_enter_alone_or_esc_goes_back(self): ask = asked("s1", "/code/log") for keys, after in ( ((*" Use B. ", ENTER), Send(ask, "Use B.")), ((*" /talk", ENTER), Open(ask)), (("U", "s", "e", "x", BACKSPACE), Answering(ask, "Use")), ((" ", ENTER), Listing()), (("U", ESCAPE), Listing()), (("\t",), Answering(ask)), ): with self.subTest(keys=keys): self.assertEqual(keyed(Answering(ask), *keys), after) def test_curses_keys_get_inboxs_names(self): for key, name in (("\n", ENTER), (main.curses.KEY_ENTER, ENTER), ("\x7f", BACKSPACE), (main.curses.KEY_BACKSPACE, BACKSPACE), ("\x1b", ESCAPE), ("a", "a"), (main.curses.KEY_LEFT, "")): with self.subTest(key=key): self.assertEqual(main.key_name(key), name) class Waiting(unittest.TestCase): def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self): with tempfile.TemporaryDirectory() as folder: late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal()) loops_hold(self, pathlib.Path(folder), "s1", "s2") for ask in (late, early, stopped): waiting.publish(pathlib.Path(folder), ask) pathlib.Path(folder, "s4.json").write_text("{") pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}') pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"')) self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late]) def test_drops_and_removes_the_ask_of_a_loop_killed_before_it_took_it_out_whatever_its_pid_now_names(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, system_effects, waiting\nwith waiting.listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)" loop = subprocess.Popen([sys.executable, "-c", lists_and_waits, temp], cwd=pathlib.Path(__file__).parent, stdout=subprocess.PIPE) self.addCleanup(loop.wait) self.addCleanup(loop.kill) loop.stdout.readline() waiting.send(folder, asked("s1", "/a"), Typed("Use A.")) self.assertEqual(waiting.waiting(folder), [asked("s1", "/a")]) # SIGKILL runs none of the loop's cleanup, and the system may hand its pid to another process at once. loop.kill() loop.wait() self.assertEqual(waiting.waiting(folder), []) waiting.drop_ended(folder) self.assertEqual(asks_and_answers(folder), []) def test_removes_only_the_asks_and_answers_whose_loop_has_ended(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp) loops_hold(self, folder, "s1") for ask in (asked("s1", "/a"), asked("s2", "/b")): waiting.publish(folder, ask) waiting.send(folder, ask, Typed("Use A.")) waiting.drop_ended(folder) self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json"]) def test_a_talk_claim_from_pid_0_or_below_is_no_answer_since_it_would_name_a_process_group(self): with tempfile.TemporaryDirectory() as temp: ask = asked("s1", "/a") for pid in (0, -1): with self.subTest(pid=pid): waiting.send(pathlib.Path(temp), ask, waiting.ClaudeOpening(pid)) self.assertIsNone(waiting.answered(pathlib.Path(temp), ask)) def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self): with tempfile.TemporaryDirectory() as temp: path = waiting.ask_file(pathlib.Path(temp), "s1") waiting.publish(path.parent, asked("s1", "/a")) good = json.loads(path.read_text()) self.assertEqual(waiting.read_ask(path), asked("s1", "/a")) for field, value in ( ("id", 1), ("session", "s2"), ("root", None), ("question", 3), ("asked", "noon"), ("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}), ("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}), ): with self.subTest(field=field, value=value): path.write_text(json.dumps(good | {field: value})) self.assertIsNone(waiting.read_ask(path)) def test_withdraw_says_what_it_cannot_remove(self): with tempfile.TemporaryDirectory() as temp: folder = pathlib.Path(temp, "a file") folder.write_text("") self.assertEqual(waiting.withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory")) def test_a_message_reaches_only_the_ask_it_names(self): with tempfile.TemporaryDirectory() as temp: folder, ask = pathlib.Path(temp), asked("s1", "/a") another = dataclasses.replace(ask, id="another") for message, answer, ended in ((Typed("A"), Typed("A"), False), (waiting.ClaudeOpening(7), waiting.ClaudeOpening(7), False), (waiting.ClaudeEnded(), None, True)): with self.subTest(message=message): waiting.send(folder, ask, message) self.assertEqual((waiting.answered(folder, ask), waiting.claude_ended(folder, ask)), (answer, ended)) self.assertEqual((waiting.answered(folder, another), waiting.claude_ended(folder, another)), (None, False)) class Shown(unittest.TestCase): def drawn(self, screen, window): """The lines draw puts on window for screen, 3700 s after the epoch.""" main.draw(window, screen, dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: 3700)) return [window.lines[row] for row in range(len(window.lines))] def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self): log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0) cut = asked("s2", "/code/c", "Cut 0.4.0?\nIts changelog is ready.", at=3600 * 25, state=OpenInInbox(INBOX)) lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 50) self.assertEqual(lines, ([ "2 loops wait for you, oldest first.", "", "[1] /code/log, waiting since <0> (1 d 2 h)", " Which store should the cache use: Redis or", " SQLite? Redis is already deployed for…", "", "[2] /code/c, waiting since <90000> (1 h 2 min);", "claude is open in loop-inbox", " Cut 0.4.0?", " Its changelog is ready.", "", ], [ "Type a number and Enter to answer that loop; q", "quits loop-inbox, and the loops keep waiting.", "> 1", ])) def test_an_empty_list_says_no_loop_waits(self): self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 79), (["No loop waits for you.", ""], ["Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "])) def test_the_answer_screen_at_80_columns_shows_every_character_of_each_line_and_says_what_enter_alone_does(self): # The question's first line has 80 characters, one more than a line drawn at 80 columns holds. ask = asked("s1", "/code/log", "The changelog lists four fixes and three new tools, so the next release is 0.6.0\n\nCut it?", at=100) self.assertEqual(self.drawn(Answering(ask, "Yes"), Window(width=80)), [ "/code/log, waiting since <100> (1 h 0 min):", "", "The changelog lists four fixes and three new tools, so the next release is", "0.6.0", "", "Cut it?", "", "Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps", "waiting): Yes", ]) def test_an_answer_longer_than_its_line_goes_on_below_it_with_every_space_typed(self): typed = "Use B, as the cache then runs next to the sessions it serves and then cut 0.6.0." lines = self.drawn(Answering(asked("s1", "/code/log", "A or B?", at=100), typed), Window(width=80)) self.assertEqual(lines[-2:], ["waiting): Use B, as the cache then runs next to the sessions it serves and then", " cut 0.6.0."]) def test_a_line_that_runs_into_the_screens_last_cell_leaves_the_screen_drawn(self): class Refusing(Window): """Refuses the screen's last row, as curses refuses a line of wide characters, such as emoji, that runs into the last cell.""" def addnstr(self, row, column, text, count): super().addnstr(row, column, text, count) if row == self.height - 1: raise main.curses.error("addnwstr() returned ERR") self.assertEqual(self.drawn(Listing(), Refusing(height=3)), ["…", "q quits loop-inbox, and the loops keep waiting.", "> "]) def test_a_screen_too_short_keeps_the_foot_and_marks_the_cut(self): for lines, foot, height, shown in ( (["a", "b", "c"], ["> "], 4, ["a", "b", "c", "> "]), (["a", "b", "c"], ["> "], 3, ["a", "…", "> "]), (["a", "b", "c"], ["n", "> "], 4, ["a", "…", "n", "> "]), (["a", "b", "c", "d"], ["n", "h", "> "], 2, ["h", "> "]), ): with self.subTest(lines=lines, foot=foot, height=height): self.assertEqual(inbox.fitted(lines, foot, height), shown) def test_a_wait_reads_in_minutes_under_an_hour_and_in_hours_under_a_day(self): for seconds, read in ((3599, "59 min"), (3600, "1 h 0 min"), (86399, "23 h 59 min"), (86400, "1 d 0 h")): with self.subTest(seconds=seconds): self.assertEqual(inbox.waited(seconds), read) class Terminal(io.StringIO): def isatty(self): return True class Starts(unittest.TestCase): def started(self, argv, stdin, stdout): """What main returns for argv, run with stdin and stdout, and what it writes to stderr.""" stderr = io.StringIO() with unittest.mock.patch.object(sys, "stdin", stdin), contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): code = main.main(argv, pathlib.Path("/no home")) return code, stderr.getvalue() def test_help_prints_the_docstring(self): for flag in ("-h", "--help"): with self.subTest(flag): stdout = io.StringIO() self.assertEqual(self.started([flag], io.StringIO(), stdout), (0, "")) self.assertEqual(stdout.getvalue(), f"{main.__doc__.strip()}\n") def test_exits_2_on_an_unknown_argument_or_off_a_terminal(self): off_a_terminal = "loop-inbox: stdin or stdout is not a terminal; run it on one\n" for case, argv, stdin, stdout, said in ( ("an unknown argument", ["--x"], Terminal(), Terminal(), "loop-inbox: unknown argument --x; usage: loop-inbox\n"), ("stdout off a terminal", [], Terminal(), io.StringIO(), off_a_terminal), ("stdin off a terminal", [], io.StringIO(), Terminal(), off_a_terminal), ): with self.subTest(case): self.assertEqual(self.started(argv, stdin, stdout), (2, said)) if __name__ == "__main__": unittest.main()