Files
ai-agent/backend/test_worker_routing.py
gabrielvidalandClaude Opus 5.5 5d0b1e5cc4 feat(runs): an offline default worker hands the prompt to the profile's next one up
An unpinned prompt whose profile's default runner is offline (the Work
MacBook shut in a bag) now runs on the profile's next runner that can take it
and is up (the Orus devbox), on that runner's ★ login — never outside the
profile (the lab), never for an explicit Runs on pick. Every runner down is
still the 409 worker_offline, now naming the others too. The composer's
routePrompt mirrors it (the Runs on chip's auto just shows the devbox).

Unpinned Send later prompts are stored auto and routed when they fire, the
same way (before: the default runner was frozen and failed while asleep);
their card shows where they'd start right now, then where they went.

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

400 lines
21 KiB
Python

"""main's run routing across runners: a new run picks the account's online
worker (or the composer's pick), a continue follows the session to its worker,
the terminal-live guard, interrupt routing and per-runner exit baselines.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
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": ""}.items():
os.environ[k] = str(v)
from fastapi import HTTPException # noqa: E402
import accounts # noqa: E402
import main # noqa: E402
import workers # noqa: E402
from accounts.routes import _account_runner # noqa: E402
from core.state import _record_worker_files # noqa: E402
from cron.routes import CronCreateBody, CronPatchBody, cron_create, cron_delete, cron_update # noqa: E402
from cron.service import _fire_cron_job # noqa: E402
from runs.routes import InterruptBody, interrupt_conversation # noqa: E402
from runs.service import _send_message # noqa: E402
from runs.sidecar_client import _sidecar_live_sids # noqa: E402
from users.caller import OWNER # noqa: E402
DEPS = main.app.state.ai
from _fakeworker import FakeWorker # noqa: E402
SID = "11111111-2222-3333-4444-555555555555"
class Routing(unittest.TestCase):
def setUp(self):
self.fw = FakeWorker(TMP / "remote", TMP / "state")
self.w = workers.pair(DEPS.worker_store, self.fw.pairing_string("work"),
account=None, name="mac", hub_name="t",
resolve_login=lambda _l: None,
valid_account=accounts.valid)
# The Work profile's default runner (Settings → Profiles).
DEPS.profile_store.assign_worker(self.w, "work")
DEPS.profile_store.patch_runner(self.w["id"], {"default": True})
def tearDown(self):
self.fw.stop()
DEPS.worker_store.delete(self.w["id"])
DEPS.profile_store.forget_worker(self.w["id"])
def test_new_run_on_the_account_goes_to_its_worker(self):
out = _send_message(DEPS, "hi", account="work")
path, body = self.fw.calls[-1]
self.assertEqual(path, "/spawn")
self.assertNotIn("account", body) # the worker's own login
self.assertIsNone(body["cwd"]) # the worker's own default
m = DEPS.meta_store.get(out["sessionId"])
self.assertEqual((m["worker"], m["account"]), (self.w["id"], "work"))
def test_a_project_tag_no_longer_routes(self):
# tagging orus-monorepo without the account ⇒ the default profile's
# account and runner (the lab: unconfigured here ⇒ 503)
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", projects=["orus-monorepo"])
self.assertEqual(cm.exception.status_code, 503)
self.assertFalse([c for c in self.fw.calls if c[0] == "/spawn"])
def test_new_run_from_a_profile_goes_to_its_default_runner(self):
# Work's default runner is the Mac: its ★ login bills
out = _send_message(DEPS, "hi", profile="work")
self.assertEqual(self.fw.calls[-1][0], "/spawn")
m = DEPS.meta_store.get(out["sessionId"])
self.assertEqual((m["worker"], m["account"]), (self.w["id"], "work"))
card_profile = DEPS.profile_store.resolve(m["worker"], m["account"])
self.assertEqual(card_profile, "work")
# Personal (the lab, unconfigured here ⇒ 503) never reaches the Mac,
# even pinned to the work seat — the lab holds it too
for acct in (None, "work"):
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", profile="personal", account=acct)
self.assertEqual(cm.exception.status_code, 503)
# …and that run is a Personal conversation, whatever it bills
self.assertEqual(DEPS.profile_store.resolve(None, "work"), "personal")
def test_not_the_default_runner_only_runs_what_is_pinned(self):
# the Mac moves to Personal, behind the lab (its default runner)
DEPS.profile_store.patch_runner(self.w["id"], {"profile": "personal"})
self.assertEqual(DEPS.profile_store.get("personal")["workers"][0]["id"], "local")
# auto: the worker is online but isn't the profile's default ⇒ the
# host sidecar (unconfigured here ⇒ 503), never the worker
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", profile="personal")
self.assertEqual(cm.exception.status_code, 503)
self.assertFalse([c for c in self.fw.calls if c[0] == "/spawn"])
# an explicit pick still lands there
out = _send_message(DEPS, "hi", worker=self.w["id"])
self.assertEqual(self.fw.calls[-1][0], "/spawn")
self.assertEqual(DEPS.meta_store.get(out["sessionId"])["worker"],
self.w["id"])
def test_an_offline_default_runner_is_a_409_never_the_lab(self):
DEPS.worker_store.set_status(self.w["id"], status="offline")
# auto: Work's default runner is offline ⇒ refused (the composer
# offers Send later / another worker), not moved onto the lab
for kw in ({"profile": "work"}, {"account": "work"}):
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", **kw)
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
self.assertEqual(cm.exception.detail["worker"], self.w["id"])
# an explicit pick of an offline worker is refused, not rerouted
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", worker=self.w["id"])
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
self.assertEqual(self.fw.calls, [])
def test_an_offline_default_runner_hands_over_to_the_next_one_up(self):
# Work: the Mac (default) then a devbox on the same seat
# (one FakeWorker per process — its pairing state is global — so
# the devbox is a second record at the same address)
dev = DEPS.worker_store.put({**self.w, "id": "devbox000001", "name": "devbox"})
DEPS.worker_store.set_status(dev["id"], status="online")
try:
DEPS.profile_store.assign_worker(dev, "work")
self.assertEqual([e["id"] for e in DEPS.profile_store.get("work")["workers"]][:2],
[self.w["id"], dev["id"]])
# the Mac up: still the default
out = _send_message(DEPS, "hi", profile="work")
self.assertEqual(DEPS.meta_store.get(out["sessionId"])["worker"], self.w["id"])
# the Mac in a bag: the devbox takes it, on its own ★ login
DEPS.worker_store.set_status(self.w["id"], status="offline")
for kw in ({"profile": "work"}, {"account": "work"}):
out = _send_message(DEPS, "hi", **kw)
m = DEPS.meta_store.get(out["sessionId"])
self.assertEqual((m["worker"], m["account"]), (dev["id"], "work"))
self.assertEqual(self.fw.calls[-1][0], "/spawn")
# a pinned Mac stays pinned: refused, not moved
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", worker=self.w["id"])
self.assertEqual(cm.exception.detail["worker"], self.w["id"])
# every Work runner down: refused on the default, naming the rest
DEPS.worker_store.set_status(dev["id"], status="offline")
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", profile="work")
d = cm.exception.detail
self.assertEqual((d["kind"], d["worker"]), ("worker_offline", self.w["id"]))
self.assertIn("and so is devbox", d["message"])
finally:
DEPS.worker_store.delete(dev["id"])
DEPS.profile_store.forget_worker(dev["id"])
DEPS.worker_store.set_status(self.w["id"], status="online")
def test_explicit_worker_bills_its_own_login(self):
out = _send_message(DEPS, "hi", worker=self.w["id"])
self.assertEqual(DEPS.meta_store.get(out["sessionId"])["account"],
"work")
# a pin it doesn't hold is refused, not swapped
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", account="personal", worker=self.w["id"])
self.assertEqual(cm.exception.detail["kind"], "worker_harness")
def test_pi_never_goes_to_a_worker(self):
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", harness="pi", worker=self.w["id"])
self.assertEqual(cm.exception.detail["kind"], "worker_harness")
def test_continue_follows_the_session_and_guards_a_live_terminal(self):
DEPS.meta_store.update(SID, {"workerSource": self.w["id"],
"accountSource": "work"})
mirror = TMP / "mirror" / "-Users-g-repo" / f"{SID}.jsonl"
mirror.parent.mkdir(parents=True, exist_ok=True)
mirror.write_text("{}\n") # grew just now
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "more", session_id=SID, cwd="/Users/g/repo")
self.assertEqual(cm.exception.detail["kind"], "terminal_live")
self.assertEqual(self.fw.calls, [])
# confirmed takeover goes through, to the worker, force-resume
_send_message(DEPS, "more", session_id=SID, cwd="/Users/g/repo",
takeover=True)
path, body = self.fw.calls[-1]
self.assertEqual((path, body["force"], body["cwd"]),
("/resume", True, "/Users/g/repo"))
self.assertEqual(DEPS.meta_store.get(SID)["worker"], self.w["id"])
# an old transcript isn't guarded
os.utime(mirror, (time.time() - 3600, time.time() - 3600))
_send_message(DEPS, "again", session_id=SID, cwd="/Users/g/repo")
# …nor is our own live run on the worker
mirror.write_text("{}\n{}\n")
self.fw.live = {SID}
_send_message(DEPS, "again", session_id=SID, cwd="/Users/g/repo")
self.assertEqual([c[0] for c in self.fw.calls],
["/resume", "/resume", "/resume"])
def test_growth_from_our_own_finished_run_is_not_a_terminal(self):
sid = "22222222-2222-3333-4444-555555555555"
mirror = TMP / "mirror" / "-Users-g-repo" / f"{sid}.jsonl"
mirror.parent.mkdir(parents=True, exist_ok=True)
mirror.write_text("{}\n")
now = time.time()
os.utime(mirror, (now - 10, now - 10))
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(now - 8))
DEPS.meta_store.update(sid, {"worker": self.w["id"], "state": "finished",
"exitedAt": stamp})
_send_message(DEPS, "next", session_id=sid, cwd="/Users/g/repo")
self.assertEqual(self.fw.calls[-1][0], "/resume")
# …but a write after our run exited is a terminal's
DEPS.meta_store.update(sid, {"state": "finished"})
os.utime(mirror, (now, now))
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "next", session_id=sid, cwd="/Users/g/repo")
self.assertEqual(cm.exception.detail["kind"], "terminal_live")
def test_continue_into_a_live_run_goes_through_its_inbox(self):
DEPS.meta_store.update(SID, {"worker": self.w["id"], "state": "running"})
self.fw.live = {SID}
self.fw.inbox = {SID}
out = _send_message(DEPS, "Up?", session_id=SID, cwd="/Users/g/repo")
self.assertEqual(out["delivered"], "inbox")
self.assertEqual([c[0] for c in self.fw.calls], ["/message"])
self.assertEqual(self.fw.calls[-1][1]["prompt"], "Up?")
self.assertEqual(DEPS.meta_store.get(SID)["state"], "running")
# the live run can't take it (409) ⇒ the force-resume as before
self.fw.inbox = set()
_send_message(DEPS, "Up?", session_id=SID, cwd="/Users/g/repo")
path, body = self.fw.calls[-1]
self.assertEqual((path, body["force"]), ("/resume", True))
# nothing live (404) ⇒ a plain resume, still force (harmless)
self.fw.live = set()
_send_message(DEPS, "Up?", session_id=SID, cwd="/Users/g/repo")
self.assertEqual(self.fw.calls[-1][0], "/resume")
def test_restart_skips_the_inbox(self):
# *Stop & send now*: the live run could take it, but the caller wants
# it now — straight to the force-resume, which stops the run first.
DEPS.meta_store.update(SID, {"worker": self.w["id"]})
self.fw.live = {SID}
self.fw.inbox = {SID}
out = _send_message(DEPS, "Now!", session_id=SID, cwd="/Users/g/repo",
restart=True)
self.assertNotIn("delivered", out)
self.assertEqual([c[0] for c in self.fw.calls], ["/resume"])
self.assertEqual(self.fw.calls[-1][1]["force"], True)
self.assertEqual(self.fw.calls[-1][1]["prompt"], "Now!")
# leave no live-looking run behind for the next test's terminal guard
DEPS.meta_store.update(SID, {"state": "finished"})
def test_interrupt_routes_to_the_worker(self):
DEPS.meta_store.update(SID, {"worker": self.w["id"]})
interrupt_conversation(DEPS, OWNER, InterruptBody(sessionId=SID))
self.assertEqual(self.fw.calls[-1][0], "/interrupt")
def test_mirror_stamps_worker_and_account(self):
sid = "99999999-2222-3333-4444-555555555555"
_record_worker_files(DEPS, self.w, [f"-Users-g-repo/{sid}.jsonl",
f"-Users-g-repo/{sid}/subagents/a.jsonl"])
m = DEPS.meta_store.get(sid)
self.assertEqual((m["workerSource"], m["accountSource"]),
(self.w["id"], "work"))
self.assertEqual(accounts.resolve({}, m), "work")
def test_cron_job_runs_on_its_worker_and_never_auto_routes(self):
agents = TMP / ".claude" / "agents"
agents.mkdir(parents=True, exist_ok=True)
# account: work would auto-route to the Mac — an unpinned job stays home
(agents / "pr.md").write_text("---\naccount: work\n---\nwatch PRs\n")
job = cron_create(DEPS, CronCreateBody(
name="pr", schedule="0 9 * * *",
promptFile=".claude/agents/pr.md"))
self.assertIsNone(job["worker"])
with self.assertRaises(HTTPException) as cm: # lab sidecar: 503 here
_fire_cron_job(DEPS, DEPS.cron_store.get("pr"))
self.assertEqual(cm.exception.status_code, 503)
self.assertEqual(self.fw.calls, [])
# pinned to the worker: the prompt text goes there
job = cron_update(DEPS, "pr", CronPatchBody(worker=self.w["id"]))
self.assertEqual(job["worker"], self.w["id"])
out = _fire_cron_job(DEPS, DEPS.cron_store.get("pr"))
path, body = self.fw.calls[-1]
self.assertEqual((path, body["prompt"]), ("/spawn", "watch PRs"))
m = DEPS.meta_store.get(out["sessionId"])
self.assertEqual((m["worker"], m["cron"]["id"]), (self.w["id"], "pr"))
# offline ⇒ refused, not rerouted to the lab
DEPS.worker_store.set_status(self.w["id"], status="offline")
with self.assertRaises(HTTPException) as cm:
_fire_cron_job(DEPS, DEPS.cron_store.get("pr"))
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
# unknown ids are rejected up front; "" moves it back to the lab
with self.assertRaises(HTTPException):
cron_update(DEPS, "pr", CronPatchBody(worker="nope"))
job = cron_update(DEPS, "pr", CronPatchBody(worker=""))
self.assertIsNone(job["worker"])
cron_delete(DEPS, "pr")
def test_live_sids_per_runner(self):
self.fw.live = {"a", "b"}
self.assertEqual(_sidecar_live_sids(DEPS, self.w["id"]), {"a", "b"})
DEPS.worker_store.set_status(self.w["id"], status="offline")
self.assertIsNone(_sidecar_live_sids(DEPS, self.w["id"]))
class OpencodeRouting(Routing):
"""The opencode harness: a run goes where its account's opencode database
is — the worker whose sidecar declares it — never anywhere else."""
def setUp(self):
super().setUp()
DEPS.worker_store.patch(self.w["id"], {"opencodeAccounts": ["chatgpt-work"]})
def test_a_new_opencode_run_goes_to_the_worker_hosting_its_account(self):
# a Claude account only says which profile: its runner's opencode ★ bills
out = _send_message(DEPS, "hi", harness="opencode", account="work")
path, body = self.fw.calls[-1]
self.assertEqual((path, body["harness"], body["account"]),
("/spawn", "opencode", "chatgpt-work"))
m = DEPS.meta_store.get(out["sessionId"])
self.assertEqual((m["worker"], m["account"], m["harness"]),
(self.w["id"], "chatgpt-work", "opencode"))
def test_an_offline_host_is_a_409_never_the_lab(self):
DEPS.worker_store.set_status(self.w["id"], status="offline")
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", harness="opencode")
self.assertEqual(cm.exception.detail["kind"], "worker_offline")
self.assertEqual(self.fw.calls, [])
def test_a_worker_without_the_login_is_refused(self):
DEPS.worker_store.patch(self.w["id"], {"opencodeAccounts": []})
with self.assertRaises(HTTPException) as cm:
_send_message(DEPS, "hi", harness="opencode", worker=self.w["id"])
self.assertEqual(cm.exception.detail["kind"], "worker_harness")
def test_a_login_goes_to_the_machine_hosting_the_account(self):
self.assertEqual(_account_runner(DEPS, "chatgpt-work"), self.w["id"])
self.assertIsNone(_account_runner(DEPS, "work"))
DEPS.worker_store.patch(self.w["id"], {"opencodeAccounts": []})
lab = {"opencodeAccounts": ["chatgpt-work"]}
with mock.patch("accounts.routes._sidecar_get", return_value=lab):
self.assertIsNone(_account_runner(DEPS, "chatgpt-work"))
# no machine declares it: say how to fix it, never "unknown account"
with mock.patch("accounts.routes._sidecar_get", return_value={"opencodeAccounts": []}):
with self.assertRaises(HTTPException) as cm:
_account_runner(DEPS, "chatgpt-work")
self.assertEqual(cm.exception.status_code, 409)
self.assertEqual(cm.exception.detail["kind"], "unhosted")
self.assertIn("install-macos.sh --update", cm.exception.detail["message"])
def test_signing_in_a_workers_own_login_goes_to_that_worker(self):
from accounts.routes import (AccountLoginBody, AccountLoginCodeBody,
account_login_code, account_login_start)
DEPS.worker_store.patch(self.w["id"], {"claudeMode": "own", "account": "work"})
seen = []
with mock.patch.object(DEPS.account_health, "worker_signed_in", seen.append), \
mock.patch("accounts.routes._account_changed"):
out = account_login_start(DEPS, "work", AccountLoginBody(email="g@orus.example"),
worker=self.w["id"])
self.assertTrue(out["url"].startswith("https://claude.ai/"))
self.assertEqual(self.fw.calls[-1][0], "/accounts/work/login")
account_login_code(DEPS, "work", AccountLoginCodeBody(code="c#s"), worker=self.w["id"])
self.assertEqual(self.fw.calls[-1], ("/accounts/work/login/code", {"code": "c#s"}))
self.assertEqual(seen, [self.w["id"]])
# not its account / proxied / a guest's computer: refused, never the lab's login
for patch, acct, kind in (({}, "personal", "wrong_account"),
({"claudeMode": "proxy"}, "work", "proxied"),
({"owner": "akira"}, "work", None)):
DEPS.worker_store.patch(self.w["id"], {"claudeMode": "own", "owner": None, **patch})
with self.assertRaises(HTTPException) as cm:
account_login_start(DEPS, acct, None, worker=self.w["id"])
if kind:
self.assertEqual(cm.exception.detail["kind"], kind)
else:
self.assertIn(cm.exception.status_code, (403, 409))
DEPS.worker_store.patch(self.w["id"], {"owner": None})
def test_a_terminal_session_resumes_on_opencode_where_it_lives(self):
sid = "33333333-2222-3333-4444-555555555555"
# what the feed mirror stamps for an opencode file from the worker
w = DEPS.worker_store.get(self.w["id"])
_record_worker_files(DEPS, w, [f"@opencode/chatgpt-work/-Users-g-repo/{sid}.jsonl"])
self.assertEqual(DEPS.meta_store.get(sid)["accountSource"], "chatgpt-work")
# an account the worker doesn't declare is never stamped
other = "44444444-2222-3333-4444-555555555555"
_record_worker_files(DEPS, w, [f"@opencode/personal/-Users-g-repo/{other}.jsonl"])
self.assertNotIn("accountSource", DEPS.meta_store.get(other))
_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", "opencode", "chatgpt-work"))
if __name__ == "__main__":
unittest.main()