Files
ai-agent/backend/test_agy.py

426 lines
21 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.
"""The agy harness (Antigravity's CLI on the Google AI Pro plan) on the hub
side: its account and plan windows, the Gemini models in the catalogue (greyed
while no machine hosts agy, never a guest's), Gemini list prices, a mirrored
transcript parsed as agy's, the feed's ``@agy/`` files, the quota read from
the lab and the workers (freshest wins), and the run routing — a run goes to a
machine that declares the account, a guest never runs agy, an agy
conversation neither switches harness nor forks.
Imports ``main`` against throwaway paths (no startup event → no threads).
``python3 -m unittest test_agy``"""
import json
import os
import pathlib
import tempfile
import time
import unittest
from unittest import mock
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",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "SIDECAR_TOKEN": "",
"PROFILES_PATH": TMP / "profiles.json",
"PI_TRANSCRIPTS_DIR": "", "AGY_TRANSCRIPTS_DIR": TMP / "agy"}.items():
os.environ.setdefault(k, str(v))
from fastapi import HTTPException # noqa: E402
import accounts # noqa: E402
import main # noqa: E402
import models # noqa: E402
import workers # noqa: E402
from accounts.routes import _account_runner # noqa: E402
from conversations.parse import parse_conversation # noqa: E402
from conversations.pricing import (book_key, norm_usage, plan_units, # noqa: E402
rates_for, usage_cost)
from core.state import _record_worker_files # noqa: E402
from models import catalog, routes as model_routes # noqa: E402
from runs.service import _send_message # noqa: E402
from usage import plans # noqa: E402
from usage.poller import UsagePoller # noqa: E402
from usage.service import _agy_snapshots # noqa: E402
from workers.remotefeed import agy_account, local_rel, opencode_account # noqa: E402
DEPS = main.app.state.ai
from _fakeworker import FakeWorker # noqa: E402
SID = "aaaaaaaa-2222-3333-4444-555555555555"
ACCT = "google-personal"
class Account(unittest.TestCase):
def test_the_google_login(self):
a = accounts.get(ACCT)
self.assertEqual((a["harness"], a["provider"]), ("agy", "google"))
self.assertEqual(accounts.for_harness("agy"), [ACCT])
self.assertEqual(accounts.valid_for(ACCT, "agy"), ACCT)
self.assertIsNone(accounts.valid_for(ACCT, "claude"))
self.assertEqual(accounts.plan_windows(ACCT), ["h5", "week"])
self.assertFalse(accounts.counts_in_totals(ACCT)) # his call
self.assertIn("agy", accounts.HARNESSES)
pub = next(x for x in accounts.public() if x["id"] == ACCT)
self.assertEqual((pub["harness"], pub["provider"]), ("agy", "google"))
def test_its_mirror_is_an_import_source(self):
with mock.patch.dict(os.environ, {"AGY_TRANSCRIPTS_DIR": str(TMP / "agy")}):
dirs = accounts.transcripts_dirs()
self.assertEqual(dirs[ACCT], (TMP / "agy" / ACCT).resolve())
def test_the_plan_tier(self):
self.assertEqual(plans.describe("google_ai_pro")["label"], "Google AI Pro")
self.assertEqual(plans.tier_of({"harness": "agy", "subscriptionType": "ai_pro"}),
"google_ai_pro")
self.assertEqual(plans.describe("default_claude_max_20x")["label"], "Max 20×")
class Catalogue(unittest.TestCase):
def test_the_four_gemini_models(self):
agy = [m for m in catalog.list_models() if m.get("harness") == "agy"]
self.assertEqual([m["id"] for m in agy],
["gemini-4-neon", "gemini-4-hydrogen", "gemini-4-argon",
"gemini-3.8-flash"])
self.assertTrue(all(m["harness"] == "agy" and m["provider"] == "google"
and m["family"] == "gemini" for m in agy))
self.assertEqual(agy[0]["efforts"], ["low", "medium", "high", "xhigh"])
self.assertEqual(models.agy_base("gemini-4-neon-xhigh"), "gemini-4-neon")
self.assertEqual(models.agy_model("gemini-4-hydrogen-low")["id"], "gemini-4-hydrogen")
self.assertEqual(models.context_window("gemini-4-neon-high"), 524_288)
self.assertEqual(models.AGY_DEFAULT_MODEL, "gemini-4-neon")
def test_greyed_while_unhosted_and_never_a_guests(self):
ms = [{"id": "opus", "harness": "claude"}, {"id": "gemini-4-neon", "harness": "agy"}]
self.assertEqual([m["id"] for m in model_routes.for_caller(ms, False, None)], ["opus"])
out = model_routes.for_caller(ms, True, "nobody runs agy")
self.assertEqual([m.get("unavailable") for m in out], [None, "nobody runs agy"])
self.assertIsNone(model_routes.for_caller(ms, True, None)[1].get("unavailable"))
class Health:
def __init__(self, held):
self.held = held
def host_accounts(self):
return self.held
class Store:
def __init__(self, ws, up):
self.ws, self.up = ws, up
def list(self):
return self.ws
def online(self, wid):
return wid in self.up
class D:
pass
d = D()
d.account_health, d.worker_store = Health({ACCT}), Store([], set())
self.assertIsNone(model_routes.agy_down(d)) # the lab hosts it
d.account_health = Health(set())
self.assertTrue(model_routes.agy_down(d)) # nobody
d.worker_store = Store([{"id": "mac", "agyAccounts": [ACCT]}], {"mac"})
self.assertIsNone(model_routes.agy_down(d)) # the Mac, online
d.worker_store = Store([{"id": "mac", "agyAccounts": [ACCT]}], set())
self.assertTrue(model_routes.agy_down(d)) # …asleep
def _u(inp=0, out=0, cache=0):
return norm_usage({"input_tokens": inp, "output_tokens": out,
"cache_read_input_tokens": cache})
def gemini_model(model):
"""The book key when provider-google prices the id."""
hit = book_key(model)
return hit[1] if hit and hit[0] == "google" else None
class Pricing(unittest.TestCase):
def test_gemini_ids(self):
self.assertEqual(gemini_model("gemini-4-neon"), "gemini-4-neon")
self.assertEqual(gemini_model("gemini-4-neon-high"), "gemini-4-neon")
self.assertEqual(gemini_model("gemini-3.8-flash-low"), "gemini-3.8-flash")
self.assertEqual(gemini_model("gemini-5-krypton"), "gemini-4-neon") # newer: Neon
self.assertIsNone(gemini_model("google/gemini-2.5-pro")) # OpenRouter's
self.assertIsNone(gemini_model("claude-opus-5-5"))
self.assertEqual(rates_for("gemini-4-neon-high"), (3.0, 15.0, 0.15))
self.assertEqual(rates_for("gemini-4-hydrogen"), (1.5, 7.5, 0.075))
def test_cost_and_plan_units(self):
u = _u(inp=10_000, out=2_000, cache=100_000)
self.assertAlmostEqual(usage_cost(u, "gemini-4-neon-high"),
(10_000 * 3 + 2_000 * 15 + 100_000 * 0.15) / 1e6)
# Antigravity draws its Gemini quota down by API price
self.assertAlmostEqual(plan_units(u, "gemini-4-neon"), usage_cost(u, "gemini-4-neon"))
def _rec(**kw):
return {"sessionId": SID, "cwd": "/home/u/repo", "entrypoint": "agy",
"timestamp": "2026-11-22T01:00:00.000Z", **kw}
class Parse(unittest.TestCase):
def test_a_mirrored_agy_transcript(self):
usage = {"input_tokens": 2775, "output_tokens": 112,
"cache_read_input_tokens": 7441, "cache_creation_input_tokens": 0}
p = TMP / "proj" / f"{SID}.jsonl"
p.parent.mkdir(parents=True, exist_ok=True)
recs = [
_rec(type="user", uuid="u1", message={"role": "user", "content": "edit notes"}),
_rec(type="assistant", uuid="a1", parentUuid="u1", effort="high",
message={"id": "agy:1", "role": "assistant", "model": "gemini-4-neon",
"usage": usage, "content": [
{"type": "tool_use", "id": "agy:1:0", "name": "Edit",
"input": {"file_path": "/home/u/repo/notes.txt",
"old_string": "beta", "new_string": "gamma"}}]}),
_rec(type="user", uuid="u2", parentUuid="a1", message={"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "agy:1:0", "content": "Made 1 replacement"}]}),
_rec(type="assistant", uuid="a2", parentUuid="u2", effort="high",
message={"id": "agy:3", "role": "assistant", "model": "gemini-4-neon",
"usage": {**usage, "output_tokens": 20},
"content": [{"type": "text", "text": "Done."}]}),
]
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
s = parse_conversation(p)
self.assertEqual(s["harness"], "agy")
self.assertEqual(s["models"], ["gemini-4-neon"])
self.assertEqual(s["efforts"], ["high"])
want = (2 * (2775 * 3 + 7441 * 0.15) + (112 + 20) * 15) / 1e6
self.assertAlmostEqual(s["cost"], want, places=6)
class Feed(unittest.TestCase):
def test_agy_files_land_in_claudes_layout(self):
rel = pathlib.PurePosixPath(f"@agy/{ACCT}/-Users-g-repo/{SID}.jsonl")
self.assertEqual(local_rel(rel).as_posix(), f"-Users-g-repo/{SID}.jsonl")
sub = pathlib.PurePosixPath(f"@agy/{ACCT}/-x/{SID}/subagents/agent-a.jsonl")
self.assertEqual(local_rel(sub).as_posix(), f"-x/{SID}/subagents/agent-a.jsonl")
self.assertEqual(agy_account(rel.as_posix()), ACCT)
self.assertIsNone(opencode_account(rel.as_posix()))
self.assertIsNone(agy_account(f"-x/{SID}.jsonl"))
def _quota(updated, five, week):
return {"updated_at": updated, "plan_type": "google_ai_pro", "limit_reached": False,
"rate_limits": {
"five_hour": {"used_percentage": five, "resets_at": updated + 3600,
"window_seconds": 18000},
"seven_day": {"used_percentage": week, "resets_at": updated + 86400,
"window_seconds": 604800}}}
class Usage(unittest.TestCase):
def test_both_windows_are_recorded(self):
now = time.time()
class Store:
def __init__(self):
self.rows = []
def record(self, rows):
self.rows += rows
def __getattr__(self, _name):
return lambda *a, **k: None
poller = UsagePoller(Store(), dirs={}, remote=lambda: {ACCT: _quota(now, 12.0, 40.0)})
try:
poller.poll_once()
except Exception:
pass # a stub store; the snapshot is what this checks
snap = poller.latest[ACCT]
self.assertEqual(snap["windows"]["five_hour"]["pct"], 12.0)
self.assertEqual(snap["windows"]["seven_day"]["pct"], 40.0)
self.assertEqual(plans.windows_of(snap), ["week", "h5"])
def test_the_freshest_machine_wins(self):
now = time.time()
class Store:
def list(self):
return [{"id": "mac", "url": "http://mac", "token": "t",
"agyAccounts": [ACCT]},
{"id": "guest-pc", "url": "http://g", "token": "t",
"agyAccounts": [ACCT], "owner": "akira"}]
def online(self, wid):
return True
class D:
worker_store = Store()
lab = {"accounts": {ACCT: _quota(now - 600, 10.0, 30.0)}}
mac = {"accounts": {ACCT: _quota(now, 15.0, 31.0), "personal": _quota(now, 1, 1)}}
asked = []
def worker_get(url, *a, **k):
asked.append(url)
return mac
with mock.patch("runs.sidecar_client._sidecar_get", return_value=lab), \
mock.patch("workers.store.sidecar_request", side_effect=worker_get):
got = _agy_snapshots(D(), {ACCT})
self.assertEqual(list(got), [ACCT]) # never another account's
self.assertEqual(got[ACCT]["rate_limits"]["five_hour"]["used_percentage"], 15.0)
self.assertEqual(asked, ["http://mac"]) # a guest's computer: never
class Routing(unittest.TestCase):
"""A run goes to a machine that declares the agy account; the personal Mac
is a Personal runner behind the lab."""
def setUp(self):
self.fw = FakeWorker(TMP / "remote", TMP / "state")
self.w = workers.pair(DEPS.worker_store, self.fw.pairing_string(None),
account=None, name="mac-perso", hub_name="t",
resolve_login=lambda _l: None,
valid_account=accounts.valid)
DEPS.profile_store.assign_worker(self.w, "personal")
DEPS.worker_store.patch(self.w["id"], {"agyAccounts": [ACCT]})
self.lab = mock.patch.object(DEPS.account_health, "host_accounts", return_value=set())
self.lab.start()
def tearDown(self):
self.lab.stop()
self.fw.stop()
DEPS.worker_store.delete(self.w["id"])
DEPS.profile_store.forget_worker(self.w["id"])
def test_a_new_run_goes_to_a_machine_holding_the_login(self):
out = _send_message(DEPS, "hi", harness="agy", model="gemini-4-neon", effort="high")
path, body = self.fw.calls[-1]
self.assertEqual((path, body["harness"], body["account"], body["model"], body["effort"]),
("/spawn", "agy", ACCT, "gemini-4-neon", "high"))
m = DEPS.meta_store.get(out["sessionId"])
self.assertEqual((m["worker"], m["account"], m["harness"]), (self.w["id"], ACCT, "agy"))
def test_an_effort_the_model_lacks_is_dropped(self):
_send_message(DEPS, "hi", harness="agy", model="gemini-4-argon", effort="xhigh",
worker=self.w["id"])
self.assertIsNone(self.fw.calls[-1][1]["effort"])
def test_no_machine_with_the_login_is_refused(self):
DEPS.worker_store.patch(self.w["id"], {"agyAccounts": []})
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", harness="agy", worker=self.w["id"])
self.assertEqual(cm.exception.detail["kind"], "worker_harness")
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", harness="agy")
self.assertEqual(cm.exception.detail["kind"], "worker_harness")
def test_a_guests_agy_run_stays_on_the_lab(self):
# Settings → Models can put a Gemini model in the guest pool; a
# guest's run is pinned to the lab, never the owner's Mac.
n = len(self.fw.calls)
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", harness="agy", run_as="akira", worker="local")
self.assertEqual(cm.exception.detail["kind"], "worker_harness")
self.assertEqual(len(self.fw.calls), n)
def test_a_continue_stays_on_agy_where_it_lives(self):
out = _send_message(DEPS, "hi", harness="agy", worker=self.w["id"])
sid = out["sessionId"]
_send_message(DEPS, "more", session_id=sid, cwd="/Users/g/repo", takeover=True)
path, body = self.fw.calls[-1]
self.assertEqual((path, body["harness"], body["account"]), ("/resume", "agy", ACCT))
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "x", session_id=sid, harness="claude", takeover=True)
self.assertEqual(cm.exception.detail["kind"], "harness_switch")
def test_a_terminal_session_from_the_mac_is_stamped_with_its_login(self):
sid = "bbbbbbbb-2222-3333-4444-555555555555"
w = DEPS.worker_store.get(self.w["id"])
_record_worker_files(DEPS, w, [f"@agy/{ACCT}/-Users-g-repo/{sid}.jsonl"])
self.assertEqual(DEPS.meta_store.get(sid)["accountSource"], ACCT)
other = "cccccccc-2222-3333-4444-555555555555"
_record_worker_files(DEPS, w, [f"@agy/work/-Users-g-repo/{other}.jsonl"])
self.assertNotIn("accountSource", DEPS.meta_store.get(other))
def test_a_login_goes_to_the_machine_asked_for(self):
lab = {"agyAccounts": [ACCT]}
with mock.patch("accounts.routes._sidecar_get", return_value=lab):
self.assertIsNone(_account_runner(DEPS, ACCT)) # the lab first
self.assertEqual(_account_runner(DEPS, ACCT, self.w["id"]), self.w["id"])
self.assertIsNone(_account_runner(DEPS, ACCT, "local"))
with mock.patch("accounts.routes._sidecar_get", return_value={"agyAccounts": []}):
self.assertEqual(_account_runner(DEPS, ACCT), self.w["id"]) # else the Mac
DEPS.worker_store.patch(self.w["id"], {"agyAccounts": []})
for worker in (None, self.w["id"]):
with self.assertRaises(HTTPException) as cm:
_account_runner(DEPS, ACCT, worker)
self.assertEqual(cm.exception.detail["kind"], "unhosted")
def test_each_machines_own_login_is_listed(self):
from accounts.routes import list_accounts
lab = {"accounts": [{"id": ACCT, "harness": "agy", "loggedIn": True,
"email": "g@gmail.example"}]}
mac = {ACCT: {"local": lab["accounts"][0],
self.w["id"]: {"loggedIn": False, "worker": self.w["id"]}}}
with mock.patch("accounts.routes._sidecar_get", return_value=lab), \
mock.patch.object(DEPS.account_health, "per_host_rows", return_value=mac):
out = list_accounts(DEPS, health=True)
a = next(x for x in out["accounts"] if x["id"] == ACCT)
self.assertTrue(a["status"]["loggedIn"])
self.assertEqual([(h["id"], h["loggedIn"]) for h in a["hosts"]],
[("local", True), (self.w["id"], False)])
self.assertNotIn("hosts", next(x for x in out["accounts"] if x["id"] == "personal"))
def test_a_login_starts_and_finishes_on_that_machine(self):
from accounts.routes import (AccountLoginCodeBody, account_login_code,
account_login_start)
with mock.patch("accounts.routes._account_changed"):
account_login_start(DEPS, ACCT, None, worker=self.w["id"])
self.assertEqual(self.fw.calls[-1][0], f"/accounts/{ACCT}/login")
account_login_code(DEPS, ACCT, AccountLoginCodeBody(code="4/0Abc"),
worker=self.w["id"])
self.assertEqual(self.fw.calls[-1], (f"/accounts/{ACCT}/login/code",
{"code": "4/0Abc"}))
def _live(self, lab_rows: list[dict], mac_row: dict) -> dict:
h = DEPS.account_health
with mock.patch.object(h, "_sidecar_get", lambda path, timeout=40: {"accounts": lab_rows}), \
mock.patch("workers.store.sidecar_request",
return_value={"id": ACCT, "harness": "agy", **mac_row}), \
mock.patch.object(DEPS.worker_store, "online", return_value=True):
h._fetch_live()
return h
def test_the_labs_login_decides_the_accounts_health(self):
# 2026-11-22: the personal Mac declared google-personal before signing
# in, and its row overwrote the lab's fresh sign-in — the account read
# signed out 44 s after Gabriel signed in.
lab = [{"id": ACCT, "harness": "agy", "loggedIn": True, "email": "g@gmail.example",
"credentialsAt": "2026-11-22T02:11:06Z"}]
h = self._live(lab, {"loggedIn": False})
self.assertTrue(h.live_rows()[ACCT]["loggedIn"])
self.assertEqual(h._compute()[ACCT]["status"], "ok")
self.assertFalse(h.per_host_rows()[ACCT][self.w["id"]]["loggedIn"])
# …and the lab signed out is the account signed out, the Mac's login or not
lab[0]["loggedIn"] = False
h = self._live(lab, {"loggedIn": True, "email": "g@gmail.example"})
self.assertEqual(h._compute()[ACCT]["status"], "signed_out")
def test_without_the_lab_a_signed_in_machine_decides(self):
h = self._live([], {"loggedIn": True, "email": "g@gmail.example"})
self.assertEqual(h._compute()[ACCT]["status"], "ok")
h = self._live([], {"loggedIn": False})
self.assertEqual(h._compute()[ACCT]["status"], "signed_out")
def test_the_health_rows_carry_each_machines_login(self):
import types
from accounts.routes import accounts_health
lab = [{"id": ACCT, "harness": "agy", "loggedIn": True, "email": "g@gmail.example"}]
self._live(lab, {"loggedIn": False})
DEPS.account_health.refresh(fetch=False)
out = accounts_health(DEPS, types.SimpleNamespace(is_owner=True))
row = next(r for r in out["accounts"] if r["id"] == ACCT)
self.assertEqual(row["status"], "ok")
self.assertEqual([(x["id"], x["loggedIn"]) for x in row["hosts"]],
[("local", True), (self.w["id"], False)])
self.assertNotIn("hosts", next(r for r in out["accounts"] if r["id"] == "personal"))
if __name__ == "__main__":
unittest.main()