From 51fa1a7f7437429ef5fca583fb68b4f20e2c21fe Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:11:00 +0800 Subject: [PATCH] refactor: remove unreachable code and redundant tests (#6729) * refactor: prune unreachable runtime and WebUI paths * test: drop duplicate cases and assertions for obsolete selectors --- nanobot/agent/subagent.py | 4 +- nanobot/channels/manager.py | 9 +--- nanobot/channels/qq/runtime.py | 4 +- nanobot/channels/signal/runtime.py | 10 ----- .../wecom/tests/test_wecom_channel.py | 4 -- nanobot/channels/weixin/runtime.py | 24 +++-------- nanobot/utils/helpers.py | 6 --- nanobot/webui/history.py | 4 -- nanobot/webui/mcp_presets_api.py | 41 +++++++++---------- nanobot/webui/transcript.py | 8 ---- tests/agent/test_memory_store.py | 23 ----------- .../test_responses_circuit_breaker.py | 6 --- tests/tools/test_mcp_tool.py | 10 ----- webui/src/globals.css | 30 -------------- webui/src/providers/UpdateFlowProvider.tsx | 2 +- webui/src/tests/app-layout.test.tsx | 2 - webui/src/tests/automations-settings.test.tsx | 1 - webui/src/tests/message-bubble.test.tsx | 3 +- webui/src/tests/thread-composer.test.tsx | 3 -- webui/src/tests/thread-shell.test.tsx | 1 - 20 files changed, 32 insertions(+), 163 deletions(-) diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 26d81f7c4..0522be259 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -557,11 +557,11 @@ class SubagentManager: def _build_tools( self, - workspace: Path | None = None, + *, tools_config: ToolsConfig | None = None, exec_manager: ExecSessionManager | None = None, ) -> ToolRegistry: - root = self.workspace if workspace is None else workspace + root = self.workspace registry = ToolRegistry() cfg = tools_config if tools_config is not None else self._subagent_tools_config() ctx = ToolContext( diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index c6be72d2f..a805a0310 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -34,7 +34,6 @@ from nanobot.channels.contracts import ( resolve_channel_action_target, ) from nanobot.channels.outbox import RETRY_SECONDS, DeliveryOutbox -from nanobot.channels.registry import channel_default_enabled from nanobot.config.schema import Config from nanobot.security.workspace_access import WorkspaceScopeResolver from nanobot.security.workspace_policy import resolve_allowed_path @@ -174,14 +173,10 @@ class ChannelManager: self, name: str, *, - config: Config | None = None, + default_enabled: bool, default_sections: dict[str, Any] | None = None, - default_enabled: bool | None = None, ) -> Any: - config = config or self.config - section = getattr(config.channels, name, None) - if default_enabled is None: - default_enabled = channel_default_enabled(name) + section = getattr(self.config.channels, name, None) if section is not None or not default_enabled: return section if default_sections is None: diff --git a/nanobot/channels/qq/runtime.py b/nanobot/channels/qq/runtime.py index 09505fb6c..d6fe98730 100644 --- a/nanobot/channels/qq/runtime.py +++ b/nanobot/channels/qq/runtime.py @@ -514,7 +514,6 @@ class QQChannel(BaseChannel): file_type=file_type, file_data=file_data_b64, file_name=filename, - srv_send_msg=False, ) if not media_obj: self.logger.error("media upload failed: empty response") @@ -608,7 +607,6 @@ class QQChannel(BaseChannel): file_type: int, file_data: str, file_name: str | None = None, - srv_send_msg: bool = False, ) -> dict[str, Any]: if not self._client: raise RuntimeError("QQ client not initialized") @@ -624,7 +622,7 @@ class QQChannel(BaseChannel): id_key: chat_id, "file_type": file_type, "file_data": file_data, - "srv_send_msg": srv_send_msg, + "srv_send_msg": False, } # Only pass file_name for non-image types (file_type=4). # Passing file_name for images causes QQ client to render them as diff --git a/nanobot/channels/signal/runtime.py b/nanobot/channels/signal/runtime.py index 12557c42a..a97677987 100644 --- a/nanobot/channels/signal/runtime.py +++ b/nanobot/channels/signal/runtime.py @@ -405,11 +405,6 @@ class SignalChannel(BaseChannel): content: str, media: list[str] | None = None, metadata: dict[str, Any] | None = None, - session_key: str | None = None, - is_dm: bool = False, - authorization_id: str | None = None, - require_existing_session: bool = False, - session_generation: str | None = None, ) -> None: """Publish only an inbound message whose Signal policy has already been checked. @@ -421,7 +416,6 @@ class SignalChannel(BaseChannel): ``super()._handle_message`` instead, which goes through ``is_allowed`` and issues a pairing code. """ - del authorization_id meta = metadata or {} if self.supports_streaming: meta = {**meta, "_wants_stream": True} @@ -433,9 +427,6 @@ class SignalChannel(BaseChannel): content=content, media=media or [], metadata=meta, - session_key_override=session_key, - session_generation=session_generation, - require_existing_session=require_existing_session, ) ) @@ -778,7 +769,6 @@ class SignalChannel(BaseChannel): "is_group": is_group_message, "group_id": group_id, }, - is_dm=not is_group_message, ) except Exception: await self._stop_typing(chat_id) diff --git a/nanobot/channels/wecom/tests/test_wecom_channel.py b/nanobot/channels/wecom/tests/test_wecom_channel.py index 8ee91c7f1..5c1a37c41 100644 --- a/nanobot/channels/wecom/tests/test_wecom_channel.py +++ b/nanobot/channels/wecom/tests/test_wecom_channel.py @@ -80,10 +80,6 @@ def test_sanitize_filename_keeps_chinese_chars() -> None: assert _sanitize_filename("文件(1).jpg") == "文件(1).jpg" -def test_sanitize_filename_empty_input() -> None: - assert _sanitize_filename("") == "unnamed" - - def test_sanitize_filename_empty_or_dots_fallback() -> None: assert _sanitize_filename("...") == "unnamed" assert _sanitize_filename("..", fallback="fallback.txt") == "fallback.txt" diff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.py index 127f2107d..0fdab1c38 100644 --- a/nanobot/channels/weixin/runtime.py +++ b/nanobot/channels/weixin/runtime.py @@ -2239,18 +2239,14 @@ class WeixinChannel(BaseChannel): to_user_id: str, text: str, context_token: str, - *, - client_id: str | None = None, - run_id: str = "", ) -> None: options = _SEND_OPTIONS.get() self._ensure_context_budget( context_token, reserve=options.reserve_budget if options else 0, ) - client_id = client_id or (options.client_id if options else None) - client_id = client_id or f"nanobot-{uuid.uuid4().hex[:12]}" - run_id = run_id or (options.run_id if options else "") + client_id = (options.client_id if options else None) or f"nanobot-{uuid.uuid4().hex[:12]}" + run_id = options.run_id if options else "" item_list: list[dict[str, Any]] = [] if text: @@ -2284,11 +2280,6 @@ class WeixinChannel(BaseChannel): to_user_id: str, media_path: str, context_token: str, - *, - client_id: str | None = None, - file_key: str | None = None, - aes_key_raw: bytes | None = None, - run_id: str = "", ) -> None: """Upload a local file to WeChat CDN and send it as a media message. @@ -2327,16 +2318,14 @@ class WeixinChannel(BaseChannel): item_key = "file_item" options = _SEND_OPTIONS.get() - aes_key_raw = aes_key_raw or (options.aes_key_raw if options else None) - aes_key_raw = aes_key_raw or os.urandom(16) + aes_key_raw = (options.aes_key_raw if options else None) or os.urandom(16) aes_key_hex = aes_key_raw.hex() # Compute encrypted size: PKCS7 padding to 16-byte boundary # Matches aesEcbPaddedSize: Math.ceil((size + 1) / 16) * 16 padded_size = ((raw_size + 1 + 15) // 16) * 16 - file_key = file_key or (options.file_key if options else None) - file_key = file_key or os.urandom(16).hex() + file_key = (options.file_key if options else None) or os.urandom(16).hex() upload_body: dict[str, Any] = { "filekey": file_key, "media_type": upload_type, @@ -2408,9 +2397,8 @@ class WeixinChannel(BaseChannel): media_item["len"] = str(raw_size) # Send each media item as its own message (matching reference plugin) - client_id = client_id or (options.client_id if options else None) - client_id = client_id or f"nanobot-{uuid.uuid4().hex[:12]}" - run_id = run_id or (options.run_id if options else "") + client_id = (options.client_id if options else None) or f"nanobot-{uuid.uuid4().hex[:12]}" + run_id = options.run_id if options else "" item_list: list[dict[str, Any]] = [ {"type": item_type, item_key: media_item} ] diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.py index 619691638..b5503114e 100644 --- a/nanobot/utils/helpers.py +++ b/nanobot/utils/helpers.py @@ -6,7 +6,6 @@ import re import shutil import time from contextlib import suppress -from datetime import datetime from pathlib import Path from threading import Lock from typing import TYPE_CHECKING, Any, TypeVar, cast, overload @@ -351,11 +350,6 @@ def build_image_content_blocks( ] -def timestamp() -> str: - """Current ISO timestamp.""" - return datetime.now().isoformat() - - _UNSAFE_CHARS = re.compile(r'[<>:"/\\|?*]') _TOOL_RESULTS_DIR = ".nanobot/tool-results" _TOOL_RESULT_RETENTION_SECS = 7 * 24 * 60 * 60 diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py index 288831a26..eb920b48a 100644 --- a/nanobot/webui/history.py +++ b/nanobot/webui/history.py @@ -108,10 +108,6 @@ def _records_from_entries( for position, fact in entries] -def turn_records(history: HistoryReader, ordinal: int) -> list[dict[str, Any]]: - return _records_from_entries(history, ordinal, history.read_entries(ordinal)) - - def turn_record_page( history: HistoryReader, ordinal: int, *, start: int, end: int, reverse: bool, max_records: int, max_bytes: int, allow_oversized: bool = False, diff --git a/nanobot/webui/mcp_presets_api.py b/nanobot/webui/mcp_presets_api.py index b57233398..84b43eb25 100644 --- a/nanobot/webui/mcp_presets_api.py +++ b/nanobot/webui/mcp_presets_api.py @@ -658,39 +658,36 @@ def _display_name_for(name: str, preset: McpPreset | None = None) -> str: return preset.display_name if preset is not None else name -def _action_message(action: str, preset: McpPreset, *, ok: bool = True) -> dict[str, Any]: - verb = { - "enable": "Enabled", - "remove": "Removed", - "test": "Checked", - }.get(action, "Updated") - payload: dict[str, Any] = { - "ok": ok, - "message": f"{verb} MCP preset for {preset.display_name}.", - } +def _action_message(action: Literal["enable", "remove"], preset: McpPreset) -> dict[str, Any]: if action == "enable": - payload["installed"] = True - payload["verification"] = ["config_present"] - elif action == "remove": - payload["removed"] = True - payload["verification"] = ["config_absent"] - return payload + return { + "ok": True, + "message": f"Enabled MCP preset for {preset.display_name}.", + "installed": True, + "verification": ["config_present"], + } + return { + "ok": True, + "message": f"Removed MCP preset for {preset.display_name}.", + "removed": True, + "verification": ["config_absent"], + } -def _server_action_message(action: str, name: str, *, ok: bool = True) -> dict[str, Any]: +def _server_action_message( + action: Literal["custom", "tools", "remove", "reconnect"], name: str, +) -> dict[str, Any]: verb = { "custom": "Saved", - "import": "Imported", - "import-cursor": "Imported", "tools": "Updated tools for", "remove": "Removed", "reconnect": "Retried connection for", - }.get(action, "Updated") + }[action] payload: dict[str, Any] = { - "ok": ok, + "ok": True, "message": f"{verb} MCP server {name}.", } - if action in {"custom", "import", "import-cursor"}: + if action == "custom": payload["installed"] = True payload["verification"] = ["config_present"] elif action == "remove": diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 66c660588..9292b54d0 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -44,7 +44,6 @@ from nanobot.webui.history import ( initialize_history, record_from_fact, turn_record_page, - turn_records, ) from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY from nanobot.webui.outbound_wire import project_tool_events @@ -943,16 +942,9 @@ def has_pending_tool_calls( "file_edit", }: return True - if ev in {WEBUI_FORK_MARKER_EVENT}: - continue return False -def has_unfinished_transcript_tail(session_key: str, *, history: HistoryReader) -> bool: - count = history.turn_count - return bool(count and has_pending_tool_calls(turn_records(history, count - 1))) - - def completed_turn_ids(lines: list[dict[str, Any]]) -> list[str]: """Return stable identities for turns with an explicitly persisted completion.""" completed: list[str] = [] diff --git a/tests/agent/test_memory_store.py b/tests/agent/test_memory_store.py index 97bf11e9d..204f6ab62 100644 --- a/tests/agent/test_memory_store.py +++ b/tests/agent/test_memory_store.py @@ -90,14 +90,6 @@ class TestHistoryWithCursor: assert data["cursor"] == cursor assert data["content"] == expected_content - def test_read_unprocessed_history(self, store): - store.append_history("event 1") - store.append_history("event 2") - store.append_history("event 3") - entries = store.read_unprocessed_history(since_cursor=1) - assert len(entries) == 2 - assert entries[0]["cursor"] == 2 - def test_read_unprocessed_history_returns_all_when_cursor_zero(self, store): store.append_history("event 1") store.append_history("event 2") @@ -189,21 +181,6 @@ class TestHistoryWithCursor: entries = store.read_unprocessed_history(since_cursor=0) assert [entry["cursor"] for entry in entries] == list(range(21, 101)) - def test_write_entries_uses_atomic_write(self, tmp_path): - store = MemoryStore(tmp_path) - store.append_history("event 1") - store.append_history("event 2") - store.append_history("event 3") - entries = store.read_unprocessed_history(since_cursor=0) - - tmp_path_obj = store.history_file.with_suffix(".jsonl.tmp") - assert not tmp_path_obj.exists() - - store._write_entries(entries) - - assert not tmp_path_obj.exists() - assert store.history_file.exists() - def test_write_entries_cleans_up_tmp_on_exception(self, tmp_path, monkeypatch): store = MemoryStore(tmp_path) store.append_history("event 1") diff --git a/tests/providers/test_responses_circuit_breaker.py b/tests/providers/test_responses_circuit_breaker.py index d48586247..2a181f50d 100644 --- a/tests/providers/test_responses_circuit_breaker.py +++ b/tests/providers/test_responses_circuit_breaker.py @@ -129,12 +129,6 @@ def test_responses_declaration_routes_other_models(provider): assert provider._should_use_responses_api("gpt-4o", None) is True -def test_circuit_opens_after_threshold(provider): - for _ in range(_RESPONSES_FAILURE_THRESHOLD): - provider._record_responses_failure("gpt-5", None) - assert provider._should_use_responses_api("gpt-5", None) is False - - def test_circuit_does_not_affect_other_models(provider): for _ in range(_RESPONSES_FAILURE_THRESHOLD): provider._record_responses_failure("gpt-5", None) diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.py index 86f72a6cc..92b43e1e2 100644 --- a/tests/tools/test_mcp_tool.py +++ b/tests/tools/test_mcp_tool.py @@ -2307,16 +2307,6 @@ def test_sanitize_name_noop_for_already_clean_names() -> None: assert _sanitize_name("mcp_server_tool") == "mcp_server_tool" -def test_tool_wrapper_sanitizes_name() -> None: - tool_def = SimpleNamespace( - name="My Tool", - description="tool with spaces", - inputSchema={"type": "object", "properties": {}}, - ) - wrapper = MCPToolWrapper(SimpleNamespace(call_tool=None), "srv", tool_def) - assert wrapper.name == "mcp_srv_My_Tool" - - def test_resource_wrapper_sanitizes_name() -> None: resource_def = SimpleNamespace( name="PostgreSQL System Information", diff --git a/webui/src/globals.css b/webui/src/globals.css index b3c4fe7df..a8bfcf436 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -348,36 +348,6 @@ overflow: hidden; } - .kv-cache-not-reused { - background: hsl(var(--usage-token) / 0.84); - } - - .kv-cache-reused { - background-color: hsl(var(--usage-token) / 0.1); - background-image: repeating-linear-gradient( - 135deg, - hsl(var(--usage-token) / 0.46) 0, - hsl(var(--usage-token) / 0.46) 1px, - transparent 1px, - transparent 4px - ); - } - - .dark .kv-cache-not-reused { - background: hsl(var(--usage-token) / 0.92); - } - - .dark .kv-cache-reused { - background-color: hsl(var(--usage-token) / 0.15); - background-image: repeating-linear-gradient( - 135deg, - hsl(var(--usage-token) / 0.58) 0, - hsl(var(--usage-token) / 0.58) 1px, - transparent 1px, - transparent 4px - ); - } - .composer-model-badge::before { content: ""; position: absolute; diff --git a/webui/src/providers/UpdateFlowProvider.tsx b/webui/src/providers/UpdateFlowProvider.tsx index 81de30690..93bd82c15 100644 --- a/webui/src/providers/UpdateFlowProvider.tsx +++ b/webui/src/providers/UpdateFlowProvider.tsx @@ -324,7 +324,7 @@ export function UpdateFlowProvider({ client, token, enabled, canSettleHandoff = : blocked ? ownerInstructions : null}
{!done && !blocked && }