- typed_manifest: harness.workerSetup {tool, order, guestAllowed, update,
enablesHarness, installerEnv, recipe}; in the capability fingerprint.
- worker/tools.sh keeps gh, ask-form and the helpers; the claude / pi recipes
are the plugins' (sourced from WORKER_TOOL_RECIPES), opencode / agy go
through WORKER_INSTALLER_TOOLS.
- sidecar tools_check / tools_install read the rows off the loaded harness
drivers (setup_check hook); backend workers/tools.py off the registry.
- A guest's computer: gh + guestAllowed harness tools (claude) — pi's plugin
never reaches it, so pi left its checklist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
264 lines
12 KiB
Python
264 lines
12 KiB
Python
"""tools_install: the Setup checklist's Install / Update — core's gh +
|
|
ask-form and the harness plugins' ``workerSetup`` rows (the real plugins,
|
|
conftest), per kind of machine; worker/tools.sh started detached with the
|
|
plugins' recipes handed over, its progress files read back for /health — and
|
|
gh's device-code sign-in."""
|
|
|
|
import json
|
|
import os
|
|
import stat
|
|
import subprocess
|
|
import time
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
|
|
import config
|
|
import link
|
|
import tools_check
|
|
import tools_install as ti
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def worker(tmp_path, monkeypatch):
|
|
"""A paired owner's worker with its state dir in tmp."""
|
|
monkeypatch.setenv("WORKER_STATE_DIR", str(tmp_path / "state"))
|
|
monkeypatch.setattr(config, "IS_WORKER", True)
|
|
monkeypatch.setattr(link, "config", lambda: {})
|
|
return tmp_path / "state" / "tools"
|
|
|
|
|
|
def _script(tmp_path, body: str):
|
|
"""A stand-in tools.sh: marks each tool queued with its own pid, like the
|
|
real one, then runs ``body``."""
|
|
p = tmp_path / "tools.sh"
|
|
p.write_text(
|
|
"#!/usr/bin/env bash\n"
|
|
'D="$WORKER_STATE_DIR/tools"; mkdir -p "$D"\n'
|
|
'A="$1"; shift\n'
|
|
'for t in "$@"; do printf \'{"tool":"%s","action":"%s","state":"queued","pid":%s}\' '
|
|
'"$t" "$A" "$$" > "$D/$t.json"; done\n' + body)
|
|
p.chmod(p.stat().st_mode | stat.S_IEXEC)
|
|
return p
|
|
|
|
|
|
def _refused(fn, *a, **kw) -> tuple[int, str]:
|
|
with pytest.raises(HTTPException) as e:
|
|
fn(*a, **kw)
|
|
return e.value.status_code, e.value.detail["kind"]
|
|
|
|
|
|
def test_the_host_sidecar_installs_nothing(monkeypatch):
|
|
monkeypatch.setattr(config, "IS_WORKER", False)
|
|
assert _refused(ti.start, ["gh"]) == (409, "host")
|
|
|
|
|
|
def test_only_listed_tools_and_actions(monkeypatch):
|
|
assert _refused(ti.start, ["rm -rf ~"]) == (400, "tool_unknown")
|
|
assert _refused(ti.start, []) == (400, "no_tool")
|
|
assert _refused(ti.start, ["gh"], "uninstall") == (400, "bad_action")
|
|
# claude and agy update themselves; update is gh and pi only
|
|
assert _refused(ti.start, ["gh", "claude"], "update") == (400, "not_updatable")
|
|
assert ti.updatable() == ("gh", "pi")
|
|
|
|
|
|
def test_the_rows_come_from_core_and_the_harness_plugins():
|
|
assert ti.allowed() == ("claude", "gh", "opencode", "agy", "pi", "ask-form")
|
|
rows = {r["tool"]: r for r in ti.harness_tools()}
|
|
assert set(rows) == {"claude", "opencode", "agy", "pi"}
|
|
assert rows["claude"]["recipe"].endswith("harness-claude/sidecar/setup.sh")
|
|
assert rows["pi"]["recipe"].endswith("harness-pi/sidecar/setup.sh")
|
|
assert (rows["opencode"]["installerEnv"], rows["agy"]["installerEnv"]) == \
|
|
("WORKER_OPENCODE", "WORKER_AGY")
|
|
assert rows["claude"]["guestAllowed"] and not rows["pi"]["guestAllowed"]
|
|
|
|
|
|
def test_a_harness_plugin_gone_offers_nothing(monkeypatch):
|
|
monkeypatch.setattr(ti, "harness_tools", lambda: [])
|
|
assert ti.allowed() == ("gh", "ask-form")
|
|
assert _refused(ti.start, ["claude"]) == (400, "tool_unknown")
|
|
|
|
|
|
def test_a_guests_computer_gets_claude_and_gh_only(monkeypatch):
|
|
"""Only the guestAllowed harnesses' tools (harness-claude: the only
|
|
harness plugin a guest's computer gets at all) — pi's plugin never
|
|
reaches it, so neither does its recipe."""
|
|
monkeypatch.setattr(link, "config", lambda: {"hub": "https://h", "workerId": "g1"})
|
|
assert ti.guest_computer() and ti.allowed() == ("claude", "gh")
|
|
for t in ("agy", "opencode", "ask-form", "pi"):
|
|
assert _refused(ti.start, [t]) == (400, "tool_unknown")
|
|
# the owner's own machine on the link is not a guest's
|
|
monkeypatch.setattr(link, "config", lambda: {"hub": "https://h", "owner": True})
|
|
assert "agy" in ti.allowed()
|
|
|
|
|
|
def test_starts_the_script_detached_and_reports_queued(tmp_path, monkeypatch, worker):
|
|
monkeypatch.setattr(ti, "SCRIPT", _script(tmp_path, "sleep 5\n"))
|
|
out = ti.start(["gh", "pi", "gh"])
|
|
assert out["started"] and out["tools"] == ["gh", "pi"] # deduplicated
|
|
jobs = ti.public()
|
|
assert jobs["gh"]["state"] == "queued" and jobs["pi"]["action"] == "install"
|
|
# one batch at a time
|
|
(worker / "lock").mkdir()
|
|
(worker / "lock" / "pid").write_text(str(out["pid"]))
|
|
assert _refused(ti.start, ["claude"]) == (409, "tools_busy")
|
|
os.kill(out["pid"], 15)
|
|
|
|
|
|
def test_the_plugins_recipes_are_handed_to_tools_sh(tmp_path, monkeypatch, worker):
|
|
monkeypatch.setattr(ti, "SCRIPT", _script(
|
|
tmp_path, 'printf "%s" "$WORKER_TOOL_RECIPES" > "$D/recipes"; '
|
|
'printf "%s" "$WORKER_INSTALLER_TOOLS" > "$D/installers"\n'))
|
|
out = ti.start(["pi", "gh"])
|
|
for _ in range(100):
|
|
if (worker / "installers").exists():
|
|
break
|
|
time.sleep(0.02)
|
|
lines = (worker / "recipes").read_text().splitlines()
|
|
assert [ln.split("\t")[0] for ln in lines] == ["pi"]
|
|
assert lines[0].split("\t")[1].endswith("harness-pi/sidecar/setup.sh")
|
|
assert (worker / "installers").read_text() == ""
|
|
assert out["tools"] == ["pi", "gh"]
|
|
|
|
|
|
def test_the_real_tools_sh_runs_a_plugin_recipe(tmp_path, worker):
|
|
"""worker/tools.sh sources a recipe (its helpers in scope) and calls its
|
|
tool_main; a name it was handed nothing for is refused."""
|
|
recipe = tmp_path / "setup.sh"
|
|
recipe.write_text('tool_main() { say "made it ($ACTION)"; }\n')
|
|
env = {**os.environ, "WORKER_STATE_DIR": str(worker.parent),
|
|
"WORKER_TOOL_RECIPES": f"zz\t{recipe}"}
|
|
p = subprocess.run(["bash", str(ti.SCRIPT), "install", "zz"], env=env,
|
|
capture_output=True, text=True, timeout=60)
|
|
assert p.returncode == 0, p.stderr
|
|
assert "==> made it (install)" in (worker / "zz.log").read_text()
|
|
assert json.loads((worker / "zz.json").read_text())["state"] == "done"
|
|
p = subprocess.run(["bash", str(ti.SCRIPT), "install", "claude"],
|
|
env={**env, "WORKER_TOOL_RECIPES": ""}, capture_output=True, text=True)
|
|
assert p.returncode == 2 and "unknown tool: claude" in p.stderr
|
|
|
|
|
|
def test_a_harness_waits_for_the_auto_update(tmp_path, monkeypatch):
|
|
import selfupdate
|
|
monkeypatch.setattr(ti, "SCRIPT", _script(tmp_path, ""))
|
|
monkeypatch.setattr(selfupdate, "running_pid", lambda: 4242)
|
|
assert _refused(ti.start, ["agy"]) == (409, "updating")
|
|
assert ti.start(["gh"])["started"] # a plain tool doesn't restart anything
|
|
|
|
|
|
def test_an_older_checkout_without_the_script(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(ti, "SCRIPT", tmp_path / "nope.sh")
|
|
assert _refused(ti.start, ["gh"]) == (409, "no_script")
|
|
|
|
|
|
def test_progress_files_read_back(worker):
|
|
worker.mkdir(parents=True)
|
|
dead = subprocess.Popen(["true"]); dead.wait()
|
|
(worker / "gh.json").write_text(json.dumps(
|
|
{"tool": "gh", "action": "install", "state": "failed", "pid": dead.pid,
|
|
"startedAt": "a", "finishedAt": "b", "error": "error: checksum mismatch"}))
|
|
(worker / "gh.log").write_text("\x1b[32m==> downloading\x1b[0m\r\nerror: checksum mismatch\n")
|
|
(worker / "pi.json").write_text(json.dumps(
|
|
{"tool": "pi", "action": "update", "state": "running", "pid": dead.pid}))
|
|
(worker / "evil.json").write_text(json.dumps({"tool": "evil", "state": "done"}))
|
|
jobs = ti.public()
|
|
assert set(jobs) == {"gh", "pi"}
|
|
assert jobs["gh"]["state"] == "failed"
|
|
assert jobs["gh"]["tail"] == ["==> downloading", "error: checksum mismatch"]
|
|
assert jobs["pi"]["state"] == "interrupted" # its batch is gone
|
|
assert ti.last_finished() > 0
|
|
|
|
|
|
def test_tools_check_rechecks_after_an_install(monkeypatch, worker):
|
|
monkeypatch.setattr(tools_check, "_state", {"at": time.time(), "tools": {}, "running": False})
|
|
started = []
|
|
monkeypatch.setattr(tools_check.threading, "Thread",
|
|
lambda **kw: type("T", (), {"start": lambda self: started.append(1)})())
|
|
tools_check.public()
|
|
assert not started # fresh
|
|
worker.mkdir(parents=True)
|
|
time.sleep(0.01)
|
|
(worker / "gh.json").write_text(json.dumps({"tool": "gh", "state": "done", "pid": 1}))
|
|
tools_check.public()
|
|
assert started # gh just landed: look again
|
|
|
|
|
|
def test_pi_check_knows_its_own_wrapper(monkeypatch, tmp_path):
|
|
w = tmp_path / "pi"
|
|
w.write_text("#!/bin/sh\n# pi — installed by ai-agent-worker (worker/tools.sh)\nexec node x \"$@\"\n")
|
|
monkeypatch.setattr(tools_check, "_which", lambda n: str(w))
|
|
monkeypatch.setattr(tools_check, "_run", lambda a, timeout=0: (0, "1.6.0\n"))
|
|
check_pi = tools_check.checks()["pi"] # harness-pi's setup_check
|
|
assert check_pi() == {"installed": True, "path": str(w), "signedIn": None,
|
|
"version": "1.6.0", "managed": True}
|
|
w.write_text("#!/usr/bin/env node\n")
|
|
assert check_pi()["managed"] is False
|
|
|
|
|
|
def test_guest_checklist_is_its_tools(monkeypatch):
|
|
monkeypatch.setattr(link, "config", lambda: {"hub": "https://h"})
|
|
assert list(tools_check.checks()) == ["claude", "gh"]
|
|
|
|
|
|
def test_harness_rows(monkeypatch, tmp_path):
|
|
import opencode_cli
|
|
b = tmp_path / "opencode"
|
|
b.write_text("#!/bin/sh\necho 2.0.32\n"); b.chmod(0o755)
|
|
monkeypatch.setattr(config, "OPENCODE_BIN", str(b))
|
|
monkeypatch.setattr(config, "OPENCODE_ACCOUNTS", {})
|
|
check_opencode = tools_check.checks()["opencode"] # harness-opencode's
|
|
row = check_opencode()
|
|
assert row["installed"] and row["harness"] is False and row["signedIn"] is False
|
|
monkeypatch.setattr(config, "OPENCODE_ACCOUNTS", {"chatgpt-work": None})
|
|
monkeypatch.setattr(opencode_cli, "status",
|
|
lambda a: {"loggedIn": True, "email": "g@x", "accessToken": "never"})
|
|
row = check_opencode()
|
|
assert row["harness"] and row["signedIn"] and row["account"] == "chatgpt-work"
|
|
assert row["login"] == "g@x" and "never" not in json.dumps(row)
|
|
|
|
|
|
# ── gh's device-code sign-in ─────────────────────────────────────────────────
|
|
def _fake_gh(tmp_path, then: str):
|
|
gh = tmp_path / "gh"
|
|
gh.write_text("#!/bin/sh\n"
|
|
"echo '! First copy your one-time code: AB12-CD34' >&2\n"
|
|
"echo 'Open this URL to continue in your web browser: https://github.com/login/device'\n"
|
|
+ then)
|
|
gh.chmod(0o755)
|
|
return str(gh)
|
|
|
|
|
|
def test_gh_sign_in_hands_out_the_code(monkeypatch, tmp_path):
|
|
monkeypatch.setattr(ti, "gh_bin", lambda: _fake_gh(tmp_path, "sleep 0.3; echo '✓ Logged in as octocat'\n"))
|
|
invalidated = []
|
|
monkeypatch.setattr(tools_check, "invalidate", lambda: invalidated.append(1))
|
|
out = ti.gh_login_start()
|
|
assert out["userCode"] == "AB12-CD34" and out["url"] == "https://github.com/login/device"
|
|
assert ti.gh_login_state()["state"] == "pending"
|
|
for _ in range(50):
|
|
st = ti.gh_login_state()
|
|
if st["state"] != "pending":
|
|
break
|
|
time.sleep(0.05)
|
|
assert st == {"state": "complete"} and invalidated
|
|
assert ti.gh_login_state() == {"state": "none"}
|
|
|
|
|
|
def test_gh_sign_in_failure_and_cancel(monkeypatch, tmp_path):
|
|
monkeypatch.setattr(ti, "gh_bin", lambda: _fake_gh(tmp_path, "echo 'error: the code expired' >&2; exit 1\n"))
|
|
ti.gh_login_start()
|
|
for _ in range(50):
|
|
st = ti.gh_login_state()
|
|
if st["state"] != "pending":
|
|
break
|
|
time.sleep(0.05)
|
|
assert st["state"] == "failed" and "expired" in st["message"]
|
|
monkeypatch.setattr(ti, "gh_bin", lambda: _fake_gh(tmp_path, "sleep 30\n"))
|
|
ti.gh_login_start()
|
|
assert ti.gh_login_cancel() is True and ti.gh_login_state() == {"state": "none"}
|
|
|
|
|
|
def test_gh_sign_in_needs_gh(monkeypatch):
|
|
monkeypatch.setattr(ti, "gh_bin", lambda: None)
|
|
assert _refused(ti.gh_login_start) == (409, "not_installed")
|