386 lines
14 KiB
Python
386 lines
14 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from pathlib import Path
|
||
|
||
from airouter.config import Config
|
||
from airouter.session import Session
|
||
|
||
from .fake import FakeProvider, turn_text, turn_with_tool
|
||
|
||
|
||
def make_config(**kwargs) -> Config:
|
||
config = Config()
|
||
config.orchestrator_model = kwargs.pop("orchestrator_model", "main-fake")
|
||
config.worker_model = kwargs.pop("worker_model", "worker-fake")
|
||
config.limits.max_steps = kwargs.pop("max_steps", 10)
|
||
config.limits.max_worker_steps = kwargs.pop("max_worker_steps", 8)
|
||
config.limits.wait_timeout = kwargs.pop("wait_timeout", 10)
|
||
for key, value in kwargs.items():
|
||
setattr(config.limits, key, value)
|
||
return config
|
||
|
||
|
||
def test_followup_reuses_worker_context(tmp_path: Path):
|
||
provider = FakeProvider(
|
||
{
|
||
"worker-fake": [
|
||
turn_with_tool("write_file", {"path": "out.txt", "content": "one"}),
|
||
turn_text("Status: done\nSummary: wrote one"),
|
||
turn_text("Status: done\nSummary: follow-up applied"),
|
||
]
|
||
}
|
||
)
|
||
config = make_config()
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
worker = session.spawn_worker(task="Create out.txt", workspace=".")
|
||
await session.wait_for_workers([worker.id], mode="all", timeout=10)
|
||
assert worker.status == "done"
|
||
reply = await session._tool_message_worker(worker.id, "Also write second.txt")
|
||
assert '"running"' in reply
|
||
result = await session.wait_for_workers([worker.id], mode="all", timeout=10)
|
||
assert result["completed"][0]["followups"] == 1
|
||
assert worker.followups == 1
|
||
assert worker.status == "done"
|
||
assert any("Also write second.txt" in str(m.get("content", "")) for m in worker.messages)
|
||
assert len(session.workers) == 1
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_cancel_worker_wakes_waiters(tmp_path: Path):
|
||
async def responder(messages, count, session_id):
|
||
await asyncio.sleep(30)
|
||
return turn_text("never")
|
||
|
||
provider = FakeProvider({"worker-fake": responder})
|
||
config = make_config()
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
worker = session.spawn_worker(task="long task", workspace=".")
|
||
await asyncio.sleep(0.05)
|
||
result = await session._tool_cancel_worker(worker.id, "test")
|
||
assert "cancelled" in result
|
||
assert worker.status == "cancelled"
|
||
snapshot = session.check_workers([worker.id])
|
||
assert snapshot["workers"][0]["status"] == "cancelled"
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_role_model_routing(tmp_path: Path):
|
||
provider = FakeProvider({"review-model": [turn_text("Status: done\nSummary: reviewed")]})
|
||
config = make_config()
|
||
config.roles["reviewer"].model = "review-model"
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
worker = session.spawn_worker(task="Review the code", role="reviewer", workspace=".")
|
||
assert worker.model == "review-model"
|
||
await session.wait_for_workers([worker.id], mode="all", timeout=10)
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_worker_runs_and_persists(tmp_path: Path):
|
||
provider = FakeProvider(
|
||
{
|
||
"worker-fake": [
|
||
turn_with_tool("bash", {"command": "printf hello > out.txt"}),
|
||
turn_text("Status: done\nSummary: wrote out.txt\nFiles changed: out.txt"),
|
||
]
|
||
}
|
||
)
|
||
config = make_config()
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
events = []
|
||
session.listener = events.append
|
||
worker = session.spawn_worker(task="Create out.txt with hello", workspace=".")
|
||
result = await session.wait_for_workers([worker.id], mode="all", timeout=10)
|
||
assert result["completed"][0]["status"] == "done"
|
||
assert worker.status == "done"
|
||
assert (tmp_path / "out.txt").read_text() == "hello"
|
||
assert "out.txt" in worker.files_changed
|
||
assert worker.report_path and Path(worker.report_path).is_file()
|
||
types = [event.type for event in events]
|
||
assert "main_sleep" in types
|
||
assert types.index("main_sleep") < types.index("worker_started") < types.index("worker_done")
|
||
assert types.index("worker_done") < types.index("main_wake")
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
assert provider.closed
|
||
|
||
|
||
def test_orchestrator_delegates_and_waits(tmp_path: Path):
|
||
provider = FakeProvider(
|
||
{
|
||
"main-fake": [
|
||
turn_with_tool(
|
||
"spawn_worker",
|
||
{"task": "Create out.txt with hello and verify it", "workspace": "."},
|
||
"call_spawn",
|
||
),
|
||
turn_with_tool("wait_for_workers", {"mode": "all"}, "call_wait"),
|
||
turn_text("Готово: out.txt создан воркером."),
|
||
],
|
||
"worker-fake": [
|
||
turn_with_tool("write_file", {"path": "out.txt", "content": "hello"}),
|
||
turn_text("Status: done\nSummary: wrote out.txt\nFiles changed: out.txt"),
|
||
],
|
||
}
|
||
)
|
||
config = make_config()
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
events = []
|
||
session.listener = events.append
|
||
final = await session.run_turn("Создай out.txt с hello")
|
||
assert "out.txt" in final
|
||
assert (tmp_path / "out.txt").read_text() == "hello"
|
||
assert session.workers["w1"].status == "done"
|
||
assert session.workers["w1"].reported is True
|
||
main_calls = [call for call in provider.calls if call["model"] == "main-fake"]
|
||
assert len(main_calls) == 3 # spawn, wait, final; no polling
|
||
types = [event.type for event in events]
|
||
assert "main_sleep" in types
|
||
assert types.index("main_sleep") < types.index("main_wake")
|
||
# The worker report must be in the lead's context as a tool result.
|
||
tool_contents = [m.get("content", "") for m in session.main_messages if m.get("role") == "tool"]
|
||
assert any("out.txt" in content for content in tool_contents)
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_auto_wait_when_lead_tries_to_finish(tmp_path: Path):
|
||
provider = FakeProvider(
|
||
{
|
||
"main-fake": [
|
||
turn_with_tool(
|
||
"spawn_worker",
|
||
{"task": "Create out.txt with hello", "workspace": "."},
|
||
"call_spawn",
|
||
),
|
||
turn_text("Сейчас отвечу без ожидания."),
|
||
turn_text("Готово, учёл отчёт воркера."),
|
||
],
|
||
"worker-fake": [
|
||
turn_with_tool("write_file", {"path": "out.txt", "content": "hello"}),
|
||
turn_text("Status: done\nSummary: wrote out.txt"),
|
||
],
|
||
}
|
||
)
|
||
config = make_config()
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
events = []
|
||
session.listener = events.append
|
||
final = await session.run_turn("Создай out.txt")
|
||
assert "учёл" in final
|
||
assert any(event.type == "notice" for event in events)
|
||
assert (tmp_path / "out.txt").read_text() == "hello"
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_wait_any_then_all(tmp_path: Path):
|
||
async def responder(messages, count, session_id):
|
||
if "_w1" in session_id:
|
||
await asyncio.sleep(0.2)
|
||
else:
|
||
await asyncio.sleep(0.05)
|
||
return turn_text("Status: done\nSummary: ok")
|
||
|
||
provider = FakeProvider({"worker-fake": responder})
|
||
config = make_config()
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
w1 = session.spawn_worker(task="slow", workspace="one")
|
||
w2 = session.spawn_worker(task="fast", workspace="two")
|
||
first = await session.wait_for_workers([w1.id, w2.id], mode="any", timeout=10)
|
||
assert [item["id"] for item in first["completed"]] == [w2.id]
|
||
assert first["still_running"] == [w1.id]
|
||
second = await session.wait_for_workers([w1.id, w2.id], mode="all", timeout=10)
|
||
assert [item["id"] for item in second["completed"]] == [w1.id]
|
||
assert not second["still_running"]
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_session_resume(tmp_path: Path):
|
||
provider = FakeProvider(
|
||
{
|
||
"worker-fake": [
|
||
turn_with_tool("write_file", {"path": "out.txt", "content": "hello"}),
|
||
turn_text("Status: done\nSummary: wrote out.txt"),
|
||
],
|
||
"main-fake": [turn_text("unused")],
|
||
}
|
||
)
|
||
config = make_config()
|
||
root = tmp_path / ".airouter" / "sessions"
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=root, config=config, provider=provider, cwd=tmp_path
|
||
)
|
||
worker = session.spawn_worker(task="Create out.txt", workspace=".")
|
||
await session.wait_for_workers([worker.id], mode="all", timeout=10)
|
||
session.main_messages.append({"role": "user", "content": "после перезапуска"})
|
||
session.save_all()
|
||
session_id = session.id
|
||
await session.close()
|
||
|
||
loaded = Session.load(
|
||
sessions_root=root,
|
||
session_id=session_id,
|
||
config=config,
|
||
provider=FakeProvider({}),
|
||
)
|
||
assert loaded.id == session_id
|
||
assert loaded.workers[worker.id].status == "done"
|
||
assert loaded.workers[worker.id].messages
|
||
assert loaded.main_messages[-1]["content"] == "после перезапуска"
|
||
await loaded.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_intelligence_and_explicit_model_routing(tmp_path: Path):
|
||
provider = FakeProvider(
|
||
{
|
||
"high-model": [turn_text("Status: done\nSummary: high")],
|
||
"explicit-model": [turn_text("Status: done\nSummary: explicit")],
|
||
}
|
||
)
|
||
config = make_config()
|
||
config.intelligence["high"] = "high-model"
|
||
config.roles["coder"].model = "role-model"
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=tmp_path / ".airouter" / "sessions",
|
||
config=config,
|
||
provider=provider,
|
||
cwd=tmp_path,
|
||
)
|
||
fixed_role = session.spawn_worker(
|
||
task="hard task", workspace="fixed", intelligence="high"
|
||
)
|
||
high = session.spawn_worker(
|
||
task="hard task", role="reviewer", workspace="high", intelligence="high"
|
||
)
|
||
explicit = session.spawn_worker(
|
||
task="explicit task", workspace="explicit", model="explicit-model"
|
||
)
|
||
assert fixed_role.model == "role-model"
|
||
assert high.model == "high-model"
|
||
assert high.intelligence == "high"
|
||
assert explicit.model == "explicit-model"
|
||
await session.wait_for_workers(
|
||
[fixed_role.id, high.id, explicit.id], mode="all", timeout=10
|
||
)
|
||
await session.close()
|
||
|
||
asyncio.run(scenario())
|
||
|
||
|
||
def test_plan_update_and_settings_persist(tmp_path: Path):
|
||
provider = FakeProvider({"main-fake": [turn_text("ok")]})
|
||
config = make_config()
|
||
root = tmp_path / ".airouter" / "sessions"
|
||
|
||
async def scenario():
|
||
session = Session.create(
|
||
sessions_root=root, config=config, provider=provider, cwd=tmp_path
|
||
)
|
||
result = session.set_plan(
|
||
[
|
||
{
|
||
"id": "build",
|
||
"title": "Build feature",
|
||
"status": "in_progress",
|
||
"worker_id": "w1",
|
||
"subtasks": [
|
||
{"title": "write code", "status": "done"},
|
||
{"title": "test it", "status": "pending"},
|
||
],
|
||
}
|
||
]
|
||
)
|
||
assert result["tasks"] == 1
|
||
assert session.todos[0]["status"] == "in_progress"
|
||
assert session.todos[0]["subtasks"][1]["status"] == "pending"
|
||
session.apply_settings(
|
||
max_workers=3,
|
||
orchestrator_model="main-fake",
|
||
worker_model="worker-fake",
|
||
intelligence={"low": "l", "medium": "m", "high": "h"},
|
||
)
|
||
session_id = session.id
|
||
session.save_all()
|
||
await session.close()
|
||
|
||
config2 = make_config()
|
||
loaded = Session.load(
|
||
sessions_root=root,
|
||
session_id=session_id,
|
||
config=config2,
|
||
provider=FakeProvider({}),
|
||
)
|
||
assert loaded.todos == session.todos
|
||
assert loaded.config.limits.max_workers == 3
|
||
assert loaded.config.intelligence == {"low": "l", "medium": "m", "high": "h"}
|
||
await loaded.close()
|
||
|
||
asyncio.run(scenario())
|