727 lines
35 KiB
Python
727 lines
35 KiB
Python
"""The live harness drivers and usage readers (harness_loader.py,
|
|
usage_loader.py, routes_harnesses.py) and the /sync half that writes them
|
|
(labsync.apply_plugins). Strict plugin-only: no built-in driver — the module's
|
|
own registry is the real harness-* / provider-* plugins (conftest.py), and a
|
|
cold host falls back to the seed plugins."""
|
|
|
|
import base64
|
|
import json
|
|
import pathlib
|
|
import sys
|
|
import types
|
|
|
|
import pytest
|
|
from fastapi import FastAPI, HTTPException
|
|
from fastapi.testclient import TestClient
|
|
|
|
import harness_base
|
|
import harness_loader
|
|
import labsync
|
|
import routes_accounts
|
|
import routes_harnesses
|
|
import routes_runs
|
|
import usage_loader
|
|
import validate
|
|
|
|
SID = "11111111-2222-4333-8444-555555555555"
|
|
|
|
DRIVER = '''
|
|
from . import helper
|
|
from harness_base import SidecarHarness
|
|
|
|
EVENTS = []
|
|
|
|
class Harness(SidecarHarness):
|
|
harness_id = "{hid}"
|
|
def startup(self, ctx):
|
|
EVENTS.append(("start", helper.TAG))
|
|
{startup_extra}
|
|
def shutdown(self):
|
|
EVENTS.append(("stop", helper.TAG))
|
|
def valid_model(self, model):
|
|
return model
|
|
def spawn(self, body, sid, cwd, ctx):
|
|
return {{"harness": "{hid}", "sid": sid, "tag": helper.TAG, "prompt": body.prompt}}
|
|
def resume(self, body, sid, cwd, ctx):
|
|
return {{"resumed": sid}}
|
|
def fork(self, body, sid, new_sid, cwd, ctx):
|
|
return {{"forked": new_sid}}
|
|
def owns_account(self, account):
|
|
return account == "{hid}-acct"
|
|
def accounts_list(self):
|
|
return [{{"id": "{hid}-acct", "loggedIn": True}}]
|
|
def account_status(self, account, fresh=False):
|
|
return {{"id": account, "via": "{hid}"}}
|
|
'''
|
|
|
|
READER = '''
|
|
from harness_base import SidecarUsageReader
|
|
|
|
class Reader(SidecarUsageReader):
|
|
vendor_id = "{vid}"
|
|
aliases = ("{vid}-alias",)
|
|
def snapshots(self):
|
|
return {{"acct": {{"five_hour": {{"used_percentage": 42}}}}}}
|
|
'''
|
|
|
|
|
|
def write_harness(root: pathlib.Path, pid: str, hid: str, *, tag: str = "v1",
|
|
startup_extra: str = "pass", driver: str | None = None,
|
|
guest: bool = False, index: bool = True) -> None:
|
|
d = root / pid
|
|
(d / "sidecar").mkdir(parents=True, exist_ok=True)
|
|
(d / "plugin.json").write_text(json.dumps({
|
|
"id": pid, "kind": "harness", "version": "1.0.0",
|
|
"harness": {"harnessId": hid, "order": 50, "guestAllowed": guest,
|
|
"sidecar": {"dir": "sidecar", "entry": "driver.py"}}}))
|
|
(d / "sidecar" / "helper.py").write_text(f"TAG = {tag!r}\n")
|
|
(d / "sidecar" / "driver.py").write_text(
|
|
driver if driver is not None else DRIVER.format(hid=hid, startup_extra=startup_extra))
|
|
if index:
|
|
idx_p = root / "index.json"
|
|
idx = json.loads(idx_p.read_text()) if idx_p.exists() else {"version": 1, "harnesses": {}}
|
|
idx["harnesses"][hid] = {"pluginId": pid, "dir": pid, "entry": "driver.py",
|
|
"guestAllowed": guest}
|
|
idx_p.write_text(json.dumps(idx))
|
|
|
|
|
|
def write_reader(root: pathlib.Path, pid: str, vid: str) -> None:
|
|
d = root / pid
|
|
(d / "sidecar").mkdir(parents=True, exist_ok=True)
|
|
(d / "plugin.json").write_text(json.dumps({
|
|
"id": pid, "kind": "provider",
|
|
"provider": {"vendorId": vid, "usageReader": {"dir": "sidecar", "entry": "usage.py"}}}))
|
|
(d / "sidecar" / "usage.py").write_text(READER.format(vid=vid))
|
|
idx_p = root / "index.json"
|
|
idx = json.loads(idx_p.read_text()) if idx_p.exists() else {"version": 1, "providers": {}}
|
|
idx["providers"][vid] = {"pluginId": pid, "dir": pid, "entry": "usage.py",
|
|
"config": {"region": "eu"}}
|
|
idx_p.write_text(json.dumps(idx))
|
|
|
|
|
|
@pytest.fixture
|
|
def loader(tmp_path, monkeypatch):
|
|
root = tmp_path / "live-harnesses"
|
|
root.mkdir()
|
|
monkeypatch.setenv("TEST_LIVE_HARNESSES", str(root))
|
|
monkeypatch.setenv("SIDECAR_SEED_PLUGINS_DIR", "") # no seed unless a test says so
|
|
ld = harness_loader.DriverLoader(
|
|
kind="harness", index_key="harnesses", manifest_key="harness", id_key="harnessId",
|
|
code_key="sidecar", default_entry="driver.py", check=harness_base.check_harness,
|
|
factories=("create", "harness", "Harness"), root_env="TEST_LIVE_HARNESSES",
|
|
host_root="/nonexistent", worker_root="/nonexistent")
|
|
ld.set_context(harness_base.make_context())
|
|
yield ld, root
|
|
ld.reset()
|
|
_drop_test_modules()
|
|
|
|
|
|
# The real plugins' namespaces (conftest's registry): a test never drops them.
|
|
_REAL = {"harness_claude", "harness_pi", "harness_opencode", "harness_agy",
|
|
"provider_anthropic", "provider_openai", "provider_google"}
|
|
|
|
|
|
def _drop_test_modules() -> None:
|
|
for n in list(sys.modules):
|
|
parts = n.split(".")
|
|
if parts[0] == "sidecar_ext" and len(parts) > 2 and parts[2] not in _REAL:
|
|
sys.modules.pop(n, None)
|
|
|
|
|
|
# ── the real plugins ─────────────────────────────────────────────────────────
|
|
def test_the_four_harness_plugins_and_three_readers_are_there():
|
|
assert harness_loader.ids()[:4] == ("claude", "pi", "opencode", "agy")
|
|
assert harness_loader.get("claude").harness_id == "claude"
|
|
assert all(e.source == "plugin" and e.plugin_id == f"harness-{e.id}"
|
|
for e in harness_loader.LOADER.entries())
|
|
# evox2: provider-evox2's sidecar module (no usage reader — no snapshots)
|
|
assert usage_loader.vendor_ids() == ("anthropic", "openai", "google", "evox2")
|
|
assert usage_loader.snapshots("evox2") == {}
|
|
for alias, vid in (("claude", "anthropic"), ("opencode", "openai"), ("agy", "google")):
|
|
assert usage_loader.get(alias).vendor_id == vid
|
|
# its manifest is kept, its servers read from it
|
|
assert "evox2" in usage_loader.provider_configs()
|
|
ev = usage_loader.evox2()
|
|
assert ev["servers"]["evox2"]["root"].endswith(":8090") and ev["wolMac"]
|
|
assert harness_loader.module("opencode", "cli").__name__ == \
|
|
"sidecar_ext.harness.harness_opencode.cli"
|
|
assert validate._valid_harness("AGY") == "agy"
|
|
# a well-formed id passes the shape check (whether it runs here is the
|
|
# route's 409); a malformed one is a bad request
|
|
assert validate._valid_harness("nope") == "nope"
|
|
with pytest.raises(HTTPException) as e:
|
|
validate._valid_harness("no pe!")
|
|
assert e.value.status_code == 400 and "invalid harness" in e.value.detail
|
|
|
|
|
|
def test_account_dispatch_keeps_the_old_order(monkeypatch):
|
|
import agy_cli
|
|
import opencode_cli
|
|
monkeypatch.setattr(opencode_cli, "known", lambda a: a == "oc")
|
|
monkeypatch.setattr(agy_cli, "known", lambda a: a == "g")
|
|
ids = lambda a: [d.harness_id for d in harness_loader.account_drivers(a)] # noqa: E731
|
|
assert ids("oc") == ["opencode", "claude"]
|
|
assert ids("g") == ["agy", "claude"]
|
|
assert ids("work") == ["claude"]
|
|
|
|
|
|
# ── loading ───────────────────────────────────────────────────────────────────
|
|
def test_a_plugin_driver_loads_in_its_own_namespace(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake")
|
|
out = ld.reload()
|
|
assert out["ok"] and out["loaded"] == ["fake"]
|
|
d = ld.get("fake")
|
|
assert d.spawn(type("B", (), {"prompt": "hi"})(), SID, "/tmp", None)["tag"] == "v1"
|
|
assert "sidecar_ext.harness.harness_fake.driver" in sys.modules
|
|
assert "sidecar_ext.harness.harness_fake.helper" in sys.modules
|
|
assert "helper" not in sys.modules # nothing leaks into the top level
|
|
assert sys.modules["sidecar_ext.harness.harness_fake.driver"].EVENTS == [("start", "v1")]
|
|
assert ld.ids() == ("fake",) # no built-in driver beside it
|
|
e = ld.entry("fake")
|
|
assert e.source == "plugin" and e.plugin_id == "harness-fake" and e.hash
|
|
|
|
|
|
def test_without_an_index_the_plugin_dirs_are_scanned(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake", index=False)
|
|
assert ld.reload()["ok"] and ld.get("fake") is not None
|
|
|
|
|
|
def test_an_unchanged_reload_keeps_the_instance_force_replaces_it(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake")
|
|
ld.reload()
|
|
first = ld.get("fake")
|
|
assert ld.reload()["loaded"] == [] and ld.get("fake") is first
|
|
out = ld.reload(force=True)
|
|
assert out["loaded"] == ["fake"] and ld.get("fake") is not first
|
|
# the old one was shut down after the swap, the new one started
|
|
ev = sys.modules["sidecar_ext.harness.harness_fake.driver"].EVENTS
|
|
assert ev == [("start", "v1")]
|
|
assert first.__class__.__module__ == "sidecar_ext.harness.harness_fake.driver"
|
|
|
|
|
|
def test_a_plugin_that_leaves_is_shut_down_and_gone(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake")
|
|
assert ld.reload()["ok"] and ld.get("fake") is not None
|
|
(root / "index.json").write_text(json.dumps({"harnesses": {}}))
|
|
out = ld.reload()
|
|
assert out["ok"] and out["removed"] == ["fake"]
|
|
assert ld.get("fake") is None and ld.ids() == ()
|
|
assert sys.modules["sidecar_ext.harness.harness_fake.driver"].EVENTS == \
|
|
[("start", "v1"), ("stop", "v1")]
|
|
|
|
|
|
def test_the_first_read_boots_the_registry_unstarted(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake")
|
|
assert ld.get("fake") is not None # no reload asked: the read boots it
|
|
assert sys.modules["sidecar_ext.harness.harness_fake.driver"].EVENTS == []
|
|
ld.startup() # the lifespan starts it, once
|
|
assert ld.entry("fake").started
|
|
assert sys.modules["sidecar_ext.harness.harness_fake.driver"].EVENTS == [("start", "v1")]
|
|
|
|
|
|
@pytest.mark.parametrize("bad", ["syntax", "contract", "startup", "id"])
|
|
def test_a_broken_driver_rolls_back_and_the_old_one_stays(loader, bad):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake", tag="good")
|
|
write_harness(root, "harness-other", "other")
|
|
assert ld.reload()["ok"]
|
|
good, other = ld.get("fake"), ld.get("other")
|
|
good_mod = sys.modules["sidecar_ext.harness.harness_fake.driver"]
|
|
if bad == "syntax":
|
|
write_harness(root, "harness-fake", "fake", driver="def broken(:\n")
|
|
elif bad == "contract":
|
|
write_harness(root, "harness-fake", "fake",
|
|
driver="class Harness:\n harness_id = 'fake'\n")
|
|
elif bad == "startup":
|
|
write_harness(root, "harness-fake", "fake", tag="v2",
|
|
startup_extra="raise RuntimeError('cannot start')")
|
|
else:
|
|
write_harness(root, "harness-fake", "fake",
|
|
driver=DRIVER.format(hid="someone-else", startup_extra="pass"))
|
|
# …and a new third driver in the same reload, which must not stay started
|
|
write_harness(root, "harness-new", "newbie")
|
|
out = ld.reload()
|
|
assert out["ok"] is False and out["rolledBack"] is True and out["error"]
|
|
assert ld.get("fake") is good and ld.get("other") is other
|
|
assert ld.get("newbie") is None
|
|
assert sys.modules["sidecar_ext.harness.harness_fake.driver"] is good_mod
|
|
assert ld.public()["last"]["rolledBack"] is True
|
|
if bad == "startup":
|
|
assert sys.modules.get("sidecar_ext.harness.harness_new.driver") is None
|
|
|
|
|
|
def test_an_unreadable_index_is_an_error_not_an_empty_set(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake")
|
|
ld.reload()
|
|
(root / "index.json").write_text("{not json")
|
|
out = ld.reload()
|
|
assert not out["ok"] and out["rolledBack"] and ld.get("fake") is not None
|
|
|
|
|
|
# ── last-known-good ───────────────────────────────────────────────────────────
|
|
def test_a_good_load_is_snapshotted_and_a_broken_boot_uses_it(loader):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake", tag="lkg-tag")
|
|
assert ld.reload()["ok"]
|
|
lkg = ld.lkg_root()
|
|
assert (lkg / "index.json").is_file() and (lkg / "harness-fake" / "sidecar" / "driver.py").is_file()
|
|
# A new boot whose live dir got broken (a half-written materialization)
|
|
ld.reset()
|
|
(root / "harness-fake" / "sidecar" / "driver.py").write_text("raise ImportError('half')\n")
|
|
_drop_test_modules()
|
|
out = ld.reload()
|
|
assert out["ok"] is False and out["rolledBack"] and out["fallback"] == "lkg"
|
|
assert ld.entry("fake").source == "lkg"
|
|
assert ld.get("fake").spawn(type("B", (), {"prompt": "x"})(), SID, "/", None)["tag"] == "lkg-tag"
|
|
|
|
|
|
def test_a_missing_live_dir_at_boot_loads_the_last_good(loader):
|
|
import shutil
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake")
|
|
ld.reload()
|
|
ld.reset()
|
|
shutil.rmtree(root)
|
|
out = ld.reload()
|
|
assert out["ok"] and out.get("fallback") == "lkg" and ld.entry("fake").source == "lkg"
|
|
|
|
|
|
# ── the seed plugins: a host never comes up empty ─────────────────────────────
|
|
def _seed(tmp_path, monkeypatch, *, worker=False):
|
|
import config
|
|
seed = tmp_path / "seed"
|
|
seed.mkdir()
|
|
write_harness(seed, "harness-fake", "fake", tag="seed", index=False)
|
|
write_harness(seed, "app-thing", "x", index=False)
|
|
(seed / "app-thing" / "plugin.json").write_text(json.dumps({"id": "app-thing"}))
|
|
monkeypatch.setenv("SIDECAR_SEED_PLUGINS_DIR", str(seed))
|
|
monkeypatch.setattr(config, "IS_WORKER", worker)
|
|
return seed
|
|
|
|
|
|
def test_a_host_never_materialized_boots_on_the_seed_plugins(loader, tmp_path, monkeypatch):
|
|
import shutil
|
|
ld, root = loader
|
|
shutil.rmtree(root) # the hub never wrote it
|
|
_seed(tmp_path, monkeypatch)
|
|
out = ld.reload()
|
|
assert out["ok"] and out["fallback"] == "seed" and ld.ids() == ("fake",)
|
|
assert ld.entry("fake").source == "seed"
|
|
assert not ld.lkg_root().exists() # a seed load is never the last good copy
|
|
# …then the hub materializes: the live dir wins
|
|
root.mkdir()
|
|
write_harness(root, "harness-fake", "fake", tag="live")
|
|
assert ld.reload()["ok"] and ld.entry("fake").source == "plugin"
|
|
assert ld.get("fake").spawn(type("B", (), {"prompt": "x"})(), SID, "/", None)["tag"] == "live"
|
|
|
|
|
|
def test_an_index_without_plugins_is_respected(loader, tmp_path, monkeypatch):
|
|
ld, root = loader
|
|
(root / "index.json").write_text(json.dumps({"version": 3, "harnesses": {}}))
|
|
_seed(tmp_path, monkeypatch)
|
|
out = ld.reload()
|
|
assert out["ok"] and ld.ids() == () # every harness disabled: no fallback
|
|
|
|
|
|
def test_a_worker_has_no_seed(loader, tmp_path, monkeypatch):
|
|
import shutil
|
|
ld, root = loader
|
|
shutil.rmtree(root)
|
|
_seed(tmp_path, monkeypatch, worker=True)
|
|
out = ld.reload()
|
|
assert out["ok"] and ld.ids() == ()
|
|
|
|
|
|
def test_a_broken_live_dir_at_boot_takes_the_seed(loader, tmp_path, monkeypatch):
|
|
ld, root = loader
|
|
write_harness(root, "harness-fake", "fake", driver="def broken(:\n")
|
|
_seed(tmp_path, monkeypatch)
|
|
out = ld.reload()
|
|
assert out["ok"] is False and out["fallback"] == "seed"
|
|
assert ld.entry("fake").source == "seed"
|
|
|
|
|
|
def test_a_codeless_provider_keeps_its_config(tmp_path, monkeypatch):
|
|
root = tmp_path / "live-providers"
|
|
write_reader(root, "provider-fake", "fakevendor")
|
|
d = root / "provider-local"
|
|
d.mkdir()
|
|
(d / "plugin.json").write_text(json.dumps({"id": "provider-local", "kind": "provider",
|
|
"provider": {"vendorId": "local", "servers": {"box": {"url": "http://box:1/v1"}}}}))
|
|
(d / "config.json").write_text(json.dumps({"config": {"a": 1}, "accounts": []}))
|
|
idx = json.loads((root / "index.json").read_text())
|
|
# the hub's own shape for it: entry None, its absolute (container) dir
|
|
idx["providers"]["local"] = {"pluginId": "provider-local", "dir": "/data/x/provider-local",
|
|
"entry": None, "sidecarDir": None}
|
|
(root / "index.json").write_text(json.dumps(idx))
|
|
monkeypatch.setenv("TEST_LIVE_PROVIDERS", str(root))
|
|
ld = harness_loader.DriverLoader(
|
|
kind="provider", index_key="providers", manifest_key="provider", id_key="vendorId",
|
|
code_key="usageReader", default_entry="usage.py", check=harness_base.check_reader,
|
|
factories=("create", "reader", "Reader"), root_env="TEST_LIVE_PROVIDERS",
|
|
host_root="/nonexistent", worker_root="/nonexistent")
|
|
try:
|
|
out = ld.reload(start=False)
|
|
assert out["ok"] and ld.ids() == ("fakevendor",)
|
|
cfg = ld.configs()
|
|
assert cfg["local"]["code"] is False and cfg["local"]["config"]["config"] == {"a": 1}
|
|
assert cfg["local"]["manifest"]["servers"]["box"]["url"] == "http://box:1/v1"
|
|
assert cfg["local"]["dir"] == str(d) # resolved by name under the base
|
|
finally:
|
|
ld.reset()
|
|
for n in [n for n in sys.modules if n.startswith("sidecar_ext.provider.provider_fake")]:
|
|
sys.modules.pop(n, None)
|
|
|
|
|
|
# ── the routes ────────────────────────────────────────────────────────────────
|
|
@pytest.fixture
|
|
def live(tmp_path, monkeypatch):
|
|
"""The real loaders pointed at temp dirs, nothing started."""
|
|
h, p = tmp_path / "h", tmp_path / "p"
|
|
h.mkdir()
|
|
p.mkdir()
|
|
monkeypatch.setenv("SIDECAR_LIVE_HARNESSES_DIR", str(h))
|
|
monkeypatch.setenv("SIDECAR_LIVE_PROVIDERS_DIR", str(p))
|
|
monkeypatch.setenv("SIDECAR_SEED_PLUGINS_DIR", "")
|
|
saved = [(ld, ld._active, ld._configs, ld._last)
|
|
for ld in (harness_loader.LOADER, usage_loader.LOADER)]
|
|
for ld, *_ in saved:
|
|
ld._active = None
|
|
ld._last = {"ok": None}
|
|
yield h, p
|
|
# the real plugins come back (conftest's registry) for the tests after
|
|
for ld, active, configs, last in saved:
|
|
ld._active, ld._configs, ld._last = active, configs, last
|
|
_drop_test_modules()
|
|
|
|
|
|
def _client(monkeypatch):
|
|
for m in (routes_runs, routes_accounts, routes_harnesses):
|
|
monkeypatch.setattr(m, "_auth", lambda _a: None)
|
|
monkeypatch.setattr(harness_loader.LOADER, "reload",
|
|
lambda force=False, start=True, _r=harness_loader.LOADER.reload:
|
|
_r(force, start=False))
|
|
monkeypatch.setattr(usage_loader.LOADER, "reload",
|
|
lambda force=False, start=True, _r=usage_loader.LOADER.reload:
|
|
_r(force, start=False))
|
|
app = FastAPI()
|
|
for r in (routes_runs.router, routes_accounts.router, routes_harnesses.router):
|
|
app.include_router(r)
|
|
return TestClient(app)
|
|
|
|
|
|
def test_spawn_resume_fork_and_accounts_dispatch_to_a_plugin_driver(live, monkeypatch, tmp_path):
|
|
import fork
|
|
h, _ = live
|
|
write_harness(h, "harness-fake", "fake")
|
|
monkeypatch.setattr(fork, "_auth", lambda _a: None)
|
|
c = _client(monkeypatch)
|
|
app = c.app
|
|
app.include_router(fork.router)
|
|
r = c.post("/harnesses/reload", json={})
|
|
assert r.status_code == 200 and r.json()["ok"], r.json()
|
|
r = c.post("/spawn", json={"prompt": "hi", "harness": "fake", "sessionId": SID,
|
|
"cwd": str(tmp_path)})
|
|
assert r.json() == {"harness": "fake", "sid": SID, "tag": "v1", "prompt": "hi"}
|
|
r = c.post("/resume", json={"prompt": "again", "harness": "fake", "sessionId": SID,
|
|
"cwd": str(tmp_path)})
|
|
assert r.json() == {"resumed": SID}
|
|
other = "99999999-2222-4333-8444-555555555555"
|
|
r = c.post("/fork", json={"prompt": "x", "harness": "fake", "sessionId": other,
|
|
"srcSessionId": SID, "cutLine": 1, "cwd": str(tmp_path)})
|
|
assert r.json() == {"forked": other}
|
|
assert c.get("/accounts/fake-acct").json() == {"id": "fake-acct", "via": "fake"}
|
|
assert {"id": "fake-acct", "loggedIn": True} in c.get("/accounts").json()["accounts"]
|
|
listed = c.get("/harnesses").json()["harnesses"]["harnesses"]
|
|
assert [e["id"] for e in listed if e["source"] == "plugin"] == ["fake"]
|
|
assert [e["id"] for e in listed] == ["fake"] # nothing built in
|
|
# a harness whose plugin isn't here doesn't exist on this runner: a 409
|
|
# harness_unavailable on every run route, a malformed id still a 400
|
|
r = c.post("/spawn", json={"prompt": "hi", "harness": "agy", "cwd": str(tmp_path)})
|
|
assert r.status_code == 409 and r.json()["detail"]["kind"] == "harness_unavailable"
|
|
assert "no harness-agy plugin" in r.json()["detail"]["message"]
|
|
r = c.post("/resume", json={"prompt": "x", "harness": "agy", "sessionId": SID,
|
|
"cwd": str(tmp_path)})
|
|
assert r.status_code == 409 and r.json()["detail"]["kind"] == "harness_unavailable"
|
|
r = c.post("/fork", json={"prompt": "x", "harness": "agy", "sessionId": other,
|
|
"srcSessionId": SID, "cutLine": 1, "cwd": str(tmp_path)})
|
|
assert r.status_code == 409 and r.json()["detail"]["kind"] == "harness_unavailable"
|
|
r = c.post("/spawn", json={"prompt": "hi", "harness": "Bad Id!", "cwd": str(tmp_path)})
|
|
assert r.status_code == 400 and "invalid harness" in r.json()["detail"]
|
|
assert c.get("/health").json()["harnesses"][-1]["id"] == "fake"
|
|
|
|
|
|
def test_a_broken_reload_answers_rolled_back(live, monkeypatch):
|
|
h, _ = live
|
|
write_harness(h, "harness-fake", "fake", driver="def broken(:\n")
|
|
c = _client(monkeypatch)
|
|
out = c.post("/harnesses/reload").json()
|
|
assert out["ok"] is False and out["rolledBack"] is True and "harnesses:" in out["error"]
|
|
assert harness_loader.get("fake") is None and harness_loader.ids() == ()
|
|
|
|
|
|
def test_usage_by_vendor_and_the_legacy_routes(live, monkeypatch):
|
|
_, p = live
|
|
write_reader(p, "provider-fake", "fakevendor")
|
|
c = _client(monkeypatch)
|
|
assert c.post("/harnesses/reload").json()["ok"]
|
|
want = {"accounts": {"acct": {"five_hour": {"used_percentage": 42}}}}
|
|
assert c.get("/usage/fakevendor").json() == want
|
|
assert c.get("/usage/fakevendor-alias").json() == want
|
|
assert c.get("/usage/nobody").status_code == 404
|
|
assert usage_loader.provider_configs()["fakevendor"]["config"] == {"region": "eu"}
|
|
assert harness_loader.context().providers["fakevendor"]["pluginId"] == "provider-fake"
|
|
# the legacy routes read the vendor's reader — none here but this one
|
|
write_reader(p, "provider-anthropic-fake", "anthropic")
|
|
assert c.post("/harnesses/reload").json()["ok"]
|
|
assert c.get("/claude/usage").json() == want
|
|
assert c.get("/usage/anthropic").json() == want
|
|
assert c.get("/opencode/usage").status_code == 404
|
|
assert c.get("/agy/usage").status_code == 404
|
|
|
|
|
|
# ── /sync: the worker's bundles ──────────────────────────────────────────────
|
|
def _bundle(src: pathlib.Path, pid: str) -> dict:
|
|
files = {p.relative_to(src / pid).as_posix(): base64.b64encode(p.read_bytes()).decode()
|
|
for p in (src / pid).rglob("*") if p.is_file()}
|
|
return {"hash": "h-" + pid, "files": files}
|
|
|
|
|
|
def _sync_body(src, harnesses=(), providers=()):
|
|
return labsync.SyncBody(hash="abcdef12",
|
|
harnesses={pid: _bundle(src, pid) for pid in harnesses},
|
|
providers={pid: _bundle(src, pid) for pid in providers} or None)
|
|
|
|
|
|
def test_sync_writes_the_bundles_and_reloads(tmp_path, monkeypatch):
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-fake", "fake", index=False)
|
|
write_reader(src, "provider-fake", "fakevendor")
|
|
roots = {"harnesses": tmp_path / "w" / "harnesses", "providers": tmp_path / "w" / "providers"}
|
|
calls = []
|
|
out = labsync.apply_plugins(_sync_body(src, ["harness-fake"], ["provider-fake"]), roots,
|
|
reload=lambda: calls.append(1) or {"ok": True})
|
|
assert calls == [1] and out["harnesses"]["plugins"] == ["harness-fake"]
|
|
base = harness_loader.DriverLoader.base_of(roots["harnesses"])
|
|
idx = json.loads((base / "index.json").read_text())
|
|
assert idx["harnesses"]["fake"]["pluginId"] == "harness-fake"
|
|
assert (base / "harness-fake" / "sidecar" / "driver.py").is_file()
|
|
pidx = json.loads((harness_loader.DriverLoader.base_of(roots["providers"]) / "index.json")
|
|
.read_text())
|
|
assert "fakevendor" in pidx["providers"]
|
|
# A loader reading that root finds the driver.
|
|
monkeypatch.setenv("SIDECAR_LIVE_HARNESSES_DIR", str(roots["harnesses"]))
|
|
cands = harness_loader.LOADER._candidates(base)
|
|
assert [c["id"] for c in cands] == ["fake"]
|
|
|
|
|
|
def test_a_sync_whose_reload_fails_is_put_back(tmp_path):
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-a", "aaa", index=False)
|
|
write_harness(src, "harness-b", "bbb", index=False)
|
|
roots = {"harnesses": tmp_path / "w" / "harnesses", "providers": tmp_path / "w" / "providers"}
|
|
labsync.apply_plugins(_sync_body(src, ["harness-a"]), roots, reload=lambda: {"ok": True})
|
|
before = (roots["harnesses"] / "current").resolve()
|
|
calls = []
|
|
|
|
def failing():
|
|
calls.append(1)
|
|
return {"ok": len(calls) > 1, "error": "boom"}
|
|
|
|
with pytest.raises(HTTPException) as e:
|
|
labsync.apply_plugins(_sync_body(src, ["harness-a", "harness-b"]), roots, reload=failing)
|
|
assert e.value.status_code == 409 and e.value.detail["rolledBack"] is True
|
|
assert (roots["harnesses"] / "current").resolve() == before
|
|
assert calls == [1, 1] # the failed reload, then the one back onto the old version
|
|
|
|
|
|
def test_a_guest_computer_gets_guest_allowed_harnesses_only(tmp_path, monkeypatch):
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-claude", "claude", index=False, guest=True)
|
|
write_harness(src, "harness-opencode", "opencode", index=False, guest=False)
|
|
write_reader(src, "provider-fake", "fakevendor")
|
|
monkeypatch.setattr(labsync, "_guest_computer", lambda: True)
|
|
roots = {"harnesses": tmp_path / "w" / "harnesses", "providers": tmp_path / "w" / "providers"}
|
|
labsync.apply_plugins(_sync_body(src, ["harness-claude", "harness-opencode"],
|
|
["provider-fake"]), roots, reload=lambda: {"ok": True})
|
|
idx = json.loads((harness_loader.DriverLoader.base_of(roots["harnesses"]) / "index.json")
|
|
.read_text())
|
|
assert list(idx["harnesses"]) == ["claude"]
|
|
pidx = json.loads((harness_loader.DriverLoader.base_of(roots["providers"]) / "index.json")
|
|
.read_text())
|
|
assert pidx["providers"] == {}
|
|
|
|
|
|
def test_a_bad_bundle_is_refused_with_nothing_swapped(tmp_path):
|
|
roots = {"harnesses": tmp_path / "harnesses", "providers": tmp_path / "providers"}
|
|
body = labsync.SyncBody(hash="abcdef12", harnesses={
|
|
"harness-x": {"hash": "x", "files": {"../escape.py": base64.b64encode(b"x").decode()}}})
|
|
with pytest.raises(HTTPException) as e:
|
|
labsync.apply_plugins(body, roots, reload=lambda: {"ok": True})
|
|
assert e.value.status_code == 400
|
|
assert not (roots["harnesses"] / "current").exists()
|
|
|
|
|
|
def test_a_sync_without_plugin_maps_leaves_the_drivers_alone(tmp_path):
|
|
roots = {"harnesses": tmp_path / "h", "providers": tmp_path / "p"}
|
|
assert labsync.apply_plugins(labsync.SyncBody(hash="abcdef12"), roots,
|
|
reload=lambda: pytest.fail("no reload")) is None
|
|
|
|
|
|
def test_empty_maps_clear_the_drivers_off_a_worker(tmp_path):
|
|
"""The hub always sends both maps: ``{}`` = the harness plugins were
|
|
disabled or removed there — the worker's live dir goes empty with them."""
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-fake", "fake", index=False)
|
|
roots = {"harnesses": tmp_path / "w" / "harnesses", "providers": tmp_path / "w" / "providers"}
|
|
labsync.apply_plugins(_sync_body(src, ["harness-fake"]), roots, reload=lambda: {"ok": True})
|
|
calls = []
|
|
out = labsync.apply_plugins(labsync.SyncBody(hash="abcdef13", harnesses={}, providers={}),
|
|
roots, reload=lambda: calls.append(1) or {"ok": True})
|
|
assert calls == [1] and out["harnesses"]["plugins"] == []
|
|
idx = json.loads((harness_loader.DriverLoader.base_of(roots["harnesses"]) / "index.json")
|
|
.read_text())
|
|
assert idx["harnesses"] == {}
|
|
|
|
|
|
def test_a_provider_without_a_reader_syncs_as_config(tmp_path):
|
|
"""provider-evox2 has no usage reader: its bundle is its plugin.json and
|
|
config.json — kept as a config-only entry, never refused."""
|
|
src = tmp_path / "src"
|
|
d = src / "provider-evox2"
|
|
d.mkdir(parents=True)
|
|
(d / "plugin.json").write_text(json.dumps({"id": "provider-evox2", "kind": "provider",
|
|
"provider": {"vendorId": "evox2", "localInfra": {"wolMac": "aa:bb:cc:dd:ee:ff"}}}))
|
|
(d / "config.json").write_text(json.dumps({"config": {}, "accounts": []}))
|
|
roots = {"harnesses": tmp_path / "w" / "harnesses", "providers": tmp_path / "w" / "providers"}
|
|
labsync.apply_plugins(_sync_body(src, providers=["provider-evox2"]), roots,
|
|
reload=lambda: {"ok": True})
|
|
base = harness_loader.DriverLoader.base_of(roots["providers"])
|
|
ent = json.loads((base / "index.json").read_text())["providers"]["evox2"]
|
|
assert ent["entry"] is None and ent["config"] == {"config": {}, "accounts": []}
|
|
ld = harness_loader.DriverLoader(
|
|
kind="provider", index_key="providers", manifest_key="provider", id_key="vendorId",
|
|
code_key="usageReader", default_entry="usage.py", check=harness_base.check_reader,
|
|
factories=("create", "reader", "Reader"), root_env="NO_SUCH_ENV_X",
|
|
host_root=str(roots["providers"]), worker_root=str(roots["providers"]))
|
|
assert ld.reload(start=False)["ok"] and ld.ids() == ()
|
|
assert ld.configs()["evox2"]["manifest"]["localInfra"]["wolMac"] == "aa:bb:cc:dd:ee:ff"
|
|
|
|
|
|
# ── the plugin maps a worker holds, checked apart from the bundle's hash ─────
|
|
class _Loader:
|
|
"""A loader stand-in: the drivers it runs, as (id, hash)."""
|
|
|
|
def __init__(self, *pairs):
|
|
self._e = [types.SimpleNamespace(id=i, hash=h) for i, h in pairs]
|
|
|
|
def entries(self):
|
|
return self._e
|
|
|
|
|
|
def _roots(tmp_path):
|
|
return {"harnesses": tmp_path / "w" / "harnesses", "providers": tmp_path / "w" / "providers"}
|
|
|
|
|
|
def test_plugin_sync_says_which_version_a_worker_holds_and_runs(tmp_path):
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-fake", "fake", index=False)
|
|
write_reader(src, "provider-fake", "fakevendor")
|
|
roots = _roots(tmp_path)
|
|
none = {"harnesses": _Loader(), "providers": _Loader()}
|
|
assert labsync.plugin_sync(roots, none) == {
|
|
"harnesses": {"version": None, "loaded": None},
|
|
"providers": {"version": None, "loaded": None}}
|
|
body = _sync_body(src, ["harness-fake"], ["provider-fake"])
|
|
labsync.apply_plugins(body, roots, reload=lambda: {"ok": True})
|
|
running = {"harnesses": _Loader(("fake", "h-harness-fake")),
|
|
"providers": _Loader(("fakevendor", "h-provider-fake"))}
|
|
got = labsync.plugin_sync(roots, running)
|
|
assert got["harnesses"] == {"version": labsync._plugins_hash(body.harnesses), "loaded": True}
|
|
assert got["providers"] == {"version": labsync._plugins_hash(body.providers), "loaded": True}
|
|
# the right version on disk, nothing loaded from it
|
|
assert labsync.plugin_sync(roots, none)["harnesses"]["loaded"] is False
|
|
|
|
|
|
def test_maps_taken_without_their_drivers_are_stale_under_the_same_hash(tmp_path, monkeypatch):
|
|
"""The 2026-11-26 outage: a sidecar from before the plugin maps applied a
|
|
bundle's skills and kept its hash, dropping the maps; updated, it ran no
|
|
harness and every later /sync of that hash was a no-op."""
|
|
monkeypatch.setattr(labsync, "_guest_computer", lambda: False)
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-fake", "fake", index=False)
|
|
roots = _roots(tmp_path)
|
|
body = _sync_body(src, ["harness-fake"])
|
|
running = {"harnesses": _Loader(("fake", "h-harness-fake")), "providers": _Loader()}
|
|
none = {"harnesses": _Loader(), "providers": _Loader()}
|
|
assert labsync.plugins_stale(body, roots, none) # never written
|
|
labsync.apply_plugins(body, roots, reload=lambda: {"ok": True})
|
|
assert not labsync.plugins_stale(body, roots, running) # held and run
|
|
assert labsync.plugins_stale(body, roots, none) # held, not run
|
|
write_harness(src, "harness-b", "bbb", index=False)
|
|
assert labsync.plugins_stale(_sync_body(src, ["harness-fake", "harness-b"]), roots, running)
|
|
# a bundle without maps never is
|
|
assert not labsync.plugins_stale(labsync.SyncBody(hash="abcdef12"), roots, none)
|
|
|
|
|
|
def test_a_guest_computer_holds_no_provider_map(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(labsync, "_guest_computer", lambda: True)
|
|
src = tmp_path / "src"
|
|
write_harness(src, "harness-claude", "claude", index=False, guest=True)
|
|
write_reader(src, "provider-fake", "fakevendor")
|
|
roots = _roots(tmp_path)
|
|
body = _sync_body(src, ["harness-claude"], ["provider-fake"])
|
|
labsync.apply_plugins(body, roots, reload=lambda: {"ok": True})
|
|
running = {"harnesses": _Loader(("claude", "h-harness-claude")), "providers": _Loader()}
|
|
assert not labsync.plugins_stale(body, roots, running)
|
|
|
|
|
|
def test_the_sync_route_re_applies_maps_a_worker_lacks(monkeypatch):
|
|
monkeypatch.setattr(labsync, "IS_WORKER", True)
|
|
monkeypatch.setattr(labsync, "state", lambda *a, **k: {"hash": "abcdef12", "conflicts": []})
|
|
monkeypatch.setattr(labsync, "apply", lambda *a, **k: pytest.fail("skills re-applied"))
|
|
applied = []
|
|
monkeypatch.setattr(labsync, "apply_plugins",
|
|
lambda body: applied.append(body.hash) or {"harnesses": {}})
|
|
app = FastAPI()
|
|
app.include_router(labsync.make_router(lambda _a: None))
|
|
c = TestClient(app)
|
|
body = {"hash": "abcdef12", "harnesses": {}, "providers": {}}
|
|
monkeypatch.setattr(labsync, "plugins_stale", lambda b: False)
|
|
assert c.post("/sync", json=body).json()["changed"] is False and applied == []
|
|
monkeypatch.setattr(labsync, "plugins_stale", lambda b: True)
|
|
out = c.post("/sync", json=body).json()
|
|
assert out["changed"] is True and applied == ["abcdef12"] and "plugins" in out
|
|
|
|
|
|
def test_a_worker_without_any_harness_says_its_sync_is_missing(monkeypatch):
|
|
import config
|
|
monkeypatch.setattr(config, "IS_WORKER", True)
|
|
monkeypatch.setattr(harness_loader, "ids", lambda: ())
|
|
e = validate.harness_unavailable("claude")
|
|
assert e.status_code == 409 and e.detail["kind"] == "harness_unavailable"
|
|
assert "not on this machine yet" in e.detail["message"]
|
|
monkeypatch.setattr(harness_loader, "ids", lambda: ("pi",))
|
|
assert "no harness-claude plugin" in validate.harness_unavailable("claude").detail["message"]
|
|
|
|
|
|
def test_provider_evox2s_module_answers_the_core_hooks(monkeypatch):
|
|
"""The EVOX2 helpers are provider-evox2's: /sessions' ``progress`` and the
|
|
pre-launch room-making go through usage_loader's hooks to its module."""
|
|
usage_loader.reload(force=True)
|
|
import gen_progress # the plugin's (conftest alias)
|
|
monkeypatch.setitem(gen_progress._progress, "s-1", {"phase": "decode", "decoded": 5})
|
|
assert usage_loader.live_progress("s-1") == {"phase": "decode", "decoded": 5}
|
|
assert usage_loader.live_progress("nope") is None
|
|
seen = []
|
|
import local_room
|
|
monkeypatch.setattr(local_room, "make_room_async", lambda h, m: seen.append((h, m)))
|
|
usage_loader.before_launch("pi", "inkling-2-mini")
|
|
assert seen == [("pi", "inkling-2-mini")]
|