Files
ai-agent/backend/test_guest_computers.py
gabrielvidal 44832cdb5a Merge branch 'merge-4-tracks'
# Conflicts:
#	sidecar/labsync.py
#	sidecar/routes_runs.py
#	sidecar/test_harness_loader.py
2026-11-26 19:50:56 +01:00

1206 lines
65 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""A guest's own computers (users/computers.py, workers/link.py,
workers/guests.py, claudeproxy/limits.py): enrolling through the portal, the
worker link's relay, what a guest computer may write back, what its proxy
token may spend, and where its runs go. ``python -m pytest
test_guest_computers.py`` from ``backend/``."""
import asyncio
import json
import os
import pathlib
import tempfile
import time
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects", "PROXY_LEDGER_DIR": TMP / "ledger",
"WORKER_ENROLL_PATH": TMP / "enroll.json",
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"GUEST_PUBLIC_URL": "https://claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
(TMP / "projects" / "film").mkdir(parents=True)
import httpx # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
import runs.routes as run_routes # noqa: E402
import notifications.service as notify_service # noqa: E402
from claudeproxy import limits, routes as proxy_routes, service # noqa: E402
from conversations import ids # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
from users.runs import spend_by_user, with_computers # noqa: E402
from workers import guests, labsync, link, terminal # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
GUEST_HOST = "https://claude.example.test"
PTOK = "p" * 43
def _sse(model="claude-sonnet-5-5", out=200):
start = {"type": "message_start", "message": {
"model": model, "usage": {"input_tokens": 1000, "cache_read_input_tokens": 5000,
"cache_creation_input_tokens": 0, "output_tokens": 1}}}
delta = {"type": "message_delta", "usage": {"output_tokens": out}}
text = {"type": "content_block_delta", "delta": {"type": "text_delta",
"text": 'the word "usage" in text'}}
return (f"event: message_start\ndata: {json.dumps(start)}\n\n"
f"event: content_block_delta\ndata: {json.dumps(text)}\n\n"
f"event: message_delta\ndata: {json.dumps(delta)}\n\n").encode()
class Base(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
for w in DEPS.worker_store.list():
DEPS.worker_store.delete(w["id"])
for f in (TMP / "ledger").glob("*.jsonl"):
f.unlink()
limits.LEDGER.__init__(TMP / "ledger")
DEPS.meta_store._data.clear()
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"},
models=["sonnet", "haiku"])
self.cookie = DEPS.auth.open_session(self.dom["id"])
self.owner = TestClient(main.app)
def guest(self):
c = TestClient(main.app, base_url=GUEST_HOST)
c.cookies.set(SESSION_COOKIE, self.cookie)
return c
def computer(self, wid="gmac", owner=None, **kw):
rec = {"id": wid, "name": "Mac mini", "owner": owner or self.dom["id"],
"link": True, "url": link.tunnel_url(wid), "token": "bearer",
"linkToken": "L" * 43, "proxyToken": PTOK, "claudeMode": "proxy", **kw}
return DEPS.worker_store.put(rec)
# ── the meter ────────────────────────────────────────────────────────────────
class Meter(Base):
def test_tap_reads_a_streamed_reply_split_anywhere(self):
raw = _sse()
tap = limits.UsageTap("text/event-stream; charset=utf-8")
for i in range(0, len(raw), 7):
tap.feed(raw[i:i + 7])
tap.finish()
self.assertEqual(tap.model, "claude-sonnet-5-5")
self.assertEqual(tap.usage["output_tokens"], 200)
self.assertEqual(tap.usage["input_tokens"], 1000)
self.assertGreater(tap.cost(), 0)
def test_tap_reads_a_plain_reply(self):
tap = limits.UsageTap("application/json")
tap.feed(json.dumps({"type": "message", "model": "claude-haiku-5-5",
"usage": {"input_tokens": 10, "output_tokens": 5}}).encode())
tap.finish()
self.assertEqual((tap.model, tap.usage["output_tokens"]), ("claude-haiku-5-5", 5))
def test_ledger_sums_per_guest_worker_and_account_and_reloads(self):
limits.LEDGER.record({"t": time.time(), "worker": "gmac", "guest": "dom",
"account": "personal", "usd": 1.5})
limits.LEDGER.record({"t": time.time(), "worker": "gmac", "guest": "dom",
"account": "personal", "usd": 0.5})
limits.LEDGER.record({"t": time.time(), "worker": "mac", "guest": None,
"account": "work", "usd": 3})
fresh = limits.Ledger(TMP / "ledger")
self.assertAlmostEqual(fresh.spent("guest", "dom"), 2.0)
self.assertAlmostEqual(fresh.spent("worker", "gmac", "personal"), 2.0)
self.assertAlmostEqual(fresh.spent("worker", "mac"), 3.0)
self.assertEqual(fresh.spent("guest", "dom", month="1999-01"), 0.0)
def test_budget_counts_the_lab_and_the_computers_once(self):
cards = [{"meta": {"owner": "dom", "account": "personal"}, "cost": 4,
"endedAt": "2099-01-01"},
# mirrored from their computer: the ledger has it already
{"meta": {"owner": "dom", "account": "personal", "workerSource": "gmac"},
"cost": 2, "endedAt": "2099-01-01"}]
s = spend_by_user(cards)["dom"]
self.assertEqual((s["month"], s["machineMonth"]), (4, 2))
limits.LEDGER.record({"t": time.time(), "worker": "gmac", "guest": "dom",
"account": "personal", "usd": 2.5})
self.assertAlmostEqual(with_computers(spend_by_user(cards), ["dom"])["dom"]["month"],
6.5)
def test_an_owner_credit_comes_off_the_month(self):
from users.runs import month_credit, month_spend_all
uid = self.dom["id"]
month = time.strftime("%Y-%m", time.gmtime())
limits.LEDGER.record({"t": time.time(), "worker": "gmac", "guest": uid,
"account": "personal", "usd": 10.0})
before = month_spend_all(DEPS, uid, max_age=0)
DEPS.users.update(uid, {"budgetCredit": {"month": month, "usd": 4,
"note": "leaked own-login runs"}})
self.assertEqual(month_credit(DEPS, uid), 4)
self.assertAlmostEqual(month_spend_all(DEPS, uid, max_age=0), before - 4)
s = with_computers(spend_by_user([]), [uid], DEPS)[uid]
self.assertEqual(s["creditMonth"], 4)
# never below zero, another month untouched, 0 takes it back
DEPS.users.update(uid, {"budgetCredit": {"month": month, "usd": 10_000}})
self.assertEqual(month_spend_all(DEPS, uid, max_age=0), 0)
self.assertEqual(month_credit(DEPS, uid, "1999-01"), 0)
DEPS.users.update(uid, {"budgetCredit": {"month": month, "usd": 0}})
self.assertEqual(month_credit(DEPS, uid), 0)
with self.assertRaises(ValueError):
DEPS.users.update(uid, {"budgetCredit": {"month": "11-2026", "usd": 1}})
# ── what a guest computer may write back ─────────────────────────────────────
class Trust(Base):
def test_only_sessions_the_hub_started_there_are_mirrored(self):
w = self.computer()
DEPS.meta_store.update("s-mine", {"worker": "gmac", "owner": self.dom["id"]})
DEPS.meta_store.update("s-owner", {"worker": None})
DEPS.meta_store.update("s-other", {"workerSource": "mac"})
DEPS.meta_store.update("s-claire", {"worker": "gmac", "owner": "claire"})
self.assertTrue(guests.may_mirror(DEPS, w, "-Users-dom/s-mine.jsonl"))
self.assertTrue(guests.may_mirror(DEPS, w, "-Users-dom/s-mine/subagents/a.jsonl"))
for sid in ("s-owner", "s-other", "s-claire", "s-terminal"):
self.assertFalse(guests.may_mirror(DEPS, w, f"-Users-dom/{sid}.jsonl"), sid)
# the owner's own workers are trusted as before
self.assertTrue(guests.may_mirror(DEPS, {"id": "mac"}, "-x/anything.jsonl"))
def test_outbox_items_must_name_one_of_its_sessions(self):
w = self.computer()
DEPS.meta_store.update("s-mine", {"worker": "gmac", "owner": self.dom["id"]})
DEPS.meta_store.update("s-owner", {})
ok = guests.outbox_allowed
self.assertTrue(ok(DEPS, w, "notify", {"sessionId": "s-mine"}))
self.assertFalse(ok(DEPS, w, "notify", {"sessionId": "s-owner"}))
self.assertFalse(ok(DEPS, w, "notify", {})) # would be the owner's push
self.assertTrue(ok(DEPS, w, "askform", {"form": {"meta": {"session": "s-mine"}}}))
self.assertFalse(ok(DEPS, w, "askform", {"form": {"meta": {}}}))
def test_lab_sync_sends_only_the_guests_shared_skills(self):
items = [{"key": "skill:a", "kind": "skill", "name": "a", "portable": True},
{"key": "skill:b", "kind": "skill", "name": "b", "portable": False},
{"key": "agent:c", "kind": "agent", "name": "c", "portable": True}]
orig_cat, orig_build, orig_g = labsync.catalog, labsync.build, labsync.guest_skills
orig_tools, orig_plugins = labsync.tool_items, labsync.with_plugins
labsync.catalog = lambda source=None: items
labsync.build = lambda chosen: [i["key"] for i in chosen]
labsync.guest_skills = lambda: ["b"]
# The paid tools' hub editions (test_tool_proxy.py) and the harness /
# provider maps (test_labsync_plugins.py) aren't this test's.
labsync.tool_items = lambda names: []
labsync.with_plugins = lambda bundle, plugins: bundle
try:
self.assertEqual(labsync.for_worker({"owner": "dom"}), ["skill:b"])
self.assertEqual(labsync.for_worker({}), ["skill:a", "agent:c"])
finally:
labsync.catalog, labsync.build, labsync.guest_skills = orig_cat, orig_build, orig_g
labsync.tool_items, labsync.with_plugins = orig_tools, orig_plugins
# ── enrolling from the portal ────────────────────────────────────────────────
class Enroll(Base):
def test_off_until_the_owner_switches_it_on(self):
g = self.guest()
self.assertFalse(g.get("/api/me/computers").json()["enabled"])
self.assertEqual(g.post("/api/me/computers", headers={"Origin": GUEST_HOST})
.status_code, 403)
def test_code_pairs_once_and_the_hub_names_the_worker(self):
DEPS.users.update(self.dom["id"], {"computers": {"enabled": True, "max": 1}})
g = self.guest()
r = g.post("/api/me/computers", headers={"Origin": GUEST_HOST})
self.assertEqual(r.status_code, 200, r.text)
code = r.json()["code"]
self.assertIn(f"WORKER_ENROLL={code}", r.json()["command"])
self.assertIn("WORKER_HUB=https://claude.example.test", r.json()["command"])
self.assertTrue(g.get("/api/me/computers").json()["enrolling"])
pub = TestClient(main.app, base_url=GUEST_HOST)
body = {"code": code, "pairCode": "ABCDEF2345", "hostname": "a8ed565255ed"}
e = pub.post("/worker-link/enroll", json=body)
self.assertEqual(e.status_code, 200, e.text)
wid = e.json()["workerId"]
self.assertTrue(wid.startswith("g"))
w = DEPS.worker_store.get(wid)
self.assertEqual((w["owner"], w["link"], w["pending"]), (self.dom["id"], True, True))
self.assertEqual(w["url"], link.tunnel_url(wid))
self.assertEqual(pub.post("/worker-link/enroll", json=body).status_code, 403)
# one computer max: the next code is refused
self.assertEqual(g.post("/api/me/computers", headers={"Origin": GUEST_HOST})
.status_code, 403)
# not in the owner's profiles; listed for the guest; the owner revokes it
self.assertNotIn(wid, [x["id"] for x in DEPS.profile_store._workers()])
self.assertEqual([c["id"] for c in g.get("/api/me/computers").json()["computers"]],
[wid])
self.assertEqual(self.owner.delete(f"/api/workers/{wid}", headers=OWNER_H)
.status_code, 200)
self.assertIsNone(DEPS.worker_store.get(wid))
def test_reopening_add_keeps_the_pasted_line_good(self):
# 2026-11-03: Akira opened Add twice and ran the first line.
DEPS.users.update(self.dom["id"], {"computers": {"enabled": True, "max": 1}})
g = self.guest()
h = {"Origin": GUEST_HOST}
first = g.post("/api/me/computers", headers=h).json()["code"]
second = g.post("/api/me/computers", headers=h).json()["code"]
pub = TestClient(main.app, base_url=GUEST_HOST)
chk = pub.post("/worker-link/enroll/check", json={"code": first})
self.assertEqual(chk.status_code, 200, chk.text)
self.assertTrue(chk.json()["ok"])
e = pub.post("/worker-link/enroll", json={"code": first, "pairCode": "ABCDEF2345"})
self.assertEqual(e.status_code, 200, e.text)
# the first one used retires the rest of that Add
for code in (first, second):
r = pub.post("/worker-link/enroll/check", json={"code": code})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]),
(403, "enroll_code"))
self.assertFalse(g.get("/api/me/computers").json()["enrolling"])
def test_live_codes_are_capped_per_guest(self):
DEPS.users.update(self.dom["id"], {"computers": {"enabled": True, "max": 1}})
codes = [link.ENROLL.mint(self.dom["id"])["code"] for _ in range(link.ENROLL_LIVE_MAX + 1)]
self.assertIsNone(link.ENROLL.peek(codes[0]))
self.assertTrue(all(link.ENROLL.peek(c) for c in codes[1:]))
def test_check_never_consumes_and_says_why(self):
DEPS.users.update(self.dom["id"], {"computers": {"enabled": True, "max": 1}})
code = link.ENROLL.mint(self.dom["id"])["code"]
pub = TestClient(main.app, base_url=GUEST_HOST)
for _ in range(2):
self.assertEqual(pub.post("/worker-link/enroll/check", json={"code": code})
.status_code, 200)
self.computer() # the one computer allowed is already there
r = pub.post("/worker-link/enroll", json={"code": code, "pairCode": "ABCDEF2345"})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "enroll_refused"))
self.assertIsNotNone(link.ENROLL.peek(code)) # a refusal leaves it unused
r = pub.post("/worker-link/enroll/check", json={"code": "NOPE" * 4})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "enroll_code"))
def test_enroll_counts_again_with_the_code_in_hand(self):
"""Two installers finishing at once both passed the first check
before either computer existed: the count is read again, under a
lock, right before the record is made."""
DEPS.users.update(self.dom["id"], {"computers": {"enabled": True, "max": 1}})
code = link.ENROLL.mint(self.dom["id"])["code"]
vet = link._vet
self.addCleanup(setattr, link, "_vet", vet)
def stale_vet(request, c):
out = vet(request, c) # passes: no computer yet…
self.computer() # …and a concurrent enroll lands one
return out
link._vet = stale_vet
pub = TestClient(main.app, base_url=GUEST_HOST)
before = len(DEPS.worker_store.list())
r = pub.post("/worker-link/enroll", json={"code": code, "pairCode": "ABCDEF2345"})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (403, "enroll_refused"))
self.assertEqual(len(DEPS.worker_store.list()), before + 1) # only the other one
def test_guests_hear_the_bare_workers_ping(self):
from core.routes import _guest_filter
from users.caller import guest_from_record
flt = _guest_filter(DEPS, guest_from_record(DEPS.users.get(self.dom["id"])))
self.assertEqual(flt({"type": "workers"}), {"type": "workers"})
self.assertIsNone(flt({"type": "workers", "id": "mac"}))
def test_a_guest_cant_touch_another_guests_computer(self):
self.computer("gclaire", owner="claire")
g = self.guest()
h = {"Origin": GUEST_HOST}
self.assertEqual(g.delete("/api/me/computers/gclaire", headers=h).status_code, 404)
self.assertEqual(g.patch("/api/me/computers/gclaire", json={"name": "x"},
headers=h).status_code, 404)
class Rotation(Base):
def test_tokens_rotate_and_the_old_ones_work_for_an_hour(self):
from workers import store as store_mod
sent = []
orig = store_mod.sidecar_request
store_mod.sidecar_request = lambda url, tok, path, payload, **kw: (
sent.append((path, payload)) or {"ok": True})
self.addCleanup(setattr, store_mod, "sidecar_request", orig)
w = self.computer()
now = time.time()
self.assertFalse(guests.maybe_rotate(DEPS.worker_store, w, 7, now)) # dated only
w = DEPS.worker_store.get("gmac")
self.assertFalse(guests.maybe_rotate(DEPS.worker_store, w, 7, now + 86400))
self.assertTrue(guests.maybe_rotate(DEPS.worker_store, w, 7, now + 8 * 86400))
new = DEPS.worker_store.get("gmac")
self.assertEqual(sent[0][0], "/link/token")
self.assertEqual(new["linkToken"], sent[0][1]["token"])
self.assertNotEqual(new["proxyToken"], PTOK)
self.assertEqual(new["proxyTokenPrev"], PTOK)
# (prevTokensUntil is an hour after the simulated rotation, 8 days out)
self.assertTrue(guests.token_matches(new, "proxyToken", PTOK))
self.assertTrue(guests.token_matches(new, "linkToken", "L" * 43))
DEPS.worker_store.patch("gmac", {"prevTokensUntil": "2000-01-01T00:00:00Z"})
self.assertFalse(guests.token_matches(DEPS.worker_store.get("gmac"),
"proxyToken", PTOK))
class Tokens(Base):
def test_a_stale_record_never_mints_a_second_token(self):
w = self.computer(proxyToken=None)
first = service.ensure_token(DEPS.worker_store, w)["proxyToken"]
again = service.ensure_token(DEPS.worker_store, w)["proxyToken"] # same stale w
self.assertEqual(first, again)
self.assertEqual(DEPS.worker_store.get("gmac")["proxyToken"], first)
class Quota(Base):
def test_mirror_quota_per_computer(self):
w = self.computer()
q = guests.MirrorQuota(TMP / "quota")
orig = guests.MIRROR
guests.MIRROR = q
self.addCleanup(setattr, guests, "MIRROR", orig)
DEPS.users.set_defaults({"computerLimits": {"mirrorMb": 10}})
self.addCleanup(DEPS.users.set_defaults, {"computerLimits": {"mirrorMb": 500}})
self.assertTrue(guests.mirror_ok(DEPS, w))
q.add("gmac", 11 * 1024 * 1024)
self.assertFalse(guests.mirror_ok(DEPS, w))
self.assertTrue(guests.mirror_ok(DEPS, {"id": "mac"})) # not a guest's
# ── the relay ────────────────────────────────────────────────────────────────
class Relay(Base):
def test_call_poll_reply_round_trip(self):
async def go():
hub = link.LinkHub()
self.assertEqual((await hub.call("w", "GET", "/health", {}, b""))[0], 502)
poller = asyncio.ensure_future(hub.poll("w", wait=2))
await asyncio.sleep(0)
call = asyncio.ensure_future(hub.call("w", "POST", "/spawn?x=1",
{"authorization": "Bearer t"}, b"{}"))
reqs = await poller
self.assertEqual([r["path"] for r in reqs], ["/spawn?x=1"])
big = b"x" * (link.INLINE_MAX + 1)
self.assertTrue(hub.reply("w", reqs[0]["id"], 201, {"x-feed-size": "3"}, b"abc"))
self.assertEqual(await call, (201, {"x-feed-size": "3"}, b"abc"))
# a big body is fetched, and only by its own worker
poller = asyncio.ensure_future(hub.poll("w", wait=2))
await asyncio.sleep(0)
call = asyncio.ensure_future(hub.call("w", "PUT", "/uploads/b/f", {}, big))
r = (await poller)[0]
self.assertNotIn("body", r)
self.assertEqual(hub.body("w", r["id"]), big)
self.assertIsNone(hub.body("other", r["id"]))
self.assertFalse(hub.reply("other", r["id"], 200, {}, b""))
hub.reply("w", r["id"], 200, {}, b"ok")
self.assertEqual((await call)[2], b"ok")
asyncio.run(go())
def test_tunnel_is_loopback_only(self):
self.computer()
r = TestClient(main.app, base_url=GUEST_HOST).get("/_tunnel/gmac/health")
self.assertEqual(r.status_code, 404)
def test_poll_needs_a_link_token(self):
pub = TestClient(main.app, base_url=GUEST_HOST)
self.assertEqual(pub.post("/worker-link/poll", headers={
"Authorization": "Bearer nope"}).status_code, 401)
# ── an owner's machine that dials out (Pair a worker → It dials out) ─────────
class OwnerDialOut(Base):
"""An Orus devbox: on the company's tailnet only, so the hub can't call
it — it enrolls through the link with an owner code and becomes one of
the owner's workers, on its own login, in the profile the dialog picked."""
def enroll(self, **body):
r = self.owner.post("/api/workers/enroll", headers=OWNER_H, json={
"account": "work", "cwd": "~/src/orus-monorepo", "profile": "work",
"name": "Orus devbox", **body})
self.assertEqual(r.status_code, 200, r.text)
return r.json()
def test_the_line_carries_the_answers(self):
out = self.enroll()
cmd = out["command"]
for part in ("WORKER_HUB=https://claude.example.test", f"WORKER_ENROLL={out['code']}",
"WORKER_ACCOUNT=work", "WORKER_CWD='~/src/orus-monorepo'",
"WORKER_OPENCODE=0", "worker/install.sh"):
self.assertIn(part, cmd)
bad = self.owner.post("/api/workers/enroll", headers=OWNER_H, json={"account": "nope"})
self.assertEqual((bad.status_code, bad.json()["detail"]["kind"]), (400, "account"))
def test_guests_cannot_mint_one(self):
r = self.guest().post("/api/workers/enroll", headers={"Origin": GUEST_HOST},
json={"account": "work"})
self.assertEqual(r.status_code, 403)
def test_it_enrolls_as_an_owner_worker_and_joins_the_profile(self):
code = self.enroll(default=True)["code"]
pub = TestClient(main.app, base_url=GUEST_HOST)
chk = pub.post("/worker-link/enroll/check", json={"code": code})
self.assertEqual(chk.status_code, 200, chk.text)
self.assertEqual((chk.json()["owner"], chk.json()["account"]), (True, "work"))
e = pub.post("/worker-link/enroll", json={"code": code, "pairCode": "ABCDEF2345",
"hostname": "devbox-gabriel",
"platform": "linux"})
self.assertEqual(e.status_code, 200, e.text)
self.assertTrue(e.json()["owner"])
wid = e.json()["workerId"]
self.assertTrue(wid.startswith("w"))
self.addCleanup(DEPS.profile_store.forget_worker, wid)
w = DEPS.worker_store.get(wid)
self.assertIsNone(w.get("owner"))
self.assertEqual((w["link"], w["pending"], w["claudeMode"], w["account"], w["name"]),
(True, True, "own", "work", "Orus devbox"))
self.assertEqual(w["url"], link.tunnel_url(wid))
self.assertNotIn("enrollProfile", DEPS.worker_store.public(w))
self.assertEqual(pub.post("/worker-link/enroll", json={"code": code,
"pairCode": "X" * 10})
.status_code, 403) # once
# its owner's, not a guest's: no guest listing, no guest limits
self.assertNotIn(wid, [c["id"] for c in self.guest().get("/api/me/computers")
.json().get("computers", [])])
# the pairing came through the link: it joins Work, as its default
DEPS.worker_store.patch(wid, {"pending": False, "token": "bearer"})
link.on_paired(DEPS, DEPS.worker_store.get(wid))
work = DEPS.profile_store.get("work")
self.assertEqual(work["workers"][0]["id"], wid) # first = its default runner
self.assertIsNone(DEPS.worker_store.get(wid).get("enrollProfile"))
def test_it_stays_on_its_own_login(self):
w = self.computer("wdevbox", owner=None, claudeMode="own", account="work")
DEPS.worker_store.patch("wdevbox", {"owner": None})
for body in ({"claudeMode": "proxy"}, {"claudeAccounts": ["work"]}):
r = self.owner.patch("/api/workers/wdevbox", headers=OWNER_H, json=body)
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (400, "worker_link"), body)
r = self.owner.patch("/api/workers/wdevbox", headers=OWNER_H, json={"name": "devbox"})
self.assertEqual(r.status_code, 200, r.text)
self.assertTrue(w["link"])
def test_its_link_token_rotates_too(self):
from workers import store as store_mod
orig = store_mod.sidecar_request
store_mod.sidecar_request = lambda *a, **kw: {"ok": True}
self.addCleanup(setattr, store_mod, "sidecar_request", orig)
self.computer("wdevbox", claudeMode="own", account="work")
DEPS.worker_store.patch("wdevbox", {"owner": None})
w = DEPS.worker_store.get("wdevbox")
now = time.time()
guests.maybe_rotate(DEPS.worker_store, w, 7, now) # dated
w = DEPS.worker_store.get("wdevbox")
self.assertTrue(guests.maybe_rotate(DEPS.worker_store, w, 7, now + 8 * 86400))
self.assertNotEqual(DEPS.worker_store.get("wdevbox")["linkToken"], "L" * 43)
# ── the proxy on a guest computer ────────────────────────────────────────────
class Proxy(Base):
def setUp(self):
super().setUp()
self.seen = []
self.computer()
DEPS.worker_store.put({"id": "mac", "name": "Mac", "url": "http://mac:8790",
"token": "b", "claudeMode": "proxy",
"claudeAccounts": ["personal"], "proxyToken": "o" * 43})
service.TOKENS._fetch = lambda account, refresh=False: {
"accessToken": "oat", "expiresAt": 9_999_999_999_000}
service.TOKENS.forget()
def upstream(req):
self.seen.append(req)
return httpx.Response(200, headers={"content-type": "text/event-stream"},
stream=httpx.ByteStream(_sse()))
proxy_routes._client = httpx.AsyncClient(transport=httpx.MockTransport(upstream))
DEPS.usage_poller.latest.clear()
DEPS.usage_poller._observed.clear()
def call(self, model="claude-sonnet-5-5", account="personal", token=PTOK,
path="v1/messages", host=GUEST_HOST):
return TestClient(main.app, base_url=host).post(
f"/proxy/claude/{account}/{path}", headers={"Authorization": f"Bearer {token}"},
content=json.dumps({"model": model}))
def test_meters_into_the_guest_ledger(self):
r = self.call()
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.seen[0].headers["accept-encoding"], "identity")
self.assertGreater(limits.LEDGER.spent("guest", self.dom["id"]), 0)
self.assertEqual(limits.inflight("gmac"), 0)
def test_the_public_host_takes_guest_computers_only(self):
self.assertEqual(self.call(token="o" * 43).status_code, 401)
self.assertEqual(self.call(token="o" * 43, host="https://ai-agent.example.test")
.status_code, 200)
def test_refusals(self):
self.assertEqual(self.call(account="work").status_code, 403) # owner's default only
r = self.call(model="claude-opus-5-5")
self.assertEqual((r.status_code, r.json()["error"]["type"]), (403, "permission_error"))
DEPS.usage_poller._observed["personal"] = {
"updatedAt": time.time(), "windows": {"five_hour": {"pct": 81}}}
self.assertEqual(self.call().status_code, 429)
DEPS.usage_poller._observed.clear()
DEPS.users.update(self.dom["id"], {"budgetUsd": 1})
limits.LEDGER.record({"t": time.time(), "worker": "gmac", "guest": self.dom["id"],
"account": "personal", "usd": 1.2})
r = self.call()
self.assertEqual(r.status_code, 429)
self.assertIn("budget", r.json()["error"]["message"])
DEPS.users.update(self.dom["id"], {"budgetUsd": 100, "disabled": True})
self.assertEqual(self.call().status_code, 403)
self.assertEqual(self.seen, [])
def test_guest_hardening(self):
self.assertEqual(self.call(path="v1/models").status_code, 404)
self.assertEqual(self.call(path="v1/messages/batches").status_code, 404)
r = TestClient(main.app, base_url=GUEST_HOST).post(
"/proxy/claude/personal/v1/messages",
headers={"Authorization": f"Bearer {PTOK}",
"anthropic-beta": "oauth-2025-04-20,context-1m-2025-08-07"},
content=json.dumps({"model": "claude-sonnet-5-5"}))
self.assertEqual(r.status_code, 403)
r = TestClient(main.app, base_url=GUEST_HOST).post(
"/proxy/claude/personal/v1/messages", headers={"Authorization": f"Bearer {PTOK}"},
content=json.dumps({"model": "claude-sonnet-5-5", "speed": "fast"}))
self.assertEqual(r.status_code, 403)
DEPS.worker_store.patch("gmac", {"paused": True})
self.assertEqual(self.call().status_code, 403)
DEPS.worker_store.patch("gmac", {"paused": False})
self.assertEqual(self.seen, [])
# the owner's own workers keep every path
self.assertEqual(self.call(token="o" * 43, path="v1/models",
host="https://ai-agent.example.test").status_code, 200)
def test_per_minute_cap(self):
limits.PER_MINUTE._hits.clear()
DEPS.users.set_defaults({"computerLimits": {"perMinute": 2}})
self.addCleanup(DEPS.users.set_defaults, {"computerLimits": {"perMinute": 60}})
self.assertEqual([self.call().status_code for _ in range(3)], [200, 200, 429])
def test_bad_tokens_lock_the_address(self):
guests.BAD.__init__()
for _ in range(guests.BadTokens.LIMIT):
self.assertEqual(self.call(token="x" * 43).status_code, 401)
r = self.call() # even a good token now
self.assertEqual(r.status_code, 429)
guests.BAD.__init__()
self.assertEqual(self.call().status_code, 200)
def test_in_flight_cap(self):
lim = DEPS.users.defaults()["computerLimits"]["inFlight"]
for _ in range(lim):
limits.enter("gmac")
try:
self.assertEqual(self.call().status_code, 429)
finally:
for _ in range(lim):
limits.leave("gmac")
def test_config_points_at_the_public_host_and_writes_no_default(self):
d = service.desired(DEPS.worker_store, DEPS.worker_store.get("gmac"))
self.assertEqual(d["url"], "https://claude.example.test/proxy/claude")
self.assertEqual((d["accounts"], d["default"]), (["personal"], None))
# ── where its runs go ────────────────────────────────────────────────────────
class Routing(Base):
def _capture(self):
calls = []
orig = run_routes._send_message
run_routes._send_message = lambda deps, prompt, **kw: (
calls.append((prompt, kw)) or {"sessionId": "new", "pid": 1})
self.addCleanup(setattr, run_routes, "_send_message", orig)
return calls
def test_a_guest_runs_on_their_computer(self):
calls = self._capture()
self.computer(cwd="/Users/dom/work")
r = self.guest().post("/api/spawn", headers={"Origin": GUEST_HOST}, json={
"prompt": "hello", "worker": "gmac", "model": "sonnet"})
self.assertEqual(r.status_code, 200, r.text)
_, kw = calls[0]
self.assertEqual((kw["worker"], kw["account"]), ("gmac", "personal"))
self.assertEqual(kw["stamp"], {"owner": self.dom["id"], "projects": []})
# confined to its start folder, told whose machine it is on
self.assertEqual(kw["scope"]["writeDirs"], ["/Users/dom/work", "/tmp"])
self.assertIn("own computer", kw["scope"]["systemPrompt"])
self.assertIs(kw["scope"]["remoteControl"], False)
r = self.guest().post("/api/spawn", headers={"Origin": GUEST_HOST}, json={
"prompt": "hello", "worker": "gmac", "model": "opus"})
self.assertEqual(r.status_code, 403)
DEPS.worker_store.patch("gmac", {"paused": True})
r = self.guest().post("/api/spawn", headers={"Origin": GUEST_HOST}, json={
"prompt": "hello", "worker": "gmac"})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (409, "computer_paused"))
def test_a_guest_runs_in_one_of_their_computers_projects(self):
from projects import worker_projects
calls = self._capture()
self.computer(cwd="/Users/dom/work")
reg = worker_projects.Registry()
reg.projects = {
"far-waste@gmac": {"slug": "far-waste@gmac", "name": "far-waste",
"path": "/Users/dom/PROJETS/far-waste", "worker": "gmac"},
"other@omac": {"slug": "other@omac", "name": "other",
"path": "/Users/x/other", "worker": "omac"},
}
orig = worker_projects.registry
worker_projects.registry = lambda deps: reg
self.addCleanup(setattr, worker_projects, "registry", orig)
def spawn(projects):
return self.guest().post("/api/spawn", headers={"Origin": GUEST_HOST}, json={
"prompt": "hello", "worker": "gmac", "model": "sonnet", "projects": projects})
r = spawn(["far-waste@gmac"])
self.assertEqual(r.status_code, 200, r.text)
_, kw = calls[-1]
# starts in the project's folder, may edit there and in its start folder
self.assertEqual(kw["cwd"], "/Users/dom/PROJETS/far-waste")
self.assertEqual(kw["stamp"], {"owner": self.dom["id"], "projects": ["far-waste@gmac"]})
self.assertEqual(kw["scope"]["writeDirs"],
["/Users/dom/PROJETS/far-waste", "/Users/dom/work", "/tmp"])
# another machine's project, a lab project, an unknown one: refused
for bad in (["other@omac"], ["bffr"], ["gone@gmac"]):
r = spawn(bad)
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (400, "guest_project"), bad)
# none: the start folder, as before
r = spawn([])
self.assertEqual(r.status_code, 200, r.text)
self.assertIsNone(calls[-1][1]["cwd"])
# a turn in a session started there keeps the project's folder writable
DEPS.meta_store.update("s-p", {"worker": "gmac", "owner": self.dom["id"],
"projects": ["far-waste@gmac"]})
from users import runs as guest_runs
from users.caller import guest_from_record
dom = guest_from_record(DEPS.users.get(self.dom["id"]))
w = DEPS.worker_store.get("gmac")
self.assertEqual(guest_runs.session_computer_project(DEPS, dom, w, "s-p"),
"/Users/dom/PROJETS/far-waste")
DEPS.meta_store.update("s-q", {"worker": "gmac", "projects": ["gone@gmac"]})
self.assertIsNone(guest_runs.session_computer_project(DEPS, dom, w, "s-q"))
def test_a_start_on_their_computer_pings_nobody(self):
# their machine, their business: no "Dom started a conversation"
# push to the owner (a lab start still pings — test_guests)
self._capture()
pings = []
orig_ping, orig_notify = run_routes.deliver.owner_ping_start, notify_service._create_notify
run_routes.deliver.owner_ping_start = lambda *a, **kw: pings.append(a)
notify_service._create_notify = lambda deps, d, *a, **kw: pings.append(d)
self.addCleanup(setattr, run_routes.deliver, "owner_ping_start", orig_ping)
self.addCleanup(setattr, notify_service, "_create_notify", orig_notify)
self.computer(cwd="/Users/dom/work")
r = self.guest().post("/api/spawn", headers={"Origin": GUEST_HOST}, json={
"prompt": "hello", "worker": "gmac", "model": "sonnet"})
self.assertEqual((r.status_code, pings), (200, []), r.text)
def test_the_guest_may_stop_and_continue_on_their_computer(self):
from users import access
from users.caller import guest_from_record
self.computer()
DEPS.meta_store.update("s-2", {"worker": "gmac", "owner": self.dom["id"]})
dom = guest_from_record(DEPS.users.get(self.dom["id"]))
self.assertTrue(access.can_send(DEPS, dom, "s-2"))
DEPS.worker_store.delete("gmac") # removed: no project to fall back on
self.assertFalse(access.can_send(DEPS, dom, "s-2"))
def test_nobody_else_runs_there(self):
from fastapi import HTTPException
from runs.service import route_new_run
self.computer()
with self.assertRaises(HTTPException) as e:
route_new_run(DEPS, "claude", None, "gmac") # the owner
self.assertEqual(e.exception.status_code, 403)
with self.assertRaises(HTTPException):
route_new_run(DEPS, "claude", None, "gmac", guest="claire")
sid = "0c6f8c1e-3c1a-4c8e-9a52-0d5b1d2f0a11"
DEPS.meta_store.update(sid, {"worker": "gmac", "owner": self.dom["id"]})
r = self.owner.post("/api/resume", headers=OWNER_H,
json={"sessionId": sid, "prompt": "hi"})
self.assertEqual(r.status_code, 403)
# ── their own Claude on their own computer (users/runs.run_on_computer) ─────
class OwnClaude(Routing):
def setUp(self):
super().setUp()
from users import runs as guest_runs
guest_runs._hold_scanned.clear()
self.computer(cwd="/home/dom/work")
self.own = f"guest-{self.dom['id']}"
def signed_in(self, plan="pro"):
DEPS.worker_store.set_status("gmac", ownLogin={
"signedIn": True, "subscriptionType": plan,
"credentialsAt": "2026-11-01T00:00:00Z"})
def spawn(self, **kw):
return self.guest().post("/api/spawn", headers={"Origin": GUEST_HOST},
json={"prompt": "hello", "worker": "gmac", **kw})
def test_their_own_account_reaches_the_computer(self):
# 2026-11-10: the hub's _sidecar_call dropped any account the worker
# doesn't proxy — guest-<uid> included — so the computer ran its
# default, the proxied `personal`, under a card saying "his own
# Claude". Through the real send path down to the HTTP call.
import workers as workers_mod
from runs import service as run_service
sent = []
orig = workers_mod.sidecar_request
workers_mod.sidecar_request = lambda base, token, path, payload=None, **kw: (
sent.append((path, payload)) or {"pid": 1})
self.addCleanup(setattr, workers_mod, "sidecar_request", orig)
orig_extras = run_service._extras
run_service._extras = lambda *a, **k: {}
self.addCleanup(setattr, run_service, "_extras", orig_extras)
DEPS.worker_store.set_status("gmac", status="online",
claudeProxy={"accounts": ["personal"]})
self.signed_in()
r = self.spawn(model="opus")
self.assertEqual((r.status_code, r.json()["account"]), (200, self.own), r.text)
path, payload = sent[-1]
self.assertEqual((path, payload.get("account")), ("/spawn", self.own))
sid = r.json()["sessionId"]
r = self.guest().post("/api/resume", headers={"Origin": GUEST_HOST},
json={"sessionId": sid, "prompt": "more", "now": True})
self.assertEqual(r.status_code, 200, r.text)
resumed = [p for path, p in sent if path == "/resume"]
self.assertEqual(resumed[-1].get("account"), self.own)
# someone else's guest id is still dropped (the computer's default)
from runs.sidecar_client import _own_login
w = DEPS.worker_store.get("gmac")
self.assertTrue(_own_login(w, self.own))
self.assertFalse(_own_login(w, "guest-claire"))
self.assertFalse(_own_login(DEPS.worker_store.get("mac") or {}, self.own))
def test_signed_in_there_it_bills_their_own_claude(self):
calls = self._capture()
self.signed_in()
r = self.spawn(model="opus") # not one of theirs on the host's account
self.assertEqual((r.status_code, r.json()["account"]), (200, self.own), r.text)
_, kw = calls[0]
self.assertEqual((kw["account"], kw["model"], kw["worker"]), (self.own, "opus", "gmac"))
self.assertNotIn("maxBudgetUsd", kw["scope"]) # their plan: no budget
self.assertEqual(kw["scope"]["writeDirs"], ["/home/dom/work", "/tmp"])
listing = self.guest().get("/api/me/computers").json()["computers"][0]
self.assertEqual(listing["ownClaude"], {"signedIn": True, "subscriptionType": "pro",
"usable": True, "hold": None})
def test_not_signed_in_or_host_picked_it_stays_on_the_hosts(self):
calls = self._capture()
self.assertEqual(self.spawn(model="sonnet").json()["account"], "personal")
self.assertEqual(self.spawn(model="opus").status_code, 403) # their models apply
self.signed_in()
self.assertEqual(self.guest().put("/api/me/claude/bill", headers={"Origin": GUEST_HOST},
json={"bill": "host"}).status_code, 200)
self.assertEqual(self.spawn(model="sonnet").json()["account"], "personal")
self.assertEqual([kw["account"] for _, kw in calls], ["personal", "personal"])
def test_a_refused_own_launch_falls_back_to_the_hosts(self):
from fastapi import HTTPException
calls = []
orig = run_routes._send_message
def fake(deps, prompt, **kw):
calls.append(kw)
if kw["account"] != "personal":
raise HTTPException(409, {"message": "not signed in", "kind": "auth"})
return {"sessionId": "new", "pid": 1}
run_routes._send_message = fake
self.addCleanup(setattr, run_routes, "_send_message", orig)
self.signed_in()
r = self.spawn(model="opus")
self.assertEqual((r.status_code, r.json()["account"]), (200, "personal"), r.text)
# the model swapped for one they may use there
self.assertEqual([(c["account"], c["model"]) for c in calls],
[(self.own, "opus"), ("personal", "sonnet")])
def test_a_usage_limit_there_holds_their_claude_for_a_while(self):
calls = self._capture()
self.signed_in()
sid = "1d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
DEPS.meta_store.update(sid, {"worker": "gmac", "owner": self.dom["id"],
"account": self.own})
at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 600))
summ = [("/x.jsonl", {"sessionId": sid,
"lastApiError": {"kind": "rate_limit", "at": at}})]
orig = DEPS.store.all_summaries
DEPS.store.all_summaries = lambda: summ
self.addCleanup(setattr, DEPS.store, "all_summaries", orig)
self.assertEqual(self.spawn(model="sonnet").json()["account"], "personal")
# a host turn in that session answered (the error left the transcript,
# the account moved): the hold stays
summ.clear()
DEPS.meta_store.update(sid, {"account": "personal"})
self.assertEqual(self.spawn(model="sonnet").json()["account"], "personal")
own = self.guest().get("/api/me/computers").json()["computers"][0]["ownClaude"]
self.assertEqual((own["usable"], own["hold"]), (False, "limited"))
DEPS.worker_store.set_status("gmac", ownHold={"rate_limit": time.time() - 6 * 3600})
self.assertEqual(self.spawn(model="sonnet").json()["account"], self.own)
self.assertEqual([kw["account"] for _, kw in calls], ["personal", "personal", self.own])
def test_a_dead_login_there_holds_until_the_computer_signs_in_again(self):
self._capture()
self.signed_in()
DEPS.worker_store.set_status("gmac", ownHold={"auth": time.time() - 60})
self.assertEqual(self.spawn(model="sonnet").json()["account"], "personal")
DEPS.worker_store.set_status("gmac", ownLogin={
"signedIn": True, "subscriptionType": "pro",
"credentialsAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
self.assertEqual(self.spawn(model="sonnet").json()["account"], self.own)
def test_a_turn_there_bills_their_own_claude_too(self):
calls = self._capture()
self.signed_in()
sid = "2d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
DEPS.meta_store.update(sid, {"worker": "gmac", "owner": self.dom["id"]})
r = self.guest().post("/api/resume", headers={"Origin": GUEST_HOST},
json={"sessionId": sid, "prompt": "more"})
self.assertEqual((r.status_code, r.json()["account"]), (200, self.own), r.text)
self.assertEqual(calls[0][1]["resume_account"], self.own)
def test_an_app_run_is_never_claimed_as_a_terminal_session(self):
from runs import service as run_service
sid_box = {}
DEPS.worker_store.set_status("gmac", status="online")
def launch(deps, account, path, payload, worker=None):
# the CLI's first proxied call beats the spawn's meta stamp
sid_box["sid"] = payload["sessionId"]
terminal.claim(DEPS, DEPS.worker_store.get("gmac"), payload["sessionId"], "proxy")
return {"pid": 1}
for name, fn in (("_launch", launch), ("_extras", lambda *a, **k: {})):
orig = getattr(run_service, name)
setattr(run_service, name, fn)
self.addCleanup(setattr, run_service, name, orig)
terminal.forget()
r = self.spawn(model="sonnet")
self.assertEqual(r.status_code, 200, r.text)
m = DEPS.meta_store.peek(sid_box["sid"])
self.assertEqual(m.get("worker"), "gmac")
self.assertNotIn("terminal", m)
# …and on their own Claude, through the real routing: the computer
# holds its owner's own login (profiles/runners.holds), nobody else's
self.signed_in()
r = self.spawn(model="opus")
self.assertEqual((r.status_code, r.json()["account"]), (200, self.own), r.text)
m = DEPS.meta_store.peek(sid_box["sid"])
self.assertEqual((m["account"], m["worker"], m["owner"]), (self.own, "gmac", self.dom["id"]))
from profiles import runners
self.assertFalse(runners.holds(DEPS, "gmac", "guest-claire", "claude"))
# ── the computer's own terminal sessions (workers/terminal.py) ───────────────
SID = "7d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
class TerminalSessions(Proxy):
def setUp(self):
super().setUp()
terminal.forget()
def tcall(self, sid=SID):
return TestClient(main.app, base_url=GUEST_HOST).post(
"/proxy/claude/personal/v1/messages",
headers={"Authorization": f"Bearer {PTOK}", "X-Claude-Code-Session-Id": sid},
content=json.dumps({"model": "claude-sonnet-5-5"}))
def test_ai_agent_claude_claims_the_session_on_its_first_call(self):
w = DEPS.worker_store.get("gmac")
self.assertFalse(guests.may_mirror(DEPS, w, f"-home-dom/{SID}.jsonl"))
self.assertEqual(self.tcall().status_code, 200)
m = DEPS.meta_store.peek(SID)
self.assertEqual((m["workerSource"], m["owner"], m["terminal"]),
("gmac", self.dom["id"], "proxy"))
self.assertTrue(guests.may_mirror(DEPS, w, f"-home-dom/{SID}.jsonl"))
row = json.loads((TMP / "ledger").glob("*.jsonl").__next__().read_text()
.splitlines()[-1])
self.assertEqual(row["session"], SID)
def test_a_session_known_elsewhere_is_never_claimed(self):
other = "8d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
DEPS.meta_store.update(SID, {"workerSource": "mac"})
DEPS.meta_store.update(other, {"owner": "claire"})
for sid in (SID, other):
self.assertEqual(self.tcall(sid).status_code, 200) # the call still runs
self.assertNotEqual(DEPS.meta_store.peek(sid).get("workerSource"), "gmac")
# an owner session nothing in its meta places: its transcript does
lab = "9d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
(TMP / "t" / "-home-gabriel").mkdir(parents=True, exist_ok=True)
(TMP / "t" / "-home-gabriel" / f"{lab}.jsonl").write_text("{}\n")
self.tcall(lab)
self.assertEqual(DEPS.meta_store.peek(lab), {})
# …and one launched a moment ago has no transcript yet, only the
# launch stamp: known to the hub, not this computer's — never claimed
fresh = "ab1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
DEPS.meta_store.update(fresh, {"state": "running", "runAs": "owner"})
self.assertEqual(self.tcall(fresh).status_code, 200)
self.assertFalse(terminal.claim(DEPS, DEPS.worker_store.get("gmac"), fresh, "proxy"))
self.assertIsNone(DEPS.meta_store.peek(fresh).get("workerSource"))
self.assertIsNone(DEPS.meta_store.peek(fresh).get("owner"))
self.assertFalse(terminal.claim(DEPS, DEPS.worker_store.get("mac"), SID, "proxy"))
def test_an_own_login_run_reaching_the_proxy_is_restamped_as_the_hosts(self):
# Akira, 2026-11: runs routed to his own Pro still came through the
# proxy (a settings file on his computer held its pair) — the cards
# said "his own Claude" while the host's plan paid.
from claudeproxy import routes as proxy_routes
from notifications import service as notif
pushes = []
orig = notif._create_notify
notif._create_notify = lambda deps, body: pushes.append(body)
self.addCleanup(setattr, notif, "_create_notify", orig)
proxy_routes._pushed_leak.clear()
own = f"guest-{self.dom['id']}"
DEPS.worker_store.set_status("gmac", ownLogin={"signedIn": True, "override": [
{"source": "user", "path": "/home/dom/.claude/settings.json",
"keys": ["ANTHROPIC_BASE_URL"]}]})
DEPS.meta_store.update(SID, {"worker": "gmac", "owner": self.dom["id"], "account": own})
self.assertEqual(self.tcall().status_code, 200) # never refused
m = DEPS.meta_store.peek(SID)
self.assertEqual((m["account"], m["ownLoginLeak"]), ("personal", True))
self.assertNotIn("terminal", m) # still the app's run
self.assertEqual(len(pushes), 1)
self.assertIn("/home/dom/.claude/settings.json", pushes[0]["message"])
# its next turn, stamped their own again, leaks again: restamped, no 2nd push today
DEPS.meta_store.update(SID, {"account": own})
self.tcall()
self.assertEqual(DEPS.meta_store.peek(SID)["account"], "personal")
self.assertEqual(len(pushes), 1)
# a later stamp back to their own (its calls beat it) still counts as the host's
from users.runs import spend_by_user
DEPS.meta_store.update(SID, {"account": own})
card = {"meta": DEPS.meta_store.peek(SID), "cost": 3, "endedAt": "2099-01-01"}
s = spend_by_user([card])[self.dom["id"]]
self.assertEqual((s["ownMonth"], s["machineMonth"]), (0, 3))
# a run already on the host's account, or someone else's session: untouched
other = "6d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d"
DEPS.meta_store.update(other, {"worker": "gmac", "owner": self.dom["id"],
"account": "personal"})
self.tcall(other)
self.assertNotIn("ownLoginLeak", DEPS.meta_store.peek(other))
def test_a_synced_session_keeps_its_own_login_until_it_uses_the_proxy(self):
from core.state import _record_worker_files
w = DEPS.worker_store.get("gmac")
terminal.claim_synced(DEPS, w, [SID, "nope", 3])
m = DEPS.meta_store.peek(SID)
self.assertEqual((m["terminal"], m["accountSource"]), ("local", f"guest-{self.dom['id']}"))
_record_worker_files(DEPS, w, [f"-home-dom/{SID}.jsonl"])
self.assertEqual(DEPS.meta_store.peek(SID)["accountSource"], f"guest-{self.dom['id']}")
self.tcall() # resumed on ai-agent Claude
self.assertEqual(DEPS.meta_store.peek(SID)["terminal"], "proxy")
_record_worker_files(DEPS, w, [f"-home-dom/{SID}.jsonl"])
self.assertEqual(DEPS.meta_store.peek(SID)["accountSource"], "personal")
def test_stop_syncing_keeps_the_copy_and_takes_no_more(self):
w = DEPS.worker_store.get("gmac")
terminal.claim_synced(DEPS, w, [SID])
rel = f"-home-dom/{SID}.jsonl"
DEPS.feed_mirror._synced["gmac"] = {SID}
self.assertTrue(guests.may_mirror(DEPS, w, rel))
DEPS.feed_mirror._synced["gmac"] = set() # unsynced on the computer
self.assertFalse(guests.may_mirror(DEPS, w, rel))
self.assertEqual(DEPS.meta_store.peek(SID)["workerSource"], "gmac") # kept
self.tcall() # resumed on ai-agent Claude
self.assertTrue(guests.may_mirror(DEPS, w, rel))
DEPS.feed_mirror._synced.clear()
def test_the_figures_are_pushed_when_they_change(self):
from workers import store as wstore
sent = []
orig = wstore.sidecar_request
wstore.sidecar_request = lambda *a, **k: sent.append((a, k)) or {}
try:
DEPS.users.update(self.dom["id"], {"budgetUsd": 10})
w = DEPS.worker_store.get("gmac")
DEPS.worker_store.set_status("gmac", status="online")
d = terminal.desired_status(DEPS, w)
self.assertEqual((d["leftUsd"], d["paused"], d["computer"]), (10.0, False, "Mac mini"))
self.assertTrue(terminal.maybe_push_status(DEPS, w, {"statusHash": None}))
self.assertEqual(sent[0][0][2], "/terminal/status")
self.assertFalse(terminal.maybe_push_status(DEPS, w, {"statusHash": None})) # retry later
self.assertFalse(terminal.maybe_push_status(DEPS, w, {"statusHash": terminal.status_hash(d)}))
self.assertFalse(terminal.maybe_push_status(DEPS, w, None)) # an older sidecar
finally:
wstore.sidecar_request = orig
terminal._pushed.clear()
def test_the_portal_lists_and_syncs_the_computers_sessions(self):
from workers import store as wstore
calls = []
def fake(base, token, path, payload=None, **k):
calls.append((path, payload, k.get("method")))
if path.startswith("/terminal/sessions"):
return {"launcher": True, "sessions": [
{"id": SID, "project": "-home-dom", "title": "Fix login", "mtime": 1.0,
"synced": False},
{"id": "8d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d", "project": "-home-dom",
"title": "From the app", "mtime": 2.0}]}
return {"ok": True, "launcher": False}
orig = wstore.sidecar_request
wstore.sidecar_request = fake
try:
DEPS.worker_store.set_status("gmac", status="online")
g = self.guest()
self.assertEqual(g.get("/api/me/computers/gmac/sessions").status_code, 409) # not updated
DEPS.worker_store.set_status("gmac", terminal={"launcher": True, "synced": 0})
DEPS.meta_store.update("8d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d",
{"worker": "gmac", "owner": self.dom["id"]})
rows = g.get("/api/me/computers/gmac/sessions").json()["sessions"]
self.assertEqual([r["inApp"] for r in rows], [None, "run"])
self.assertEqual(rows[1]["conversationId"], ids.uid_for_rel(
"-home-dom/8d1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d.jsonl"))
self.assertEqual(g.post(f"/api/me/computers/gmac/sessions/{SID}/sync").json(), {"ok": True})
self.assertEqual(calls[-1][:2], ("/terminal/sync", {"sid": SID}))
# a malformed session id: refused (the handler's 400 since the gate
# checks permissions, not id shapes — authz/routes.py), never sent on
for path in ("/api/me/computers/gmac/sessions/..%2Fx/sync",
"/api/me/computers/gmac/sessions/zd1c2b3a-4e5f-4a6b-8c7d-9e0f1a2b3c4d/sync"):
n = len(calls)
self.assertIn(g.delete(path).status_code, (400, 403, 404), path)
self.assertEqual(len(calls), n, path)
r = g.patch("/api/me/computers/gmac", json={"launcher": False}).json()
self.assertIs(r["launcher"], False)
self.assertEqual(calls[-1], ("/terminal/launcher", {"on": False}, "PUT"))
other = self.computer("gother", owner="claire")
self.assertEqual(g.get(f"/api/me/computers/{other['id']}/sessions").status_code, 404)
finally:
wstore.sidecar_request = orig
def test_a_hub_run_stays_a_hub_run(self):
DEPS.meta_store.update(SID, {"worker": "gmac", "owner": self.dom["id"]})
self.tcall()
self.assertNotIn("terminal", DEPS.meta_store.peek(SID))
# ── tools installed from the Setup checklist (workers/tools.py) ──────────────
class Tools(Base):
CAPS = {"tools": ["claude", "gh"], "update": ["gh"]}
def fake(self, calls, jobs=None):
from workers import store as wstore
def f(base, token, path, payload=None, **k):
calls.append((path, payload, k.get("method", "POST")))
if path == "/tools/install":
return {"ok": True, "started": True, "pid": 7, "tools": payload["tools"],
"action": payload["action"]}
if path == "/gh/login":
if k.get("method") == "GET":
return {"state": "complete"}
return {"state": "pending", "userCode": "AB12-CD34",
"url": "https://github.com/login/device"}
return {}
orig = wstore.sidecar_request
wstore.sidecar_request = f
self.addCleanup(setattr, wstore, "sidecar_request", orig)
def test_a_guest_installs_claude_and_gh_on_their_computer(self):
calls = []
self.fake(calls)
self.computer()
g = self.guest()
DEPS.worker_store.set_status("gmac", status="online")
# a sidecar from before: no toolInstall in its /health
r = g.post("/api/me/computers/gmac/tools", json={"tools": ["gh"]})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (409, "tools_unsupported"))
DEPS.worker_store.set_status("gmac", toolInstall=self.CAPS,
tools={"gh": {"installed": False}})
r = g.post("/api/me/computers/gmac/tools", json={"tools": ["gh", "claude"]})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls[-1][:2], ("/tools/install", {"tools": ["gh", "claude"], "action": "install"}))
self.assertEqual(r.json()["toolJobs"]["gh"]["state"], "queued")
self.assertEqual(r.json()["toolInstall"], self.CAPS)
self.assertEqual(r.json()["tools"], {"gh": {"installed": False}})
# the owner's harnesses and forms are not theirs — nor pi, whose
# plugin (not guestAllowed) never reaches a guest's computer
for t in ("agy", "opencode", "ask-form", "pi"):
r = g.post("/api/me/computers/gmac/tools", json={"tools": [t]})
self.assertEqual(r.json()["detail"]["kind"], "tool_unknown", t)
r = g.post("/api/me/computers/gmac/tools", json={"tools": ["claude"], "action": "update"})
self.assertEqual(r.json()["detail"]["kind"], "not_updatable")
# French for a guest who reads French
DEPS.users.update(self.dom["id"], {"lang": "fr"})
r = self.guest().post("/api/me/computers/gmac/tools", json={"tools": ["agy"]})
self.assertIn("ne s’installe pas", r.json()["detail"]["message"])
# someone else's computer: not found
other = self.computer("gother", owner="claire")
self.assertEqual(g.post(f"/api/me/computers/{other['id']}/tools",
json={"tools": ["gh"]}).status_code, 404)
# offline
DEPS.worker_store.set_status("gmac", status="offline")
r = g.post("/api/me/computers/gmac/tools", json={"tools": ["gh"]})
self.assertEqual(r.json()["detail"]["kind"], "worker_offline")
def test_gh_sign_in_on_a_guests_computer(self):
calls = []
self.fake(calls)
self.computer()
DEPS.worker_store.set_status("gmac", status="online")
g = self.guest()
r = g.post("/api/me/computers/gmac/gh-login").json()
self.assertEqual((r["userCode"], calls[-1][:1]), ("AB12-CD34", ("/gh/login",)))
self.assertEqual(g.get("/api/me/computers/gmac/gh-login").json(), {"state": "complete"})
self.assertEqual(calls[-1][2], "GET")
def test_the_owner_installs_on_his_workers_not_on_a_guests(self):
calls = []
self.fake(calls)
self.computer()
DEPS.worker_store.set_status("gmac", status="online", toolInstall=self.CAPS)
r = self.owner.post("/api/workers/gmac/tools", headers=OWNER_H, json={"tools": ["gh"]})
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (409, "guest_computer"))
DEPS.worker_store.put({"id": "wmac", "name": "Orus Mac", "url": "http://127.0.0.1:1",
"token": "t", "account": "work"})
DEPS.worker_store.set_status("wmac", status="online", toolInstall={
"tools": ["claude", "gh", "opencode", "agy", "pi", "ask-form"], "update": ["gh", "pi"]})
r = self.owner.post("/api/workers/wmac/tools", headers=OWNER_H,
json={"tools": ["agy", "opencode", "agy"]})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls[-1][1], {"tools": ["agy", "opencode"], "action": "install"})
self.assertEqual(set(r.json()["toolJobs"]), {"agy", "opencode"})
r = self.owner.post("/api/workers/wmac/tools", headers=OWNER_H,
json={"tools": ["gh"], "action": "update"})
self.assertEqual(calls[-1][1], {"tools": ["gh"], "action": "update"})
r = self.owner.post("/api/workers/wmac/tools", headers=OWNER_H,
json={"tools": ["sh -c id"]})
self.assertEqual(r.json()["detail"]["kind"], "tool_unknown")
r = self.owner.post("/api/workers/wmac/gh-login", headers=OWNER_H).json()
self.assertEqual(r["url"], "https://github.com/login/device")
# and nobody but the owner reaches the owner's route
self.assertIn(self.guest().post("/api/workers/wmac/tools", json={"tools": ["gh"]}).status_code,
(401, 403, 404))
def test_the_probe_keeps_what_the_worker_says(self):
from workers import store as wstore
w = self.computer()
orig = wstore._get_json
health = {"ok": True, "toolInstall": self.CAPS,
"toolJobs": {"gh": {"state": "running", "action": "install", "tail": ["==> gh"]}},
"tools": {"gh": {"installed": False}}}
wstore._get_json = lambda url, token=None: health if url.endswith("/health") else {"count": 0}
self.addCleanup(setattr, wstore, "_get_json", orig)
wstore.probe(DEPS.worker_store, w)
pub = DEPS.worker_store.public(DEPS.worker_store.get("gmac"))
self.assertEqual(pub["toolJobs"]["gh"]["tail"], ["==> gh"])
self.assertEqual(pub["toolInstall"], self.CAPS)
def test_an_install_makes_the_worker_hot(self):
from workers.store import installing
now = time.time()
iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(t))
self.assertTrue(installing({"toolJobs": {"gh": {"state": "running", "startedAt": iso(now - 5)}}}, now))
self.assertTrue(installing({"toolJobs": {"gh": {"state": "queued", "startedAt": iso(now)}}}, now))
self.assertFalse(installing({"toolJobs": {"gh": {"state": "done", "startedAt": iso(now)}}}, now))
self.assertFalse(installing({"toolJobs": {"gh": {"state": "running", "startedAt": iso(now - 3600)}}}, now))
self.assertFalse(installing({"toolJobs": None}, now))
if __name__ == "__main__":
unittest.main()