Files
claude-config/bin/loop_inbox/test_loop_inbox.py
T

198 lines
9.6 KiB
Python

import dataclasses
import pathlib
import shutil
import sys
import tempfile
import unittest
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, ClaudeCommand, OpenInInbox, OpenOnTerminal, Typed
from loop_inbox import inbox, main
from loop_claude import waiting
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
# The pids of a running loop, of this loop-inbox, and of a loop that has stopped.
LOOP, INBOX, GONE = 4242, 4343, 13
def alive(pid):
return pid != GONE
def asked(session, root, question="Which one?", at=100.0, pid=LOOP, state=ASKING):
return Ask(f"ask-{session}", session, root, question, at, pid, state)
def keyed(screen, *keys):
for key in keys:
screen = inbox.pressed(screen, key)
return screen
class Answers(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
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, alive))), *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, alive))), "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 on its terminal, or stopped.")
self.assertEqual(sorted(path.name for path in self.folder.iterdir()), ["s2.json"])
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, alive), 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, alive), Answering(ask, "Us"))
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Listing(note="/code/log no longer waits for that answer: it was answered on its terminal, 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")
for loop_does, claimed in (
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(INBOX))), (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)
# A claim the loop didn't make way for in time is taken back: a loop that reads it late ends its wait at once, as for a claude that has ended.
self.assertIsNone(waiting.answered(self.folder, ask))
self.assertTrue(waiting.claude_ended(self.folder, ask))
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", BACKSPACE), Listing((ask,), "1")),
(("x",), 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", "x", BACKSPACE), Answering(ask, "U")),
((" ", 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, pid=GONE, state=OpenOnTerminal())
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('{"pid": 0}')
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
self.assertEqual(waiting.waiting(pathlib.Path(folder), alive), [early, late])
self.assertEqual(waiting.waiting(pathlib.Path(folder), lambda pid: True), [stopped, early, late])
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 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?", at=3600 * 25, state=OpenOnTerminal())
lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 34)
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…",
"",
"[2] /code/c, waiting since <90000> (1 h 2 min); claude is open on its terminal",
" Cut 0.4.0?",
"",
"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, 80), ["No loop waits for you.", "", "Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "])
def test_the_answer_screen_shows_the_whole_question_and_says_what_enter_alone_does(self):
lines = inbox.answering_lines(Answering(asked("s1", "/code/log", "A or B?\n\nB is cheaper.", at=0), "Use B"), 59, lambda seconds: f"<{seconds}>", 80)
self.assertEqual(lines, ["/code/log, waiting since <0> (0 min):", "", "A or B?", "", "B is cheaper.", "", "Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting): Use B"])
def test_a_screen_too_short_keeps_the_prompt_and_marks_the_cut(self):
self.assertEqual(inbox.fitted(["a", "b", "c", "d", "> "], 4), ["a", "b", "…", "> "])
self.assertEqual(inbox.fitted(["a", "> "], 4), ["a", "> "])
if __name__ == "__main__":
unittest.main()