Show every waiting loop-claude in loop-inbox and take each one's answer there

This commit is contained in:
2026-10-28 23:24:29 +01:00
parent d13c4fb0db
commit a7fe878631
24 changed files with 938 additions and 81 deletions
View File
+146
View File
@@ -0,0 +1,146 @@
"""What loop-inbox shows, and what each key does there: the core that main.py's curses screen runs.
How it shows the loops and a question was picked on 2026-10-28 by a bench of three readers seated as the README's
audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it: a block per
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone stops nothing.
"""
import dataclasses
import textwrap
import typing
from loop_claude.waiting import Ask
from loop_claude.cycle.interrupt import TALK
ENTER = "enter"
BACKSPACE = "backspace"
ESCAPE = "escape"
# Lines of a question the list shows; the answer screen shows it whole.
SHOWN_LINES = 2
QUIT = "q"
@dataclasses.dataclass(frozen=True)
class Listing:
"""The waiting loops, as shown when the human began typing a number, which keeps a loop's number from changing under them."""
shown: tuple[Ask, ...] = ()
typed: str = ""
note: str = ""
@dataclasses.dataclass(frozen=True)
class Answering:
ask: Ask
typed: str = ""
Screen = Listing | Answering
@dataclasses.dataclass(frozen=True)
class Send:
ask: Ask
text: str
@dataclasses.dataclass(frozen=True)
class Open:
"""Opens the worker's claude session for /talk."""
ask: Ask
@dataclasses.dataclass(frozen=True)
class Quit:
pass
def pressed(screen: Screen, key: str) -> Screen | Send | Open | Quit:
"""What follows key, which is ENTER, BACKSPACE, ESCAPE or one character typed."""
match screen:
case Listing(shown, typed):
if key == QUIT and not typed:
return Quit()
if key == ENTER:
return picked(shown, typed)
if key == BACKSPACE:
return Listing(shown, typed[:-1])
return Listing(shown, typed + key) if key.isdigit() else screen
case Answering(ask, typed):
if key == ESCAPE or (key == ENTER and not typed.strip()):
return Listing()
if key == ENTER:
return Open(ask) if typed.strip() == TALK else Send(ask, typed.strip())
if key == BACKSPACE:
return Answering(ask, typed[:-1])
return Answering(ask, typed + key) if len(key) == 1 and key.isprintable() else screen
case _:
typing.assert_never(screen)
def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering:
if not typed:
return Listing()
number = int(typed)
if not 1 <= number <= len(shown):
return Listing(note=f"No loop has the number {number}.")
ask = shown[number - 1]
if ask.talk is None:
return Listing(note=f"{ask.root}: claude is open {where_open(ask)}; answer there.")
return Answering(ask)
def where_open(ask: Ask) -> str:
return "in loop-inbox" if ask.talking else "on its terminal"
def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> list[str]:
"""The list, its last line the prompt for a number."""
count = len(screen.shown)
head = "No loop waits for you." if not count else "1 loop waits for you." if count == 1 else f"{count} loops wait for you, oldest first."
lines = [head, ""]
for number, ask in enumerate(screen.shown, 1):
state = f"; claude is open {where_open(ask)}" if ask.talk is None else ""
lines.append(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}")
lines += cut(wrapped(ask.question, width - 4), SHOWN_LINES, " ")
lines.append("")
lines += [screen.note] if screen.note else []
ask_for = "Type a number and Enter to answer that loop; " if count else ""
return [*lines, f"{ask_for}{QUIT} quits loop-inbox, and the loops keep waiting.", f"> {screen.typed}"]
def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> list[str]:
"""The whole question, its last line the prompt for the answer."""
ask = screen.ask
return [
f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):",
"",
*wrapped(ask.question, width),
"",
f"Answer ({TALK} opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting): {screen.typed}",
]
def fitted(lines: list[str], height: int) -> list[str]:
"""lines cut to height, keeping the last, the prompt; a cut is marked with an ellipsis."""
if len(lines) <= height:
return lines
return [*lines[: max(height - 2, 0)], "…", lines[-1]][-height:]
def wrapped(text: str, width: int) -> list[str]:
return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, 20)) or [""]]
def cut(lines: list[str], count: int, indent: str) -> list[str]:
shown = [f"{indent}{line}" for line in lines[:count]]
return [*shown[:-1], f"{shown[-1]}…"] if len(lines) > count else shown
def waited(seconds: float) -> str:
minutes = int(seconds // 60)
if minutes < 60:
return f"{minutes} min"
hours, minutes = divmod(minutes, 60)
if hours < 24:
return f"{hours} h {minutes} min"
days, hours = divmod(hours, 24)
return f"{days} d {hours} h"
+176
View File
@@ -0,0 +1,176 @@
"""Show every loop-claude on this machine that waits for you, oldest first, and answer each one here.
usage: loop-inbox
Each loop-claude that asks you a question lists it here, as well as on its own terminal, until it is
answered or the loop stops. The list shows each loop's checkout, when it asked and how long it has
waited, and the question's first lines; it refreshes every second. Type a loop's number and Enter
to see its whole question, then answer as on the loop's terminal:
- A line and Enter sends it to that loop, which goes on with it.
- /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's
terminal. Once that claude ends, the loop goes on, and the judge rules on what was typed there; a
loop whose claude ends with nothing typed stops.
- Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop.
The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no
loop-inbox running. A loop whose release is ready to cut, or whose /talk is open, shows that claude
is open, and is answered there. A loop whose process is gone drops off the list. q quits
loop-inbox; the loops keep waiting.
The loops' questions are files in ~/.local/state/loop-claude, read and written as
bin/loop_claude/waiting.py describes.
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
"""
import curses
import os
import pathlib
import signal
import subprocess
import sys
import time
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
from loop_claude.waiting import Ask, ask_file, read_ask, send, Talked, Talking, Typed, waiting
from loop_claude.paths import Paths, paths_from
from loop_claude.effects import system_effects
from claude_code.trust import trust
from loop_claude.project.checkout import worktrees
USAGE = "usage: loop-inbox"
# Milliseconds between refreshes of the list while no key is pressed.
REFRESH_MS = 1000
# Seconds loop-inbox waits for a loop to stop reading its terminal before it opens claude for /talk; the loop looks for an answer every half second.
MAKE_WAY_SECONDS = 5
KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE}
def main(argv: list[str], home: pathlib.Path) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv:
print(f"loop-inbox: unknown argument {argv[0]}; {USAGE}", file=sys.stderr)
return 2
if not (sys.stdin.isatty() and sys.stdout.isatty()):
print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr)
return 2
try:
curses.wrapper(lambda window: run(window, paths_from(home)))
except KeyboardInterrupt:
pass
return 0
def run(window: curses.window, paths: Paths) -> None:
folder = paths.waiting
window.timeout(REFRESH_MS)
screen: Screen = Listing()
while True:
screen = refreshed(screen, folder)
draw(window, screen)
try:
key = window.get_wch()
except curses.error:
continue # No key within REFRESH_MS.
match pressed(screen, key_name(key)):
case Quit():
return
case Send(ask, text):
screen = Listing(note=sent(folder, ask, text))
case Open(ask):
screen = Listing(note=talked(window, paths, ask))
case Listing() | Answering() as next_screen:
screen = next_screen
def key_name(key: str | int) -> str:
"""inbox's name for a key curses read; an empty string for a key loop-inbox has no use for, such as an arrow."""
return KEYS.get(key, key if isinstance(key, str) else "")
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
"""screen with the loops as they wait now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
match screen:
case Listing(_, "", note):
return Listing(tuple(waiting(folder)), "", note)
case Answering(ask) if not still_waits(folder, ask):
return Listing(note=no_longer_waits(ask))
return screen
def draw(window: curses.window, screen: Screen) -> None:
height, width = window.getmaxyx()
now = time.time()
lines = listing_lines(screen, now, local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, local_time, width)
window.erase()
for row, line in enumerate(fitted(lines, height)):
# The last cell of the screen cannot be written without an error, so each line stops one short of it.
window.addnstr(row, 0, line, width - 1)
window.refresh()
def local_time(seconds: float) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds))
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether ask still waits for an answer from loop-inbox."""
now = read_ask(ask_file(folder, ask.session))
return now is not None and now.id == ask.id and now.talk is not None
def no_longer_waits(ask: Ask) -> str:
return f"{ask.root} no longer waits for that answer: it was answered on its terminal, or stopped."
def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
"""Sends text to the loop that asked ask, and says what came of it."""
if not still_waits(folder, ask):
return no_longer_waits(ask)
if unsent := send(folder, ask, Typed(text)):
return f"Could not send the answer to {ask.root}: {unsent.reason}"
return f"Sent to {ask.root}."
def talked(window: curses.window, paths: Paths, ask: Ask) -> str:
"""Opens the worker's claude session on this terminal once the loop has stopped reading its own, and says what came of it."""
folder = paths.waiting
if not still_waits(folder, ask) or ask.talk is None:
return no_longer_waits(ask)
if unsent := send(folder, ask, Talking(os.getpid())):
return f"Could not open claude for {ask.root}: {unsent.reason}"
if not made_way(folder, ask):
return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS} s; it was answered on its terminal, or stopped."
curses.def_prog_mode()
curses.endwin()
# As loop-claude's hand_over does before it opens claude on its own terminal.
trust(paths.claude_json, worktrees(ask.talk.cwd, system_effects()), lambda text: print(f"loop-inbox: {text}", file=sys.stderr))
# Ctrl-C belongs to claude while it runs, not to loop-inbox.
interrupt = signal.signal(signal.SIGINT, signal.SIG_IGN)
try:
subprocess.run(["claude", *ask.talk.args], cwd=ask.talk.cwd, env={**os.environ, **ask.talk.env})
said = f"claude for {ask.root} has ended; the loop goes on."
except OSError as failure:
said = f"Could not start claude for {ask.root}: {failure.strerror}"
finally:
signal.signal(signal.SIGINT, interrupt)
unsent = send(folder, ask, Talked())
curses.reset_prog_mode()
window.refresh()
# Without Talked, the loop goes on only once loop-inbox quits.
return f"{said} Could not tell the loop: {unsent.reason}; quit loop-inbox to let it go on." if unsent else said
def made_way(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether the loop shows, within MAKE_WAY_SECONDS, that it has stopped reading its terminal for this loop-inbox."""
deadline = time.monotonic() + MAKE_WAY_SECONDS
while time.monotonic() < deadline:
now = read_ask(ask_file(folder, ask.session))
if now is None or now.id != ask.id:
return False
if now.talking == os.getpid():
return True
time.sleep(0.1)
return False
+177
View File
@@ -0,0 +1,177 @@
import dataclasses
import os
import pathlib
import shutil
import subprocess
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, TalkCommand, Typed
from loop_inbox import inbox, main
from loop_claude import waiting
TALK = TalkCommand(["--resume", "s"], "/c", {})
def asked(session, root, question="Which one?", at=100.0, pid=None, talk=TALK, talking=None):
return Ask(f"ask-{session}", session, root, question, at, os.getpid() if pid is None else pid, talk, talking)
def keyed(screen, *keys):
for key in keys:
screen = inbox.pressed(screen, key)
return screen
def gone_pid():
"""The pid of a process that has exited."""
return int(subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout)
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))), *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 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), typing)
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
for talking, where in ((None, "on its terminal"), (7, "in loop-inbox")):
with self.subTest(where=where):
self.assertEqual(keyed(Listing((asked("s1", "/code/log", talk=None, talking=talking),)), "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 on its terminal, or stopped."))
def test_talk_opens_claude_only_once_the_loop_has_stopped_reading_its_terminal(self):
ask = asked("s1", "/code/log")
waiting.publish(self.folder, dataclasses.replace(ask, talk=None, talking=os.getpid()))
self.assertTrue(main.made_way(self.folder, ask))
waiting.withdraw(self.folder, "s1")
self.assertFalse(main.made_way(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), asked("s2", "/b", at=100), asked("s3", "/c", at=50, pid=gone_pid())
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}')
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
def test_an_answer_names_the_ask_it_answers(self):
with tempfile.TemporaryDirectory() as folder:
ask = asked("s1", "/a")
for answer in (Typed("A"), waiting.Talking(7), waiting.Talked()):
with self.subTest(answer=answer):
waiting.send(pathlib.Path(folder), ask, answer)
self.assertEqual(waiting.answered(pathlib.Path(folder), ask), answer)
self.assertIsNone(waiting.answered(pathlib.Path(folder), dataclasses.replace(ask, id="another")))
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, talk=None)
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()