Files
barsic/tests/test_antigravity_agent.py
T
2026-11-23 16:35:53 +03:00

501 lines
18 KiB
Python

"""Unit tests for AntigravityAgent, MCPToolBridge, and Antigravity SubagentRunner."""
from __future__ import annotations
import asyncio
import json
from typing import Any, Optional
from unittest.mock import patch
import httpx
import pytest
from homeagent.agent.antigravity import (
AntigravityAgent,
_format_cli_error,
_parse_models_output,
_strip_mcp_tool_prefix,
)
from homeagent.agent.conversation import ConversationManager
from homeagent.agent.mcp_bridge import MCPToolBridge, normalize_mcp_schema
from homeagent.agent.subagent import SubagentRunner
from homeagent.config import Settings
from homeagent.tools.base import tool
from homeagent.tools.registry import ToolRegistry
class FakeStreamReader:
"""Async line reader mimicking asyncio.StreamReader for mocked subprocess stdout."""
def __init__(self, lines: list[bytes]) -> None:
self._lines = list(lines)
async def readline(self) -> bytes:
if not self._lines:
return b""
return self._lines.pop(0)
async def read(self) -> bytes:
data = b"".join(self._lines)
self._lines.clear()
return data
class FakeProcess:
"""Minimal asyncio subprocess stub."""
def __init__(
self,
stdout_lines: list[str],
stderr_text: str = "",
returncode: int = 0,
) -> None:
self.stdout = FakeStreamReader([(line + "\n").encode("utf-8") for line in stdout_lines])
self.stderr = FakeStreamReader([stderr_text.encode("utf-8")] if stderr_text else [])
self.returncode = returncode
self._stdout_raw = "\n".join(stdout_lines).encode("utf-8")
self._stderr_raw = stderr_text.encode("utf-8")
self.killed = False
async def wait(self) -> int:
return self.returncode
async def communicate(self) -> tuple[bytes, bytes]:
return self._stdout_raw, self._stderr_raw
def kill(self) -> None:
self.killed = True
# ------------------------------------------------------------------------------
# MCPToolBridge tests
# ------------------------------------------------------------------------------
def test_normalize_mcp_schema_strips_nullable_recursively():
schema = {
"type": "object",
"properties": {
"category": {"type": "string", "nullable": True, "description": "Optional category"},
"items": {
"type": "array",
"items": {"type": "string", "nullable": True},
},
},
}
normalized = normalize_mcp_schema(schema)
assert "nullable" not in normalized["properties"]["category"]
assert "nullable" not in normalized["properties"]["items"]["items"]
assert normalized["properties"]["category"]["type"] == "string"
@pytest.mark.asyncio
async def test_mcp_tool_bridge_protocol_and_auth(tmp_path):
registry = ToolRegistry()
@tool(description="Add two numbers")
async def add_numbers(a: int, b: int, label: Optional[str] = None) -> str:
return f"{label or 'sum'}={a + b}"
@tool(description="Spawn subagent")
async def spawn_subagent(task: str) -> str:
return f"spawned:{task}"
registry.register(add_numbers)
registry.register(spawn_subagent)
bridge = MCPToolBridge(registry)
await bridge.ensure_started()
try:
url = bridge.get_endpoint_url(subagent=False)
sub_url = bridge.get_endpoint_url(subagent=True)
headers = {"Authorization": f"Bearer {bridge.token}"}
async with httpx.AsyncClient(trust_env=False) as client:
# 1. Rejects missing/invalid auth
unauth = await client.post(url, json={"jsonrpc": "2.0", "id": 1, "method": "ping"})
assert unauth.status_code == 401
# 2. GET returns 405, DELETE returns 204
assert (await client.get(url, headers=headers)).status_code == 405
assert (await client.delete(url, headers=headers)).status_code == 204
# 3. initialize handshake
init_resp = await client.post(
url,
headers=headers,
json={
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {"protocolVersion": "2025-03-26"},
},
)
assert init_resp.status_code == 200
init_data = init_resp.json()["result"]
assert init_data["protocolVersion"] == "2025-03-26"
assert init_data["serverInfo"]["name"] == "homeagent"
# 4. notifications/initialized -> 202
notif_resp = await client.post(
url,
headers=headers,
json={"jsonrpc": "2.0", "method": "notifications/initialized"},
)
assert notif_resp.status_code == 202
# 5. tools/list on main includes both; subagent excludes spawn_subagent
main_tools = (
await client.post(url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
).json()["result"]["tools"]
assert {t["name"] for t in main_tools} == {"add_numbers", "spawn_subagent"}
sub_tools = (
await client.post(sub_url, headers=headers, json={"jsonrpc": "2.0", "id": 3, "method": "tools/list"})
).json()["result"]["tools"]
assert {t["name"] for t in sub_tools} == {"add_numbers"}
# 6. tools/call executes registered tool
call_resp = await client.post(
url,
headers=headers,
json={
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {"name": "add_numbers", "arguments": {"a": 19, "b": 23, "label": "ans"}},
},
)
call_result = call_resp.json()["result"]
assert call_result["isError"] is False
assert call_result["content"][0]["text"] == "ans=42"
# 7. Calling excluded subagent tool on /mcp-subagent returns isError=True
blocked = (
await client.post(
sub_url,
headers=headers,
json={
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {"name": "spawn_subagent", "arguments": {"task": "recurse"}},
},
)
).json()["result"]
assert blocked["isError"] is True
# 8. write_mcp_config writes valid eager config
cfg_path = bridge.write_mcp_config(tmp_path)
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
server_cfg = cfg["mcpServers"]["homeagent"]
assert server_cfg["serverUrl"] == url
assert server_cfg["tools"]["add_numbers"] == {"eager": True}
finally:
await bridge.stop()
# ------------------------------------------------------------------------------
# Helper parsing & formatting tests
# ------------------------------------------------------------------------------
def test_parse_models_output_strips_spinner_and_ansi():
raw = (
"\r⠋ Fetching available models...\r⠙ Fetching available models...\r"
"\x1b[32mgemini-4-neon-high\x1b[0m Gemini 4 Neon (High)\n"
"claude-sonnet-5-5-high\tClaude Sonnet 5.5 (High)\n"
"gpt-oss-120b-medium GPT-OSS 120B (Medium)\n"
)
parsed = _parse_models_output(raw)
assert parsed == [
("gemini-4-neon-high", "Gemini 4 Neon (High)"),
("claude-sonnet-5-5-high", "Claude Sonnet 5.5 (High)"),
("gpt-oss-120b-medium", "GPT-OSS 120B (Medium)"),
]
def test_strip_mcp_tool_prefix():
assert _strip_mcp_tool_prefix("mcp_homeagent_calendar_today_schedule") == "calendar_today_schedule"
assert _strip_mcp_tool_prefix("web_search") == "web_search"
def test_format_cli_error_messages():
assert "не авторизован" in _format_cli_error("authentication required", "gemini-4-neon-high")
assert "Исчерпан лимит" in _format_cli_error("quota exceeded for model", "claude-opus-5-5-high")
assert "недоступна" in _format_cli_error("invalid model selection", "bad-model")
# ------------------------------------------------------------------------------
# AntigravityAgent tests
# ------------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_antigravity_agent_missing_cli_returns_help(tmp_path):
settings = Settings(
LLM_PROVIDER="antigravity",
ANTIGRAVITY_CLI_PATH="/nonexistent/agy-missing-bin",
DATA_DIR=tmp_path,
)
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=ConversationManager(tmp_path))
reply = await agent.chat(chat_id=100, thread_id=None, user_message="Привет")
assert "не найден" in reply
await agent.close()
@pytest.mark.asyncio
async def test_antigravity_agent_chat_streams_progress_and_resumes_topic(tmp_path):
settings = Settings(
LLM_PROVIDER="antigravity",
ANTIGRAVITY_MODEL="gemini-4-neon-high",
ANTIGRAVITY_TIMEOUT_SECONDS=120,
DATA_DIR=tmp_path,
)
registry = ToolRegistry()
cm = ConversationManager(tmp_path)
agent = AntigravityAgent(settings=settings, registry=registry, conversation_manager=cm)
captured_cmds: list[list[str]] = []
turn1_events = [
json.dumps({"event": "init", "conversation_id": "conv-aaa-111", "init": {"model": "gemini-4-neon-high"}}),
json.dumps(
{
"event": "step_update",
"step_update": {
"conversation_id": "conv-aaa-111",
"step_index": 1,
"state": "ACTIVE",
"step_type": "tool",
"tool_name": "mcp_homeagent_calendar_today_schedule",
"tool_info": {"name": "mcp_homeagent_calendar_today_schedule", "parameters": {}},
},
}
),
json.dumps(
{
"event": "step_update",
"step_update": {
"conversation_id": "conv-aaa-111",
"step_index": 2,
"state": "ACTIVE",
"step_type": "agent_response",
"text_delta": "Сегодня 2 встречи.",
},
}
),
json.dumps(
{
"event": "result",
"result": {
"conversation_id": "conv-aaa-111",
"status": "SUCCESS",
"response": "Сегодня 2 встречи.",
"num_turns": 1,
},
}
),
]
turn2_events = [
json.dumps(
{
"event": "result",
"result": {
"conversation_id": "conv-aaa-111",
"status": "SUCCESS",
"response": "Первая в 10:00.",
"num_turns": 2,
},
}
)
]
turn3_after_reset_events = [
json.dumps(
{
"event": "result",
"result": {
"conversation_id": "conv-bbb-222",
"status": "SUCCESS",
"response": "Новый диалог!",
"num_turns": 1,
},
}
)
]
procs = [
FakeProcess(turn1_events),
FakeProcess(turn2_events),
FakeProcess(turn3_after_reset_events),
]
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
captured_cmds.append(list(cmd))
return procs.pop(0)
progress_updates: list[str] = []
async def on_progress(text: str) -> None:
progress_updates.append(text)
try:
with (
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
):
# Turn 1: fresh session
res1 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Что сегодня?", on_progress=on_progress)
assert res1 == "Сегодня 2 встречи."
assert "--conversation" not in captured_cmds[0]
assert "--model" in captured_cmds[0] and "gemini-4-neon-high" in captured_cmds[0]
assert any("Проверяю расписание на сегодня" in p for p in progress_updates)
# Turn 2: resumes conversation_id conv-aaa-111
res2 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Во сколько первая?")
assert res2 == "Первая в 10:00."
assert "--conversation" in captured_cmds[1]
cid_idx = captured_cmds[1].index("--conversation") + 1
assert captured_cmds[1][cid_idx] == "conv-aaa-111"
# Verify ConversationManager also persisted messages
msgs = cm.get_openai_messages(-1001, 5)
assert len(msgs) == 4
assert msgs[-1]["content"] == "Первая в 10:00."
# /reset via conversation_manager.clear() must reset Antigravity session too!
cm.clear(-1001, 5)
res3 = await agent.chat(chat_id=-1001, thread_id=5, user_message="Начнем сначала")
assert res3 == "Новый диалог!"
assert "--conversation" not in captured_cmds[2]
finally:
await agent.close()
@pytest.mark.asyncio
async def test_antigravity_agent_retries_when_saved_conversation_is_stale(tmp_path):
settings = Settings(LLM_PROVIDER="antigravity", DATA_DIR=tmp_path)
cm = ConversationManager(tmp_path)
cm.append_openai_turn_sequence(
10,
None,
[
{"role": "user", "content": "Старый вопрос"},
{"role": "assistant", "content": "Старый ответ"},
],
)
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm)
agent._conversation_ids[agent._topic_key(10, None)] = "stale-conv-id"
cmds: list[list[str]] = []
procs = [
FakeProcess(
[
json.dumps(
{
"event": "result",
"result": {
"conversation_id": "",
"status": "ERROR",
"response": "",
"error": "conversation not found: stale-conv-id",
},
}
)
],
returncode=1,
),
FakeProcess(
[
json.dumps(
{
"event": "result",
"result": {
"conversation_id": "fresh-conv-id",
"status": "SUCCESS",
"response": "Восстановленный ответ",
},
}
)
],
returncode=0,
),
]
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
cmds.append(list(cmd))
return procs.pop(0)
try:
with (
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
):
res = await agent.chat(chat_id=10, thread_id=None, user_message="Продолжаем")
assert res == "Восстановленный ответ"
assert len(cmds) == 2
assert "--conversation" in cmds[0]
assert "--conversation" not in cmds[1]
# Carryover history should be injected into retry prompt
retry_prompt = cmds[1][cmds[1].index("-p") + 1]
assert "Старый вопрос" in retry_prompt
assert agent._conversation_ids[agent._topic_key(10, None)] == "fresh-conv-id"
finally:
await agent.close()
@pytest.mark.asyncio
async def test_antigravity_agent_set_model_updates_runtime_and_settings(tmp_path):
settings = Settings(LLM_PROVIDER="antigravity", ANTIGRAVITY_MODEL="gemini-4-neon-high", DATA_DIR=tmp_path)
agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=ConversationManager(tmp_path))
agent.set_model("claude-opus-5-5-high")
assert agent.model == "claude-opus-5-5-high"
assert settings.ANTIGRAVITY_MODEL == "claude-opus-5-5-high"
assert settings.get_active_model() == "claude-opus-5-5-high"
await agent.close()
# ------------------------------------------------------------------------------
# SubagentRunner with Antigravity provider
# ------------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_subagent_runner_antigravity_mocked(tmp_path):
settings = Settings(
LLM_PROVIDER="antigravity",
ANTIGRAVITY_SUBAGENT_MODEL="gemini-3.8-flash-medium",
DATA_DIR=tmp_path,
)
registry = ToolRegistry()
runner = SubagentRunner(settings=settings, registry=registry)
captured_cmd: list[str] = []
sub_proc = FakeProcess(
[
json.dumps(
{
"conversation_id": "sub-conv-1",
"status": "SUCCESS",
"response": "Найдено 3 активных тикета в Jira.",
}
)
]
)
async def fake_exec(*cmd: str, **kwargs: Any) -> FakeProcess:
captured_cmd.extend(cmd)
return sub_proc
try:
with (
patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"),
patch("asyncio.create_subprocess_exec", side_effect=fake_exec),
):
res = await runner.run_task(task="Проверь задачи Jira", role="Jira Specialist")
assert res == "Найдено 3 активных тикета в Jira."
assert "--model" in captured_cmd
assert captured_cmd[captured_cmd.index("--model") + 1] == "gemini-3.8-flash-medium"
finally:
if getattr(runner, "_mcp_bridge", None) is not None:
await runner._mcp_bridge.stop()