refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
"""Backend helpers for the bundled WebUI surface."""
-2
View File
@@ -1,5 +1,3 @@
"""Read-only local attachment checks shared by WebUI and native TUI ingress."""
from __future__ import annotations
import mimetypes
-2
View File
@@ -1,5 +1,3 @@
"""Resolve authenticated WebUI choices to existing, same-scope session routes."""
from collections import Counter
from dataclasses import dataclass, replace
from typing import Any, cast
-2
View File
@@ -1,5 +1,3 @@
"""Read the response of a selected automation run without exposing its audit metadata."""
from __future__ import annotations
import json
-2
View File
@@ -1,5 +1,3 @@
"""Helpers for keeping the bundled WebUI build in sync with source checkouts."""
from __future__ import annotations
import os
-2
View File
@@ -1,5 +1,3 @@
"""CLI Apps helpers for the WebUI HTTP and message surfaces."""
from __future__ import annotations
import asyncio
-1
View File
@@ -63,7 +63,6 @@ def assess_webui_contract(value: object) -> Compatibility:
}
if not isinstance(value, dict):
return result
# Only the mapping shape is established here; validate each value below.
data = cast(dict[object, object], value)
version = data.get("version")
if isinstance(version, str) and len(version) <= 80 and version.isprintable():
-2
View File
@@ -1,5 +1,3 @@
"""Vite development-server lifecycle for the WebUI source checkout."""
from __future__ import annotations
import os
-2
View File
@@ -1,5 +1,3 @@
"""Workspace-scoped source preview payloads for the WebUI."""
from __future__ import annotations
import base64
-2
View File
@@ -1,5 +1,3 @@
"""WebUI chat fork orchestration."""
from __future__ import annotations
import uuid
-2
View File
@@ -1,5 +1,3 @@
"""HTTP and handshake composition for the WebUI gateway listener."""
from __future__ import annotations
import hmac
-2
View File
@@ -1,5 +1,3 @@
"""Composition helpers for the embedded WebUI gateway."""
from __future__ import annotations
from collections.abc import Awaitable, Mapping
-2
View File
@@ -1,5 +1,3 @@
"""Token state for the embedded WebUI gateway."""
from __future__ import annotations
import secrets
-2
View File
@@ -1,5 +1,3 @@
"""WebUI projection of durable session facts."""
from __future__ import annotations
from collections.abc import Mapping
-2
View File
@@ -1,5 +1,3 @@
"""Shared HTTP helpers for the embedded WebUI gateway."""
from __future__ import annotations
import email.utils
-2
View File
@@ -1,5 +1,3 @@
"""Application orchestration for typed WebUI WebSocket commands."""
from __future__ import annotations
import asyncio
-2
View File
@@ -1,5 +1,3 @@
"""Gateway-owned browser authorization flows for remote MCP servers."""
from __future__ import annotations
import asyncio
-2
View File
@@ -1,5 +1,3 @@
"""Typed loader for the bundled MCP service catalogue."""
from __future__ import annotations
from dataclasses import dataclass
+2 -4
View File
@@ -1,5 +1,3 @@
"""MCP preset helpers for the WebUI settings and message surfaces."""
from __future__ import annotations
import asyncio
@@ -920,7 +918,7 @@ def _normalize_transport(value: str | None, *, command: str = "", url: str = "")
if url.rstrip("/").endswith("/sse"):
return "sse"
return "streamableHttp"
aliases = {
aliases: dict[str, Literal["stdio", "sse", "streamableHttp"]] = {
"stdio": "stdio",
"sse": "sse",
"streamableHttp": "streamableHttp",
@@ -931,7 +929,7 @@ def _normalize_transport(value: str | None, *, command: str = "", url: str = "")
normalized = aliases.get(raw)
if normalized is None:
raise McpPresetError("unsupported MCP transport")
return normalized # type: ignore[return-value]
return normalized
def _normalize_auth(
-2
View File
@@ -1,5 +1,3 @@
"""Compatibility export for persisted WebUI MCP preset metadata."""
from nanobot.agent.tools.mcp import session_extra
__all__ = ["session_extra"]
-3
View File
@@ -1,5 +1,3 @@
"""Signed media helpers for the WebUI HTTP surface."""
from __future__ import annotations
import base64
@@ -77,7 +75,6 @@ _BYTE_RANGE_RE = re.compile(r"^bytes=(\d*)-(\d*)$")
def _parse_single_byte_range(range_header: str, size: int) -> tuple[int, int]:
"""Parse a single HTTP byte range for signed media responses."""
if size <= 0 or "," in range_header:
raise ValueError("invalid byte range")
m = _BYTE_RANGE_RE.fullmatch(range_header.strip())
-2
View File
@@ -1,5 +1,3 @@
"""Media gateway services shared by WebUI HTTP routes and WebSocket frames."""
from __future__ import annotations
import secrets
-2
View File
@@ -1,5 +1,3 @@
"""Shared WebUI metadata keys."""
from nanobot.bus.events import INBOUND_META_TURN_ID
WEBUI_TURN_METADATA_KEY = INBOUND_META_TURN_ID
-1
View File
@@ -1,4 +1,3 @@
"""Nanobot optional feature helpers for WebUI Settings."""
from __future__ import annotations
from pathlib import Path
-3
View File
@@ -1,5 +1,3 @@
"""Select local SSH files for the WebUI without reading their contents."""
from __future__ import annotations
import asyncio
@@ -132,7 +130,6 @@ def _picker_command() -> _PickerCommand | None:
def _picker_environment() -> dict[str, str]:
"""Pass only host UI/runtime variables, never provider or gateway secrets."""
keys: list[str] = list(_COMMON_ENV_KEYS)
if sys.platform == "darwin":
keys.extend(_MACOS_GUI_ENV_KEYS)
-2
View File
@@ -1,5 +1,3 @@
"""Own WebUI outbound projection, stream state and durable delivery completion."""
from __future__ import annotations
import json
-3
View File
@@ -1,5 +1,3 @@
"""Encode typed outbound events for the WebUI wire protocol."""
from __future__ import annotations
import time
@@ -29,7 +27,6 @@ def _is_base64_data_url(value: str) -> bool:
def _project_tool_event_value(value: object) -> _JSONValue:
"""Copy one dynamic value while removing inline binary payloads."""
if value is None or isinstance(value, bool | int | float):
return value
if isinstance(value, str):
-6
View File
@@ -1,5 +1,3 @@
"""WebUI restart recovery over durable session checkpoints."""
from __future__ import annotations
import asyncio
@@ -74,7 +72,6 @@ class RecoveryCoordinator:
self._active_recovery_tasks.pop(session_key, None)
async def _cancel_active_recovery(self, session_key: str) -> None:
"""Stop an explicit continuation before accepting newer user input."""
task = self._active_recovery_tasks.get(session_key)
if task is None or task is asyncio.current_task() or task.done():
return
@@ -115,7 +112,6 @@ class RecoveryCoordinator:
await self._publish(route[1], failed)
async def _recovery_candidates(self) -> list[str]:
"""Display-only sessions also have canonical headers in SQLite."""
return [item["key"] for item in await self.sessions.state.list_sessions()]
@staticmethod
@@ -418,7 +414,6 @@ class RecoveryCoordinator:
)
async def _requeue_pending_followups(self, session: Session) -> None:
"""Return durable live-turn follow-ups to the bus after a restart."""
for message in pending_followups(session):
await self.bus.publish_inbound(message)
@@ -436,7 +431,6 @@ class RecoveryCoordinator:
chat_id: str,
state: Mapping[str, Any],
) -> None:
"""Publish the recovery state and invalidate its sidebar projection."""
await self.bus.publish_outbound(
outbound_message_for_event(
channel="websocket",
-2
View File
@@ -1,5 +1,3 @@
"""Local connection directory. Owns SSH tunnels, never remote gateway lifetimes."""
from __future__ import annotations
import asyncio
-2
View File
@@ -1,5 +1,3 @@
"""An owned OpenSSH master, never a user's shared control socket."""
from __future__ import annotations
import asyncio
-2
View File
@@ -1,5 +1,3 @@
"""Shared validation and secret handling for request settings editors."""
from __future__ import annotations
import json
-2
View File
@@ -1,5 +1,3 @@
"""Validate WebUI session references against persisted session metadata."""
from __future__ import annotations
import json
+2 -4
View File
@@ -1,5 +1,3 @@
"""Automation payloads for the embedded WebUI."""
from __future__ import annotations
from collections.abc import Collection
@@ -10,8 +8,8 @@ from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
message_preview_text, # pyright: ignore[reportPrivateUsage]
metadata_title, # pyright: ignore[reportPrivateUsage]
message_preview_text,
metadata_title,
)
from nanobot.triggers.local_types import LocalTrigger
from nanobot.webui.session_identity import is_webui_session_key
-2
View File
@@ -1,5 +1,3 @@
"""Read-only projection of the session material available to the agent."""
from __future__ import annotations
from typing import Any, cast
-2
View File
@@ -1,5 +1,3 @@
"""Stable mapping between public WebUI chat IDs and persisted session keys."""
from __future__ import annotations
import re
-2
View File
@@ -1,5 +1,3 @@
"""Sidebar projection from session headers and SQLite display summaries."""
from __future__ import annotations
import json
-2
View File
@@ -1,5 +1,3 @@
"""WebUI session read models exposed to interactive clients."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Protocol, cast
-2
View File
@@ -1,5 +1,3 @@
"""Capability settings domain logic for Web, media, network, and API features."""
from __future__ import annotations
import asyncio
-2
View File
@@ -1,5 +1,3 @@
"""Stable request and error contracts shared by WebUI settings domains."""
from __future__ import annotations
from dataclasses import dataclass
-6
View File
@@ -407,7 +407,6 @@ def _provider_settings_rows(
selected_provider: str | None,
oauth_status: OAuthStatusReader,
) -> list[dict[str, Any]]:
"""Return one Settings row per provider family while preserving legacy configs."""
aliases: dict[str, list[Any]] = {}
for spec in PROVIDERS:
if spec.settings_alias_for:
@@ -525,7 +524,6 @@ def _model_shutdown_date(row: object) -> date | None:
def _model_catalog_row_active(row: object, *, on: date | None = None) -> bool:
"""True when a provider catalog row should stay in the advisory model list."""
shutdown = _model_shutdown_date(row)
if shutdown is None:
return True
@@ -828,7 +826,6 @@ def _model_configuration_slug(label: str) -> str:
def _model_configuration_name(value: str) -> str:
"""Validate a user-facing preset name without inventing a second identity."""
name = value.strip()
if not name:
raise WebUISettingsError("configuration name is required")
@@ -855,7 +852,6 @@ def _model_configuration_name_exists(
def _rename_model_configuration(config: Config, old_name: str, new_name: str) -> bool:
"""Rename one preset and every config reference to it."""
if old_name == new_name:
return False
if _model_configuration_name_exists(config, new_name, exclude=old_name):
@@ -916,7 +912,6 @@ def _provider_display_name_exists(
def _unique_model_configuration_name(config: Config, label: str) -> str:
"""Return a stable, unused preset name for a migrated model configuration."""
try:
base = _model_configuration_slug(label)
except WebUISettingsError:
@@ -1962,7 +1957,6 @@ class ModelSettingsHandler:
self._remove_pending_work = None
def _refresh_runtime_config(self) -> None:
"""Make a successful model-settings mutation visible to live clients now."""
if self.settings.refresh_runtime_config is not None:
self.settings.refresh_runtime_config()
-2
View File
@@ -1,5 +1,3 @@
"""Stable WebSocket/HTTP dispatcher for WebUI settings domains."""
from __future__ import annotations
import asyncio
+1 -3
View File
@@ -1,5 +1,3 @@
"""Explicit non-channel runtime configuration exposed by the settings UI."""
from __future__ import annotations
import ipaddress
@@ -162,7 +160,7 @@ def update_runtime_config(
raise WebUISettingsError("tools.ssrf_whitelist: enter valid IP addresses or CIDR ranges") from None
for path in ("tools.exec.allow_patterns", "tools.exec.deny_patterns"):
if path in values:
patterns = cast(list[str], values[path]) # Schema validation above guarantees list[str].
patterns = cast(list[str], values[path])
for pattern in patterns:
try:
re.compile(pattern)
-2
View File
@@ -1,5 +1,3 @@
"""Gateway-owned state for the WebUI settings surface."""
from __future__ import annotations
import threading
-2
View File
@@ -1,5 +1,3 @@
"""System and channel settings domain logic."""
from __future__ import annotations
import asyncio
-3
View File
@@ -1,5 +1,3 @@
"""Lightweight skill summaries for the WebUI."""
from __future__ import annotations
import json
@@ -203,7 +201,6 @@ def _nanobot_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
def _install_options(metadata: dict[str, Any] | None) -> list[dict[str, str]]:
"""Return safe, copyable setup commands declared by a skill."""
raw_install = _nanobot_metadata(metadata).get("install")
if not isinstance(raw_install, list):
return []
-4
View File
@@ -1,5 +1,3 @@
"""Search and install skills from public Agent Skills catalogs."""
from __future__ import annotations
import asyncio
@@ -57,7 +55,6 @@ _weekly_cache_expires_at = 0.0
def _response_json_object(response: httpx.Response) -> dict[str, Any] | None:
"""Narrow an untyped HTTP JSON response at the external-data boundary."""
payload = cast(object, response.json())
return cast(dict[str, Any], payload) if isinstance(payload, dict) else None
@@ -118,7 +115,6 @@ async def _trending_skills_sh_skills(
*,
limit: int,
) -> dict[str, Any]:
"""Return a source-diverse snapshot of skills.sh's real 24-hour leaderboard."""
try:
async with _skills_client() as client:
response = await client.get(_TRENDING_URL)
-2
View File
@@ -1,5 +1,3 @@
"""Shared SSH errors and owned subprocess shutdown."""
from __future__ import annotations
import asyncio
-2
View File
@@ -1,5 +1,3 @@
"""Instance-local usage and dismissal state for the optional GitHub invitation."""
from __future__ import annotations
import time
-2
View File
@@ -1,5 +1,3 @@
"""Connection-owned Temporary Chat behavior for the WebUI."""
from __future__ import annotations
import uuid
-9
View File
@@ -1,5 +1,3 @@
"""WebUI history projection over durable SQLite session facts."""
from __future__ import annotations
import base64
@@ -90,7 +88,6 @@ _SESSION_HANDLE_ID_RE = re.compile(r"^handle_[0-9a-f]{32}$")
def _response_sources(value: object) -> list[dict[str, str | bool]]:
"""Allow only recorded display identity, never settings or credential blobs."""
if not isinstance(value, list):
return []
result: list[dict[str, str | bool]] = []
@@ -250,7 +247,6 @@ def _stream_key(record: dict[str, Any], stream: str) -> tuple[str, str, str]:
def _projection_receipts(records: Sequence[Mapping[str, Any]]) -> list[_ProjectionReceipt]:
"""Compress actual represented facts by turn, without covering missing sequences."""
members: dict[str, set[int]] = {}
for record in records:
turn_id, sequence = record.get("turn_id"), record.get("turn_seq")
@@ -276,7 +272,6 @@ def _compact_completed_stream_deltas(
*,
include_projection_receipts: bool = False,
) -> tuple[list[dict[str, Any]], int]:
"""Fold transport deltas into canonical end records for a completed turn."""
if not turn or turn[-1].get("event") != "turn_end":
return turn, 0
@@ -904,7 +899,6 @@ def _stable_record_digest(record: dict[str, Any]) -> str:
def _ensure_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Give backfilled/recovered rows a stable identity beside persisted rows."""
annotated: list[dict[str, Any]] = []
for fallback_turn_index, turn in enumerate(_split_transcript_turns(lines)):
anchor = next(
@@ -945,7 +939,6 @@ def _ensure_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Any
def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]:
"""Return durable assistant answer texts used only for backfill matching."""
texts: list[str] = []
stream_parts: list[str] = []
@@ -1537,7 +1530,6 @@ def _client_projection_event(
def _client_projection_deferred_trace_groups(
lines: list[dict[str, Any]],
) -> dict[int, _DeferredTraceGroup]:
"""Group oversized consecutive activity events behind one stable detail ref."""
groups: dict[int, _DeferredTraceGroup] = {}
start: int | None = None
detail_bytes = 0
@@ -1590,7 +1582,6 @@ def _client_projection_deferred_trace_groups(
def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int:
"""Apply the soft page limit in canonical protocol events, not UI rows."""
supported = {
"user",
"delta",
-2
View File
@@ -1,5 +1,3 @@
"""Channel-aware discovery using the same verified feed as update planning."""
from __future__ import annotations
from typing import Any
-2
View File
@@ -1,5 +1,3 @@
"""Logging helpers for the WebUI WebSocket server surface."""
from __future__ import annotations
import logging
-2
View File
@@ -1,5 +1,3 @@
"""Directory metadata for the authenticated WebUI project selector."""
from __future__ import annotations
import heapq
-4
View File
@@ -1,5 +1,3 @@
"""Persisted WebUI project workspace state."""
from __future__ import annotations
import asyncio
@@ -41,7 +39,6 @@ _MAX_DRAFT_SCOPES = 128
def _scope_change_is_non_escalating(current: WorkspaceScope, requested: WorkspaceScope) -> bool:
"""Allow a remote request only when it keeps the project and does not add access."""
return (
requested.project_path == current.project_path
and (not current.restrict_to_workspace or requested.restrict_to_workspace)
@@ -230,7 +227,6 @@ class WebUIWorkspaceController:
self._scope_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
def _scope_lock(self, chat_id: str) -> asyncio.Lock:
"""Serialize draft edits with message admission, not with agent execution."""
lock = self._scope_locks.get(chat_id)
if lock is None:
lock = asyncio.Lock()
-24
View File
@@ -348,11 +348,6 @@ def _resolve_bootstrap_model_name(
return _default_model_name_from_config(config_path) or ""
# ---------------------------------------------------------------------------
# GatewayHTTPHandler
# ---------------------------------------------------------------------------
class _HistoryProjection(Protocol):
def __call__(self, request: WsRequest, key: str, *, history: HistoryReader) -> Response: ...
@@ -461,14 +456,12 @@ class GatewayHTTPHandler:
"""
return True
# -- Token management ---------------------------------------------------
def check_api_token(self, request: WsRequest) -> bool:
if getattr(request, "_nanobot_trusted_proxy_authenticated", False):
return True
return self.tokens.check_api_token(request)
# -- Main dispatch ------------------------------------------------------
async def dispatch(self, connection: Any, request: WsRequest) -> Any | None:
"""Route an HTTP request. Returns Response or None."""
@@ -588,24 +581,20 @@ class GatewayHTTPHandler:
) -> Any | None:
if got == "/api/remote-instances" or got.startswith("/api/remote-instances/"):
return await self._dispatch_remote_instances(connection, request, got)
# Token issue endpoint
if self.config.token_issue_path:
issue_expected = _normalize_config_path(self.config.token_issue_path)
if got == issue_expected:
return self._handle_token_issue(connection, request)
# Bootstrap
if got == "/webui/bootstrap":
return self._handle_bootstrap(connection, request)
if got == "/webui/terminal":
return self._handle_bootstrap(connection, request, terminal_probe=True)
# Settings routes (delegated)
response = await self.settings_routes.dispatch(connection, request, got)
if response is not None:
return response
# Recovery routes
response = await self._dispatch_recovery_route(request, got)
if response is not None:
return response
@@ -613,22 +602,18 @@ class GatewayHTTPHandler:
if got == "/api/webui/subagents/cancel":
return await self._handle_subagent_cancel(request)
# Session routes
response = await self._dispatch_session_routes(request, got)
if response is not None:
return response
# Media routes
response = self._dispatch_media_routes(request, got)
if response is not None:
return response
# Automation routes
response = await self._dispatch_automation_routes(request, got)
if response is not None:
return response
# Misc routes
response = await self._dispatch_misc_routes(connection, request, got)
if response is not None:
return response
@@ -637,7 +622,6 @@ class GatewayHTTPHandler:
if got.startswith("/api/"):
return _http_error(404, "API route not found")
# Static SPA serving
if self.static_dist_path is not None:
response = self._serve_static(
got,
@@ -696,7 +680,6 @@ class GatewayHTTPHandler:
elapsed_ms,
)
# -- Token issue --------------------------------------------------------
def _handle_token_issue(self, connection: Any, request: Any) -> Any:
secret = self.config.token_issue_secret.strip() or self.config.token.strip()
@@ -724,7 +707,6 @@ class GatewayHTTPHandler:
extra_headers=_NO_STORE_HEADERS,
)
# -- Bootstrap ----------------------------------------------------------
def _handle_bootstrap(
self, connection: Any, request: Any, *, terminal_probe: bool = False,
@@ -819,14 +801,12 @@ class GatewayHTTPHandler:
return f"{scheme}://{host}{expected_path}"
def _mcp_oauth_redirect_uri(self, request: WsRequest) -> str:
"""Derive the browser callback from the same public origin as WebSocket bootstrap."""
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH
public_ws_url = urlsplit(self._bootstrap_ws_url(request))
scheme = "https" if public_ws_url.scheme == "wss" else "http"
return urlunsplit((scheme, public_ws_url.netloc, MCP_OAUTH_CALLBACK_PATH, "", ""))
# -- Session routes -----------------------------------------------------
async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None:
m = re.fullmatch(r"/api/sessions/([^/]+)/webui-thread/prompts", got)
@@ -1405,7 +1385,6 @@ class GatewayHTTPHandler:
session_deleted = await self.session_manager.state.delete(decoded_key)
return _http_json_response({"deleted": bool(draft_deleted or session_deleted)})
# -- Automation routes --------------------------------------------------
async def _dispatch_automation_routes(
self,
@@ -1668,7 +1647,6 @@ class GatewayHTTPHandler:
if not ran:
logger.warning("WebUI automation run-now task did not execute")
# -- Media routes -------------------------------------------------------
def _dispatch_media_routes(self, request: WsRequest, got: str) -> Response | None:
m = re.match(r"^/api/media/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)$", got)
@@ -1686,7 +1664,6 @@ class GatewayHTTPHandler:
scope_for_session=self.workspaces.existing_scope_for_session_key,
)
# -- Misc routes --------------------------------------------------------
async def _dispatch_misc_routes(
self, connection: Any, request: WsRequest, got: str
@@ -1997,7 +1974,6 @@ class GatewayHTTPHandler:
return _http_error(500, "failed to write sidebar state")
return _http_json_response(state)
# -- Static file serving ------------------------------------------------
def _serve_static(
self,