685 lines
33 KiB
Python
685 lines
33 KiB
Python
"""harness-opencode: the manifest (the hub's own ``validate_manifest``), the
|
|
art, and the sidecar driver loaded the way the sidecar loads it —
|
|
``harness_loader`` with ``SIDECAR_HARNESS_BUILTINS=0``, no legacy module —
|
|
then driven: spawn / resume / fork argv and env, accounts (device-code login,
|
|
status, probe, logout, the proxy's access token), the mirror thread, the
|
|
EVOX2 local providers (provider-evox2 plugin, else pi's models.json); plus
|
|
parity — the sidecar's own legacy opencode suites run against this plugin's
|
|
modules, and the mirror-replay fixtures written byte for byte alike.
|
|
|
|
Needs the ai-agent checkout (``~/projects/ai-agent`` or ``AI_AGENT_SIDECAR``)
|
|
and the sidecar's requirements::
|
|
|
|
cd ~/projects/ai-agent/sidecar && uv run --no-project \\
|
|
--with-requirements requirements.txt --with pytest --with httpx \\
|
|
python -m pytest <this plugin>/tests -q
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import types
|
|
|
|
import pytest
|
|
|
|
PLUGIN = pathlib.Path(__file__).resolve().parents[1]
|
|
SIDECAR = pathlib.Path(os.environ.get("AI_AGENT_SIDECAR")
|
|
or pathlib.Path.home() / "projects/ai-agent/sidecar").resolve()
|
|
BACKEND = SIDECAR.parent / "backend"
|
|
FIXTURES = BACKEND / "fixtures" / "typed_plugins"
|
|
if not (SIDECAR / "harness_loader.py").is_file():
|
|
pytest.skip(f"no ai-agent sidecar at {SIDECAR}", allow_module_level=True)
|
|
|
|
# The sidecar's config is read once, at import: everything it would write
|
|
# goes to a throw-away dir, and no built-in bridge exists.
|
|
_TMP = pathlib.Path(tempfile.mkdtemp(prefix="harness-tests-"))
|
|
for k, v in {"SIDECAR_HARNESS_BUILTINS": "0", "SIDECAR_USAGE_BUILTINS": "0",
|
|
"SIDECAR_LOG_DIR": str(_TMP / "logs"), "SIDECAR_OPENCODE_DIR": str(_TMP / "oc"),
|
|
"SIDECAR_AGY_DIR": str(_TMP / "agy"), "PI_MODELS_FILE": str(_TMP / "no-models.json"),
|
|
"SIDECAR_LIVE_PROVIDERS_DIR": str(_TMP / "no-providers"),
|
|
"WORKER_STATE_DIR": str(_TMP / "worker")}.items():
|
|
os.environ.setdefault(k, v)
|
|
os.environ["SIDECAR_HARNESS_BUILTINS"] = "0"
|
|
os.environ["SIDECAR_USAGE_BUILTINS"] = "0"
|
|
if str(SIDECAR) not in sys.path:
|
|
sys.path.insert(0, str(SIDECAR))
|
|
|
|
import harness_base # noqa: E402
|
|
import harness_loader # noqa: E402
|
|
from fastapi import HTTPException # noqa: E402
|
|
|
|
LEGACY = ("claude_cli", "claude_accounts", "opencode_cli", "opencode_mirror", "opencode_tools", "opencode_usage",
|
|
"agy_cli", "agy_mirror", "agy_tools", "agy_usage", "harness_builtin")
|
|
PKG = "sidecar_ext.harness.harness_opencode"
|
|
SID = "11111111-2222-4333-8444-555555555555"
|
|
NEW = "22222222-3333-4444-8555-666666666666"
|
|
CWD = "/home/u/projects/demo"
|
|
|
|
|
|
def raw() -> dict:
|
|
return json.loads((PLUGIN / "plugin.json").read_text())
|
|
|
|
|
|
# ── the manifest and the art ─────────────────────────────────────────────────
|
|
def _validate(plugin_dir: pathlib.Path) -> dict:
|
|
code = ("import json,pathlib,sys; sys.path.insert(0, sys.argv[1]);"
|
|
"from plugins.manifest import validate_manifest;"
|
|
"print(json.dumps(validate_manifest(pathlib.Path(sys.argv[2])), default=str))")
|
|
p = subprocess.run([sys.executable, "-c", code, str(BACKEND), str(plugin_dir)],
|
|
capture_output=True, text=True, timeout=60)
|
|
assert p.returncode == 0, p.stderr[-2000:]
|
|
return json.loads(p.stdout)
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def manifest() -> dict:
|
|
return _validate(PLUGIN)
|
|
|
|
|
|
def test_the_hub_validates_the_manifest(manifest):
|
|
assert manifest["id"] == "harness-opencode" and manifest["kind"] == "harness"
|
|
h = manifest["harness"]
|
|
assert h["harnessId"] == "opencode" and h["guestAllowed"] is False
|
|
assert (h["loginMode"], h["loginFlow"], h["runsOn"]) == ("worker", "device", "any")
|
|
assert h["caps"] == ["fork", "mcp"] and h["knob"] == "effort"
|
|
assert h["sidecar"]["dir"] == "sidecar" and h["sidecar"]["entry"] == "driver.py"
|
|
assert [s["vendor"] for s in h["supports"]] == ["openai", "evox2"]
|
|
|
|
|
|
def test_the_manifest_keeps_the_fixtures_tables():
|
|
"""Same harness tables as the hub's test fixture (what the hard-coded
|
|
tables were), bar what this plugin owns: guestAllowed, its art, its
|
|
version."""
|
|
fx = json.loads((FIXTURES / "harness-opencode" / "plugin.json").read_text())["harness"]
|
|
ours = dict(raw()["harness"])
|
|
for k in ("guestAllowed", "switchTo"):
|
|
ours.pop(k, None)
|
|
# `mcp` is this plugin's (its MCP adapter, sidecar/mcp.py — 2026-11-26)
|
|
assert [c for c in ours.pop("caps") if c != "mcp"] == fx.pop("caps")
|
|
# the display text (`hint`) is this published plugin's own wording
|
|
ours.pop("hint", None)
|
|
fx.pop("hint", None)
|
|
assert ours == fx
|
|
|
|
|
|
def test_icon_svg_is_a_24px_monochrome_glyph():
|
|
svg = (PLUGIN / "icon.svg").read_text()
|
|
assert 'viewBox="0 0 24 24"' in svg and 'width="24"' in svg and 'height="24"' in svg
|
|
import re
|
|
colours = set(re.findall(r'(?:stroke|fill)="([^"]+)"', svg)) - {"none"}
|
|
assert colours == {"currentColor"}
|
|
|
|
|
|
def test_illustration_webp():
|
|
b = (PLUGIN / "illustration.webp").read_bytes()
|
|
assert (b[:4], b[8:12]) == (b"RIFF", b"WEBP") and len(b) < 60 * 1024
|
|
if not shutil.which("ffprobe"):
|
|
pytest.skip("no ffprobe")
|
|
out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=width,height",
|
|
"-of", "csv=p=0", str(PLUGIN / "illustration.webp")],
|
|
capture_output=True, text=True, timeout=20).stdout.strip()
|
|
w, h = map(int, out.split(","))
|
|
assert w == 960 and abs(w / h - 16 / 9) < 0.05
|
|
|
|
|
|
def test_colour_is_the_sampled_slate_steel_blue():
|
|
c = raw()["color"]
|
|
assert c == "#3b4e63"
|
|
r, g, b = (int(c[i:i + 2], 16) for i in (1, 3, 5))
|
|
assert b > g > r # a blue, muted
|
|
|
|
|
|
def test_readme(manifest):
|
|
lines = [ln for ln in (PLUGIN / "README.md").read_text().splitlines() if ln.strip()]
|
|
assert 6 <= len(lines) <= 12, len(lines)
|
|
assert (manifest["iconSvg"], manifest["illustration"], manifest["readme"]) == \
|
|
("icon.svg", "illustration.webp", "README.md")
|
|
assert manifest["artVersion"]
|
|
|
|
|
|
# ── loading through harness_loader, builtins off ─────────────────────────────
|
|
def _live_dir(root: pathlib.Path, plugins=(PLUGIN,)) -> pathlib.Path:
|
|
idx = {"version": 1, "harnesses": {}}
|
|
for p in plugins:
|
|
mf = json.loads((p / "plugin.json").read_text())
|
|
shutil.copytree(p / "sidecar", root / mf["id"] / "sidecar",
|
|
ignore=shutil.ignore_patterns("__pycache__"))
|
|
shutil.copy2(p / "plugin.json", root / mf["id"] / "plugin.json")
|
|
idx["harnesses"][mf["harness"]["harnessId"]] = {
|
|
"pluginId": mf["id"], "dir": mf["id"], "entry": "driver.py",
|
|
"guestAllowed": bool(mf["harness"].get("guestAllowed"))}
|
|
(root / "index.json").write_text(json.dumps(idx))
|
|
return root
|
|
|
|
|
|
@pytest.fixture
|
|
def loaded(tmp_path, monkeypatch):
|
|
"""The plugin, loaded (not started) by the sidecar's own loader."""
|
|
monkeypatch.setenv("SIDECAR_LIVE_HARNESSES_DIR", str(_live_dir(tmp_path / "live")))
|
|
harness_loader.LOADER.reset()
|
|
out = harness_loader.LOADER.reload(start=False)
|
|
assert out["ok"], out
|
|
d = harness_loader.get("opencode")
|
|
mods = types.SimpleNamespace(cli=sys.modules[f"{PKG}.cli"],
|
|
mirror=sys.modules[f"{PKG}.mirror"],
|
|
usage=sys.modules[f"{PKG}.usage"])
|
|
ctx = harness_loader.context()
|
|
yield d, mods, ctx
|
|
harness_loader.LOADER.reset()
|
|
|
|
|
|
def test_it_loads_with_builtins_off_and_no_legacy_module(loaded):
|
|
d, mods, ctx = loaded
|
|
assert not harness_loader.LOADER.builtins_enabled()
|
|
assert harness_loader.ids() == ("opencode",)
|
|
e = harness_loader.LOADER.entry("opencode")
|
|
assert (e.source, e.plugin_id, e.meta["guestAllowed"]) == ("plugin", "harness-opencode", False)
|
|
assert harness_base.check_harness(d, "opencode") == "opencode"
|
|
assert type(d).__module__ == f"{PKG}.driver"
|
|
assert [m for m in LEGACY if m in sys.modules] == []
|
|
for m in ("cli", "mirror", "tools", "usage", "driver"):
|
|
src = (PLUGIN / "sidecar" / f"{m}.py").read_text()
|
|
for leg in LEGACY:
|
|
assert f"import {leg}" not in src and f"from {leg} " not in src, (m, leg)
|
|
|
|
|
|
def test_a_clean_process_never_imports_a_legacy_module(tmp_path):
|
|
"""Load, start, spawn, resume, fork, every account route — in a fresh
|
|
interpreter, then check sys.modules."""
|
|
live = _live_dir(tmp_path / "live")
|
|
code = f"""
|
|
import json, os, sys, pathlib
|
|
sys.path.insert(0, {str(SIDECAR)!r})
|
|
import harness_loader
|
|
out = harness_loader.LOADER.reload(start=True)
|
|
assert out["ok"], out
|
|
d = harness_loader.get("opencode"); ctx = harness_loader.context()
|
|
cli = sys.modules["{PKG}.cli"]
|
|
cli.OPENCODE_ACCOUNTS.clear(); cli.OPENCODE_ACCOUNTS["chatgpt-work"] = pathlib.Path({str(tmp_path / 'acct')!r})
|
|
cli.FORKS_PATH = pathlib.Path({str(tmp_path / 'ids.json')!r})
|
|
cli.credential = lambda a: {{"id": "c", "label": "x", "active": True, "updatedAt": 0,
|
|
"value": {{"access": "t", "expires": 9e15, "methodID": "chatgpt-headless"}}}}
|
|
cli.fork_session = lambda *a, **k: "ses_minted"
|
|
ctx.launch._launch = lambda args, sid, cwd, **kw: {{"argv": args}}
|
|
B = type("B", (), dict(account="chatgpt-work", model=None, effort=None, prompt="hi", scope=None,
|
|
force=False, cutUserOrd=0, cutText=None, cutKey=None))
|
|
d.spawn(B(), {SID!r}, "/tmp", ctx); d.resume(B(), {SID!r}, "/tmp", ctx)
|
|
d.fork(B(), {SID!r}, {NEW!r}, "/tmp", ctx)
|
|
d.accounts_list(); d.account_status("chatgpt-work"); d.health_meta()
|
|
d.account_login_status("chatgpt-work"); d.account_login_cancel("chatgpt-work")
|
|
harness_loader.LOADER.shutdown()
|
|
print(json.dumps(sorted(m for m in {list(LEGACY)!r} if m in sys.modules)))
|
|
"""
|
|
env = {**os.environ, "SIDECAR_LIVE_HARNESSES_DIR": str(live),
|
|
"SIDECAR_HARNESS_BUILTINS": "0", "SIDECAR_USAGE_BUILTINS": "0",
|
|
"SIDECAR_OPENCODE_ACCOUNTS": "chatgpt-work=" + str(tmp_path / "acct"),
|
|
"SIDECAR_OPENCODE_MIRROR": "0"}
|
|
p = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
|
|
timeout=120, env=env, cwd=str(tmp_path))
|
|
assert p.returncode == 0, p.stderr[-3000:]
|
|
assert json.loads(p.stdout.strip().splitlines()[-1]) == []
|
|
|
|
|
|
# ── runs ─────────────────────────────────────────────────────────────────────
|
|
class Body:
|
|
def __init__(self, **kw):
|
|
self.account = None
|
|
self.model = None
|
|
self.effort = None
|
|
self.prompt = " do it "
|
|
self.scope = None
|
|
self.force = False
|
|
self.cutUserOrd = None
|
|
self.cutText = None
|
|
self.cutKey = None
|
|
self.cutLine = 0
|
|
self.__dict__.update(kw)
|
|
|
|
|
|
CRED = {"id": "cred_1", "label": "me@x.com", "active": True, "updatedAt": 0,
|
|
"value": {"access": "a.b.c", "expires": (time.time() + 3600) * 1000,
|
|
"methodID": "chatgpt-headless", "metadata": {"accountID": "acc-1"}}}
|
|
|
|
|
|
@pytest.fixture
|
|
def run(loaded, tmp_path, monkeypatch):
|
|
"""The loaded driver with two accounts (one keyless), its launches
|
|
captured instead of started."""
|
|
d, mods, ctx = loaded
|
|
cli = mods.cli
|
|
monkeypatch.setattr(cli, "OPENCODE_ACCOUNTS", {"chatgpt-work": tmp_path / "work",
|
|
"opencode-lab": tmp_path / "lab"})
|
|
monkeypatch.setattr(cli, "OPENCODE_KEYLESS", {"opencode-lab"})
|
|
monkeypatch.setattr(cli, "FORKS_PATH", tmp_path / "ids.json")
|
|
monkeypatch.setattr(ctx.config, "OPENCODE_ACCOUNTS", cli.OPENCODE_ACCOUNTS)
|
|
monkeypatch.setattr(ctx.config, "OPENCODE_RUNNER_DIR", tmp_path / "runner")
|
|
monkeypatch.setattr(mods.usage, "OPENCODE_RUNNER_DIR", tmp_path / "runner")
|
|
creds = {"chatgpt-work": CRED}
|
|
monkeypatch.setattr(cli, "credential", lambda a: creds.get(a))
|
|
launches = []
|
|
|
|
def fake_launch(args, sid, cwd, **kw):
|
|
launches.append({"args": args, "sid": sid, "cwd": cwd, **kw})
|
|
return {"sessionId": sid, "pid": 4242}
|
|
|
|
monkeypatch.setattr(ctx.launch, "_launch", fake_launch)
|
|
monkeypatch.setattr(ctx.pids, "_live_record", lambda sid: None)
|
|
return types.SimpleNamespace(d=d, cli=cli, ctx=ctx, mods=mods, launches=launches,
|
|
creds=creds, tmp=tmp_path)
|
|
|
|
|
|
def test_spawn_launches_opencode_run_on_the_accounts_database(run):
|
|
out = run.d.spawn(Body(account="chatgpt-work", model="gpt-6.1-sol"), SID, CWD, run.ctx)
|
|
assert out == {"sessionId": SID, "pid": 4242}
|
|
(L,) = run.launches
|
|
assert L["args"][1:] == ["run", "--standalone", "--format", "json", "--auto",
|
|
"-s", f"ses_{SID}", "-m", "openai/gpt-6.1-sol#high"]
|
|
assert L["args"][0] == run.cli.OPENCODE_BIN
|
|
assert (L["harness"], L["account"], L["model"], L["append"]) == \
|
|
("opencode", "chatgpt-work", "gpt-6.1-sol", False)
|
|
assert L["stdin_text"] == "do it" and L["failure"] is run.cli.run_failure
|
|
env = L["env"]
|
|
assert env["PWD"] == CWD and env["CLAUDE_SESSION_ID"] == SID
|
|
assert env["OPENCODE_DB"] == str(run.tmp / "work" / "opencode.db")
|
|
assert "OPENAI_API_KEY" not in env and env["OPENCODE_DISABLE_AUTOUPDATE"] == "1"
|
|
cfg = json.loads(env["OPENCODE_CONFIG_CONTENT"])
|
|
assert {"action": "question", "resource": "*", "effect": "deny"} in cfg["permissions"]
|
|
|
|
|
|
def test_spawn_defaults_and_the_keyless_account(run):
|
|
run.d.spawn(Body(account="chatgpt-work"), SID, CWD, run.ctx)
|
|
assert run.launches[-1]["args"][-1] == f"openai/{run.ctx.config.OPENCODE_DEFAULT_MODEL}#high"
|
|
run.d.spawn(Body(account="opencode-lab"), SID, CWD, run.ctx)
|
|
assert run.launches[-1]["args"][-1] == run.ctx.config.OPENCODE_LOCAL_MODEL # no GPT effort
|
|
run.d.spawn(Body(account="opencode-lab", effort="think",
|
|
model="evox2/qwen3.6-35b-a3b"), SID, CWD, run.ctx)
|
|
assert run.launches[-1]["args"][-1] == "evox2/qwen3.6-35b-a3b#think"
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.spawn(Body(account="opencode-lab", model="gpt-6-sol"), SID, CWD, run.ctx)
|
|
assert e.value.status_code == 400 and "no ChatGPT login" in e.value.detail
|
|
|
|
|
|
def test_spawn_refusals(run):
|
|
for body, code in ((Body(account="nobody"), 400), (Body(account="chatgpt-work", scope={}), 400),
|
|
(Body(account="chatgpt-work", model="bad model!"), 400),
|
|
(Body(account="chatgpt-work", effort="ultra"), 400)):
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.spawn(body, SID, CWD, run.ctx)
|
|
assert e.value.status_code == code
|
|
run.creds.clear()
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.spawn(Body(account="chatgpt-work"), SID, CWD, run.ctx)
|
|
assert e.value.status_code == 409 and e.value.detail["kind"] == "auth"
|
|
assert run.launches == []
|
|
|
|
|
|
def test_resume_keeps_the_sessions_model_and_takes_over(run, monkeypatch):
|
|
monkeypatch.setattr(run.cli, "session_model", lambda a, s: ("gpt-5.5", "xhigh"))
|
|
run.d.resume(Body(account="chatgpt-work"), SID, CWD, run.ctx)
|
|
L = run.launches[-1]
|
|
assert L["args"][-1] == "openai/gpt-5.5#xhigh" and L["append"] is True
|
|
# another model picked: its own default effort, not the session's
|
|
run.d.resume(Body(account="chatgpt-work", model="gpt-6-sol"), SID, CWD, run.ctx)
|
|
assert run.launches[-1]["args"][-1] == "openai/gpt-6-sol#high"
|
|
# a live run: reused, nothing launched (a scope is refused before anything)
|
|
n = len(run.launches)
|
|
monkeypatch.setattr(run.ctx.pids, "_live_record", lambda sid: {"pid": 99})
|
|
out = run.d.resume(Body(account="chatgpt-work"), SID, CWD, run.ctx)
|
|
assert out["reused"] is True and out["pid"] == 99 and len(run.launches) == n
|
|
stopped = []
|
|
monkeypatch.setattr(run.ctx.launch, "_stop_run", lambda sid, rec: stopped.append(sid))
|
|
run.d.resume(Body(account="chatgpt-work", force=True), SID, CWD, run.ctx)
|
|
assert stopped == [SID] and len(run.launches) == n + 1
|
|
with pytest.raises(HTTPException):
|
|
run.d.resume(Body(account="chatgpt-work", scope={"x": 1}, force=True), SID, CWD, run.ctx)
|
|
assert stopped == [SID]
|
|
|
|
|
|
def test_fork_branches_natively_and_records_the_minted_id(run, monkeypatch):
|
|
seen = {}
|
|
|
|
def fork_session(account, env, src_sid, src_ses, ord_, text, cwd, cut_key=None):
|
|
seen.update(account=account, src_sid=src_sid, src_ses=src_ses, ord=ord_, text=text,
|
|
cwd=cwd, key=cut_key)
|
|
return "ses_mintedbyopencode00000"
|
|
|
|
monkeypatch.setattr(run.cli, "fork_session", fork_session)
|
|
monkeypatch.setattr(run.cli, "session_model",
|
|
lambda a, s: ("gpt-5.5", "low") if s == "ses_mintedbyopencode00000"
|
|
else (None, None))
|
|
run.d.fork(Body(account="chatgpt-work", cutUserOrd=2, cutText="hello",
|
|
cutKey="user:msg_1"), SID, NEW, CWD, run.ctx)
|
|
assert seen == {"account": "chatgpt-work", "src_sid": SID, "src_ses": f"ses_{SID}",
|
|
"ord": 2, "text": "hello", "cwd": CWD, "key": "user:msg_1"}
|
|
assert json.loads((run.tmp / "ids.json").read_text()) == {NEW: "ses_mintedbyopencode00000"}
|
|
L = run.launches[-1]
|
|
assert L["sid"] == NEW and L["args"][7] == "ses_mintedbyopencode00000"
|
|
assert L["args"][-1] == "openai/gpt-5.5#low" # the fork keeps its source's model
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.fork(Body(account="chatgpt-work", scope={}), SID, NEW, CWD, run.ctx)
|
|
assert e.value.status_code == 400
|
|
|
|
|
|
def test_valid_model_and_health(run):
|
|
assert run.d.valid_model(" gpt-5.5 ") == "gpt-5.5" and run.d.valid_model("") is None
|
|
with pytest.raises(HTTPException):
|
|
run.d.valid_model("rm -rf /")
|
|
assert run.d.stop_extra(1, SID) is None
|
|
assert run.d.health_meta()["opencodeAccounts"] == ["chatgpt-work", "opencode-lab"]
|
|
|
|
|
|
# ── accounts ─────────────────────────────────────────────────────────────────
|
|
def _jwt(claims: dict) -> str:
|
|
import base64
|
|
p = base64.urlsafe_b64encode(json.dumps(claims).encode()).decode().rstrip("=")
|
|
return f"h.{p}.s"
|
|
|
|
|
|
def test_accounts_route_dispatch_and_status(run):
|
|
run.creds["chatgpt-work"] = {**CRED, "value": {**CRED["value"], "access": _jwt({
|
|
"https://api.openai.com/auth": {"chatgpt_plan_type": "pro", "organization_name": "Org"},
|
|
"https://api.openai.com/profile": {"email": "me@x.com"}})}}
|
|
assert harness_loader.account_drivers("chatgpt-work") == [run.d]
|
|
assert harness_loader.account_drivers("someone-else") == []
|
|
st = harness_loader.dispatch_account("chatgpt-work", "account_status")
|
|
assert st["loggedIn"] and st["email"] == "me@x.com" and st["subscriptionType"] == "pro"
|
|
assert st["harness"] == "opencode" and "usage" in st
|
|
lab = run.d.account_status("opencode-lab")
|
|
assert lab["keyless"] and lab["loggedIn"] and lab["authMethod"] == "none"
|
|
assert [a["id"] for a in run.d.accounts_list()] == ["chatgpt-work", "opencode-lab"]
|
|
assert run.d.account_probe("opencode-lab")["ok"] is True
|
|
# a code to paste is not this flow's: the route answers 404 as before
|
|
assert harness_loader.dispatch_account("chatgpt-work", "account_login_code", "x") \
|
|
is harness_base.NOT_HANDLED
|
|
|
|
|
|
def test_probe_reads_usage_and_reports_a_dead_login(run, monkeypatch):
|
|
import urllib.error
|
|
snap = {"plan_type": "pro", "limit_reached": False,
|
|
"rate_limits": {"seven_day": {"used_percentage": 12.0, "resets_at": 1,
|
|
"window_seconds": 604800}}}
|
|
|
|
real_fetch = run.mods.usage.fetch
|
|
|
|
def ok(account):
|
|
run.mods.usage._last[account] = {"at": time.time(), "ok": True}
|
|
return snap
|
|
|
|
monkeypatch.setattr(run.mods.usage, "fetch", ok)
|
|
out = run.d.account_probe("chatgpt-work")
|
|
assert out["ok"] is True and out["usage"]["ok"] is True
|
|
written = json.loads((run.tmp / "runner" / "usage" / "chatgpt-work" /
|
|
"rate-limits.json").read_text())
|
|
assert written["source"] == "chatgpt" and written["rate_limits"] == snap["rate_limits"]
|
|
|
|
# the real read, with ChatGPT refusing the token
|
|
def dead(req, timeout=0):
|
|
raise urllib.error.HTTPError("u", 401, "no", {}, None)
|
|
|
|
monkeypatch.setattr(run.mods.usage, "fetch", real_fetch)
|
|
monkeypatch.setattr(run.mods.usage.urllib.request, "urlopen", dead)
|
|
out = run.d.account_probe("chatgpt-work")
|
|
assert (out["ok"], out["kind"], out["message"]) == (False, "auth", "HTTP 401")
|
|
|
|
|
|
def _fake_opencode(tmp: pathlib.Path, *, code_ok: bool = True) -> pathlib.Path:
|
|
b = tmp / "opencode"
|
|
b.write_text("#!/bin/sh\n"
|
|
'if [ "$1 $2" = "auth login" ]; then\n'
|
|
' echo "Open https://auth.openai.com/codex/device"\n'
|
|
+ (' echo "Enter code: ABCD-12345"\n' if code_ok else "")
|
|
+ ' sleep 1; exit 0\nfi\n'
|
|
'if [ "$1 $2" = "auth logout" ]; then echo "$@" > "$OUT_FILE"; exit 0; fi\n'
|
|
'if [ "$1 $2" = "auth list" ]; then echo refreshed >> "$OUT_FILE"; exit 0; fi\n'
|
|
"exit 3\n")
|
|
b.chmod(0o755)
|
|
return b
|
|
|
|
|
|
def test_device_code_login_flow(run, monkeypatch):
|
|
monkeypatch.setattr(run.cli, "OPENCODE_BIN", str(_fake_opencode(run.tmp)))
|
|
monkeypatch.setenv("OUT_FILE", str(run.tmp / "out"))
|
|
start = harness_loader.dispatch_account("chatgpt-work", "account_login_start", None)
|
|
assert (start["url"], start["userCode"], start["flow"]) == \
|
|
("https://auth.openai.com/codex/device", "ABCD-12345", "device")
|
|
assert run.d.account_status("chatgpt-work")["pendingLogin"]["userCode"] == "ABCD-12345"
|
|
assert run.d.account_login_status("chatgpt-work")["state"] == "pending"
|
|
deadline = time.time() + 10
|
|
while time.time() < deadline:
|
|
st = run.d.account_login_status("chatgpt-work")
|
|
if st["state"] != "pending":
|
|
break
|
|
time.sleep(0.2)
|
|
assert st["state"] == "complete" and st["loggedIn"] is True
|
|
assert run.d.account_login_status("chatgpt-work") == {"state": "none"}
|
|
# a restart, then a cancel
|
|
run.d.account_login_start("chatgpt-work", None)
|
|
assert run.d.account_login_cancel("chatgpt-work") == {"cancelled": True}
|
|
assert run.d.account_login_cancel("chatgpt-work") == {"cancelled": False}
|
|
|
|
|
|
def test_a_login_without_a_code_is_a_502(run, monkeypatch):
|
|
monkeypatch.setattr(run.cli, "OPENCODE_BIN", str(_fake_opencode(run.tmp, code_ok=False)))
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.account_login_start("chatgpt-work", None)
|
|
assert e.value.status_code == 502 and e.value.detail["kind"] == "login"
|
|
|
|
|
|
def test_logout(run, monkeypatch):
|
|
monkeypatch.setattr(run.cli, "OPENCODE_BIN", str(_fake_opencode(run.tmp)))
|
|
monkeypatch.setenv("OUT_FILE", str(run.tmp / "out"))
|
|
out = run.d.account_logout("chatgpt-work")
|
|
assert out["message"] == "logged out"
|
|
assert (run.tmp / "out").read_text().split()[:4] == ["auth", "logout", "openai", "cred_1"]
|
|
run.creds.clear()
|
|
assert run.d.account_logout("chatgpt-work")["message"] == "not logged in"
|
|
|
|
|
|
def test_access_token_for_the_hubs_proxy(run, monkeypatch):
|
|
with pytest.raises(HTTPException) as e: # a worker's logins aren't the hub's
|
|
monkeypatch.setattr(run.ctx.config, "IS_WORKER", True)
|
|
run.d.access_token("chatgpt-work")
|
|
assert e.value.status_code == 409
|
|
monkeypatch.setattr(run.ctx.config, "IS_WORKER", False)
|
|
tok = run.d.access_token(" ChatGPT-Work ")
|
|
assert tok == {"accessToken": "a.b.c", "expiresAt": CRED["value"]["expires"],
|
|
"accountId": "acc-1"}
|
|
refreshed = []
|
|
monkeypatch.setattr(run.cli, "refresh_token", lambda a, env: refreshed.append(a) or True)
|
|
run.d.access_token("chatgpt-work", refresh=True)
|
|
run.creds["chatgpt-work"] = {**CRED, "value": {**CRED["value"], "expires": 1000}}
|
|
run.d.access_token("chatgpt-work") # stale: opencode refreshes it
|
|
assert refreshed == ["chatgpt-work", "chatgpt-work"]
|
|
for acct in ("opencode-lab", "nobody"):
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.access_token(acct)
|
|
assert e.value.status_code == 404
|
|
run.creds.clear()
|
|
with pytest.raises(HTTPException) as e:
|
|
run.d.access_token("chatgpt-work")
|
|
assert e.value.status_code == 409
|
|
|
|
|
|
# ── the mirror thread ────────────────────────────────────────────────────────
|
|
def _fixture_db(path: pathlib.Path):
|
|
ab = SIDECAR.parent / "scripts" / "ab"
|
|
sys.path.insert(0, str(ab))
|
|
try:
|
|
import _mirror_worker as mw
|
|
from mirror_fixtures import opencode as fx
|
|
finally:
|
|
sys.path.remove(str(ab))
|
|
w = mw.OcWriter(path)
|
|
for op in fx.OPS:
|
|
if op["op"] != "forks":
|
|
w.apply(op)
|
|
w.close()
|
|
return fx
|
|
|
|
|
|
def test_startup_mirrors_each_account_kick_and_shutdown(run, monkeypatch):
|
|
(run.tmp / "work").mkdir()
|
|
_fixture_db(run.tmp / "work" / "opencode.db")
|
|
monkeypatch.setattr(run.ctx.config, "OPENCODE_ACCOUNTS", {"chatgpt-work": run.tmp / "work"})
|
|
monkeypatch.setattr(run.ctx.config, "OPENCODE_MIRROR", True)
|
|
monkeypatch.setattr(run.mods.mirror, "POLL_S", 0.2)
|
|
run.d.startup(run.ctx)
|
|
try:
|
|
assert run.d.mirror is not None
|
|
assert [m.account for m in run.d.mirror.mirrors] == ["chatgpt-work"]
|
|
run.d.kick()
|
|
out = run.tmp / "runner" / "transcripts" / "chatgpt-work"
|
|
deadline = time.time() + 15
|
|
while time.time() < deadline and not list(out.rglob("*.jsonl")):
|
|
time.sleep(0.1)
|
|
files = list(out.rglob("*.jsonl"))
|
|
assert files
|
|
first = json.loads(files[0].read_text().splitlines()[0])
|
|
assert first.get("v") == 1 or first.get("t") == "session"
|
|
# a proxied account joins the same thread
|
|
run.d.mirror_accounts(["proxied-acct"])
|
|
assert {m.account for m in run.d.mirror.mirrors} == {"chatgpt-work", "proxied-acct"}
|
|
finally:
|
|
t = run.d.mirror
|
|
run.d.shutdown()
|
|
assert run.d.mirror is None and t._stop.is_set()
|
|
|
|
|
|
def test_no_mirror_when_switched_off(run, monkeypatch):
|
|
monkeypatch.setattr(run.ctx.config, "OPENCODE_MIRROR", False)
|
|
run.d.startup(run.ctx)
|
|
assert run.d.mirror is None
|
|
run.d.shutdown()
|
|
|
|
|
|
@pytest.mark.skipif(not (SIDECAR / "opencode_mirror.py").is_file(),
|
|
reason="the sidecar has no legacy mirror any more (strict plugin-only): "
|
|
"parity with the old one is scripts/ab/mirror-replay.py --base")
|
|
def test_the_mirror_writes_what_the_legacy_one_wrote():
|
|
"""``scripts/ab/mirror_fixtures`` through the legacy mirror and this one,
|
|
every replay mode: byte for byte the same v1 JSONL."""
|
|
p = subprocess.run([sys.executable, str(PLUGIN / "tests" / "replay_parity.py"), str(PLUGIN),
|
|
"--sidecar", str(SIDECAR)], capture_output=True, text=True, timeout=300)
|
|
assert p.returncode == 0, p.stderr[-3000:]
|
|
res = json.loads(p.stdout)
|
|
assert set(res) == {"oneshot", "stepwise", "chunked", "restart"}
|
|
for mode, r in res.items():
|
|
assert r["same"], mode
|
|
assert r["files"] > 0 and r["lines"] > 0
|
|
|
|
|
|
def test_the_legacy_opencode_suites_pass_on_this_plugin():
|
|
"""The sidecar's own opencode tests, its modules aliased to this
|
|
plugin's (``legacy_alias``): the same behaviour, test for test."""
|
|
# (test_local_room / test_gen_progress are provider-evox2's: its own tests run them)
|
|
suites = [s for s in ("test_opencode.py", "test_opencode_proxy.py") if (SIDECAR / s).is_file()]
|
|
env = {**os.environ, "LEGACY_ALIAS_PLUGIN": str(PLUGIN),
|
|
"PYTHONPATH": str(PLUGIN / "tests")}
|
|
args = [sys.executable, "-m", "pytest", "-q", "-p", "legacy_alias", "-p", "no:cacheprovider",
|
|
*suites]
|
|
try:
|
|
import httpx # noqa: F401 — test_opencode_proxy's TestClient
|
|
except ImportError:
|
|
args.remove("test_opencode_proxy.py") if "test_opencode_proxy.py" in args else None
|
|
p = subprocess.run(args, cwd=str(SIDECAR), env=env, capture_output=True, text=True,
|
|
timeout=600)
|
|
assert p.returncode == 0, p.stdout[-4000:] + p.stderr[-2000:]
|
|
assert " passed" in p.stdout and "failed" not in p.stdout
|
|
|
|
|
|
# ── the local GPU machine's local providers ──────────────────────────────────────────────
|
|
PI_MODELS = {"providers": {
|
|
"evox2": {"baseUrl": "http://fedora:8090/v1", "apiKey": "local-key", "models": [
|
|
{"id": "qwen3.6-35b-a3b", "name": "Qwen pi", "contextWindow": 65536, "maxTokens": 8192,
|
|
"reasoning": True, "compat": {"chatTemplateKwargs": {"enable_thinking": False}}}]},
|
|
"evox2-inkling": {"baseUrl": "http://fedora:8091/v1", "models": [
|
|
{"id": "inkling-2-mini", "reasoning": True, "defaultThinking": "low",
|
|
"compat": {"chatTemplateKwargs": {"reasoning_effort": "none"}}}]},
|
|
"openrouter": {"baseUrl": "https://openrouter.ai/api/v1", "models": [{"id": "x"}]}}}
|
|
|
|
|
|
def _evox2_plugin(root: pathlib.Path) -> pathlib.Path:
|
|
d = root / "provider-evox2"
|
|
(d / "sidecar").mkdir(parents=True)
|
|
shutil.copy2(FIXTURES / "provider-evox2" / "plugin.json", d / "plugin.json")
|
|
return d
|
|
|
|
|
|
def test_local_providers_fall_back_to_pis_models_json(run, monkeypatch):
|
|
monkeypatch.setattr(run.cli, "PI_MODELS_FILE", run.tmp / "models.json")
|
|
monkeypatch.setenv("SIDECAR_LIVE_PROVIDERS_DIR", str(run.tmp / "none"))
|
|
run.cli.set_context_providers({})
|
|
assert run.cli.local_providers() == {}
|
|
(run.tmp / "models.json").write_text(json.dumps(PI_MODELS))
|
|
prov = run.cli.local_providers()
|
|
assert set(prov) == {"evox2", "evox2-inkling"}
|
|
assert prov["evox2"]["options"] == {"baseURL": "http://fedora:8090/v1", "apiKey": "local-key"}
|
|
q = prov["evox2"]["models"]["qwen3.6-35b-a3b"]
|
|
assert q["limit"] == {"context": 65536, "output": 8192}
|
|
assert set(q["variants"]) == {"none", "think"}
|
|
ink = prov["evox2-inkling"]["models"]["inkling-2-mini"]
|
|
assert ink["options"] == {"chat_template_kwargs": {"reasoning_effort": "low"}}
|
|
|
|
|
|
def test_local_providers_come_from_the_evox2_plugin(run, monkeypatch):
|
|
"""provider-evox2 in the live providers dir: its servers and models,
|
|
with pi's key / chat-template switches where models.json has them."""
|
|
monkeypatch.setattr(run.cli, "PI_MODELS_FILE", run.tmp / "models.json")
|
|
(run.tmp / "models.json").write_text(json.dumps(PI_MODELS))
|
|
live = run.tmp / "live-providers"
|
|
_evox2_plugin(live)
|
|
monkeypatch.setenv("SIDECAR_LIVE_PROVIDERS_DIR", str(live))
|
|
run.cli.set_context_providers({})
|
|
prov = run.cli.local_providers()
|
|
assert set(prov) == {"evox2", "evox2-inkling"}
|
|
assert prov["evox2"]["options"] == {"baseURL": "http://fedora:8090/v1", "apiKey": "local-key"}
|
|
models = prov["evox2"]["models"]
|
|
assert set(models) == {"ggml-org/qwen3.8-27b", "qwen3.8-flash-next-coder", "qwen3.6-35b-a3b"}
|
|
assert models["ggml-org/qwen3.8-27b"]["name"] == "Qwen 3.8 27B (EVOX2, local)"
|
|
assert set(models["ggml-org/qwen3.8-27b"]["variants"]) == {"none", "think"}
|
|
assert models["qwen3.6-35b-a3b"]["limit"] == {"context": 131072, "output": 8192}
|
|
ink = prov["evox2-inkling"]["models"]["inkling-2-mini"]
|
|
assert ink["options"] == {"chat_template_kwargs": {"reasoning_effort": "low"}} # pi's
|
|
# the run config carries them
|
|
cfg = json.loads(run.cli.run_env("opencode-lab", {}, CWD, "evox2/qwen3.6-35b-a3b")
|
|
["OPENCODE_CONFIG_CONTENT"])
|
|
assert set(cfg["provider"]) == {"evox2", "evox2-inkling"}
|
|
# a machine with an agent limit: the subagent tool is denied too
|
|
assert [p["action"] for p in cfg["permissions"]] == ["question"]
|
|
cfg = json.loads(run.cli.run_env("opencode-lab", {}, CWD, "evox2/qwen3.6-35b-a3b",
|
|
no_subagents=True)["OPENCODE_CONFIG_CONTENT"])
|
|
assert [(p["action"], p["effect"]) for p in cfg["permissions"]] == [
|
|
("question", "deny"), ("task", "deny"), ("subagent", "deny")]
|
|
# no models.json at all: the manifest alone (efforts → reasoning levels)
|
|
(run.tmp / "models.json").unlink()
|
|
prov = run.cli.local_providers()
|
|
assert prov["evox2"]["options"] == {"baseURL": "http://fedora:8090/v1"}
|
|
ink = prov["evox2-inkling"]["models"]["inkling-2-mini"]
|
|
assert ink["options"] == {"chat_template_kwargs": {"reasoning_effort": "none"}}
|
|
assert set(ink["variants"]) == {"none", "low", "medium", "high"}
|
|
|
|
|
|
def test_provider_configs_win_over_the_dir_scan(run, monkeypatch):
|
|
"""``usage_loader.provider_configs()`` (or the SidecarContext's copy)
|
|
naming provider-evox2's dir is read first."""
|
|
import usage_loader
|
|
monkeypatch.setattr(run.cli, "PI_MODELS_FILE", run.tmp / "none.json")
|
|
monkeypatch.setenv("SIDECAR_LIVE_PROVIDERS_DIR", str(run.tmp / "empty"))
|
|
d = _evox2_plugin(run.tmp / "elsewhere")
|
|
monkeypatch.setattr(usage_loader, "provider_configs",
|
|
lambda: {"evox2": {"pluginId": "provider-evox2",
|
|
"dir": str(d / "sidecar"), "config": {}}})
|
|
assert set(run.cli.local_providers()) == {"evox2", "evox2-inkling"}
|
|
monkeypatch.setattr(usage_loader, "provider_configs", lambda: {})
|
|
run.cli.set_context_providers({"evox2": {"pluginId": "provider-evox2", "dir": str(d)}})
|
|
assert set(run.cli.local_providers()) == {"evox2", "evox2-inkling"}
|
|
run.cli.set_context_providers({})
|
|
assert run.cli.local_providers() == {}
|