Files
ai-agent/sidecar/test_code_mode.py

311 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Code Mode runs (launch.py "Code Mode", ptyrun.py): the interactive argv,
which sessions must take it, the turn-end marker and the wrapper's screen
reading — plus one real run of the wrapper on a fake CLI."""
import io
import json
import os
import pathlib
import subprocess
import sys
import textwrap
import time
import pytest
from fastapi import HTTPException
import claude_proxy
import launch
import claude_launch
import ptyrun
import stop_guard as sg
from config import CLAUDE_BIN
from claude_launch import _claude_args, code_mode_args, code_mode_gate, is_code_mode_session
SID = "11111111-2222-3333-4444-555555555555"
def _settings(args):
return json.loads(args[args.index("--settings") + 1])
# ── the argv ────────────────────────────────────────────────────────────────
def test_code_mode_args_drop_the_print_flags_and_put_the_prompt_last():
base = _claude_args("-start with a dash", "--session-id", SID, chrome=True,
code_mode=True) + ["--model", "opus", "--remote-control"]
args = code_mode_args(base, SID)
assert args[:3] == [sys.executable, "-I", str(claude_launch.PTYRUN)]
i = args.index("--")
assert args[3:i] == ["--sid", SID, "--state", str(launch.LOG_DIR)]
cli = args[i + 1:]
assert cli[0] == CLAUDE_BIN and cli[1:3] == ["--session-id", SID]
assert cli[-2:] == ["--", "-start with a dash"]
for flag in ("-p", "--output-format", "json", "--remote-control", "--chrome"):
assert flag not in cli[:-2]
assert cli[cli.index("--model") + 1] == "opus"
assert "--permission-mode" in cli
def test_code_mode_args_refuse_an_argv_that_isnt_a_print_run():
with pytest.raises(ValueError):
code_mode_args([CLAUDE_BIN, "--resume", SID], SID)
def test_code_mode_settings_keep_a_stop_hook_and_let_the_diff_hooks_fail_open(monkeypatch):
monkeypatch.setattr(claude_launch, "STOP_GUARD_ENABLED", False)
plain = _settings(_claude_args("hi", "--session-id", SID))
assert "Stop" not in plain.get("hooks", {})
s = _settings(_claude_args("hi", "--session-id", SID, code_mode=True))
stop = s["hooks"]["Stop"][0]["hooks"][0]["command"]
assert stop.endswith("--mark-only") and "stop_guard.py" in stop
if claude_launch.BASH_DIFF_ENABLED and claude_launch.BASH_DIFF.is_file():
for event in ("PreToolUse", "PostToolUse"):
diff = [h for e in s["hooks"][event] for h in e["hooks"]
if "bash_diff" in h["command"]]
assert diff and all(h["onFailure"] == "continue" for h in diff)
normal = _settings(_claude_args("hi", "--session-id", SID))
assert all("onFailure" not in h for e in normal["hooks"]["PreToolUse"]
for h in e["hooks"])
def test_chrome_is_left_out_of_a_code_mode_run():
assert "--chrome" in _claude_args("hi", "--session-id", SID, chrome=True)
assert "--chrome" not in _claude_args("hi", "--session-id", SID, chrome=True,
code_mode=True)
# ── which runs go on the wrapper ────────────────────────────────────────────
def _transcript(tmp_path, *records):
p = tmp_path / f"{SID}.jsonl"
p.write_text("".join(json.dumps(r, separators=(",", ":")) + "\n" for r in records))
return p
def test_a_code_mode_session_is_known_by_its_repl_mode_record(tmp_path):
on = _transcript(tmp_path, {"type": "mode", "mode": "normal"},
{"type": "repl-mode", "replMode": True, "sessionId": SID})
assert is_code_mode_session(on)
off = _transcript(tmp_path, {"type": "user", "message": {"content": "repl-mode"}})
assert not is_code_mode_session(off)
assert not is_code_mode_session(None)
assert not is_code_mode_session(tmp_path / "missing.jsonl")
@pytest.fixture
def healthy(monkeypatch):
monkeypatch.setattr(claude_launch, "code_mode_health",
lambda: {"ok": True, "cli": "2.1.327", "reason": None})
monkeypatch.setattr(claude_proxy, "proxied", lambda a: False)
def test_gate_runs_code_mode_when_asked(healthy):
assert code_mode_gate(True, "personal") == (True, None)
assert code_mode_gate(None, "personal") == (False, None)
def test_gate_keeps_a_code_mode_session_in_it(healthy, tmp_path):
p = _transcript(tmp_path, {"type": "repl-mode", "replMode": True})
assert code_mode_gate(None, "personal", p) == (True, None)
assert code_mode_gate(False, "personal", p) == (True, None)
def test_gate_says_why_a_proxied_run_goes_without(healthy, monkeypatch, tmp_path):
monkeypatch.setattr(claude_proxy, "proxied", lambda a: True)
on, why = code_mode_gate(True, "personal")
assert on is False and why == {"on": False, "reason": claude_launch.CODE_MODE_PROXIED}
p = _transcript(tmp_path, {"type": "repl-mode", "replMode": True})
with pytest.raises(HTTPException) as e:
code_mode_gate(None, "personal", p)
assert e.value.status_code == 409
assert e.value.detail["kind"] == "code_mode_unavailable"
def test_gate_says_why_an_old_cli_goes_without(monkeypatch):
monkeypatch.setattr(claude_proxy, "proxied", lambda a: False)
monkeypatch.setattr(claude_launch, "cli_version", lambda: (2, 1, 300))
on, why = code_mode_gate(True, "personal")
assert on is False and "2.1.323" in why["reason"]
def test_health_reads_the_cli_version(monkeypatch):
monkeypatch.setattr(claude_launch, "cli_version", lambda: (2, 1, 327))
assert claude_launch.code_mode_health() == {"ok": True, "cli": "2.1.327", "reason": None}
monkeypatch.setattr(claude_launch, "cli_version", lambda: None)
assert claude_launch.code_mode_health()["ok"] is False
# ── the turn-end marker ─────────────────────────────────────────────────────
def _stop_input(tasks=()):
return {"session_id": SID, "hook_event_name": "Stop", "background_tasks": list(tasks)}
def test_the_guard_marks_the_turn_end_only_in_a_wrapper_run(tmp_path, monkeypatch):
monkeypatch.setattr(sg, "STATE_DIR", str(tmp_path))
monkeypatch.setattr(sg, "SESSION_ID", SID)
monkeypatch.delenv("AIA_PTYRUN", raising=False)
sg.mark_turn_end(_stop_input())
assert not (tmp_path / f"{SID}.turnend").exists()
monkeypatch.setenv("AIA_PTYRUN", "1")
sg.mark_turn_end(_stop_input([
{"id": "a1", "type": "subagent", "status": "running", "description": "sleep"},
{"id": "s1", "type": "shell", "status": "completed"}]))
m = json.loads((tmp_path / f"{SID}.turnend").read_text())
assert m["background"] == [{"id": "a1", "type": "subagent", "description": "sleep"}]
def _run_guard(tmp_path, hook_input, *args):
env = {**os.environ, "AIA_PTYRUN": "1", "STOP_GUARD_STATE_DIR": str(tmp_path)}
return subprocess.run([sys.executable, "-I", str(claude_launch.STOP_GUARD), *args],
input=json.dumps(hook_input), capture_output=True, text=True,
env=env, timeout=30)
def test_the_guard_letting_a_stop_through_marks_it(tmp_path):
r = _run_guard(tmp_path, _stop_input())
assert r.returncode == 0 and r.stdout.strip() == ""
assert json.loads((tmp_path / f"{SID}.turnend").read_text())["background"] == []
def test_mark_only_never_holds(tmp_path):
shell = {"id": "b1", "type": "shell", "status": "running", "command": "make"}
r = _run_guard(tmp_path, _stop_input([shell]), "--mark-only")
assert r.returncode == 0 and r.stdout.strip() == ""
assert json.loads((tmp_path / f"{SID}.turnend").read_text())["background"][0]["id"] == "b1"
# ── the wrapper's screen ───────────────────────────────────────────────────
def test_plain_strips_escapes():
raw = b"\x1b[2J\x1b[1;1H\x1b[38;5;12mCode Mode\x1b[0m (experimental) is on\x07"
assert ptyrun.flat(ptyrun.plain(raw)).strip() == "Code Mode (experimental) is on"
@pytest.mark.parametrize("screen, want", [
("⚠ Code Mode (experimental) is on · this session can be resumed only with Code Mode on",
{"on": True, "reason": None}),
("⚠ Code Mode (experimental) isn't available: for now it only works directly with the "
"Anthropic API (not through a gateway). Starting with the ordinary tools. ❯ ",
{"on": False, "reason": "for now it only works directly with the Anthropic API "
"(not through a gateway)"}),
("⚠ Code Mode (experimental) is off for this session, as you chose.",
{"on": False, "reason": "declined at the Code Mode prompt"}),
("Welcome to Claude Code", None),
])
def test_banner(screen, want):
assert ptyrun.banner(screen) == want
def test_selected_reads_the_newest_render():
s = "❯ No, start without it Yes, turn on Code Mode …redraw… ❯ Yes, turn on Code Mode"
assert ptyrun.selected(s).startswith("Yes, turn on Code Mode")
def _run(tmp_path):
clock = [100.0]
r = ptyrun.Run(SID, tmp_path, tmp_path / "sessions", out=io.BytesIO(),
clock=lambda: clock[0])
(tmp_path / "sessions").mkdir()
return r, clock
def test_a_dialog_is_walked_down_to_its_option_then_confirmed(tmp_path):
r, _ = _run(tmp_path)
r.feed(b"Code Mode (experimental) \x1b[1C \xe2\x9d\xaf No, start without it\r\n"
b" Yes, turn on Code Mode\r\n Enter to confirm")
r.dialogs(100.0)
assert r.keys == [] # let it render first
r.dialogs(101.0)
assert r.keys == [ptyrun.DOWN]
r.keys.clear()
r.feed(" No, start without it ❯ Yes, turn on Code Mode".encode())
r.dialogs(101.2)
assert r.keys == [] # one key per step
r.dialogs(101.7)
assert r.keys == [ptyrun.ENTER] and "consent" in r.answered
def test_an_unknown_dialog_is_declined_after_a_while(tmp_path):
r, _ = _run(tmp_path)
r.feed("Some new question? ❯ No Yes Enter to confirm · Esc to cancel".encode())
r.dialogs(100.0)
r.dialogs(100.0 + ptyrun.DIALOG_GIVEUP_S - 1)
assert r.keys == []
r.dialogs(100.0 + ptyrun.DIALOG_GIVEUP_S + 1)
assert r.keys == [ptyrun.ESC]
def test_the_banner_is_written_once(tmp_path):
r, _ = _run(tmp_path)
r.feed(b"Code Mode (experimental) is on")
st = json.loads((tmp_path / f"{SID}.codemode.json").read_text())
assert st["on"] is True
assert claude_launch.code_mode_state.__name__ # same file shape the sidecar reads
def test_turn_end_waits_for_background_tasks_and_idle(tmp_path):
r, _ = _run(tmp_path)
reg = tmp_path / "sessions" / "123.json"
reg.write_text(json.dumps({"sessionId": SID, "status": "busy"}))
marker = tmp_path / f"{SID}.turnend"
marker.write_text(json.dumps({"background": [{"id": "a1"}]}))
r.turn(100.0)
assert r.keys == [] and not marker.exists() # a subagent still runs
marker.write_text(json.dumps({"background": []}))
r.turn(101.0)
assert r.keys == [] # the CLI is still busy
reg.write_text(json.dumps({"sessionId": SID, "status": "idle"}))
r.turn(102.0)
assert r.keys == [b"/exit", ptyrun.ENTER]
def test_turn_end_gives_up_waiting_for_idle(tmp_path):
r, _ = _run(tmp_path)
(tmp_path / "sessions" / "1.json").write_text(json.dumps({"sessionId": SID, "status": "busy"}))
(tmp_path / f"{SID}.turnend").write_text(json.dumps({"background": []}))
r.turn(100.0)
r.turn(100.0 + ptyrun.IDLE_WAIT_S + 1)
assert r.keys == [b"/exit", ptyrun.ENTER]
# ── one real run on a fake CLI ─────────────────────────────────────────────
FAKE_CLI = textwrap.dedent("""\
import json, os, pathlib, sys, time, tty
sid, state = sys.argv[1], pathlib.Path(sys.argv[2])
tty.setraw(0)
def out(s): os.write(1, s.encode())
def key():
return os.read(0, 16)
out("Quick safety check \\r\\n\\u276f No, exit\\r\\n Yes, I trust this folder\\r\\nEnter to confirm")
while True:
k = key()
if k == b"\\x1b[B":
out("\\x1b[3A No, exit\\r\\n\\u276f Yes, I trust this folder\\r\\n")
elif k == b"\\r":
break
out("\\x1b[2J\\u26a0 Code Mode (experimental) is on\\r\\n")
reg = pathlib.Path(os.environ["CLAUDE_CONFIG_DIR"]) / "sessions"
reg.mkdir(parents=True, exist_ok=True)
(reg / f"{os.getpid()}.json").write_text(json.dumps({"sessionId": sid, "status": "idle"}))
assert os.environ.get("AIA_PTYRUN") == "1"
(state / f"{sid}.turnend").write_text(json.dumps({"background": []}))
typed = b""
while b"/exit" not in typed:
typed += key()
sys.exit(3)
""")
def test_the_wrapper_drives_a_fake_cli_end_to_end(tmp_path):
cli = tmp_path / "fake_cli.py"
cli.write_text(FAKE_CLI)
env = {**os.environ, "CLAUDE_CONFIG_DIR": str(tmp_path / "cfg")}
t0 = time.monotonic()
r = subprocess.run([sys.executable, "-I", str(claude_launch.PTYRUN), "--sid", SID,
"--state", str(tmp_path), "--", sys.executable, str(cli), SID,
str(tmp_path)], capture_output=True, env=env, timeout=60)
log = r.stdout.decode()
assert r.returncode == 3, log
assert "[code-mode] answered the trust prompt" in log
assert "[code-mode] on" in log and "turn over — /exit" in log
assert json.loads((tmp_path / f"{SID}.codemode.json").read_text())["on"] is True
assert time.monotonic() - t0 < 30