refactor: remove verified unused internals (#6460)

* refactor: remove verified unused internals

* test(linear): synchronize webhook shutdown with writer join
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-26 21:45:36 +08:00
1 parent 3230013963
commit f23a6d1485
105 files changed
+207 -1282

No files matched your search

-3
View File
@@ -196,9 +196,6 @@ class TestGetFieldTypeInfo:
def test_handles_none_annotation(self):
"""Field with None annotation defaults to str."""
class Model(BaseModel):
field: Any = None
# Create a mock field_info with None annotation
field_info = SimpleNamespace(annotation=None)
type_name, inner = _get_field_type_info(field_info)
+1 -18
View File
@@ -3,13 +3,12 @@
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from unittest.mock import AsyncMock, MagicMock
import pytest
import tiktoken
from agent.runner_helpers import make_run_spec
from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput
from nanobot.agent.context_governance import (
BACKFILL_CONTENT,
@@ -77,22 +76,6 @@ def _compaction_state(spec: AgentRunSpec) -> ContextCompactionState:
)
def _make_loop(tmp_path):
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
return loop
async def test_provider_can_emit_without_an_event_specific_runner_callback():
from nanobot.events import AgentEvent
-11
View File
@@ -27,10 +27,8 @@ from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import cmd_new, register_builtin_commands
from nanobot.command.router import CommandContext, CommandRouter
from nanobot.config.schema import AgentDefaults, Config
from nanobot.providers.base import GenerationSettings
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionManager
from nanobot.utils.llm_runtime import LLMRuntime
# ---------------------------------------------------------------------------
# Helpers
@@ -54,15 +52,6 @@ def _make_loop(tmp_path: Path, unified_session: bool = False) -> AgentLoop:
return loop
def _runtime(provider) -> LLMRuntime:
provider.generation = GenerationSettings(max_tokens=100)
return LLMRuntime.capture(
provider,
"test-model",
context_window_tokens=1000,
)
def _make_msg(channel: str = "telegram", chat_id: str = "111",
session_key_override: str | None = None) -> InboundMessage:
return InboundMessage(
@@ -104,7 +104,7 @@ async def test_dispatch_forwards_all_compaction_phases_before_adapter_filtering(
def test_global_notice_policy_and_channel_override(manager, global_value, override, key):
manager.config.channels.show_compaction_notices = global_value
section = {} if override is None else {key: override}
channel = manager._build_channel("mock", _MockChannel, section)
channel = manager._build_channel(_MockChannel, section)
assert channel.show_compaction_notices is (global_value if override is None else override)
@@ -112,10 +112,10 @@ def test_global_notice_config_round_trip_and_rebuild(manager):
assert Config().channels.show_compaction_notices is False
manager.config = Config.model_validate({"channels": {"showCompactionNotices": True}})
manager.config = Config.model_validate_json(manager.config.model_dump_json(by_alias=True))
assert manager._build_channel("mock", _MockChannel, {}).show_compaction_notices is True
assert manager._build_channel(_MockChannel, {}).show_compaction_notices is True
# Rebuilding an adapter after a config change must resolve the new default.
manager.config.channels.show_compaction_notices = False
assert manager._build_channel("mock", _MockChannel, {}).show_compaction_notices is False
assert manager._build_channel(_MockChannel, {}).show_compaction_notices is False
assert manager._build_channel(
"mock", _MockChannel, {"showCompactionNotices": True},
_MockChannel, {"showCompactionNotices": True},
).show_compaction_notices
@@ -77,7 +77,7 @@ def bus():
@pytest.fixture
def manager(config, bus, tmp_path):
manager = ChannelManager(config, bus, config_path=tmp_path / "config.json")
manager.channels["mock"] = manager._build_channel("mock", MockChannel, {})
manager.channels["mock"] = manager._build_channel(MockChannel, {})
return manager
@@ -288,7 +288,6 @@ class TestProgressFiltering:
def test_progress_visibility_uses_channel_overrides(self, manager, bus):
manager.channels["mock"] = manager._build_channel(
"mock",
MockChannel,
{"sendProgress": False, "sendToolHints": False},
)
@@ -307,7 +306,6 @@ class TestProgressFiltering:
manager.bus = bus
channel = manager._build_channel(
"mattermost",
MattermostChannel,
{"enabled": True},
)
@@ -316,7 +314,6 @@ class TestProgressFiltering:
assert channel.send_tool_hints is False
opted_in = manager._build_channel(
"mattermost",
MattermostChannel,
{
"enabled": True,
+1 -1
View File
@@ -110,5 +110,5 @@ def test_qq_inherits_global_unless_legacy_override_is_explicit(
section["showCompactionNotices"] = str(override).lower() if legacy_string else override
if typed:
section = QQConfig.model_validate(section)
channel = manager._build_channel("qq", QQChannel, section)
channel = manager._build_channel(QQChannel, section)
assert channel.show_compaction_notices is (global_value if override is None else override)
+2 -7
View File
@@ -2416,10 +2416,7 @@ def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path)
def fake_dev_server(**kwargs):
seen["dev_kwargs"] = kwargs
seen["dev_running"] = True
dev_server = SimpleNamespace(
url=kwargs["browser_url"],
ensure_running=lambda: None,
)
dev_server = SimpleNamespace(ensure_running=lambda: None)
seen["dev_server"] = dev_server
try:
yield dev_server
@@ -2464,11 +2461,9 @@ def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path)
dev_kwargs = seen["dev_kwargs"]
assert isinstance(dev_kwargs, dict)
assert dev_kwargs["target_url"] == "http://127.0.0.1:8899"
browser_url = dev_kwargs["browser_url"]
assert isinstance(browser_url, str)
saved = json.loads(config_file.read_text(encoding="utf-8"))
secret = saved["channels"]["websocket"]["tokenIssueSecret"]
assert browser_url == f"http://127.0.0.1:5173/#/?bootstrapSecret={secret}"
browser_url = f"http://127.0.0.1:5173/#/?bootstrapSecret={secret}"
assert seen["start_options"].port == 18888
assert seen["attached_while_dev_running"] is True
assert seen["attach_kwargs"]["poll_hook"] == seen["dev_server"].ensure_running
@@ -16,13 +16,12 @@ from nanobot.events import ContextCompactionEvent, EventSink
from nanobot.providers.factory import make_provider
from nanobot.providers.openai_codex_provider import (
OpenAICodexProvider,
_build_codex_http_error,
_build_reasoning_options,
_codex_error_details,
_codex_error_response,
_CodexHTTPError,
_friendly_error,
_request_codex,
_should_retry_status,
)
from nanobot.providers.openai_responses import (
build_responses_state,
@@ -107,7 +106,7 @@ def codex_warning_log(monkeypatch):
def test_codex_http_friendly_error_omits_raw_body() -> None:
raw = "raw upstream body with PRIVATE PROMPT MUST NOT APPEAR"
message = _friendly_error(500, raw)
message = str(_build_codex_http_error(500, httpx.Headers(), raw))
assert message == "HTTP 500: Codex API request failed"
assert "PRIVATE PROMPT MUST NOT APPEAR" not in message
@@ -825,7 +824,10 @@ async def test_codex_429_preserves_retry_semantics(
def test_codex_429_friendly_message_fallback_does_not_override_unknown_retry() -> None:
response = _codex_error_response(
_CodexHTTPError(_friendly_error(429, ""), status_code=429)
_CodexHTTPError(
"ChatGPT usage quota exceeded or rate limit triggered. Please try again later.",
status_code=429,
)
)
assert response.error_status_code == 429
@@ -843,9 +845,9 @@ def test_codex_429_classification_uses_raw_error_semantics(
raw: str,
expected_retry: bool,
) -> None:
error_type, error_code = provider_base.LLMProvider._extract_error_type_code(raw)
error = _build_codex_http_error(429, httpx.Headers(), raw)
assert _should_retry_status(429, error_type, error_code, raw) is expected_retry
assert error.should_retry is expected_retry
def test_codex_reasoning_options_request_summary_without_forcing_effort() -> None:
-5
View File
@@ -44,11 +44,6 @@ def mock_agent():
return _make_mock_agent()
@pytest.fixture
def app(mock_agent):
return create_app(mock_agent, model_name="test-model", request_timeout=10.0, api_key=API_KEY)
@pytest_asyncio.fixture
async def aiohttp_client():
clients: list[TestClient] = []
+4 -4
View File
@@ -30,7 +30,7 @@ def test_copilot_prompt_poll_and_owned_cancellation(monkeypatch):
registry = WebUIOAuthFlowRegistry()
payload = login_oauth_provider(
Config(), {"provider": ["github_copilot"]}, oauth_flows=registry,
config_path=None, settings_payload=lambda **_: {},
config_path=None,
)
assert set(payload) == {
"status", "provider", "flow_id", "authorization_url", "user_code",
@@ -73,14 +73,14 @@ def test_cancels_copilot_login_while_device_prompt_is_loading(monkeypatch, tmp_p
get_token_path=lambda: tmp_path / "copilot.json", save=saved.append,
))
registry = WebUIOAuthFlowRegistry()
kwargs = dict(oauth_flows=registry, config_path=None, settings_payload=lambda **_: {})
kwargs = dict(oauth_flows=registry, config_path=None)
query = {"provider": ["github_copilot"]}
with ThreadPoolExecutor(max_workers=1) as pool:
started = pool.submit(login_oauth_provider, Config(), query, **kwargs)
try:
assert entered.wait(2)
if action == "logout":
logout_oauth_provider(query, **kwargs)
logout_oauth_provider(query, **kwargs, settings_payload=lambda **_: {})
else:
replacement = login_oauth_provider(Config(), query, **kwargs)
assert registry.get("github_copilot", replacement["flow_id"]) is not None
@@ -114,7 +114,7 @@ def test_failed_copilot_start_removes_registered_flow(monkeypatch):
with pytest.raises(WebUISettingsError, match="GitHub sign-in failed"):
login_oauth_provider(
Config(), {"provider": ["github_copilot"]}, oauth_flows=registry,
config_path=None, settings_payload=lambda **_: {},
config_path=None,
)
assert len(registered) == 1
provider, flow_id, flow = registered[0]
+1 -4
View File
@@ -81,7 +81,6 @@ def test_start_webui_dev_server_uses_vite_directly_and_sets_proxy_target(
server = start_webui_dev_server(
target_url="http://127.0.0.1:8899",
browser_url="http://127.0.0.1:5173/#/?bootstrapSecret=secret",
source_dir=source,
runner="bun",
environ={"EXISTING": "value"},
@@ -119,7 +118,6 @@ def test_dev_server_installs_locked_dependencies_when_vite_is_missing(tmp_path:
start_webui_dev_server(
target_url="http://127.0.0.1:8765",
browser_url="http://127.0.0.1:5173",
source_dir=source,
runner="bun",
popen=lambda *_args, **_kwargs: process,
@@ -135,7 +133,6 @@ def test_dev_server_requires_a_source_checkout(tmp_path: Path) -> None:
with pytest.raises(WebUIDevError, match="source checkout"):
start_webui_dev_server(
target_url="http://127.0.0.1:8765",
browser_url="http://127.0.0.1:5173",
source_dir=tmp_path / "missing",
)
@@ -168,7 +165,7 @@ def test_dev_server_context_stops_the_child(monkeypatch) -> None:
server.stop = lambda: stopped.append(True)
monkeypatch.setattr("nanobot.webui.dev.start_webui_dev_server", lambda **_kwargs: server)
with run_webui_dev_server(target_url="unused", browser_url="unused") as running:
with run_webui_dev_server(target_url="unused") as running:
assert running is server
assert stopped == [True]
-7
View File
@@ -8,7 +8,6 @@ import pytest
from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import (
SessionHandle,
SessionHandleResolver,
session_handle_for_name,
)
@@ -26,12 +25,6 @@ def _save_session(manager: SessionManager, key: str, title: str) -> None:
manager.save(session)
def _handle(manager: SessionManager, key: str) -> SessionHandle:
handle = SessionHandleResolver(manager).handle_for_session(key)
assert handle is not None
return handle
@pytest.mark.parametrize("raw", [None, []], ids=["missing", "empty"])
async def test_empty_mentions_do_not_wait_for_unrelated_storage(tmp_path, monkeypatch, raw):
manager = SessionManager(tmp_path)