Show every waiting loop-claude in loop-inbox and take each one's answer there
This commit is contained in:
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_inbox import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], pathlib.Path.home()))
|
||||
@@ -1,7 +1,10 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting import alive, answered, Ask, publish, TalkCommand, Talked, Talking, Typed, withdraw
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
@@ -15,41 +18,102 @@ ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were picked on 2026-10-17 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.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
# Seconds between looks at whether the claude loop-inbox opened has ended.
|
||||
TALK_POLL = 0.5
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens."""
|
||||
"""The human answers in the worker's claude session, which talk opens on loop-claude's terminal."""
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class WorkerSession:
|
||||
"""The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox."""
|
||||
root: str
|
||||
id: uuid.UUID
|
||||
rung: Rung
|
||||
transcript_path: str
|
||||
# What the worker's claude adds to its environment, as the claude /talk opens does.
|
||||
env: dict[str, str]
|
||||
|
||||
def talk_command(self) -> TalkCommand:
|
||||
return TalkCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talk | Talked | Stop:
|
||||
"""Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer: the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; a line typed in loop-inbox; or Talked once the claude loop-inbox opened ends with something typed. Else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), session.talk_command())
|
||||
shown(paths, ask, effects)
|
||||
try:
|
||||
answer = effects.input(ASK_ANSWER).strip()
|
||||
answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
|
||||
if isinstance(answer, Talking | Talked):
|
||||
return talked_in_inbox(ask, answer, session.transcript_path, paths, effects)
|
||||
if isinstance(answer, Typed):
|
||||
say(f"Answered in loop-inbox: {answer.text}", effects)
|
||||
answer = answer.text
|
||||
except EOFError:
|
||||
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
|
||||
return needs_human(ANSWER_QUESTION, "the input ended")
|
||||
finally:
|
||||
withdraw(paths.waiting, ask.session)
|
||||
answer = answer.strip()
|
||||
if not answer:
|
||||
return needs_human(ANSWER_QUESTION, "nothing was typed")
|
||||
return Talk() if answer == TALK else answer
|
||||
|
||||
|
||||
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
|
||||
entries = read_transcript(path)
|
||||
def talked_in_inbox(ask: Ask, answer: Talking | Talked, transcript_path: str, paths: Paths, effects: Effects) -> Talked | Stop:
|
||||
"""Waits, off the terminal, while the claude that loop-inbox opened on the worker's session runs; the human must type something there."""
|
||||
def waited() -> None:
|
||||
if isinstance(answer, Talked):
|
||||
return
|
||||
# Shows loop-inbox that the loop stopped reading its terminal, so loop-inbox may open claude.
|
||||
shown(paths, dataclasses.replace(ask, talk=None, talking=answer.pid), effects)
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not isinstance(answered(paths.waiting, ask), Talked) and alive(answer.pid):
|
||||
effects.sleep(TALK_POLL)
|
||||
return human_typed(transcript_path, waited) or Talked()
|
||||
|
||||
|
||||
def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
|
||||
"""Shows ask in loop-inbox. A failure only warns: the question is still answered on the terminal."""
|
||||
if unshown := publish(paths.waiting, ask):
|
||||
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
||||
|
||||
|
||||
def talk(question: str, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal, listed in loop-inbox while it runs; the human must type something there."""
|
||||
ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), talk=None)
|
||||
shown(paths, ask, effects)
|
||||
try:
|
||||
return human_typed(session.transcript_path, lambda: opened(session, paths, effects))
|
||||
finally:
|
||||
withdraw(paths.waiting, ask.session)
|
||||
|
||||
|
||||
def opened(session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
if unstarted := hand_over(session.rung, ["--resume", str(session.id)], session.root, paths, session.env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
return None
|
||||
|
||||
|
||||
def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None]) -> Stop | None:
|
||||
"""Runs held_open, which returns once the claude the human answers in has ended, then checks that the human typed something there."""
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
entries = read_transcript(path)
|
||||
if stop := held_open():
|
||||
return stop
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
@@ -59,7 +123,11 @@ def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[st
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects))
|
||||
try:
|
||||
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env)
|
||||
effects.claude_on_terminal(claude_args(rung, args), root, env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
|
||||
def claude_args(rung: Rung, args: list[str]) -> list[str]:
|
||||
return [*rung.flags(), "--permission-mode", "bypassPermissions", *args]
|
||||
|
||||
@@ -14,7 +14,7 @@ from loop_claude.cycle.judge import judge, Rejected
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk, Talked, WorkerSession
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
@@ -99,8 +99,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, _):
|
||||
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
|
||||
case Talking(transcript_path, question, _):
|
||||
return talk(question, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
@@ -124,6 +124,10 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
|
||||
|
||||
|
||||
def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
|
||||
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle))
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
@@ -160,7 +164,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | HumanTalked | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
@@ -168,11 +172,16 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st
|
||||
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
|
||||
if isinstance(answer, Stop):
|
||||
return answer
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.paths, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
case Talk():
|
||||
return TalkChosen(question)
|
||||
case Talked():
|
||||
return HumanTalked()
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
return HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
|
||||
|
||||
@@ -42,8 +42,9 @@ class Interrupting:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal."""
|
||||
"""The human answers in the worker's claude session, on the terminal; question is what they were asked."""
|
||||
transcript_path: str
|
||||
question: str
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@@ -81,12 +82,13 @@ class HumanTyped:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk, or the interrupt is for a release ready to cut."""
|
||||
"""The human typed /talk at loop-claude's terminal, or the interrupt is for a release ready to cut."""
|
||||
question: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
"""The human typed in the worker's claude session, opened on loop-claude's terminal or in loop-inbox."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -111,10 +113,10 @@ def transition(state: State, event: Event) -> State:
|
||||
return Closing(transcript_path, verdict)
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
|
||||
return Talking(transcript_path, quoted_answers)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen(question):
|
||||
return Talking(transcript_path, question, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, quoted_answers), HumanTalked():
|
||||
case Talking(transcript_path, _, quoted_answers) | Interrupting(transcript_path, _, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
@@ -9,6 +10,8 @@ import typing
|
||||
import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# Seconds between calls input_or makes while nothing is typed.
|
||||
POLL_SECONDS = 0.5
|
||||
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
PYTHON_TIMEOUT = 600
|
||||
|
||||
@@ -30,6 +33,8 @@ class Effects:
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: git_repo.Git
|
||||
input: typing.Callable[[str], str]
|
||||
# Prints a prompt, then returns the line typed at the terminal, or the first value other than None that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends.
|
||||
input_or: typing.Callable[[str, typing.Callable[[], typing.Any]], typing.Any]
|
||||
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
|
||||
local_time: typing.Callable[[float], str]
|
||||
# The machine's memory; None where it cannot be read.
|
||||
@@ -62,6 +67,7 @@ def system_effects() -> Effects:
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
input=input,
|
||||
input_or=input_or,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
|
||||
memory=read_memory,
|
||||
now=time.time,
|
||||
@@ -83,6 +89,21 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T:
|
||||
# On stderr, where input prints its prompt on a terminal.
|
||||
print(prompt, end="", file=sys.stderr, flush=True)
|
||||
while True:
|
||||
if select.select([sys.stdin], [], [], POLL_SECONDS)[0]:
|
||||
# On a terminal, one read returns at most one line, so nothing typed after it is buffered here, out of discard_typed's reach.
|
||||
line = os.read(sys.stdin.fileno(), 65536)
|
||||
if not line:
|
||||
raise EOFError
|
||||
return line.decode("utf-8", "replace").removesuffix("\n")
|
||||
if (got := other()) is not None:
|
||||
print(file=sys.stderr, flush=True) # Ends the prompt's line.
|
||||
return got
|
||||
|
||||
|
||||
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
|
||||
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
|
||||
body = text.lstrip("\n")
|
||||
|
||||
@@ -22,12 +22,15 @@ is shown the passage the judge quoted as the work remaining. The next chunk star
|
||||
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question and reads a one-line answer on its terminal. The worker resumes
|
||||
headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the
|
||||
answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session
|
||||
on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits,
|
||||
the judge rules on what was typed there. A release ready to cut opens that session at once, since
|
||||
only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked
|
||||
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows every
|
||||
loop on the machine that waits for the human. The first answer counts, from either place:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
chunk stays unfinished until the answer is recorded.
|
||||
- /talk: opens the worker's session with `claude --resume`, to read the diff or discuss first. Once
|
||||
that claude exits, the judge rules on what was typed there.
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
@@ -110,7 +113,8 @@ Exit 2, when the human is needed to go on:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, or for a release ready to cut, ends with nothing typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
||||
nothing typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session.
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ class Paths:
|
||||
home: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
# Where a loop that waits for the human shows its question to loop-inbox (bin/loop_claude/waiting.py).
|
||||
waiting: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home: pathlib.Path) -> Paths:
|
||||
@@ -21,4 +23,5 @@ def paths_from(home: pathlib.Path) -> Paths:
|
||||
home=home,
|
||||
model_catalog=claude / "cache" / "model-catalog",
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
waiting=home / ".local" / "state" / "loop-claude",
|
||||
)
|
||||
|
||||
@@ -18,6 +18,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from loop_claude import waiting
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
@@ -726,6 +727,20 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertNotIn("stray", run.calls[3]["stdin"])
|
||||
|
||||
def test_resumes_the_worker_headless_with_the_answer_typed_in_loop_inbox(self):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
def answered_in_inbox():
|
||||
[ask] = waiting.waiting(folder)
|
||||
waiting.send(folder, ask, waiting.Typed("B"))
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
|
||||
self.assertIn("Answer (/talk opens claude, Enter stops the loop): \nAnswered in loop-inbox: B\n", run.stderr)
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertEqual(list(folder.iterdir()), [])
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
|
||||
|
||||
@@ -22,7 +22,7 @@ from loop_claude.project import checkout, model_choice, records
|
||||
from chunk_pick import DefaultPlan, LastCut
|
||||
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from claude_code import entries, reply, session
|
||||
from loop_claude import escalation_mark, paths, routing
|
||||
from loop_claude import escalation_mark, paths, routing, waiting
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
@@ -81,6 +81,7 @@ class FakeEffects:
|
||||
execv=self.execv,
|
||||
git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)),
|
||||
input=lambda prompt: self.answer("input", prompt),
|
||||
input_or=self.input_or,
|
||||
local_time=lambda seconds: f"<{seconds}>",
|
||||
memory=self.memory,
|
||||
now=lambda: NOW,
|
||||
@@ -94,6 +95,14 @@ class FakeEffects:
|
||||
self.calls.append(("memory", None))
|
||||
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
|
||||
|
||||
def input_or(self, prompt, other):
|
||||
"""Answers from the input script as input does, but hands a callable in it other, which loop-inbox's answer comes from."""
|
||||
self.calls.append(("input", prompt))
|
||||
answer = self.scripts["input"].pop(0)
|
||||
if isinstance(answer, BaseException):
|
||||
raise answer
|
||||
return answer(other) if callable(answer) else answer
|
||||
|
||||
def on_terminal_claude(self, args, cwd, env):
|
||||
self.terminal_environments.append(env)
|
||||
return self.answer("claude_on_terminal", args)
|
||||
@@ -178,10 +187,13 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(), states.Talking("/t", 3)),
|
||||
(states.Talking("/t"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen("q"), states.Talking("/t", "q")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen("q"), states.Talking("/t", "q", 3)),
|
||||
(states.Talking("/t", "q"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", "q", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
# The human talked in the claude loop-inbox opened.
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
@@ -191,8 +203,8 @@ class Transitions(unittest.TestCase):
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t"), states.Talking("/t", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t", "q"), states.Talking("/t", "q", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen("q"), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
@@ -207,7 +219,7 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
|
||||
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen("q"), states.Talking("/t", "q")),
|
||||
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
):
|
||||
with self.subTest(state=state, event=event):
|
||||
@@ -638,11 +650,22 @@ class MemoryWait(unittest.TestCase):
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def put(self, fake, answer_here=True):
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.home)
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.transcript = self.home / "t.jsonl"
|
||||
self.transcript.write_text(json.dumps(human("a")) + "\n")
|
||||
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
|
||||
def put(self, fake, answer_here=True, effects=None):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
put = interrupt.put_question("Which one?", answer_here, fake.effects())
|
||||
put = interrupt.put_question("Which one?", answer_here, self.session, self.paths, effects or fake.effects())
|
||||
return put, said.getvalue()
|
||||
|
||||
def asked(self):
|
||||
return waiting.waiting(self.paths.waiting)
|
||||
|
||||
def test_stops_off_a_terminal_before_asking(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n"))
|
||||
@@ -665,24 +688,80 @@ class Interrupts(unittest.TestCase):
|
||||
for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
|
||||
with self.subTest(why=why):
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self):
|
||||
def typed(_):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.session, ask.root, ask.question, ask.asked, ask.pid, ask.talking), (str(self.session.id), str(self.home), "Which one?", NOW, os.getpid(), None))
|
||||
self.assertEqual(ask.talk, waiting.TalkCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}))
|
||||
return "Use B."
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.")
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_takes_a_line_typed_in_loop_inbox_for_this_question_and_no_other(self):
|
||||
def answered(_, other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, dataclasses.replace(ask, id="an earlier ask"), waiting.Typed("Use A."))
|
||||
self.assertIsNone(other())
|
||||
waiting.send(self.paths.waiting, ask, waiting.Typed(" Use C. "))
|
||||
return other()
|
||||
fake = FakeEffects()
|
||||
effects = dataclasses.replace(fake.effects(), input_or=answered)
|
||||
self.assertEqual(self.put(fake, effects=effects), ("Use C.", f"\n{STAMP} Which one?\n{STAMP} Answered in loop-inbox: Use C. \n"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_waits_off_the_terminal_while_loop_inbox_has_claude_open_and_goes_on_once_the_human_typed_there(self):
|
||||
inbox = os.getpid()
|
||||
def talking(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talking(inbox))
|
||||
return other()
|
||||
def claude_ran(_):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.talk, ask.talking), (None, inbox))
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talked())
|
||||
fake = FakeEffects(inputs=[talking])
|
||||
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_stops_when_loop_inbox_ends_its_claude_or_is_gone_with_nothing_typed(self):
|
||||
gone = subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout.strip()
|
||||
for pid, ended in ((os.getpid(), True), (int(gone), False)):
|
||||
with self.subTest(ended=ended):
|
||||
def talking(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talking(pid))
|
||||
if ended:
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talked())
|
||||
return other()
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[talking]))[0], Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
|
||||
def ran(args):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.question, ask.talk, ask.talking), ("Cut 0.4.0?", None, None))
|
||||
return 0
|
||||
fake = FakeEffects(on_terminal_claude=[ran], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
interrupt.talk("Cut 0.4.0?", self.session, self.paths, fake.effects())
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
stop = interrupt.talk(home, uuid.uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
stop = interrupt.talk("Which one?", self.session, self.paths, fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
|
||||
interrupt.talk(home, uuid.uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [handed])
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
interrupt.talk("Which one?", self.session, self.paths, fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}])
|
||||
|
||||
|
||||
class RoutingCheck(unittest.TestCase):
|
||||
@@ -1579,9 +1658,9 @@ class ExitContract(unittest.TestCase):
|
||||
unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
|
||||
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("cycle/interrupt.py", "talk", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/interrupt.py", "opened", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "human_typed", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
|
||||
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
|
||||
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""The files by which a loop-claude that waits for the human shows its question in loop-inbox, and takes an answer typed there.
|
||||
|
||||
A waiting loop keeps one file per session, <session id>.json, in Paths.waiting, and removes it once answered or stopped.
|
||||
loop-inbox answers by replacing <session id>.answer. The answer names the ask it answers by its id, so an answer
|
||||
meant for an earlier question, or sent as the loop took an answer on its terminal, never answers a later one.
|
||||
|
||||
/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
|
||||
1. loop-inbox writes Talking, with its pid.
|
||||
2. The loop stops reading its terminal and republishes its ask with talking set to that pid; loop-inbox opens claude only once it reads that.
|
||||
3. loop-inbox writes Talked once claude exits. The loop also stops waiting if loop-inbox's process is gone.
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
from file_writes import make_private, replace_json
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkCommand:
|
||||
"""How loop-inbox runs claude on the worker's session: claude's arguments, its folder and what it adds to the environment."""
|
||||
args: list[str]
|
||||
cwd: str
|
||||
env: dict[str, str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ask:
|
||||
id: str
|
||||
session: str
|
||||
# The checkout the loop runs in.
|
||||
root: str
|
||||
question: str
|
||||
# When the loop asked, in seconds since the epoch.
|
||||
asked: float
|
||||
pid: int
|
||||
# How loop-inbox opens claude for /talk; None while claude is open for this question, which then takes no answer from loop-inbox.
|
||||
talk: TalkCommand | None
|
||||
# The pid of the loop-inbox that has claude open for this question; None while claude is open on the loop's own terminal, or not open.
|
||||
talking: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Typed:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
pid: int
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talked:
|
||||
pass
|
||||
|
||||
|
||||
Answer = Typed | Talking | Talked
|
||||
|
||||
|
||||
def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.json"
|
||||
|
||||
|
||||
def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.answer"
|
||||
|
||||
|
||||
def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
|
||||
try:
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot make {folder}: {failure.strerror}")
|
||||
return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask))
|
||||
|
||||
|
||||
def withdraw(folder: pathlib.Path, session: str) -> None:
|
||||
"""Removes the session's ask and any answer to it."""
|
||||
for path in (ask_file(folder, session), answer_file(folder, session)):
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def waiting(folder: pathlib.Path) -> list[Ask]:
|
||||
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out, as is one being replaced."""
|
||||
try:
|
||||
paths = sorted(folder.glob("*.json"))
|
||||
except OSError:
|
||||
return []
|
||||
asks = [ask for path in paths if (ask := read_ask(path)) and alive(ask.pid)]
|
||||
return sorted(asks, key=lambda ask: ask.asked)
|
||||
|
||||
|
||||
def read_ask(path: pathlib.Path) -> Ask | None:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
talk = data["talk"] and TalkCommand(**data["talk"])
|
||||
ask = Ask(**{**data, "talk": talk})
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return None
|
||||
# A pid of 0 or below would name a process group to alive.
|
||||
return ask if isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None
|
||||
|
||||
|
||||
def send(folder: pathlib.Path, ask: Ask, answer: Answer) -> Failure | None:
|
||||
kind = dataclasses.asdict(answer) | {"kind": type(answer).__name__}
|
||||
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **kind})
|
||||
|
||||
|
||||
def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
|
||||
"""The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session."""
|
||||
try:
|
||||
data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, dict) or data.get("ask") != ask.id:
|
||||
return None
|
||||
match data:
|
||||
case {"kind": "Typed", "text": str(text)}:
|
||||
return Typed(text)
|
||||
case {"kind": "Talking", "pid": int(pid)}:
|
||||
return Talking(pid)
|
||||
case {"kind": "Talked"}:
|
||||
return Talked()
|
||||
return None
|
||||
|
||||
|
||||
def alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -23,7 +23,7 @@ def unsorted_imports(source: str) -> list[int]:
|
||||
|
||||
class ImportOrder(unittest.TestCase):
|
||||
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude", "bin/loop-inbox"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
self.assertIn("bin/loop-claude", listed)
|
||||
for name in listed:
|
||||
with self.subTest(name):
|
||||
|
||||
@@ -215,7 +215,7 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
Reference in New Issue
Block a user