refactor: remove unreachable internal code paths
Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
4212ad726d
commit
9257383bec
21 files changed
+86
-285
No files matched your search
@@ -497,12 +497,12 @@ class DiscordChannel(BaseChannel):
|
||||
self.logger.exception("client startup failed")
|
||||
finally:
|
||||
self._running = False
|
||||
await self._reset_runtime_state(close_client=True)
|
||||
await self._reset_runtime_state()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the Discord channel."""
|
||||
self._running = False
|
||||
await self._reset_runtime_state(close_client=True)
|
||||
await self._reset_runtime_state()
|
||||
|
||||
def _remember_compaction_notice(
|
||||
self,
|
||||
@@ -907,7 +907,7 @@ class DiscordChannel(BaseChannel):
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
self._working_emoji_tasks.clear()
|
||||
|
||||
async def _reset_runtime_state(self, close_client: bool) -> None:
|
||||
async def _reset_runtime_state(self) -> None:
|
||||
self._running = False
|
||||
# Drain callbacks before clearing the state they can still create after an await.
|
||||
current = asyncio.current_task()
|
||||
@@ -921,7 +921,7 @@ class DiscordChannel(BaseChannel):
|
||||
self._compaction_notices.clear()
|
||||
self._stream_bufs.clear()
|
||||
self._known_channels.clear()
|
||||
if close_client and self._client is not None and not self._client.is_closed():
|
||||
if self._client is not None and not self._client.is_closed():
|
||||
try:
|
||||
await self._client.close()
|
||||
except Exception as e:
|
||||
|
||||
@@ -1850,6 +1850,6 @@ async def test_reset_discards_in_flight_compaction_notices() -> None:
|
||||
owner, client = _client_with_channel(target)
|
||||
await client.send_outbound(_compaction_message("Compressing context…", "started"))
|
||||
|
||||
await owner._reset_runtime_state(close_client=False)
|
||||
await owner._reset_runtime_state()
|
||||
|
||||
assert owner._compaction_notices == {}
|
||||
@@ -142,7 +142,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
self._conversation_refs: dict[str, ConversationRef] = self._load_refs()
|
||||
with self._refs_guard:
|
||||
if self._prune_conversation_refs():
|
||||
self._save_refs_locked(prune=True)
|
||||
self._save_refs_locked()
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start the Teams webhook listener."""
|
||||
@@ -286,7 +286,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
resp = await self._http.post(base_url, headers=headers, json=payload)
|
||||
resp.raise_for_status()
|
||||
self.logger.info("Message sent to {}", ref.conversation_id)
|
||||
self._touch_conversation_ref(str(msg.chat_id), persist=True)
|
||||
self._touch_conversation_ref(str(msg.chat_id))
|
||||
except Exception:
|
||||
self.logger.exception("Send failed")
|
||||
raise
|
||||
@@ -736,7 +736,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
if disk_ts > mem_ts:
|
||||
self._conversation_refs[key] = disk_ref
|
||||
|
||||
def _touch_conversation_ref(self, chat_id: str, *, persist: bool = False) -> None:
|
||||
def _touch_conversation_ref(self, chat_id: str) -> None:
|
||||
with self._refs_guard:
|
||||
ref = self._conversation_refs.get(str(chat_id))
|
||||
if not ref:
|
||||
@@ -747,8 +747,7 @@ class MSTeamsChannel(BaseChannel):
|
||||
if min_interval > 0 and prev > 0 and now - prev < min_interval:
|
||||
return
|
||||
ref.updated_at = now
|
||||
if persist:
|
||||
self._save_refs_locked()
|
||||
self._save_refs_locked()
|
||||
|
||||
def _write_json_atomically(self, path: Path, data: dict[str, Any]) -> None:
|
||||
payload = json.dumps(data, indent=2)
|
||||
@@ -769,13 +768,12 @@ class MSTeamsChannel(BaseChannel):
|
||||
with suppress(OSError):
|
||||
os.unlink(tmp_path)
|
||||
|
||||
def _save_refs_locked(self, *, prune: bool = True) -> None:
|
||||
def _save_refs_locked(self) -> None:
|
||||
"""Persist conversation references (caller must hold _refs_guard)."""
|
||||
try:
|
||||
with self._refs_file_lock():
|
||||
self._merge_refs_from_disk_locked()
|
||||
if prune:
|
||||
self._prune_conversation_refs()
|
||||
self._prune_conversation_refs()
|
||||
refs_data = {
|
||||
key: {
|
||||
"service_url": ref.service_url,
|
||||
|
||||
@@ -374,9 +374,6 @@ class WebSocketChannel(BaseChannel):
|
||||
session_projection=gateway.session_projection,
|
||||
)
|
||||
self._commands = WebUICommandRouter(self, gateway, outbound=self._outbound)
|
||||
self._webui_request_tasks = self._commands.request_tasks
|
||||
self._webui_request_operations = self._commands.request_operations
|
||||
self._webui_request_locks = self._commands.request_locks
|
||||
|
||||
|
||||
def webui_subscribers(self, chat_id: str) -> tuple[ServerConnection, ...]:
|
||||
|
||||
@@ -421,7 +421,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
|
||||
assert (await preview(owner, str(outside)))["error"]["status"] == 403
|
||||
assert (await preview(owner, str(outside), probe=True))["result"] == {"available": False}
|
||||
assert (await preview(AsyncMock()))["error"]["status"] == 403
|
||||
assert not channel._webui_request_operations
|
||||
assert not channel._commands.request_operations
|
||||
assert {path for path in tmp_path.rglob("*") if path.is_file()} == disk_before
|
||||
assert sessions.list_sessions() == []
|
||||
|
||||
@@ -430,7 +430,7 @@ async def test_temporary_file_preview_is_owned_restricted_and_not_cached(bus, tm
|
||||
})
|
||||
assert (await preview(owner))["error"]["status"] == 404
|
||||
assert (await preview(owner, metadata=True))["error"]["status"] == 404
|
||||
assert not channel._webui_request_operations
|
||||
assert not channel._commands.request_operations
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1220,7 +1220,7 @@ async def test_authenticated_webui_request_returns_correlated_success(bus: Magic
|
||||
"payload": {"provider": "openrouter", "apiKey": "secret"},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once_with(
|
||||
conn,
|
||||
@@ -1281,7 +1281,7 @@ async def test_webui_mutations_preserve_request_and_response_order(bus: MagicMoc
|
||||
assert dispatch_order == ["settings.provider.update"]
|
||||
|
||||
release_first.set()
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
assert dispatch_order == [
|
||||
"settings.provider.update",
|
||||
@@ -1350,7 +1350,7 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order(
|
||||
await asyncio.sleep(0)
|
||||
assert dispatch_order == ["automation.run"]
|
||||
|
||||
pending = tuple(channel._webui_request_tasks.values())
|
||||
pending = tuple(channel._commands.request_tasks.values())
|
||||
release.set()
|
||||
await asyncio.gather(*pending)
|
||||
|
||||
@@ -1361,7 +1361,7 @@ async def test_webui_request_survives_disconnect_and_preserves_reconnect_order(
|
||||
"request-queued",
|
||||
"request-next",
|
||||
]
|
||||
assert first_conn not in channel._webui_request_locks
|
||||
assert first_conn not in channel._commands.request_locks
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1381,9 +1381,9 @@ async def test_webui_request_replays_completed_result_after_reconnect(bus: Magic
|
||||
}
|
||||
|
||||
await channel._dispatch_envelope(first_conn, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
await channel._dispatch_envelope(retry_conn, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
channel.gateway.http.dispatch_webui_mutation.assert_awaited_once()
|
||||
assert json.loads(retry_conn.send.await_args.args[0]) == {
|
||||
@@ -1416,7 +1416,7 @@ async def test_webui_request_rejects_request_id_reuse_with_different_payload(
|
||||
"payload": {"id": "job-a"},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
await channel._dispatch_envelope(
|
||||
retry_conn,
|
||||
"webui-client",
|
||||
@@ -1449,7 +1449,7 @@ def test_webui_request_cache_prunes_expired_completed_but_keeps_pending(
|
||||
channel = _ch(bus)
|
||||
now = 1_000.0
|
||||
monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
operations = cast(dict[str, Any], channel._webui_request_operations)
|
||||
operations = cast(dict[str, Any], channel._commands.request_operations)
|
||||
operations["pending"] = SimpleNamespace(completed_at=None)
|
||||
operations["expired"] = SimpleNamespace(
|
||||
completed_at=now - websocket_module._WEBUI_REQUEST_CACHE_TTL_S
|
||||
@@ -1472,7 +1472,7 @@ def test_webui_request_cache_prunes_oldest_completed_at_capacity(
|
||||
channel = _ch(bus)
|
||||
now = 1_000.0
|
||||
monkeypatch.setattr(websocket_module, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
operations = cast(dict[str, Any], channel._webui_request_operations)
|
||||
operations = cast(dict[str, Any], channel._commands.request_operations)
|
||||
operations["pending"] = SimpleNamespace(completed_at=None)
|
||||
for index in range(websocket_module._WEBUI_REQUEST_CACHE_MAX + 1):
|
||||
operations[f"completed-{index}"] = SimpleNamespace(
|
||||
@@ -1507,7 +1507,7 @@ async def test_webui_request_returns_correlated_route_error(bus: MagicMock) -> N
|
||||
"payload": {},
|
||||
},
|
||||
)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
assert json.loads(conn.send.await_args.args[0]) == {
|
||||
"event": "webui_response",
|
||||
@@ -1570,7 +1570,7 @@ async def test_webui_persists_sidebar_state_larger_than_http_request_line(
|
||||
assert len(json.dumps(envelope).encode()) > 8_192
|
||||
|
||||
await channel._dispatch_envelope(conn, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
|
||||
saved = json.loads((tmp_path / "webui" / "sidebar-state.json").read_text(encoding="utf-8"))
|
||||
assert saved["session_order"] == session_order
|
||||
@@ -1624,7 +1624,7 @@ async def test_webui_sidebar_state_update_broadcasts_workbench_to_other_devices(
|
||||
}
|
||||
try:
|
||||
await channel._dispatch_envelope(source, "webui-client", envelope)
|
||||
await asyncio.gather(*tuple(channel._webui_request_tasks.values()))
|
||||
await asyncio.gather(*tuple(channel._commands.request_tasks.values()))
|
||||
event = json.loads(other_device.send.await_args.args[0])
|
||||
assert event["event"] == "sidebar_state_updated"
|
||||
assert event["state"]["archived_keys"] == ["websocket:b"]
|
||||
|
||||
@@ -339,7 +339,7 @@ async def test_local_reference_inspection_send_recheck_and_no_staging(tmp_path,
|
||||
assert local["kind"] == "video"
|
||||
assert channel.gateway.uploads.store._entries == {}
|
||||
assert not list(channel.gateway.uploads.store.media_dir.glob("*"))
|
||||
assert channel._webui_request_operations == {}
|
||||
assert channel._commands.request_operations == {}
|
||||
|
||||
for invalid in ("missing.mp4", str(workspace), str(tmp_path / "outside.mp4")):
|
||||
failure = await inspect(invalid)
|
||||
|
||||
@@ -670,13 +670,10 @@ class WeixinChannel(BaseChannel):
|
||||
endpoint: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
auth: bool = True,
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
assert self._client is not None
|
||||
url = f"{base_url.rstrip('/')}/{endpoint}"
|
||||
hdrs = self._make_headers(auth=auth)
|
||||
if extra_headers:
|
||||
hdrs.update(extra_headers)
|
||||
return await self._request_json(
|
||||
"GET", url, endpoint=endpoint, params=params, headers=hdrs,
|
||||
)
|
||||
|
||||
@@ -6,7 +6,6 @@ import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
@@ -19,7 +18,6 @@ from nanobot.bun import BunUnavailableError, bun_environment, ensure_bun
|
||||
from nanobot.cli.process_identity import named_executable
|
||||
from nanobot.cli.runtime_config import _model_display
|
||||
from nanobot.cli.webui_support import (
|
||||
_gateway_health_ready,
|
||||
_gateway_health_url,
|
||||
_gateway_instance_command,
|
||||
_host_for_local_browser,
|
||||
@@ -64,8 +62,6 @@ _TUI_RELEASE_LIMITS = {
|
||||
}
|
||||
# Keep in sync with TUI_DETACH_EXIT_CODE in tui/src/index.ts.
|
||||
_TUI_DETACH_EXIT_CODE = 90
|
||||
_GATEWAY_READY_TIMEOUT_S = 20.0
|
||||
_GATEWAY_READY_POLL_S = 0.1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -134,7 +130,6 @@ def launch_tui(
|
||||
config,
|
||||
config_path=config_path,
|
||||
workspace_override=workspace_override,
|
||||
wait_until_ready=False,
|
||||
)
|
||||
exit_code = process.wait()
|
||||
if exit_code == _TUI_DETACH_EXIT_CODE:
|
||||
@@ -410,7 +405,6 @@ def _ensure_gateway(
|
||||
*,
|
||||
config_path: Path,
|
||||
workspace_override: str | None,
|
||||
wait_until_ready: bool = True,
|
||||
) -> _GatewayHandle:
|
||||
from nanobot.gateway import (
|
||||
GatewayClientLease,
|
||||
@@ -427,39 +421,6 @@ def _ensure_gateway(
|
||||
lease = GatewayClientLease(runtime, kind="tui")
|
||||
lease.acquire()
|
||||
try:
|
||||
def ready(status: object) -> bool:
|
||||
management_ready = getattr(status, "ready", None)
|
||||
if not isinstance(management_ready, bool):
|
||||
management_ready = _gateway_health_ready(
|
||||
config.gateway.host,
|
||||
config.gateway.port,
|
||||
)
|
||||
return _webui_endpoint_reachable(base_url) and management_ready
|
||||
|
||||
def wait_for_ready(log_path: object) -> _GatewayHandle:
|
||||
deadline = time.monotonic() + _GATEWAY_READY_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
current = runtime.status()
|
||||
if not current.running:
|
||||
break
|
||||
if current.port not in {None, config.gateway.port}:
|
||||
break
|
||||
if ready(current):
|
||||
return _GatewayHandle(base_url=base_url, lease=lease)
|
||||
time.sleep(_GATEWAY_READY_POLL_S)
|
||||
|
||||
current = runtime.status()
|
||||
if current.running:
|
||||
raise TuiUnavailableError(
|
||||
"local gateway process is running but its WebSocket/WebUI listener "
|
||||
"is unavailable; channel recovery did not restore it. "
|
||||
"Run `nanobot gateway status` and inspect logs at "
|
||||
f"{log_path}; if it remains degraded, run `nanobot gateway restart`."
|
||||
)
|
||||
raise TuiUnavailableError(
|
||||
f"local gateway did not become ready; logs: {log_path}"
|
||||
)
|
||||
|
||||
status = runtime.status()
|
||||
if status.running:
|
||||
if status.port not in {None, config.gateway.port}:
|
||||
@@ -467,11 +428,7 @@ def _ensure_gateway(
|
||||
"the matching gateway instance is running on a different port; "
|
||||
"restart it or use `nanobot agent --classic`"
|
||||
)
|
||||
if not wait_until_ready:
|
||||
return _GatewayHandle(base_url=base_url, lease=lease)
|
||||
if ready(status):
|
||||
return _GatewayHandle(base_url=base_url, lease=lease)
|
||||
return wait_for_ready(status.log_path)
|
||||
return _GatewayHandle(base_url=base_url, lease=lease)
|
||||
elif _webui_endpoint_reachable(base_url):
|
||||
raise TuiUnavailableError(
|
||||
"the configured gateway port belongs to a different nanobot instance; "
|
||||
@@ -495,9 +452,7 @@ def _ensure_gateway(
|
||||
"the matching gateway instance is running on a different port; "
|
||||
"restart it or use `nanobot agent --classic`"
|
||||
)
|
||||
if not wait_until_ready:
|
||||
return _GatewayHandle(base_url=base_url, lease=lease)
|
||||
return wait_for_ready(result.status.log_path)
|
||||
return _GatewayHandle(base_url=base_url, lease=lease)
|
||||
except BaseException:
|
||||
lease.release(timeout_s=5)
|
||||
raise
|
||||
|
||||
@@ -339,24 +339,15 @@ class LLMUsageStore:
|
||||
self,
|
||||
*,
|
||||
connection: sqlite3.Connection,
|
||||
start_ms: int | None,
|
||||
start_ms: int,
|
||||
end_ms: int,
|
||||
group_by: tuple[str, ...] = (),
|
||||
limit: int | None = None,
|
||||
) -> list[sqlite3.Row]:
|
||||
selected = f"{', '.join(group_by)}, " if group_by else ""
|
||||
where = "started_at_ms < ?"
|
||||
params: list[object] = [end_ms]
|
||||
if start_ms is not None:
|
||||
where = "started_at_ms >= ? AND started_at_ms < ?"
|
||||
params = [start_ms, end_ms]
|
||||
query = f"SELECT {selected}{_AGGREGATE_SQL} FROM llm_calls WHERE {where}"
|
||||
if group_by:
|
||||
query += f" GROUP BY {', '.join(group_by)} ORDER BY total_tokens DESC"
|
||||
if limit is not None:
|
||||
query += " LIMIT ?"
|
||||
params.append(limit)
|
||||
return list(connection.execute(query, params).fetchall())
|
||||
query = (
|
||||
f"SELECT provider, model, {_AGGREGATE_SQL} FROM llm_calls "
|
||||
"WHERE started_at_ms >= ? AND started_at_ms < ? "
|
||||
"GROUP BY provider, model ORDER BY total_tokens DESC LIMIT ?"
|
||||
)
|
||||
return list(connection.execute(query, (start_ms, end_ms, 50)).fetchall())
|
||||
|
||||
def _daily_rows(
|
||||
self,
|
||||
@@ -453,8 +444,6 @@ class LLMUsageStore:
|
||||
connection=connection,
|
||||
start_ms=last_30_start_ms,
|
||||
end_ms=end_ms,
|
||||
group_by=("provider", "model"),
|
||||
limit=50,
|
||||
)
|
||||
providers_30d = [
|
||||
{
|
||||
|
||||
@@ -478,14 +478,9 @@ class SessionManager:
|
||||
"""Public helper used by HTTP handlers to map an arbitrary key to a stable filename stem."""
|
||||
return SessionLocation.safe_key(key)
|
||||
|
||||
@staticmethod
|
||||
def _storage_key(key: str) -> str:
|
||||
"""Collision-resistant encoding for internal session storage filenames."""
|
||||
return SessionLocation.storage_key(key)
|
||||
|
||||
@staticmethod
|
||||
def _decode_storage_key(stem: str) -> str | None:
|
||||
"""Reverse _storage_key(): decode a base64url (no-padding) stem back to the original key."""
|
||||
"""Decode a base64url (no-padding) stem back to the original key."""
|
||||
return SessionLocation.decode_storage_key(stem)
|
||||
|
||||
@staticmethod
|
||||
|
||||
Reference in new issue
Block a user