Answer architecture round 1: 1 🔴, 6 🟡 (0 misread); open claude through one hand_over, route loop-inbox's /talk through the Talking state, give Ask one state
This commit is contained in:
@@ -2,13 +2,13 @@
|
||||
|
||||
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.
|
||||
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone doesn't stop the loop.
|
||||
"""
|
||||
import dataclasses
|
||||
import textwrap
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting import Ask
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.cycle.interrupt import TALK
|
||||
|
||||
ENTER = "enter"
|
||||
@@ -83,13 +83,13 @@ def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering:
|
||||
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.")
|
||||
if not isinstance(ask.state, Asking):
|
||||
return Listing(note=f"{ask.root}: claude is open {where_open(ask.state)}; answer there.")
|
||||
return Answering(ask)
|
||||
|
||||
|
||||
def where_open(ask: Ask) -> str:
|
||||
return "in loop-inbox" if ask.talking else "on its terminal"
|
||||
def where_open(state: OpenOnTerminal | OpenInInbox) -> str:
|
||||
return "in loop-inbox" if isinstance(state, OpenInInbox) else "on its terminal"
|
||||
|
||||
|
||||
def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> list[str]:
|
||||
@@ -98,7 +98,7 @@ def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[floa
|
||||
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 ""
|
||||
state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}"
|
||||
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("")
|
||||
|
||||
+28
-56
@@ -24,25 +24,20 @@ 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
|
||||
import typing
|
||||
|
||||
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.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
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}
|
||||
|
||||
|
||||
@@ -57,19 +52,19 @@ def main(argv: list[str], home: pathlib.Path) -> int:
|
||||
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)))
|
||||
curses.wrapper(lambda window: run(window, paths_from(home), system_effects()))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def run(window: curses.window, paths: Paths) -> None:
|
||||
def run(window: curses.window, paths: Paths, effects: Effects) -> None:
|
||||
folder = paths.waiting
|
||||
window.timeout(REFRESH_MS)
|
||||
screen: Screen = Listing()
|
||||
while True:
|
||||
screen = refreshed(screen, folder)
|
||||
draw(window, screen)
|
||||
screen = refreshed(screen, folder, effects.alive)
|
||||
draw(window, screen, effects)
|
||||
try:
|
||||
key = window.get_wch()
|
||||
except curses.error:
|
||||
@@ -80,7 +75,7 @@ def run(window: curses.window, paths: Paths) -> None:
|
||||
case Send(ask, text):
|
||||
screen = Listing(note=sent(folder, ask, text))
|
||||
case Open(ask):
|
||||
screen = Listing(note=talked(window, paths, ask))
|
||||
screen = Listing(note=opened(window, paths, ask, effects))
|
||||
case Listing() | Answering() as next_screen:
|
||||
screen = next_screen
|
||||
|
||||
@@ -90,20 +85,20 @@ def key_name(key: str | int) -> str:
|
||||
return KEYS.get(key, key if isinstance(key, str) else "")
|
||||
|
||||
|
||||
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
|
||||
def refreshed(screen: Screen, folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> 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)
|
||||
return Listing(tuple(waiting(folder, alive)), "", 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:
|
||||
def draw(window: curses.window, screen: Screen, effects: Effects) -> 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)
|
||||
now = effects.now()
|
||||
lines = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.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.
|
||||
@@ -111,14 +106,10 @@ def draw(window: curses.window, screen: Screen) -> None:
|
||||
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
|
||||
return now is not None and now.id == ask.id and isinstance(now.state, Asking)
|
||||
|
||||
|
||||
def no_longer_waits(ask: Ask) -> str:
|
||||
@@ -134,43 +125,24 @@ def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
|
||||
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."""
|
||||
def opened(window: curses.window, paths: Paths, ask: Ask, effects: Effects) -> str:
|
||||
"""Opens the worker's claude session on this terminal once the loop has made way for it, and says what came of it."""
|
||||
folder = paths.waiting
|
||||
if not still_waits(folder, ask) or ask.talk is None:
|
||||
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
|
||||
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."
|
||||
claimed = claim_talk(folder, ask, effects.pid(), effects.now, effects.sleep)
|
||||
if isinstance(claimed, Failure):
|
||||
return f"Could not open claude for {ask.root}: {claimed.reason}"
|
||||
if not claimed:
|
||||
return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS:g} 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}"
|
||||
unstarted = hand_over(ask.state.talk, paths, effects)
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, interrupt)
|
||||
unsent = send(folder, ask, Talked())
|
||||
unsent = send(folder, ask, ClaudeEnded())
|
||||
curses.reset_prog_mode()
|
||||
window.refresh()
|
||||
# Without Talked, the loop goes on only once loop-inbox quits.
|
||||
said = f"Could not start claude for {ask.root}: {unstarted.reason}" if unstarted else f"claude for {ask.root} has ended; the loop goes on."
|
||||
# Without ClaudeEnded, 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
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -10,15 +8,21 @@ 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_claude.waiting import Ask, Asking, ClaudeCommand, OpenInInbox, OpenOnTerminal, Typed
|
||||
from loop_inbox import inbox, main
|
||||
from loop_claude import waiting
|
||||
|
||||
TALK = TalkCommand(["--resume", "s"], "/c", {})
|
||||
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 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 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):
|
||||
@@ -27,11 +31,6 @@ def keyed(screen, *keys):
|
||||
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())
|
||||
@@ -39,7 +38,7 @@ class Answers(unittest.TestCase):
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
@@ -55,7 +54,7 @@ class Answers(unittest.TestCase):
|
||||
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)
|
||||
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.")
|
||||
@@ -65,27 +64,45 @@ class Answers(unittest.TestCase):
|
||||
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(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 talking, where in ((None, "on its terminal"), (7, "in loop-inbox")):
|
||||
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", talk=None, talking=talking),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
|
||||
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"))
|
||||
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), Listing(note="/code/log no longer waits for that answer: it was answered on its terminal, or stopped."))
|
||||
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 test_talk_opens_claude_only_once_the_loop_has_stopped_reading_its_terminal(self):
|
||||
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")
|
||||
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))
|
||||
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):
|
||||
@@ -125,27 +142,30 @@ class Keys(unittest.TestCase):
|
||||
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())
|
||||
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}')
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
|
||||
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_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")))
|
||||
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, talk=None)
|
||||
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.",
|
||||
|
||||
Reference in New Issue
Block a user