601 lines
28 KiB
Python
601 lines
28 KiB
Python
"""Tests for the ``runs.route`` live-plugin hook (``plugins/run_router.py``),
|
|
routing hub bridges, ``appendSystemPrompt`` across harnesses, enriched
|
|
``hub/conversations/{sid}?digest=1``, ``carryover.agent_presets``, and
|
|
``runs/service.py`` preset routing / turn stepping / subagent model."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
import tempfile
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
SEED = TMP / "seed"
|
|
shutil.copytree(pathlib.Path(__file__).resolve().parent / "fixtures" / "typed_plugins", SEED)
|
|
|
|
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",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"USERS_PATH": TMP / "users.json",
|
|
"AUTH_PATH": TMP / "auth.json",
|
|
"ROLES_PATH": TMP / "roles.json",
|
|
"NOTIFY_PATH": TMP / "notify.json",
|
|
"NOTIF_READ_PATH": TMP / "notif-read.json",
|
|
"FORMS_PATH": TMP / "forms.json",
|
|
"UI_STATE_PATH": TMP / "ui-state.json",
|
|
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
|
|
"SECURITY_STATE_PATH": TMP / "sec.json",
|
|
"ASKFORM_PATH": TMP / "askform.json",
|
|
"PLUGINS_DIR": TMP / "plugins",
|
|
"DRAFTS_PATH": TMP / "drafts.json",
|
|
"TAG_META_PATH": TMP / "tag-meta.json",
|
|
"PROJECT_MERGES_PATH": TMP / "project-merges.json",
|
|
"FORM_SECRETS_PATH": TMP / "form-secrets.json",
|
|
"RUN_QUEUE_PATH": TMP / "run-queue.json",
|
|
"MODEL_PRESETS_PATH": TMP / "model-presets.json",
|
|
"USAGE_DB_PATH": TMP / "usage.db",
|
|
"TELEMETRY_DB_PATH": TMP / "telemetry.db",
|
|
"PERF_DB_PATH": TMP / "perf.db",
|
|
"PERF_SETTINGS_PATH": TMP / "perf-settings.json",
|
|
"PERF_STORAGE_PATH": TMP / "perf-storage.json",
|
|
"PLUGINS_SEED_DIR": SEED,
|
|
"INTERNAL_API_TOKEN": "tok",
|
|
"SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": "",
|
|
}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import carryover, hubruns, manifest, run_router # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from runs import queue as run_queue # noqa: E402
|
|
from runs import service # noqa: E402
|
|
from runs.service import _extras, _send_message, subagent_extra # noqa: E402
|
|
from runs.sidecar_client import _mark_run_exited # noqa: E402
|
|
from toolproxy import access as tp_access # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
|
|
def _install_plugin(store: PluginStore, root: pathlib.Path, pid: str, *,
|
|
provides: dict | None = None, caps: list[str] | None = None,
|
|
actions: dict | None = None) -> dict:
|
|
pdir = root / pid
|
|
pdir.mkdir(parents=True, exist_ok=True)
|
|
script = pdir / "handler.py"
|
|
script.write_text("import json, sys\nprint(json.dumps({}))\n", encoding="utf-8")
|
|
mf = {
|
|
"schema": 1,
|
|
"id": pid,
|
|
"name": pid.title(),
|
|
"version": "1.0.0",
|
|
"description": "test plugin",
|
|
"actions": actions if actions is not None else {
|
|
"route": {"script": "handler.py", "readOnly": True},
|
|
"save": {"script": "handler.py"},
|
|
},
|
|
"capabilities": list(caps or []),
|
|
}
|
|
if provides:
|
|
mf["provides"] = provides
|
|
(pdir / "plugin.json").write_text(json.dumps(mf), encoding="utf-8")
|
|
return store.install(OWNER_UID, str(pdir), is_owner=True, approve=True)
|
|
|
|
|
|
class BaseRouterTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.pdir = pathlib.Path(self.td.name) / "plugins"
|
|
self.src = pathlib.Path(self.td.name) / "src"
|
|
self.pstore = PluginStore(str(self.pdir))
|
|
self.orig_pstore = DEPS.plugin_store
|
|
DEPS.plugin_store = self.pstore
|
|
run_router.invalidate()
|
|
self.client = TestClient(main.app)
|
|
|
|
def tearDown(self):
|
|
DEPS.plugin_store = self.orig_pstore
|
|
run_router.invalidate()
|
|
self.td.cleanup()
|
|
|
|
def install_router(self, pid: str = "agent-presets", caps: list[str] | None = None):
|
|
return _install_plugin(
|
|
self.pstore, self.src, pid,
|
|
provides={"runs.route": "route"},
|
|
caps=caps if caps is not None else ["models.read", "runs.start", "conversations.read", "conversations.send"],
|
|
)
|
|
|
|
|
|
# ── manifest & basic helpers ─────────────────────────────────────────────────
|
|
class TestRunRouterCore(BaseRouterTest):
|
|
def test_manifest_accepts_runs_route(self):
|
|
self.assertIn("runs.route", manifest._PROVIDES)
|
|
rec = self.install_router()
|
|
self.assertTrue(run_router.provides(rec))
|
|
self.assertTrue(run_router.has_provider(DEPS))
|
|
self.assertEqual(run_router.provider_id(DEPS), "agent-presets")
|
|
|
|
def test_preset_id_and_source_of(self):
|
|
self.assertEqual(run_router.preset_id("preset:best"), "best")
|
|
self.assertEqual(run_router.preset_id(" PRESET:Fast "), "fast")
|
|
self.assertIsNone(run_router.preset_id("opus"))
|
|
self.assertIsNone(run_router.preset_id(None))
|
|
|
|
self.assertEqual(run_router.source_of({"plugin": "cron-jobs", "origin": "plugin"}), "plugin:cron-jobs")
|
|
self.assertEqual(run_router.source_of({"origin": "app"}), "composer")
|
|
self.assertEqual(run_router.source_of({"origin": "script"}), "mcp")
|
|
self.assertEqual(run_router.source_of({"origin": "child", "spawnedBy": {"sessionId": "x"}}), "child")
|
|
self.assertIsNone(run_router.source_of({"origin": "webhook"}))
|
|
self.assertIsNone(run_router.source_of(None))
|
|
|
|
def test_no_provider_safe_defaults_and_explicit_refusal(self):
|
|
self.assertFalse(run_router.has_provider(DEPS))
|
|
self.assertIsNone(run_router.provider_id(DEPS))
|
|
self.assertEqual(run_router.brief(DEPS),
|
|
{"presets": [], "defaults": {}, "models": {}, "providerId": None})
|
|
self.assertEqual(run_router.brief_list(DEPS), [])
|
|
self.assertEqual(run_router.defaults(DEPS), {})
|
|
self.assertIsNone(run_router.subagent_model(DEPS, "personal", "opus"))
|
|
self.assertIsNone(run_router.resolve_new_run(
|
|
DEPS, model=None, harness=None, account=None, worker=None,
|
|
profile=None, stamp={"origin": "app"}, run_as=None, scope=None))
|
|
with self.assertRaises(HTTPException) as ctx:
|
|
run_router.resolve_new_run(
|
|
DEPS, model="preset:best", harness=None, account=None, worker=None,
|
|
profile=None, stamp=None, run_as=None, scope=None)
|
|
self.assertEqual(ctx.exception.status_code, 400)
|
|
self.assertEqual(ctx.exception.detail["kind"], "preset")
|
|
|
|
self.assertEqual(
|
|
run_router.resolve_turn(DEPS, {"preset": "best"}, preset_pick=None, exact_pick=None,
|
|
model="opus", effort="high", account="personal", harness="claude"),
|
|
("opus", "high", None, {}),
|
|
)
|
|
with self.assertRaises(HTTPException) as ctx2:
|
|
run_router.resolve_turn(DEPS, {}, preset_pick="best", exact_pick=None,
|
|
model=None, effort=None, account="personal", harness="claude")
|
|
self.assertEqual(ctx2.exception.status_code, 400)
|
|
|
|
def test_brief_caching_and_touched_invalidation_sse(self):
|
|
rec = self.install_router()
|
|
calls = []
|
|
|
|
def fake_script(deps, store, uid, r, script, payload=None, **kw):
|
|
calls.append(payload)
|
|
return {
|
|
"presets": [{"id": "best", "name": "Best", "now": {"i": 0, "model": "opus", "harness": "claude"}}],
|
|
"defaults": {"composer": "best"},
|
|
"models": {"opus": {"status": "room", "pct": 10.0}},
|
|
}
|
|
|
|
events = []
|
|
with mock.patch("plugins.runner.run_script", side_effect=fake_script), \
|
|
mock.patch.object(DEPS.hub, "publish", side_effect=events.append):
|
|
b1 = run_router.brief(DEPS, profile="personal")
|
|
b2 = run_router.brief(DEPS, profile="personal")
|
|
self.assertEqual(len(calls), 1)
|
|
self.assertEqual(b1["providerId"], "agent-presets")
|
|
self.assertEqual(b2["defaults"], {"composer": "best"})
|
|
|
|
# Read-only action does not invalidate or publish SSE
|
|
run_router.touched(DEPS, rec, action="route")
|
|
run_router.brief(DEPS, profile="personal")
|
|
self.assertEqual(len(calls), 1)
|
|
self.assertEqual(events, [])
|
|
|
|
# Write action invalidates cache and publishes {"type": "run-presets"}
|
|
run_router.touched(DEPS, rec, action="save")
|
|
self.assertIn({"type": "run-presets"}, events)
|
|
run_router.brief(DEPS, profile="personal")
|
|
self.assertEqual(len(calls), 2)
|
|
|
|
|
|
# ── API routes & hub bridges ─────────────────────────────────────────────────
|
|
class TestRoutesAndBridges(BaseRouterTest):
|
|
def test_run_presets_api_and_models_compat_and_old_routes_gone(self):
|
|
self.install_router()
|
|
fake = {
|
|
"presets": [{"id": "best", "name": "Best", "now": {"i": 0, "model": "claude-opus", "harness": "claude"}}],
|
|
"defaults": {"composer": "best"},
|
|
"models": {"opus": {"status": "room"}},
|
|
}
|
|
with mock.patch("plugins.runner.run_script", return_value=fake):
|
|
r = self.client.get("/api/plugins/run-presets", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertEqual(body["providerId"], "agent-presets")
|
|
self.assertEqual(body["defaults"], {"composer": "best"})
|
|
self.assertEqual(body["presets"][0]["id"], "best")
|
|
self.assertIsNone(body["profile"])
|
|
|
|
bad = self.client.get("/api/plugins/run-presets?profile=nonexistent", headers=OWNER_H)
|
|
self.assertEqual(bad.status_code, 400)
|
|
|
|
m = self.client.get("/api/models", headers=OWNER_H)
|
|
self.assertEqual(m.status_code, 200)
|
|
self.assertEqual(m.json()["ladders"][0]["id"], "best")
|
|
self.assertEqual(m.json()["ladderDefaults"], {"composer": "best"})
|
|
|
|
# Old /api/model-ladders API routes are removed (SPA or 404/405, never API 200)
|
|
old_post = self.client.post("/api/model-ladders", headers=OWNER_H, json={"name": "x"})
|
|
self.assertIn(old_post.status_code, (404, 405))
|
|
|
|
def test_hub_routing_state_and_check(self):
|
|
self.install_router()
|
|
_install_plugin(self.pstore, self.src, "cron-jobs", caps=["runs.start"])
|
|
tok = tp_access.mint_handler(OWNER_UID, "agent-presets", ttl=600)
|
|
h = {"Authorization": f"Bearer {tok}"}
|
|
|
|
r = self.client.get("/proxy/tools/plugins/agent-presets/hub/routing/state", headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
st = r.json()
|
|
for key in ("models", "presets", "providers", "accounts", "profiles",
|
|
"defaultProfile", "workers", "limits", "sources", "profile"):
|
|
self.assertIn(key, st)
|
|
self.assertTrue(any(s["id"] == "composer" for s in st["sources"]))
|
|
self.assertTrue(any(s["id"] == "plugin:cron-jobs" for s in st["sources"]))
|
|
# Every model has key and vendor
|
|
self.assertTrue(st["models"])
|
|
self.assertIn("key", st["models"][0])
|
|
self.assertIn("vendor", st["models"][0])
|
|
# Every provider has label, kind, quotaWindows
|
|
for pv in st["providers"].values():
|
|
self.assertIn(pv["kind"], ("free", "credit", "plan"))
|
|
self.assertIsInstance(pv["quotaWindows"], list)
|
|
|
|
bad_prof = self.client.get("/proxy/tools/plugins/agent-presets/hub/routing/state?profile=nope", headers=h)
|
|
self.assertEqual(bad_prof.status_code, 400)
|
|
|
|
# Check batch evaluation
|
|
def fake_route_new_run(deps, harness, account, worker, profile, *, check_online=True, guest=None, model=None):
|
|
if harness == "agy":
|
|
raise HTTPException(409, {"message": "no agy machine", "kind": "worker_harness"})
|
|
return None, "personal"
|
|
|
|
with mock.patch("runs.service.route_new_run", side_effect=fake_route_new_run):
|
|
c = self.client.post("/proxy/tools/plugins/agent-presets/hub/routing/check", headers=h, json={
|
|
"items": [
|
|
{"key": "r1", "harness": "claude", "model": "opus"},
|
|
{"key": "r2", "harness": "agy", "model": "gemini-4-neon"},
|
|
]
|
|
})
|
|
self.assertEqual(c.status_code, 200, c.text)
|
|
res = c.json()["results"]
|
|
self.assertTrue(res["r1"]["ok"])
|
|
self.assertEqual(res["r1"]["runner"], "local")
|
|
self.assertEqual(res["r1"]["account"], "personal")
|
|
self.assertEqual(res["r1"]["vendor"], "anthropic")
|
|
self.assertFalse(res["r2"]["ok"])
|
|
self.assertIn("no agy machine", res["r2"]["reason"])
|
|
|
|
def test_hub_conversation_one_enriched_and_digest(self):
|
|
self.install_router()
|
|
tok = tp_access.mint_handler(OWNER_UID, "agent-presets", ttl=600)
|
|
h = {"Authorization": f"Bearer {tok}"}
|
|
|
|
sid = "11111111-1111-4111-8111-111111111111"
|
|
tpath = pathlib.Path(self.td.name) / f"{sid}.jsonl"
|
|
# Minimal Claude-format transcript with user turn, tool call, assistant reply
|
|
lines = [
|
|
{"type": "user", "timestamp": "2026-12-01T10:00:00Z",
|
|
"message": {"role": "user", "content": "Refactor the routing module cleanly."}},
|
|
{"type": "assistant", "timestamp": "2026-12-01T10:00:05Z",
|
|
"message": {"role": "assistant", "model": "claude-opus-4-8", "content": [
|
|
{"type": "text", "text": "I will edit run_router.py now."},
|
|
{"type": "tool_use", "id": "tu1", "name": "Edit",
|
|
"input": {"file_path": "/repo/backend/plugins/run_router.py"}},
|
|
]}},
|
|
{"type": "user", "timestamp": "2026-12-01T10:00:06Z",
|
|
"message": {"role": "user", "content": [
|
|
{"type": "tool_result", "tool_use_id": "tu1", "content": "ok"},
|
|
]}},
|
|
{"type": "assistant", "timestamp": "2026-12-01T10:00:10Z",
|
|
"message": {"role": "assistant", "model": "claude-opus-4-8", "content": [
|
|
{"type": "text", "text": "Hit a rate limit on the next step."},
|
|
]}},
|
|
]
|
|
tpath.write_text("\n".join(json.dumps(x) for x in lines) + "\n", encoding="utf-8")
|
|
|
|
summary = {
|
|
"sessionId": sid,
|
|
"title": "Routing refactor",
|
|
"cwd": "/workspace/ai-agent",
|
|
"endedAt": "2026-12-01T10:00:10Z",
|
|
"startedAt": "2026-12-01T10:00:00Z",
|
|
"harness": "claude",
|
|
"turnEnded": True,
|
|
"userTurns": 1,
|
|
"lastApiError": {"kind": "rate_limit", "message": "5h limit reached", "resetsAt": 1900000000},
|
|
}
|
|
DEPS.meta_store.update(sid, {
|
|
"state": "finished",
|
|
"preset": "best",
|
|
"presetName": "Best",
|
|
"route": {"i": 0, "n": 3, "harness": "claude", "model": "opus", "account": "personal"},
|
|
"routeSteps": [{"at": "2026-12-01T10:00:05Z", "to": {"i": 1, "model": "sonnet"}}],
|
|
"appendSystemPrompt": "Always write concise tests.",
|
|
"profile": "personal",
|
|
"worker": "local",
|
|
"account": "personal",
|
|
"harness": "claude",
|
|
"exitedAt": "2026-12-01T10:00:12Z",
|
|
})
|
|
|
|
with mock.patch.object(DEPS.store, "all_summaries", return_value=[(str(tpath), summary)]):
|
|
r = self.client.get(f"/proxy/tools/plugins/agent-presets/hub/conversations/{sid}?digest=1",
|
|
headers=h)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
d = r.json()
|
|
self.assertEqual(d["cwd"], "/workspace/ai-agent")
|
|
self.assertEqual(d["preset"], "best")
|
|
self.assertEqual(d["presetName"], "Best")
|
|
self.assertEqual(d["appendSystemPrompt"], "Always write concise tests.")
|
|
self.assertEqual(d["profile"], "personal")
|
|
self.assertEqual(d["account"], "personal")
|
|
self.assertEqual(d["exitedAt"], "2026-12-01T10:00:12Z")
|
|
self.assertEqual(d["stoppedOn"]["kind"], "rate_limit")
|
|
self.assertEqual(d["lastApiError"]["kind"], "rate_limit")
|
|
self.assertIn("digest", d)
|
|
self.assertLessEqual(len(d["digest"]), 20_000)
|
|
self.assertIn("Refactor the routing module cleanly.", d["digest"])
|
|
self.assertIn("run_router.py", d["digest"])
|
|
self.assertIn("LAST ERROR: rate_limit", d["digest"])
|
|
|
|
|
|
# ── appendSystemPrompt & runs/service.py integration ─────────────────────────
|
|
class TestRunsIntegration(BaseRouterTest):
|
|
def test_extras_supports_append_system_prompt_on_all_harnesses(self):
|
|
for h in ("pi", "opencode", "agy"):
|
|
self.assertEqual(
|
|
_extras(DEPS, None, None, "/tmp", None, h, "Be brief."),
|
|
{"appendSystemPrompt": "Be brief."},
|
|
)
|
|
self.assertEqual(_extras(DEPS, None, None, "/tmp", None, h, None), {})
|
|
|
|
with mock.patch("runs.service.run_extras", return_value={"appendSystemPrompt": "base"}):
|
|
cl = _extras(DEPS, "personal", None, "/tmp", None, "claude", "extra")
|
|
self.assertEqual(cl["appendSystemPrompt"], "base\n\nextra")
|
|
|
|
def test_spawn_and_resume_with_preset_worker_prompt_and_step_down(self):
|
|
self.install_router()
|
|
launched = []
|
|
|
|
def fake_launch(deps, account, path, payload, *, worker=None):
|
|
launched.append((path, worker, dict(payload)))
|
|
return {"sessionId": payload["sessionId"], "pid": 42}
|
|
|
|
def fake_route(deps, harness, account, worker, profile, *, check_online=True, guest=None, model=None):
|
|
return (worker if worker and worker != "local" else None), (account or "personal")
|
|
|
|
def fake_script(deps, store, uid, rec, script, payload=None, **kw):
|
|
op = (payload or {}).get("op")
|
|
if op == "resolve":
|
|
return {
|
|
"matched": True,
|
|
"preset": "best",
|
|
"name": "Best",
|
|
"i": 0,
|
|
"n": 3,
|
|
"harness": "agy",
|
|
"model": "gemini-4-neon",
|
|
"modelId": "gemini-4-neon",
|
|
"effort": "high",
|
|
"worker": "evox2-w",
|
|
"account": "google-personal",
|
|
"runner": "evox2-w",
|
|
"appendSystemPrompt": "Preset instructions.",
|
|
"full": False,
|
|
"skipped": [],
|
|
}
|
|
if op == "turn":
|
|
return {
|
|
"matched": True,
|
|
"model": "claude-sonnet-5-5",
|
|
"effort": "medium",
|
|
"appendSystemPrompt": "Stepped-down instructions.",
|
|
"route": {"i": 1, "n": 3, "model": "claude-sonnet-5-5"},
|
|
"step": {"from": {"i": 0, "model": "gemini-4-neon"},
|
|
"to": {"i": 1, "model": "claude-sonnet-5-5"},
|
|
"why": "quota 98%"},
|
|
}
|
|
if op == "subagent":
|
|
return {"model": "haiku"}
|
|
return {}
|
|
|
|
with mock.patch("plugins.runner.run_script", side_effect=fake_script), \
|
|
mock.patch("runs.service._launch", side_effect=fake_launch), \
|
|
mock.patch("runs.service.route_new_run", side_effect=fake_route), \
|
|
mock.patch("runs.service.run_queue.gate", return_value=None), \
|
|
mock.patch("runs.service._session_worker", return_value="evox2-w"), \
|
|
mock.patch("runs.service._terminal_live_guard"), \
|
|
mock.patch.object(DEPS.worker_store, "get", return_value={"id": "evox2-w", "name": "EVOX2"}), \
|
|
mock.patch.object(DEPS.worker_store, "online", return_value=True):
|
|
# 1. Spawn on preset:best without pinning worker -> takes preset's worker & combines system prompt
|
|
res = _send_message(
|
|
DEPS, "Do the task", model="preset:best", profile="personal",
|
|
append_prompt="Caller instructions.", stamp={"origin": "app"},
|
|
)
|
|
sid = res["sessionId"]
|
|
self.assertEqual(launched[0][0], "/spawn")
|
|
self.assertEqual(launched[0][1], "evox2-w")
|
|
self.assertEqual(launched[0][2]["harness"], "agy")
|
|
self.assertEqual(launched[0][2]["model"], "gemini-4-neon")
|
|
self.assertEqual(launched[0][2]["appendSystemPrompt"],
|
|
"Preset instructions.\n\nCaller instructions.")
|
|
meta = DEPS.meta_store.get(sid)
|
|
self.assertEqual(meta["preset"], "best")
|
|
self.assertEqual(meta["presetName"], "Best")
|
|
self.assertEqual(meta["profile"], "personal")
|
|
self.assertEqual(meta["route"]["worker"], "evox2-w")
|
|
self.assertEqual(meta["appendSystemPrompt"], "Preset instructions.\n\nCaller instructions.")
|
|
|
|
# 2. Resume steps down and overrides appendSystemPrompt
|
|
_send_message(DEPS, "Continue please", session_id=sid)
|
|
self.assertEqual(launched[1][0], "/resume")
|
|
self.assertEqual(launched[1][2]["model"], "claude-sonnet-5-5")
|
|
self.assertEqual(launched[1][2]["effort"], "medium")
|
|
self.assertEqual(launched[1][2]["appendSystemPrompt"], "Stepped-down instructions.")
|
|
meta2 = DEPS.meta_store.get(sid)
|
|
self.assertEqual(meta2["route"]["i"], 1)
|
|
self.assertEqual(len(meta2["routeSteps"]), 1)
|
|
self.assertEqual(meta2["appendSystemPrompt"], "Stepped-down instructions.")
|
|
|
|
# 3. Subagent extra reads from run_router.subagent_model
|
|
self.assertEqual(
|
|
subagent_extra(DEPS, {"harness": "claude", "model": "opus"}, "personal", None),
|
|
{"subagentModel": "haiku"},
|
|
)
|
|
|
|
def test_custom_run_stamps_and_carries_append_system_prompt(self):
|
|
launched = []
|
|
|
|
def fake_launch(deps, account, path, payload, *, worker=None):
|
|
launched.append((path, dict(payload)))
|
|
return {"sessionId": payload["sessionId"], "pid": 99}
|
|
|
|
with mock.patch("runs.service._launch", side_effect=fake_launch), \
|
|
mock.patch("runs.service.route_new_run", return_value=(None, "personal")), \
|
|
mock.patch("runs.service.run_queue.gate", return_value=None), \
|
|
mock.patch("runs.service._session_worker", return_value=None):
|
|
r = self.client.post("/api/spawn", headers=OWNER_H, json={
|
|
"prompt": "Hello", "harness": "pi", "model": "qwen",
|
|
"appendSystemPrompt": "Keep replies under 3 lines.",
|
|
})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
sid = r.json()["sessionId"]
|
|
self.assertEqual(launched[0][1]["appendSystemPrompt"], "Keep replies under 3 lines.")
|
|
self.assertEqual(DEPS.meta_store.get(sid)["appendSystemPrompt"], "Keep replies under 3 lines.")
|
|
|
|
# Resume without appendSystemPrompt carries previous one forward
|
|
r2 = self.client.post("/api/resume", headers=OWNER_H, json={
|
|
"sessionId": sid, "prompt": "Follow up",
|
|
})
|
|
self.assertEqual(r2.status_code, 200, r2.text)
|
|
self.assertEqual(launched[1][1]["appendSystemPrompt"], "Keep replies under 3 lines.")
|
|
|
|
# Too-long appendSystemPrompt is rejected with 400
|
|
r3 = self.client.post("/api/spawn", headers=OWNER_H, json={
|
|
"prompt": "Hello", "appendSystemPrompt": "x" * 16_001,
|
|
})
|
|
self.assertEqual(r3.status_code, 400)
|
|
|
|
def test_hubruns_norm_run_and_turn_opts(self):
|
|
run, why = hubruns.norm_run({
|
|
"prompt": "hi", "worker": "orus", "profile": "work",
|
|
"appendSystemPrompt": "Be terse.",
|
|
})
|
|
self.assertIsNone(why)
|
|
self.assertEqual(run["appendSystemPrompt"], "Be terse.")
|
|
self.assertEqual(run["profile"], "work")
|
|
|
|
bad_run, bad_why = hubruns.norm_run({"prompt": "hi", "appendSystemPrompt": "a" * 16_001})
|
|
self.assertIsNone(bad_run)
|
|
self.assertEqual(bad_why, "bad appendSystemPrompt")
|
|
|
|
opts, twhy = hubruns._turn_opts({
|
|
"compact": {"model": "haiku", "instructions": "Keep key facts."},
|
|
"fresh": True,
|
|
"restart": True,
|
|
"appendSystemPrompt": "Focus on tests.",
|
|
})
|
|
self.assertIsNone(twhy)
|
|
self.assertEqual(opts["compact"], {"model": "haiku", "instructions": "Keep key facts."})
|
|
self.assertTrue(opts["fresh"])
|
|
self.assertTrue(opts["restart"])
|
|
self.assertEqual(opts["append_prompt"], "Focus on tests.")
|
|
|
|
_, bad_c = hubruns._turn_opts({"compact": {"model": "", "instructions": ""}})
|
|
self.assertEqual(bad_c, "bad compact")
|
|
|
|
def test_mark_run_exited_enriches_conversation_finished_event(self):
|
|
sid = "22222222-2222-4222-8222-222222222222"
|
|
DEPS.meta_store.update(sid, {
|
|
"state": "running",
|
|
"preset": "best",
|
|
"presetName": "Best",
|
|
"harness": "claude",
|
|
"account": "personal",
|
|
"worker": "local",
|
|
"projects": ["ai-agent"],
|
|
})
|
|
dispatched = []
|
|
with mock.patch("plugins.scheduler.dispatch_event",
|
|
side_effect=lambda deps, ev, payload, **kw: dispatched.append((ev, payload))):
|
|
_mark_run_exited(DEPS, sid)
|
|
self.assertEqual(len(dispatched), 1)
|
|
ev, payload = dispatched[0]
|
|
self.assertEqual(ev, "conversation.finished")
|
|
self.assertEqual(payload["preset"], "best")
|
|
self.assertEqual(payload["presetName"], "Best")
|
|
self.assertEqual(payload["harness"], "claude")
|
|
self.assertEqual(payload["account"], "personal")
|
|
self.assertEqual(payload["worker"], "local")
|
|
self.assertEqual(payload["projects"], ["ai-agent"])
|
|
|
|
|
|
# ── one-time carryover ───────────────────────────────────────────────────────
|
|
class TestCarryoverAgentPresets(BaseRouterTest):
|
|
def test_carryover_converts_ladders_once(self):
|
|
legacy = pathlib.Path(self.td.name) / "model-ladders.json"
|
|
legacy.write_text(json.dumps({
|
|
"ladders": [
|
|
{
|
|
"id": "best",
|
|
"name": "Best",
|
|
"fullAt": 92,
|
|
"whenFull": "wait",
|
|
"rungs": [
|
|
{"model": "opus", "harness": "claude", "effort": "high"},
|
|
{"model": "gemini-4-neon", "harness": "agy", "effort": ""},
|
|
],
|
|
},
|
|
],
|
|
"defaults": {"composer": "best", "subagents": "best"},
|
|
}), encoding="utf-8")
|
|
|
|
self.assertTrue(carryover.agent_presets(self.pstore, legacy=str(legacy)))
|
|
user_dir = self.pstore.user_data_dir(OWNER_UID, "agent-presets")
|
|
dst = user_dir / "presets.json"
|
|
self.assertTrue(dst.is_file())
|
|
self.assertTrue((user_dir / ".carried-over").is_file())
|
|
|
|
data = json.loads(dst.read_text(encoding="utf-8"))
|
|
self.assertEqual(data["defaults"], {"composer": "best", "subagents": "best"})
|
|
self.assertEqual(data["settings"], {"compactionPreset": "next", "maxHops": 3})
|
|
self.assertEqual(len(data["presets"]), 1)
|
|
p = data["presets"][0]
|
|
self.assertEqual(p["id"], "best")
|
|
self.assertEqual(p["name"], "Best")
|
|
self.assertIsNone(p["worker"])
|
|
self.assertEqual(p["systemPrompt"], "")
|
|
self.assertTrue(p["autoContinue"])
|
|
self.assertEqual(p["fullAt"], 92)
|
|
self.assertEqual(p["whenFull"], "wait")
|
|
self.assertEqual(p["rungs"], [
|
|
{"model": "opus", "harness": "claude", "effort": "high", "worker": None, "systemPrompt": ""},
|
|
{"model": "gemini-4-neon", "harness": "agy", "effort": "", "worker": None, "systemPrompt": ""},
|
|
])
|
|
|
|
# Second run is a no-op
|
|
self.assertFalse(carryover.agent_presets(self.pstore, legacy=str(legacy)))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|