Files
hx/tests/tui_smoke.py
T

132 lines
5.6 KiB
Python

"""Drive the interactive TUI in a pty against the fake API. Prints screen text at checkpoints."""
import os, pty, sys, time, subprocess, select, re, json, tempfile, signal
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
port = 20000 + os.getpid() % 20000
srv = subprocess.Popen([sys.executable, f"{root}/tests/fake_anthropic.py", str(port)])
# resolved: hx sees the real cwd (macOS /var -> /private/var) and derives the session dir slug from it
tmp = os.path.realpath(tempfile.mkdtemp())
os.makedirs(f"{tmp}/home/.hx"); os.makedirs(f"{tmp}/repo")
open(f"{tmp}/home/.hx/auth.json", "w").write(json.dumps({"claude": {"access": "fake-token", "refresh": "r", "expires": 99999999999999}}))
open(f"{tmp}/repo/notes.md", "w").write("NOTES\n")
os.makedirs(f"{tmp}/home/.agents/skills/deploy")
slug = "".join(c if c.isascii() and c.isalnum() else "-" for c in f"{tmp}/repo").strip("-")
os.makedirs(f"{tmp}/home/.hx/sessions/{slug}")
open(f"{tmp}/home/.hx/sessions/{slug}/1.jsonl", "w").write(json.dumps({"id": 0, "parent": None, "message": {"role": "user", "content": [{"type": "text", "text": "OLDPROMPT about parsers"}]}}) + "\n")
os.makedirs(f"{tmp}/repo/.agents/skills/lint")
open(f"{tmp}/repo/.agents/skills/lint/SKILL.md", "w").write("---\nname: lint\ndescription: project lint\n---\nBODY\n")
open(f"{tmp}/home/.agents/skills/deploy/SKILL.md", "w").write("---\nname: deploy\ndescription: ship it\n---\nBODY\n")
time.sleep(0.5)
pid, fd = pty.fork()
if pid == 0:
os.chdir(f"{tmp}/repo")
os.environ.update(HOME=f"{tmp}/home", HX_BASE_URL=f"http://127.0.0.1:{port}", TERM="xterm-256color", COLUMNS="100", LINES="30")
os.execv(f"{root}/target/debug/hx", ["hx"])
import fcntl, termios, struct
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0))
os.write(fd, b"\x1b[?62;c") # answer hx's keyboard-protocol probe like a terminal without kitty support
buf = b""
def pump(t):
global buf
end = time.time() + t
while time.time() < end:
r, _, _ = select.select([fd], [], [], 0.05)
if r:
try:
buf += os.read(fd, 65536)
except OSError:
return
def plain():
s = buf.decode(errors="replace")
s = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", " ", s)
return re.sub(r"\x1b[()][A-Z0-9]|\x1b[=>]", "", s)
def send(b, t=0.6):
os.write(fd, b); pump(t)
ok = True
def check(label, needle):
global ok
hit = needle in plain()
ok &= hit
print(f"{'PASS' if hit else 'FAIL'} {label}: {needle!r}")
pump(1.5)
check("startup footer", "Claude")
check("latest default model", "claude-sonnet-5-5")
send(b"l1"); send(b"\x1b[13;2u"); send(b"l2") # shift-enter as CSI-u (kitty protocol)
check("shift-enter is a newline, not a submit", "l1")
send(b"\x15\x7f\x15") # kill line 2, join, kill line 1
send(b"/skills\r")
check("skills from ~/.agents", "/deploy — ship it")
check("project .agents skills", "/lint — project lint")
send(b"@not"); send(b"\t")
check("tab completion", "es.md")
send(b"\x15") # ctrl-u
send(b"make hello.txt"); send(b"\r", 2)
check("permission prompt", "permission")
check("allow all edits option", "allow all edits this session")
send(b"y", 2)
check("second prompt for bash", "allow always: sed *")
send(b"y", 3)
check("tool call shown", "hello.txt")
check("tool outcome", "1 lines")
check("final answer", "Done: file says hi from hx.")
check("file written", "") if os.path.exists(f"{tmp}/repo/hello.txt") else (print("FAIL file"), None)
check("quota in footer", "5h 42%")
send(b"/usage\r")
check("usage report", "58% left, resets in 2h1")
check("1M window", "of 900k")
send(b"/model claude-opus-5-5\r")
check("model switch", "model → claude-opus-5-5 (Claude)")
send(b"/model gpt-5.6-sol\r")
check("gpt model needs codex login", "not logged in to Codex")
send(b"/model claude-sonnet-5-6-preview\r")
check("live catalog window", "2000k")
check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False))
buf = b""
# auto mode: per-prompt choice, one-turn @override, pinning turns it off
send(b"/model auto\r")
check("auto on", "model: auto")
send(b"fix the typo in notes.md\r", 3)
check("auto picks the cheap tier for a typo", "auto claude-haiku-4-5")
check("footer marks auto", "auto→")
send(b"@opus say hi\r", 4)
check("override forces one turn", "forced")
send(b"/model claude-sonnet-5-5\r")
send(b"fix the typo again\r", 3)
check("pinned model: no routing", "")
ok &= "auto claude-haiku-4-5 (Claude, think off): fast (score -2: typo)\n" not in plain().split("fix the typo again")[-1]
buf = b""
send(b"/provider ")
check("only logged-in providers offered", "claude")
ok &= "codex" not in plain(); print("PASS no codex without login" if "codex" not in plain() else "FAIL codex offered")
send(b"\x15")
send(b"/bogus\r")
check("unknown cmd", "unknown command /bogus")
send(b"\x10") # ctrl-p
send(b"OLDPROMPT")
check("picker lists past session", "session just now")
send(b"\r", 1)
# screen text can be split by ratatui's cursor-move diffing; the OSC window title is written whole
# and only carries the old prompt once the session is resumed
check("picker resumes session", "hx · OLDPROMPT about parsers")
send(b"/new\r")
check("new session", "new session")
send(b"/sessions\r")
check("sessions picker", "all projects")
send(b"make", 0.8)
check("sessions filter", "make hello.txt")
send(b"\r", 1)
check("resume from /sessions", "resumed ")
send(b"\x03", 1) # ctrl-c on empty -> quit
try:
_, st = os.waitpid(pid, 0)
print("exit status", st)
except ChildProcessError:
pass
check("exit summary", "session")
srv.kill()
sys.exit(0 if ok else 1)