llm-host/tests/test_opencode_install.py
neil c8b70afdbf Split the internet upgrades: API-only tunnel, OIDC, authenticator codes, expose-dashboard
install-newt now sets up the tunnel for the API only; the dashboard stays on the LAN.
Dashboard sign-in is its own step: install-oidc (the OIDC flow, split out) or install-otp,
which pairs authenticator apps with a QR code in the terminal (stdlib QR encoder, TOTP per
RFC 6238) so a code also opens the dashboard, with replay and lockout rules.
expose-dashboard walks through publishing the dashboard, only after install-newt, and
warns while it's protected by the API key alone; with codes it offers to switch the key off
for the dashboard. Each install-* has a remove-*.

Also opencode-install.sh: a standalone script, fetched from the repo, that installs opencode
if needed, saves the API key to a 0600 file and adds the provider to opencode.json for new
and existing configs. /v1/models reports whether the model reasons, for that script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:56:54 -08:00

180 lines
8.2 KiB
Python

"""opencode-install.sh against a fake llm-host API, in a throwaway HOME: new and existing
opencode configs, the default-model choice, the cached-key cleanup, --remove, and the
official installer stood in for by a curl wrapper."""
import json
import os
import subprocess
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths
harness.guard(paths, ROOT)
check = harness.Checks()
SCRIPT = harness.REPO / "opencode-install.sh"
KEY = "sk-test-key-for-the-installer"
STATE = {"reasoning": True}
class API(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
if self.headers.get("Authorization") != f"Bearer {KEY}":
self.send_response(401); self.end_headers(); return
if self.path != "/v1/models":
self.send_response(404); self.end_headers(); return
body = json.dumps({"object": "list", "data": [{"id": "some-model", "max_model_len": 131072,
"reasoning": STATE["reasoning"]}]}).encode()
self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers()
self.wfile.write(body)
srv = ThreadingHTTPServer(("127.0.0.1", 0), API)
threading.Thread(target=srv.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{srv.server_address[1]}"
PROV = "llmhost-127" # first label of the host, as the CLI and dashboard name it
REAL_CURL = subprocess.run(["bash", "-c", "command -v curl"], capture_output=True, text=True).stdout.strip()
def sandbox(with_opencode=True):
home = Path(tempfile.mkdtemp(dir=ROOT, prefix="home-"))
bin_dir = home / "fakebin"
bin_dir.mkdir()
# Stand-in for the official installer: drop an `opencode` into ~/.opencode/bin.
(bin_dir / "curl").write_text(f"""#!/bin/bash
for a in "$@"; do
if [ "$a" = "https://opencode.ai/install" ]; then
cat <<'EOF'
mkdir -p "$HOME/.opencode/bin"
cp "$FAKE_OPENCODE" "$HOME/.opencode/bin/opencode"
echo "fake opencode installed"
EOF
exit 0
fi
done
exec {REAL_CURL} "$@"
""")
# A fake opencode whose `models` lists the providers' models from opencode.json.
fake_oc = home / "fake-opencode"
fake_oc.write_text(f"""#!/bin/bash
[ "$1" = models ] || exit 0
{sys.executable} -c 'import json,os
c=json.load(open(os.path.expanduser("~/.config/opencode/opencode.json")))
for p,b in (c.get("provider") or {{}}).items():
for m in b.get("models") or {{}}: print(p+"/"+m)'
""")
for f in (bin_dir / "curl", fake_oc):
f.chmod(0o755)
if with_opencode:
(bin_dir / "opencode").symlink_to(fake_oc)
return home, bin_dir, fake_oc
def run(home, bin_dir, fake_oc, *args, key=KEY):
env = {"HOME": str(home), "PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_OPENCODE": str(fake_oc)}
if key is not None:
env["LLMHOST_API_KEY"] = key
r = subprocess.run(["bash", str(SCRIPT), "--", *args], env=env, capture_output=True, text=True,
stdin=subprocess.DEVNULL, start_new_session=True, timeout=60) # no terminal
return r.returncode, r.stdout + r.stderr
def conf(home):
return json.loads((home / ".config/opencode/opencode.json").read_text())
print("\n1. a new opencode user")
home, b, oc = sandbox(with_opencode=False)
code, out = run(home, b, oc, "--url", URL)
check("succeeds", code == 0, out)
check("installs opencode through the official installer", "fake opencode installed" in out
and (home / ".opencode/bin/opencode").exists(), out)
c = conf(home)
p = c["provider"][PROV]
check("provider added", p["options"]["baseURL"] == URL + "/v1", p)
check("key referenced by file, not inlined", p["options"]["apiKey"] == "{file:" + str(home / f".config/opencode/{PROV}.key") + "}"
and KEY not in json.dumps(c), p["options"])
check("made the default model", c.get("model") == f"{PROV}/default", c.get("model"))
check("schema set", c.get("$schema") == "https://opencode.ai/config.json")
check("context from the server", p["models"]["default"]["limit"] == {"context": 131072, "output": 65536})
check("thinking model: effort menu off", p["models"]["default"].get("variants", {}).get("high") == {"disabled": True})
kf = home / f".config/opencode/{PROV}.key"
check("key file saved 0600", kf.read_text().strip() == KEY and (kf.stat().st_mode & 0o777) == 0o600)
check("key not echoed", KEY not in out)
check("opencode sees it", f"opencode sees {PROV}/default" in out, out)
check("no backup for a config that didn't exist", not (home / ".config/opencode/opencode.json.before-llmhost").exists())
print("\n2. an existing opencode user")
home, b, oc = sandbox()
cd = home / ".config/opencode"; cd.mkdir(parents=True)
mine = {"$schema": "https://opencode.ai/config.json", "theme": "dark", "model": "anthropic/some-model",
"provider": {"other": {"npm": "x", "models": {"m": {}}}}}
(cd / "opencode.json").write_text(json.dumps(mine))
auth = home / ".local/share/opencode/auth.json"; auth.parent.mkdir(parents=True)
auth.write_text(json.dumps({PROV: {"type": "api", "key": "stale"}, "anthropic": {"type": "oauth"}}))
STATE["reasoning"] = False
code, out = run(home, b, oc, "--url", URL + "/v1/")
c = conf(home)
check("succeeds", code == 0, out)
check("didn't reinstall opencode", "already installed" in out and not (home / ".opencode").exists(), out)
check("other settings kept", c["theme"] == "dark" and "other" in c["provider"])
check("their default model kept (no terminal to ask on)", c["model"] == "anthropic/some-model", c["model"])
check("says how to pick it", "/models" in out, out)
check("original backed up", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
check("trailing /v1/ normalised", c["provider"][PROV]["options"]["baseURL"] == URL + "/v1")
check("non-thinking model: no variants", "variants" not in c["provider"][PROV]["models"]["default"])
a = json.loads(auth.read_text())
check("stale cached key dropped, others kept", PROV not in a and "anthropic" in a, a)
code, out = run(home, b, oc, "--url", URL, "--default")
check("--default switches the model", conf(home)["model"] == f"{PROV}/default")
check("backup not overwritten on a re-run", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
code, out = run(home, b, oc, "--url", URL)
check("a re-run keeps it the default", conf(home)["model"] == f"{PROV}/default")
STATE["reasoning"] = True
print("\n3. --remove")
code, out = run(home, b, oc, "--url", URL, "--remove", key=None)
c = conf(home)
check("succeeds without a key", code == 0, out)
check("provider gone, others kept", PROV not in c["provider"] and "other" in c["provider"], c)
check("model that pointed at it dropped", "model" not in c, c)
check("key file gone", not (cd / f"{PROV}.key").exists())
print("\n4. refusals")
home, b, oc = sandbox()
code, out = run(home, b, oc, "--url", URL, key="sk-wrong")
check("wrong key -> error", code != 0 and "rejected" in out, out)
check("nothing written after a wrong key", not (home / ".config/opencode").exists())
code, out = run(home, b, oc, "--url", URL, key=None)
check("no key and no terminal -> error", code != 0 and "no API key" in out, out)
code, out = run(home, b, oc, "--url", "ftp://x")
check("bad URL -> error", code != 0 and "https://" in out, out)
code, out = run(home, b, oc, "--url", "http://127.0.0.1:9")
check("unreachable -> error", code != 0 and "couldn't reach" in out, out)
cd = home / ".config/opencode"; cd.mkdir(parents=True)
(cd / "opencode.json").write_text("{ not json")
code, out = run(home, b, oc, "--url", URL)
check("broken JSON left alone", code != 0 and (cd / "opencode.json").read_text() == "{ not json", out)
(cd / "opencode.json").unlink()
(cd / "opencode.jsonc").write_text('{ // mine\n "theme": "dark" }')
code, out = run(home, b, oc, "--url", URL)
check("a .jsonc is never rewritten; the block is printed", code == 0 and "by hand" in out
and (cd / "opencode.jsonc").read_text().startswith("{ // mine") and not (cd / "opencode.json").exists(), out)
print("\n5. --help works when run as `bash -c`")
r = subprocess.run(["bash", "-c", SCRIPT.read_text(), "--", "--help"], capture_output=True, text=True)
check("prints usage", r.returncode == 0 and "--url" in r.stdout, r.stdout + r.stderr)
srv.shutdown()
check.done(ROOT)