The tail reads the CLI's tasks/<id>.output (never a symlink: a subagent's id there points at its transcript), ANSI and \r redraws cleaned, the end marker split off. The stop signals the task's process group (SIGTERM, SIGKILL after 3 s) and only ever looks inside the session's own process tree: a shell is the top-most process whose stdout is its output file, a Monitor the bash -c carrying its eval'd command. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
164 lines
5.7 KiB
Python
164 lines
5.7 KiB
Python
"""bgtasks: one background task's output tail, and a stop that only ever
|
|
reaches the session's own process tree."""
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
|
|
import bgtasks
|
|
import pids
|
|
import procstats
|
|
|
|
pytestmark = pytest.mark.skipif(not procstats._HAVE_PROC, reason="needs /proc")
|
|
|
|
# A fake agent run: spawns the task (its own process group, like the CLI's
|
|
# bash -c) and sleeps. argv[1] = stdout file or "-" for a pipe, argv[2:] = cmd.
|
|
ROOT = """
|
|
import subprocess, sys, time
|
|
out = sys.argv[1]
|
|
f = open(out, "ab") if out != "-" else subprocess.PIPE
|
|
subprocess.Popen(sys.argv[2:], stdout=f, stderr=subprocess.STDOUT, start_new_session=True)
|
|
time.sleep(60)
|
|
"""
|
|
|
|
|
|
def _wait(pred, timeout=5.0):
|
|
end = time.time() + timeout
|
|
while time.time() < end:
|
|
if pred():
|
|
return True
|
|
time.sleep(0.05)
|
|
return False
|
|
|
|
|
|
@pytest.fixture
|
|
def runs(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(procstats, "LOG_DIR", tmp_path)
|
|
monkeypatch.setattr(pids, "LOG_DIR", tmp_path)
|
|
monkeypatch.setattr(procstats, "_registry_dirs", lambda: [])
|
|
started: list[subprocess.Popen] = []
|
|
|
|
def start(out: str, cmd: list[str], sid: str | None = None) -> tuple[str, subprocess.Popen]:
|
|
p = subprocess.Popen([sys.executable, "-c", ROOT, out, *cmd], start_new_session=True)
|
|
started.append(p)
|
|
if sid:
|
|
assert _wait(lambda: pids._proc_starttime(p.pid) is not None)
|
|
(tmp_path / f"{sid}.pid").write_text(json.dumps(
|
|
{"pid": p.pid, "starttime": pids._proc_starttime(p.pid), "harness": "claude"}))
|
|
return sid or "", p
|
|
|
|
yield start
|
|
for p in started:
|
|
for pid in _kids(p.pid) + [p.pid]:
|
|
try:
|
|
os.killpg(pid, 9)
|
|
except OSError:
|
|
pass
|
|
p.wait(timeout=5)
|
|
|
|
|
|
def _kids(pid: int) -> list[int]:
|
|
procs = procstats._scan_proc()
|
|
return [q.pid for q in procs.values() if q.ppid == pid]
|
|
|
|
|
|
def _task_file(tmp_path, sid, tid) -> str:
|
|
d = tmp_path / "claude-1000" / "-proj" / sid / "tasks"
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
return str(d / f"{tid}.output")
|
|
|
|
|
|
# ---- tail ----------------------------------------------------------------------
|
|
|
|
def test_tail_splits_the_end_marker_and_cleans_redraws(tmp_path):
|
|
f = tmp_path / "b1.output"
|
|
f.write_text("one\n\x1b[32mtwo\x1b[0m\n10%\r50%\r100%\nlast\r\n\n[exited with code 3]\n")
|
|
out = bgtasks.tail(f, 20)
|
|
assert out["lines"] == ["one", "two", "100%", "last"]
|
|
assert out["end"] == "exited with code 3" and out["more"] is False
|
|
|
|
|
|
def test_tail_keeps_the_last_lines_and_says_there_are_more(tmp_path):
|
|
f = tmp_path / "b1.output"
|
|
f.write_text("".join(f"l{i}\n" for i in range(50)))
|
|
out = bgtasks.tail(f, 5)
|
|
assert out["lines"] == ["l45", "l46", "l47", "l48", "l49"]
|
|
assert out["more"] is True and out["end"] is None
|
|
|
|
|
|
def test_tail_of_a_big_file_drops_the_cut_first_line(tmp_path):
|
|
f = tmp_path / "b1.output"
|
|
f.write_bytes(b"x" * (bgtasks.TAIL_BYTES + 10) + b"\nend\n")
|
|
out = bgtasks.tail(f, 20)
|
|
assert out["lines"] == ["end"] and out["more"] is True
|
|
|
|
|
|
def test_find_output_never_serves_a_symlink(tmp_path):
|
|
sid = str(uuid.uuid4())
|
|
real = _task_file(tmp_path, sid, "b1")
|
|
open(real, "w").write("hi\n")
|
|
link = _task_file(tmp_path, sid, "a1")
|
|
os.symlink(real, link)
|
|
assert bgtasks.find_output(sid, "b1", [tmp_path]) == bgtasks.pathlib.Path(real)
|
|
assert bgtasks.find_output(sid, "a1", [tmp_path]) is None
|
|
assert bgtasks.find_output(sid, "nope", [tmp_path]) is None
|
|
|
|
|
|
def test_task_ids_are_validated():
|
|
with pytest.raises(HTTPException):
|
|
bgtasks._valid_task("../etc/passwd")
|
|
|
|
|
|
# ---- stop ----------------------------------------------------------------------
|
|
|
|
def test_stops_a_shell_by_its_output_file(runs, tmp_path):
|
|
sid = str(uuid.uuid4())
|
|
out = _task_file(tmp_path, sid, "bshell1")
|
|
_, root = runs(out, ["bash", "-c", "while true; do echo tick; sleep 0.2; done"], sid)
|
|
assert _wait(lambda: len(_kids(root.pid)) == 1)
|
|
shell = _kids(root.pid)[0]
|
|
res = bgtasks.stop(sid, "bshell1", "shell", None)
|
|
assert res["stopped"] == [shell]
|
|
assert _wait(lambda: not bgtasks._alive(shell))
|
|
assert root.poll() is None, "the run itself is never signalled"
|
|
|
|
|
|
def test_never_reaches_a_process_outside_the_run(runs, tmp_path):
|
|
sid, other = str(uuid.uuid4()), str(uuid.uuid4())
|
|
out = _task_file(tmp_path, sid, "bshell2")
|
|
# Same task file, but under a run that is not this session's.
|
|
_, stranger = runs(out, ["bash", "-c", "sleep 30"], other)
|
|
_, mine = runs("-", ["bash", "-c", "sleep 30"], sid)
|
|
assert _wait(lambda: len(_kids(stranger.pid)) == 1 and len(_kids(mine.pid)) == 1)
|
|
victim = _kids(stranger.pid)[0]
|
|
with pytest.raises(HTTPException) as e:
|
|
bgtasks.stop(sid, "bshell2", "shell", None)
|
|
assert e.value.status_code == 404
|
|
assert bgtasks._alive(victim)
|
|
|
|
|
|
def test_no_live_run_is_a_404(runs):
|
|
with pytest.raises(HTTPException) as e:
|
|
bgtasks.stop(str(uuid.uuid4()), "b1", "shell", None)
|
|
assert e.value.status_code == 404
|
|
|
|
|
|
def test_stops_a_monitor_by_its_command(runs, tmp_path):
|
|
sid = str(uuid.uuid4())
|
|
cmd = "while true; do echo 'it''s up'; sleep 0.2; done"
|
|
wrapped = f"true && eval '{cmd.replace(chr(39), chr(39) + chr(34) + chr(39) + chr(34) + chr(39))}' < /dev/null"
|
|
_, root = runs("-", ["bash", "-c", wrapped], sid)
|
|
assert _wait(lambda: len(_kids(root.pid)) == 1)
|
|
mon = _kids(root.pid)[0]
|
|
with pytest.raises(HTTPException):
|
|
bgtasks.stop(sid, "bmon1", "monitor", "echo something else")
|
|
res = bgtasks.stop(sid, "bmon1", "monitor", cmd)
|
|
assert res["stopped"] == [mon]
|
|
assert _wait(lambda: not bgtasks._alive(mon))
|