Skip to content
Python

run: Ctrl-C at a prompt ends the run and leaves its record

Rohit C Prasad900bc9f7f204
diff --git a/coworker/headless/runner.py b/coworker/headless/runner.py
index 2c304b1d..65ff7868 100644
--- a/coworker/headless/runner.py
+++ b/coworker/headless/runner.py
@@ -722,7 +722,8 @@ def allowed_sites(args: argparse.Namespace) -> list[str]:
EXIT_FINISHED = 0
EXIT_CRASHED = 1 # no usable record
EXIT_USAGE = 2
-EXIT_STOPPED = 3 # timeout, model error, iteration cap, interrupted: the record is written
+EXIT_STOPPED = 3 # timeout, model error, iteration cap: the record is written
+EXIT_INTERRUPTED = 130 # Ctrl-C, as a shell reports it; the record is written
def run(args: argparse.Namespace) -> int:
@@ -1037,6 +1038,12 @@ def _run(args: argparse.Namespace) -> int:
engine.request_interrupt()
except Exception: # noqa: BLE001
pass
+ except KeyboardInterrupt: # Ctrl-C: stop, and still leave the record
+ outcome = "interrupted"
+ try:
+ engine.request_interrupt()
+ except Exception: # noqa: BLE001
+ pass
except Exception as exc: # noqa: BLE001 - recorded, then reported by exit code
outcome = "crash"
error_text = "".join(traceback.format_exception(exc))
@@ -1105,6 +1112,8 @@ def _run(args: argparse.Namespace) -> int:
)
if outcome == "crash":
return EXIT_CRASHED
+ if outcome == "interrupted":
+ return EXIT_INTERRUPTED
if outcome != "completed" and error_text:
# Why it stopped, in a line: the full text is in the record.
print(f"openworker run: {redact(error_text.strip().splitlines()[-1])[:600]}", file=sys.stderr, flush=True)
diff --git a/coworker/headless/terminal.py b/coworker/headless/terminal.py
index c7c0ff04..a2127a9b 100644
--- a/coworker/headless/terminal.py
+++ b/coworker/headless/terminal.py
@@ -21,6 +21,7 @@ import asyncio
import json
import os
import sys
+import threading
from pathlib import Path
from typing import Any, Callable, Optional
@@ -123,8 +124,28 @@ class Terminal:
# -- plumbing -------------------------------------------------------------------------
async def _prompt(self) -> Optional[str]:
+ """One typed line. Read on a daemon thread, not the loop's pool: a run that ends
+ while the prompt waits (Ctrl-C, the time limit) must not wait for Enter to exit."""
self._write("> ")
- return await asyncio.to_thread(self._read_line)
+ loop = asyncio.get_running_loop()
+ typed: asyncio.Future[Optional[str]] = loop.create_future()
+
+ def deliver(line: Optional[str]) -> None:
+ if not typed.done():
+ typed.set_result(line)
+
+ def read() -> None:
+ try:
+ line = self._read_line()
+ except Exception: # noqa: BLE001 - a broken terminal reads as end of input
+ line = None
+ try:
+ loop.call_soon_threadsafe(deliver, line)
+ except RuntimeError: # the run is over
+ pass
+
+ threading.Thread(target=read, name="openworker-run-prompt", daemon=True).start()
+ return await typed
def _say(self, *lines: str) -> None:
self._write("\n".join(lines) + "\n")
diff --git a/docs/headless.md b/docs/headless.md
index 10af71d6..5408086d 100644
--- a/docs/headless.md
+++ b/docs/headless.md
@@ -149,6 +149,7 @@ record states it.
| 1 | the run crashed before it could write a record |
| 2 | the command line could not be run as given |
| 3 | the run stopped early (time limit, model error, iteration limit, cut-off reply); the record is written |
+| 130 | stopped with Ctrl-C; the record is written |
### The record
diff --git a/tests/test_run_cli.py b/tests/test_run_cli.py
index 8f4938aa..5a207596 100644
--- a/tests/test_run_cli.py
+++ b/tests/test_run_cli.py
@@ -416,3 +416,33 @@ def test_auto_answer_at_a_terminal_answers_the_question_and_still_asks_the_appro
(folder,) = _session_folders(tmp_path / "machine", ws)
summary = json.loads((folder / "summary.json").read_text(encoding="utf-8"))
assert summary["answers"]["questions_answered"] == 1 and summary["answers"]["cards_refused"] == 0
+
+
[email protected](sys.platform == "win32", reason="needs a pseudo-terminal")
+def test_ctrl_c_at_a_prompt_ends_the_run_and_leaves_the_record(tmp_path: Path) -> None:
+ import pty
+ import signal
+
+ machine = tmp_path / "machine"
+ machine.mkdir()
+ cmd, ws = _command(tmp_path, WRITE_THEN_DONE, "--model", "anthropic/claude-sonnet-5")
+ master, slave = pty.openpty()
+ proc = subprocess.Popen(cmd, env=_env(machine), stdin=slave, stderr=slave, stdout=subprocess.PIPE)
+ os.close(slave)
+ try:
+ shown = ""
+ deadline = time.time() + 60
+ while "Approval needed" not in shown or not shown.rstrip().endswith(">"):
+ assert time.time() < deadline, shown
+ if select.select([master], [], [], 0.2)[0]:
+ shown += os.read(master, 4096).decode("utf-8", errors="replace")
+ proc.send_signal(signal.SIGINT)
+ assert proc.wait(timeout=30) == 130 # without anyone pressing Enter
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+ os.close(master)
+ assert not (ws / "hello.txt").exists()
+ (folder,) = _session_folders(machine, ws)
+ assert json.loads((folder / "summary.json").read_text(encoding="utf-8"))["outcome"] == "interrupted"
+