Files
ai-agent/backend/_fakeworker.py
Gabriel VidalandClaude Opus 5.5 98b1fe85e9 fix(workers): harness plugins reach every worker — no more "invalid harness: 'claude'"
Since the strict plugin-only sidecar (Wave 3C) a worker runs only the
harness plugins the hub syncs to it, and every worker came up with none:

- the probe that asked a worker to update also pushed it the new bundle;
  the old sidecar took the bundle's hash and dropped the harness/provider
  maps it didn't know, then restarted onto the strict code empty — and the
  hub saw the hash "current" forever (a same-hash /sync was a no-op too);
- harness-pi ships runner/.gitignore, which the worker refuses, so every
  later /sync of the owner's workers failed whole (400 bad file path).

Hub: plugin bundles never ship a path the worker would refuse (hidden
parts, > 8 parts); labsync.plugins_drift makes a worker that holds the
bundle's hash without its maps "outdated", read off /health's new
pluginSync (or its harnesses list on an older sidecar); no lab-sync push
in the probe that triggers an update, nor while the worker is updating.

Sidecar: /health reports pluginSync ({kind: {version, loaded}}) and the
loaded usage readers; /sync re-applies plugin maps the worker doesn't
hold or run even under a hash it already has (labsync.plugins_stale);
a well-formed harness no driver runs is a 409 harness_unavailable on
spawn/resume/fork (only a malformed id stays a 400), and a worker with no
harness at all says its lab sync hasn't brought them yet.

Also fixes test_guest_computers' lab-sync test, broken on main since the
plugin maps (its stubbed bundle is a list).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:17:45 +01:00

159 lines
6.7 KiB
Python

"""A real HTTP worker for the worker/mirror tests: the sidecar's own feed,
pairing, uploads and media routers (``../sidecar``) plus a stub ``/sessions`` + ``/health``,
served by uvicorn on a free loopback port in a thread."""
import os
import pathlib
import socket
import sys
import threading
import time
import uvicorn
from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import JSONResponse
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent
/ "sidecar"))
import feed # noqa: E402
import media # noqa: E402
import pairing # noqa: E402
import uploads # noqa: E402
class FakeWorker:
def __init__(self, root: pathlib.Path, state: pathlib.Path):
os.environ["WORKER_STATE_DIR"] = str(state)
self.root = root
self.live: set[str] = set()
# sessions whose live run takes an inbox message (/message delivers);
# a live one not listed here answers 409 inbox_unavailable, a session
# that isn't live at all 404 — the two fallbacks main.py handles.
self.inbox: set[str] = set()
self.calls: list[tuple[str, dict]] = []
# Its version (sidecar/selfupdate.py): None = a worker from before
# auto-update, whose /health has no commit at all.
self.commit: str | None = None
self.updatable = False
self.update_state: dict | None = None
# The lab-sync bundle it holds (sidecar labsync.public): None = a
# worker from before lab sync, whose /health has no labSync.
self.lab_sync: dict | None = None
# Path prefixes this worker answers 404, as a worker from before them
# would (e.g. "/uploads/"). Filtering app.router.routes can't model
# that: FastAPI ≥ 0.163 keeps an included router whole.
self.predates: set[str] = set()
app = FastAPI()
@app.middleware("http")
async def old_worker(request, call_next):
if any(request.url.path.startswith(p) for p in self.predates):
return JSONResponse({"detail": "Not Found"}, status_code=404)
return await call_next(request)
def auth(h):
tok = pairing.token()
if not tok or h != f"Bearer {tok}":
raise HTTPException(401, "unauthorized")
@app.get("/health")
def health():
out = {"ok": True, **pairing.identity(), "cwd": "/Users/g/repo",
"permissionMode": "bypassPermissions"}
if self.commit:
out.update(commit=self.commit, updatable=self.updatable,
update=self.update_state)
if self.lab_sync is not None:
out["labSync"] = self.lab_sync
return out
@app.post("/sync")
def sync(body: dict, authorization: str | None = Header(default=None)):
auth(authorization)
self.calls.append(("/sync", body))
self.lab_sync = {"hash": body["hash"], "skills": [], "agents": [],
"conflicts": []}
return {"changed": True, "labSync": self.lab_sync}
@app.post("/update")
def update(body: dict, authorization: str | None = Header(default=None)):
auth(authorization)
self.calls.append(("/update", body))
self.update_state = {"state": "updating", "from": self.commit,
"to": body["commit"]}
return {"ok": True, "started": True, "pid": 4242}
@app.get("/sessions")
def sessions(authorization: str | None = Header(default=None)):
auth(authorization)
return {"sessions": [{"sessionId": s} for s in self.live],
"count": len(self.live)}
def _record(path):
def handler(body: dict,
authorization: str | None = Header(default=None)):
auth(authorization)
self.calls.append((path, body))
return {"sessionId": body.get("sessionId"), "pid": 4242}
app.post(path)(handler)
for path in ("/spawn", "/resume", "/fork", "/interrupt"):
_record(path)
# Its own Claude login's headless sign-in (sidecar routes_accounts).
@app.post("/accounts/{account}/login")
def login(account: str, body: dict,
authorization: str | None = Header(default=None)):
auth(authorization)
self.calls.append((f"/accounts/{account}/login", body))
return {"url": "https://claude.ai/oauth/authorize?state=s", "expiresAt": 0}
@app.post("/accounts/{account}/login/code")
def login_code(account: str, body: dict,
authorization: str | None = Header(default=None)):
auth(authorization)
self.calls.append((f"/accounts/{account}/login/code", body))
return {"id": account, "loggedIn": True, "email": "g@orus.example"}
@app.post("/message")
def message(body: dict,
authorization: str | None = Header(default=None)):
auth(authorization)
sid = body.get("sessionId")
if sid not in self.live:
raise HTTPException(404, {"message": "no running process",
"kind": "not_running"})
if sid not in self.inbox:
raise HTTPException(409, {"message": "no inbox socket",
"kind": "inbox_unavailable"})
self.calls.append(("/message", body))
return {"sessionId": sid, "pid": 4242, "delivered": "inbox"}
app.include_router(feed.make_router(auth, lambda: self.root))
app.include_router(pairing.make_router(
auth, lambda: {"email": "g@orus.example", "orgName": "Orus",
"loggedIn": True},
lambda: {"cwd": "/Users/g/repo"}))
app.include_router(uploads.make_router(auth, lambda: state / "uploads"))
app.include_router(media.make_router(auth))
s = socket.socket()
s.bind(("127.0.0.1", 0))
self.port = s.getsockname()[1]
s.close()
self.server = uvicorn.Server(uvicorn.Config(
app, host="127.0.0.1", port=self.port, log_level="warning"))
self.thread = threading.Thread(target=self.server.run, daemon=True)
self.thread.start()
for _ in range(100):
if self.server.started:
break
time.sleep(0.05)
def pairing_string(self, login: str | None = "g@orus.example") -> str:
code = pairing.new_code()
return f"127.0.0.1:{self.port}/{code}" + (f"/{login}" if login else "")
def stop(self):
self.server.should_exit = True
self.thread.join(timeout=5)