mirror of
https://github.com/0xWheatyz/handler.git
synced 2026-09-01 09:36:25 +00:00
feat!: headless is the only runner - delete the tmux run path (phase 4)
Agent runs are now always worker-owned 'claude -p' subprocesses; tmux survives only for the interactive /login flow. - deleted: worker.capture_agent_output/_pane_tail + the capture loop arm (the empty-/log bug's home), spawn's tmux launch/_claude_command, the tmux resume/kill branches (the silent-send-keys bug's home), tmux.session_name/list_sessions, the CLI attach subcommand, the 'runner' setting - spawn: task is now a hard requirement (headless has no idle REPL) - enforced in spawn (SpawnError) and the API (400); onboarding seeding dropped (-p skips the trust dialog) - resume: single headless path; pre-headless agent rows (no session_id) degrade to the context-re-injection fresh run - settings_gen: permissions allowlist is always emitted - credsync: change-triggered uploads key on .claude/.credentials.json only (claude touches ~/.claude.json every run - keying on it would ping-pong uploads between workers); logins still publish explicitly - cli list: liveness from agent_runs in the DB, not tmux - tests: spawn/kill/resume re-pointed at the fake_launch seam (conftest); integration test now drives API -> worker -> real fake claude subprocess -> events endpoint; README documents the headless model + multi-worker deployment invariants Suite 295 green; frontend unchanged since phase 3.
This commit is contained in:
+31
-6
@@ -1,7 +1,8 @@
|
||||
"""Shared fixtures. Everything runs on a fresh SQLite file per test, materialized via
|
||||
a *real* ``alembic upgrade head`` — so the migration path itself is under test, not
|
||||
just ``create_all``. No live claude/tmux/mise is ever touched: the three seams
|
||||
(``control.tmux``, ``hooks.verify``, ``control.spawn.resume``) are faked.
|
||||
just ``create_all``. No live claude/tmux/mise is ever touched: the seams
|
||||
(``control.headless.launch`` for runs, ``control.tmux`` for the login flow,
|
||||
``hooks.verify``, ``control.spawn.resume``) are faked.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -111,20 +112,44 @@ def fake_tmux(monkeypatch):
|
||||
def send_enter(name):
|
||||
calls["send_enter"].append({"name": name})
|
||||
|
||||
def list_sessions():
|
||||
return list(live)
|
||||
|
||||
monkeypatch.setattr(tmux, "new_session", new_session)
|
||||
monkeypatch.setattr(tmux, "has_session", has_session)
|
||||
monkeypatch.setattr(tmux, "kill_session", kill_session)
|
||||
monkeypatch.setattr(tmux, "send_keys", send_keys)
|
||||
monkeypatch.setattr(tmux, "send_text", send_text)
|
||||
monkeypatch.setattr(tmux, "send_enter", send_enter)
|
||||
monkeypatch.setattr(tmux, "list_sessions", list_sessions)
|
||||
|
||||
return {"calls": calls, "live": live}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_launch(monkeypatch):
|
||||
"""Record ``headless.launch`` calls instead of spawning a claude subprocess.
|
||||
|
||||
Mirrors the real launch's DB side effects (run row + agent session/worker) so kill/
|
||||
resume logic downstream of a fake spawn behaves like production, minus the process.
|
||||
"""
|
||||
from handler.control import headless
|
||||
from handler.db import repository as repo
|
||||
from handler.db.engine import connection
|
||||
|
||||
calls: list[dict] = []
|
||||
|
||||
def launch(agent, *, kind, prompt, settings_path, env, worker_id, on_exit=None):
|
||||
session_id = agent.get("session_id") if kind == "resume" else f"fake-sid-{len(calls) + 1}"
|
||||
with connection() as conn:
|
||||
run = repo.create_run(conn, agent["id"], session_id, worker_id, kind)
|
||||
repo.set_agent_session(conn, agent["id"], session_id, worker_id)
|
||||
calls.append(
|
||||
{"agent": agent, "kind": kind, "prompt": prompt, "settings_path": settings_path,
|
||||
"env": env, "worker_id": worker_id, "run": run}
|
||||
)
|
||||
return run
|
||||
|
||||
monkeypatch.setattr(headless, "launch", launch)
|
||||
return calls
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_gitops(monkeypatch):
|
||||
"""Fake the git seam: record config/add/commit, return a controllable branch/sha."""
|
||||
|
||||
+75
-27
@@ -1,4 +1,7 @@
|
||||
"""Control-layer spawn: the hard test-task gate, settings generation, identity env."""
|
||||
"""Control-layer spawn: the hard test-task gate, settings generation, identity env.
|
||||
|
||||
Spawns go through the ``fake_launch`` seam (conftest) — the headless analogue of the old
|
||||
fake tmux: it records the launch and mirrors its DB side effects, no subprocess."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,36 +27,48 @@ def _write_mise(root, with_test=True):
|
||||
(root / ".mise.toml").write_text(body)
|
||||
|
||||
|
||||
def test_spawn_refuses_without_test_task(env, fake_tmux):
|
||||
def test_spawn_refuses_without_test_task(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root, with_test=False)
|
||||
_register_project(root)
|
||||
with pytest.raises(spawn.SpawnError, match="no \\[tasks.test\\]"):
|
||||
spawn.spawn("proj", "api")
|
||||
assert fake_tmux["calls"]["new_session"] == []
|
||||
spawn.spawn("proj", "api", task="do it")
|
||||
assert fake_launch == []
|
||||
|
||||
|
||||
def test_spawn_refuses_without_mise_file(env, fake_tmux):
|
||||
def test_spawn_refuses_without_mise_file(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
_register_project(root)
|
||||
with pytest.raises(spawn.SpawnError, match="no mise config"):
|
||||
spawn.spawn("proj", "api", task="do it")
|
||||
|
||||
|
||||
def test_spawn_refuses_without_task(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root)
|
||||
_register_project(root)
|
||||
with pytest.raises(spawn.SpawnError, match="requires a task"):
|
||||
spawn.spawn("proj", "api")
|
||||
# Fail-fast: no orphaned agent row behind the refused spawn.
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "api") is None
|
||||
assert fake_launch == []
|
||||
|
||||
|
||||
def test_spawn_accepts_dotless_mise_toml(env, fake_tmux):
|
||||
def test_spawn_accepts_dotless_mise_toml(env, fake_launch):
|
||||
# mise also reads `mise.toml` (no leading dot); the gate must honor it too.
|
||||
root = env["tmp"] / "proj"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
(root / "mise.toml").write_text("[tasks.test]\nrun = 'pytest'\n")
|
||||
_register_project(root)
|
||||
|
||||
agent = spawn.spawn("proj", "api")
|
||||
agent = spawn.spawn("proj", "api", task="do it")
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "api")["id"] == agent["id"]
|
||||
|
||||
|
||||
def test_spawn_creates_agent_settings_and_session(env, fake_tmux):
|
||||
def test_spawn_creates_agent_settings_and_run(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root, with_test=True)
|
||||
_register_project(root)
|
||||
@@ -64,66 +79,99 @@ def test_spawn_creates_agent_settings_and_session(env, fake_tmux):
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "api")["id"] == agent["id"]
|
||||
|
||||
# settings.json wires all four hook events.
|
||||
# settings.json wires all four hook events AND the headless permission allowlist
|
||||
# (claude -p auto-denies anything that would prompt; the allowlist is what lets
|
||||
# normal work proceed — the hooks stay the hard gate).
|
||||
settings = json.loads((root / ".claude" / "settings.json").read_text())
|
||||
assert set(settings["hooks"]) == {"Stop", "SessionEnd", "PreToolUse", "Notification"}
|
||||
pre = settings["hooks"]["PreToolUse"][0]
|
||||
assert pre["matcher"] == "AskUserQuestion|Bash"
|
||||
assert "handler.hooks pre_tool_use" in pre["hooks"][0]["command"]
|
||||
assert settings["permissions"]["defaultMode"] == "acceptEdits"
|
||||
assert "Bash(git *)" in settings["permissions"]["allow"]
|
||||
|
||||
# tmux session named project__agent, with identity + DATABASE_URL in env.
|
||||
call = fake_tmux["calls"]["new_session"][0]
|
||||
assert call["name"] == "proj__api"
|
||||
# A headless run launched with identity + DATABASE_URL in env and the task as prompt.
|
||||
call = fake_launch[0]
|
||||
assert call["kind"] == "spawn"
|
||||
assert call["prompt"] == "build the thing"
|
||||
assert call["env"]["HANDLER_PROJECT_ID"] == "proj"
|
||||
assert call["env"]["HANDLER_AGENT_NAME"] == "api"
|
||||
assert call["env"]["HANDLER_AGENT_ID"] == str(agent["id"])
|
||||
assert call["env"]["DATABASE_URL"] == env["url"]
|
||||
# The run row + session id landed on the agent.
|
||||
with get_engine().begin() as conn:
|
||||
row = repo.get_agent_by_name(conn, "proj", "api")
|
||||
assert row["session_id"] == call["run"]["session_id"]
|
||||
assert repo.get_latest_run(conn, row["id"])["kind"] == "spawn"
|
||||
|
||||
|
||||
def test_spawn_mise_init_skips_test_gate_and_marks_env(env, fake_tmux):
|
||||
def test_spawn_mise_init_skips_test_gate_and_marks_env(env, fake_launch):
|
||||
# A repo with no .mise.toml at all: the normal gate would refuse, but the mise-init
|
||||
# bootstrap agent must launch anyway (creating that file is its whole job).
|
||||
root = env["tmp"] / "proj"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
_register_project(root)
|
||||
|
||||
agent = spawn.spawn("proj", "mise-init", require_tests=False, mise_init=True)
|
||||
agent = spawn.spawn(
|
||||
"proj", "mise-init", task="write the mise config", require_tests=False, mise_init=True
|
||||
)
|
||||
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "mise-init")["id"] == agent["id"]
|
||||
# The launched session carries HANDLER_MISE_INIT so its hooks enforce commit + push.
|
||||
call = fake_tmux["calls"]["new_session"][0]
|
||||
assert call["env"]["HANDLER_MISE_INIT"] == "1"
|
||||
# The launched run carries HANDLER_MISE_INIT so its hooks enforce commit + push.
|
||||
assert fake_launch[0]["env"]["HANDLER_MISE_INIT"] == "1"
|
||||
|
||||
|
||||
def test_spawn_still_gates_without_mise_init_flag(env, fake_tmux):
|
||||
def test_spawn_still_gates_without_mise_init_flag(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
_register_project(root)
|
||||
# require_tests defaults on, so a normal spawn against a mise-less repo still refuses.
|
||||
with pytest.raises(spawn.SpawnError, match="no mise config"):
|
||||
spawn.spawn("proj", "api")
|
||||
assert fake_tmux["calls"]["new_session"] == []
|
||||
spawn.spawn("proj", "api", task="do it")
|
||||
assert fake_launch == []
|
||||
|
||||
|
||||
def test_kill_sets_done_and_kills_session(env, fake_tmux):
|
||||
def test_kill_cancels_run_and_sets_done(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root, with_test=True)
|
||||
_register_project(root)
|
||||
spawn.spawn("proj", "api")
|
||||
spawn.spawn("proj", "api", task="do it")
|
||||
|
||||
spawn.kill("proj", "api")
|
||||
assert "proj__api" in fake_tmux["calls"]["kill_session"]
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "api")["status"] == "done"
|
||||
agent = repo.get_agent_by_name(conn, "proj", "api")
|
||||
assert agent["status"] == "done"
|
||||
# The running run was flagged; the owning supervisor terminates its own child.
|
||||
assert repo.get_latest_run(conn, agent["id"])["cancel_requested"] is True
|
||||
|
||||
|
||||
def test_resume_sends_answer_to_live_session(env, fake_tmux):
|
||||
def test_resume_reinjects_when_no_transcript(env, fake_launch):
|
||||
"""A resume with no archive and no local transcript degrades to a fresh run whose
|
||||
prompt carries the operator's answer (context re-injection)."""
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root, with_test=True)
|
||||
_register_project(root)
|
||||
agent = spawn.spawn("proj", "api")
|
||||
spawn.spawn("proj", "api", task="do it")
|
||||
with get_engine().begin() as conn:
|
||||
agent = repo.get_agent_by_name(conn, "proj", "api")
|
||||
repo.finish_run(conn, repo.get_latest_run(conn, agent["id"])["id"], "completed")
|
||||
|
||||
ok, detail = spawn.resume(agent, "use Postgres")
|
||||
assert ok is True
|
||||
assert fake_tmux["calls"]["send_keys"][0] == {"name": "proj__api", "keys": "use Postgres"}
|
||||
assert "re-injected" in detail
|
||||
assert fake_launch[-1]["kind"] == "spawn"
|
||||
assert "use Postgres" in fake_launch[-1]["prompt"]
|
||||
|
||||
|
||||
def test_resume_refused_while_run_live(env, fake_launch):
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root, with_test=True)
|
||||
_register_project(root)
|
||||
spawn.spawn("proj", "api", task="do it") # fake run stays 'running'
|
||||
with get_engine().begin() as conn:
|
||||
agent = repo.get_agent_by_name(conn, "proj", "api")
|
||||
|
||||
ok, detail = spawn.resume(agent, "answer")
|
||||
assert ok is False
|
||||
assert "live run" in detail
|
||||
|
||||
@@ -19,15 +19,15 @@ def _register(root, **kw):
|
||||
repo.create_project(conn, "proj", str(root), **kw)
|
||||
|
||||
|
||||
def test_spawn_injects_credentials_and_installs_helper(env, fake_tmux, fake_gitops, monkeypatch):
|
||||
def test_spawn_injects_credentials_and_installs_helper(env, fake_launch, fake_gitops, monkeypatch):
|
||||
monkeypatch.setenv("PROJ_TOKEN", "s3cret")
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root)
|
||||
_register(root, git_remote="https://github.com/me/proj.git", credential_ref="env:PROJ_TOKEN")
|
||||
|
||||
spawn.spawn("proj", "junior", role="junior")
|
||||
spawn.spawn("proj", "junior", role="junior", task="do it")
|
||||
|
||||
call = fake_tmux["calls"]["new_session"][0]
|
||||
call = fake_launch[0]
|
||||
# Token injected under the generic + host-specific names, never the raw ref stored.
|
||||
assert call["env"]["FORGE_TOKEN"] == "s3cret"
|
||||
assert call["env"]["GITHUB_TOKEN"] == "s3cret"
|
||||
@@ -38,43 +38,43 @@ def test_spawn_injects_credentials_and_installs_helper(env, fake_tmux, fake_gito
|
||||
assert "$FORGE_TOKEN" in helper[0]["value"]
|
||||
|
||||
|
||||
def test_spawn_ssh_remote_installs_no_https_helper(env, fake_tmux, fake_gitops, monkeypatch):
|
||||
def test_spawn_ssh_remote_installs_no_https_helper(env, fake_launch, fake_gitops, monkeypatch):
|
||||
monkeypatch.setenv("PROJ_TOKEN", "s3cret")
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root)
|
||||
_register(root, git_remote="git@github.com:me/proj.git", credential_ref="env:PROJ_TOKEN")
|
||||
spawn.spawn("proj", "junior", role="junior")
|
||||
spawn.spawn("proj", "junior", role="junior", task="do it")
|
||||
# ssh remote -> token still injected, but no HTTPS credential helper installed.
|
||||
assert fake_tmux["calls"]["new_session"][0]["env"]["GITHUB_TOKEN"] == "s3cret"
|
||||
assert fake_launch[0]["env"]["GITHUB_TOKEN"] == "s3cret"
|
||||
assert fake_gitops["config"] == []
|
||||
|
||||
|
||||
def test_spawn_fails_fast_on_broken_credential_ref(env, fake_tmux, fake_gitops, monkeypatch):
|
||||
def test_spawn_fails_fast_on_broken_credential_ref(env, fake_launch, fake_gitops, monkeypatch):
|
||||
monkeypatch.delenv("ABSENT_TOKEN", raising=False)
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root)
|
||||
_register(root, credential_ref="env:ABSENT_TOKEN")
|
||||
|
||||
with pytest.raises(spawn.SpawnError, match="not set"):
|
||||
spawn.spawn("proj", "junior", role="junior")
|
||||
spawn.spawn("proj", "junior", role="junior", task="do it")
|
||||
# No agent row and no session left behind by the failed spawn.
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "junior") is None
|
||||
assert fake_tmux["calls"]["new_session"] == []
|
||||
assert fake_launch == []
|
||||
|
||||
|
||||
def test_spawn_without_credential_ref_injects_no_token(env, fake_tmux, fake_gitops):
|
||||
def test_spawn_without_credential_ref_injects_no_token(env, fake_launch, fake_gitops):
|
||||
root = env["tmp"] / "proj"
|
||||
_write_mise(root)
|
||||
_register(root)
|
||||
spawn.spawn("proj", "api")
|
||||
call = fake_tmux["calls"]["new_session"][0]
|
||||
spawn.spawn("proj", "api", task="do it")
|
||||
call = fake_launch[0]
|
||||
assert "FORGE_TOKEN" not in call["env"]
|
||||
# No token -> no credential helper installed.
|
||||
assert fake_gitops["config"] == []
|
||||
|
||||
|
||||
def test_spawn_reports_forge_version_mismatch(env, fake_tmux, fake_gitops, fake_forge, monkeypatch):
|
||||
def test_spawn_reports_forge_version_mismatch(env, fake_launch, fake_gitops, fake_forge, monkeypatch):
|
||||
monkeypatch.setenv("FORGE_VERSION", "9.9.9")
|
||||
from handler import config
|
||||
from handler.db import engine
|
||||
@@ -88,5 +88,5 @@ def test_spawn_reports_forge_version_mismatch(env, fake_tmux, fake_gitops, fake_
|
||||
fake_forge["version_ok"] = False
|
||||
fake_forge["version_out"] = "forge 1.2.3"
|
||||
|
||||
agent = spawn.spawn("proj", "api")
|
||||
agent = spawn.spawn("proj", "api", task="do it")
|
||||
assert "9.9.9" in agent["forge_note"]
|
||||
|
||||
@@ -101,10 +101,3 @@ def test_disabled_without_secret_key(env, tmp_path):
|
||||
_write_local_credentials(tmp_path)
|
||||
assert credsync.upload() is False
|
||||
assert credsync.refresh() is None
|
||||
|
||||
|
||||
def test_note_local_write_suppresses_upload(secret_env, tmp_path):
|
||||
_write_local_credentials(tmp_path)
|
||||
credsync.note_local_write()
|
||||
# The deliberate local write (e.g. ensure_onboarded at spawn) is not re-published.
|
||||
assert credsync.refresh() is None
|
||||
|
||||
@@ -26,7 +26,6 @@ def headless_env(env, monkeypatch):
|
||||
from handler import config
|
||||
|
||||
monkeypatch.setenv("CLAUDE_BIN", FAKE_CLAUDE)
|
||||
monkeypatch.setenv("RUNNER", "headless")
|
||||
config.get_settings.cache_clear()
|
||||
yield env
|
||||
config.get_settings.cache_clear()
|
||||
@@ -250,16 +249,13 @@ def test_resume_refused_while_run_live(headless_env, tmp_path, monkeypatch):
|
||||
_wait_for(_finished_run(run["id"]), timeout=30.0)
|
||||
|
||||
|
||||
def test_headless_settings_include_permissions(headless_env, tmp_path):
|
||||
path = settings_gen.write_settings(str(tmp_path / "wd"), headless=True)
|
||||
def test_settings_include_permissions_and_hooks(headless_env, tmp_path):
|
||||
path = settings_gen.write_settings(str(tmp_path / "wd"))
|
||||
data = json.loads(Path(path).read_text())
|
||||
assert data["permissions"]["defaultMode"] == "acceptEdits"
|
||||
assert "Bash(git *)" in data["permissions"]["allow"]
|
||||
assert "hooks" in data # the hard gate is untouched
|
||||
|
||||
tmux_path = settings_gen.write_settings(str(tmp_path / "wd2"))
|
||||
assert "permissions" not in json.loads(Path(tmux_path).read_text())
|
||||
|
||||
|
||||
def test_api_rejects_empty_task_headless_spawn(headless_env, client, auth):
|
||||
client.post(
|
||||
|
||||
@@ -1,13 +1,32 @@
|
||||
"""End-to-end web management: the dashboard's HTTP calls -> command queue -> worker ->
|
||||
real ``spawn.spawn`` -> tmux seam. Proves the full container-split flow works with only the
|
||||
tmux/claude boundary faked, not the control layer itself."""
|
||||
real ``spawn.spawn`` -> a real headless subprocess (the fake claude binary). Proves the
|
||||
full container-split flow works with only the claude binary faked, not the control
|
||||
layer: events stream into the DB, the run reconciles, kill cancels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from handler.control import worker
|
||||
from handler.db import repository as repo
|
||||
from handler.db.engine import get_engine
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
FAKE_CLAUDE = str(REPO_ROOT / "tests" / "fixtures" / "fake_claude.py")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def headless_env(env, monkeypatch):
|
||||
from handler import config
|
||||
|
||||
monkeypatch.setenv("CLAUDE_BIN", FAKE_CLAUDE)
|
||||
config.get_settings.cache_clear()
|
||||
yield env
|
||||
config.get_settings.cache_clear()
|
||||
|
||||
|
||||
def _spawnable_project(root):
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
@@ -16,10 +35,21 @@ def _spawnable_project(root):
|
||||
repo.create_project(conn, "proj", str(root))
|
||||
|
||||
|
||||
def test_spawn_via_api_then_worker_creates_agent_and_session(client, auth, env, fake_tmux):
|
||||
_spawnable_project(env["tmp"] / "proj")
|
||||
def _wait(predicate, timeout=20.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(0.1)
|
||||
return None
|
||||
|
||||
# 1. The dashboard enqueues a spawn (202 + a queued command).
|
||||
|
||||
def test_spawn_via_api_then_worker_runs_headless_claude(client, auth, headless_env):
|
||||
_spawnable_project(headless_env["tmp"] / "proj")
|
||||
|
||||
# 1. The dashboard enqueues a spawn (202 + a queued command). A task is mandatory —
|
||||
# headless claude has no idle-REPL mode.
|
||||
r = client.post(
|
||||
"/projects/proj/agents/spawn",
|
||||
json={"name": "api", "task": "build the thing"},
|
||||
@@ -32,29 +62,62 @@ def test_spawn_via_api_then_worker_creates_agent_and_session(client, auth, env,
|
||||
# No agent yet — the worker hasn't run.
|
||||
assert client.get("/projects/proj/agents", headers=auth).json() == []
|
||||
|
||||
# 2. The control worker drains the queue (runs the real spawn.spawn).
|
||||
# 2. The control worker drains the queue (real spawn.spawn -> real subprocess).
|
||||
assert worker.drain("test-worker") == 1
|
||||
|
||||
# 3. The command is done and the agent + tmux session now exist.
|
||||
# 3. The command finished at launch (fire-and-forget)...
|
||||
got = client.get(f"/commands/{command_id}", headers=auth).json()
|
||||
assert got["status"] == "done"
|
||||
assert got["result"]["name"] == "api"
|
||||
|
||||
agents = client.get("/projects/proj/agents", headers=auth).json()
|
||||
assert [a["name"] for a in agents] == ["api"]
|
||||
assert fake_tmux["calls"]["new_session"][0]["name"] == "proj__api"
|
||||
# ...and the run's whole life shows up via the API: events stream in, the agent
|
||||
# reconciles to done, last_output is the assistant's text.
|
||||
def finished():
|
||||
agents = client.get("/projects/proj/agents", headers=auth).json()
|
||||
return agents if agents and agents[0]["status"] == "done" else None
|
||||
|
||||
agents = _wait(finished)
|
||||
assert agents is not None, "run never reconciled to done"
|
||||
agent = agents[0]
|
||||
assert agent["name"] == "api"
|
||||
assert agent["session_id"]
|
||||
assert agent["worker_id"] == "test-worker"
|
||||
assert agent["last_output"] == "working on: build the thing"
|
||||
|
||||
events = client.get("/projects/proj/agents/api/events", headers=auth).json()
|
||||
assert [e["type"] for e in events] == ["system", "assistant", "result"]
|
||||
|
||||
|
||||
def test_kill_via_api_then_worker(client, auth, env, fake_tmux):
|
||||
_spawnable_project(env["tmp"] / "proj")
|
||||
client.post("/projects/proj/agents/spawn", json={"name": "api"}, headers=auth)
|
||||
def test_spawn_without_task_is_rejected(client, auth, headless_env):
|
||||
_spawnable_project(headless_env["tmp"] / "proj")
|
||||
r = client.post("/projects/proj/agents/spawn", json={"name": "api"}, headers=auth)
|
||||
assert r.status_code == 400
|
||||
assert "task is required" in r.json()["detail"]
|
||||
|
||||
|
||||
def test_kill_via_api_then_worker(client, auth, headless_env, monkeypatch):
|
||||
monkeypatch.setenv("FAKE_CLAUDE_MODE", "hang")
|
||||
_spawnable_project(headless_env["tmp"] / "proj")
|
||||
client.post(
|
||||
"/projects/proj/agents/spawn", json={"name": "api", "task": "hang"}, headers=auth
|
||||
)
|
||||
worker.drain("w")
|
||||
|
||||
# The hanging run is live; kill flags it and the supervisor SIGTERMs its child.
|
||||
r = client.post("/projects/proj/agents/api/kill", headers=auth)
|
||||
assert r.status_code == 202
|
||||
worker.drain("w")
|
||||
|
||||
assert client.get(f"/commands/{r.json()['id']}", headers=auth).json()["status"] == "done"
|
||||
assert "proj__api" in fake_tmux["calls"]["kill_session"]
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_name(conn, "proj", "api")["status"] == "done"
|
||||
agent = repo.get_agent_by_name(conn, "proj", "api")
|
||||
assert agent["status"] == "done"
|
||||
|
||||
def canceled():
|
||||
with get_engine().begin() as conn:
|
||||
run = repo.get_latest_run(conn, agent["id"])
|
||||
return run if run["status"] != "running" else None
|
||||
|
||||
run = _wait(canceled, timeout=30.0)
|
||||
assert run is not None, "kill never terminated the hanging run"
|
||||
assert run["status"] == "canceled"
|
||||
|
||||
@@ -229,45 +229,6 @@ def test_bad_command_is_recorded_failed_not_raised(env):
|
||||
assert "agent name" in failed["error"]
|
||||
|
||||
|
||||
def test_capture_agent_output_snapshots_working_agents(env, monkeypatch):
|
||||
with get_engine().begin() as conn:
|
||||
repo.create_project(conn, "p", "/tmp/p")
|
||||
agent = repo.create_agent(conn, "p", "api", "/tmp/p/api", status="working")
|
||||
|
||||
monkeypatch.setattr(worker.tmux, "has_session", lambda name: True)
|
||||
monkeypatch.setattr(
|
||||
worker.tmux, "capture_pane", lambda name, escapes=False: "boot\nTheme picker\n\n\n"
|
||||
)
|
||||
|
||||
assert worker.capture_agent_output() == 1
|
||||
with get_engine().begin() as conn:
|
||||
row = repo.get_agent_by_id(conn, agent["id"])
|
||||
# The tail is stored with trailing blank lines trimmed.
|
||||
assert row["last_output"] == "boot\nTheme picker"
|
||||
assert row["output_at"] is not None
|
||||
|
||||
|
||||
def test_capture_agent_output_skips_dead_sessions_and_nonworking(env, monkeypatch):
|
||||
with get_engine().begin() as conn:
|
||||
repo.create_project(conn, "p", "/tmp/p")
|
||||
repo.create_agent(conn, "p", "gone", "/tmp/p/gone", status="working")
|
||||
done = repo.create_agent(conn, "p", "done", "/tmp/p/done", status="done")
|
||||
|
||||
captured = []
|
||||
monkeypatch.setattr(worker.tmux, "has_session", lambda name: False)
|
||||
monkeypatch.setattr(
|
||||
worker.tmux,
|
||||
"capture_pane",
|
||||
lambda name, escapes=False: captured.append(name) or "x",
|
||||
)
|
||||
|
||||
# The working agent's session is dead (skipped); the done agent isn't queried at all.
|
||||
assert worker.capture_agent_output() == 0
|
||||
assert captured == []
|
||||
with get_engine().begin() as conn:
|
||||
assert repo.get_agent_by_id(conn, done["id"])["last_output"] is None
|
||||
|
||||
|
||||
def test_drain_processes_multiple_then_stops(env, monkeypatch):
|
||||
_seed_project()
|
||||
monkeypatch.setattr(poller, "sweep", lambda project_id=None: {"checked": 0})
|
||||
|
||||
@@ -16,7 +16,6 @@ from handler.db.engine import get_engine
|
||||
def headless_env(env, monkeypatch):
|
||||
from handler import config
|
||||
|
||||
monkeypatch.setenv("RUNNER", "headless")
|
||||
monkeypatch.setenv("MAX_CONCURRENT_RUNS", "2")
|
||||
config.get_settings.cache_clear()
|
||||
yield env
|
||||
@@ -75,7 +74,3 @@ def test_slot_frees_when_run_finishes(headless_env, monkeypatch):
|
||||
with get_engine().begin() as conn:
|
||||
repo.finish_run(conn, run1["id"], "completed", exit_code=0)
|
||||
assert worker._full_slot_exclusions("w1") == ()
|
||||
|
||||
|
||||
def test_tmux_runner_never_excludes(env):
|
||||
assert worker._full_slot_exclusions("w") == ()
|
||||
|
||||
Reference in New Issue
Block a user