fix(webui): keep version checks on the gateway event loop (#6376)

* fix(webui): keep version checks on the gateway event loop

* fix(webui): keep update channel failures factual

Note: CI failed, but it’s not related to this PR.
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-21 23:08:35 +08:00
1 parent 29d1600837
commit 4dc695ca76
15 files changed
+118 -51

No files matched your search

+3 -3
View File
@@ -9,7 +9,7 @@ import platform
import re
import subprocess
import time
from collections.abc import Callable, Iterable, Mapping
from collections.abc import Awaitable, Callable, Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, TypedDict, cast
@@ -86,7 +86,7 @@ class SystemSettingsOperations:
mcp_presets_action: SettingsOperation
reload_mcp: SettingsOperation
mcp_runtime_status: Callable[[], Mapping[str, str]] | None
check_for_update: SettingsOperation
check_for_update: Callable[[], Awaitable[dict[str, Any]]]
channel_feature_action: SettingsOperation | None = None
channel_runtime_status: Callable[[], dict[str, Any]] | None = None
@@ -1225,7 +1225,7 @@ class SystemSettingsHandler:
operations: SystemSettingsOperations,
) -> SettingsRouteResult:
try:
update_info = await asyncio.to_thread(operations.check_for_update)
update_info = await operations.check_for_update()
except Exception as exc:
self.logger.warning("version check failed ({})", type(exc).__name__)
return SettingsRouteResult.failure(500, "version check failed")
+6 -11
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
from typing import Any
import httpx
@@ -14,7 +13,12 @@ from nanobot.release_feed import ReleaseFeed, ReleaseFeedError
from nanobot.update_channel import read_update_channel
async def _check() -> dict[str, Any]:
async def check_for_update() -> dict[str, Any]:
"""Check fresh release data on the caller's event loop without installing.
The feed shares the gateway's pinned-DNS transport lock. Keep discovery on
that loop rather than creating a temporary event loop in a worker thread.
"""
selection = read_update_channel()
current = nanobot.__version__
status: dict[str, Any] = {
@@ -46,12 +50,3 @@ async def _check() -> dict[str, Any]:
if read_update_channel() != selection:
raise ValueError("Update channel changed while checking; check again")
return result
def check_for_update() -> dict[str, Any]:
"""Blocking settings adapter. Every check is fresh and never installs.
The feed's ETag cache guards generations, not availability. Older clients
still read updateAvailable; channel status is additive.
"""
return asyncio.run(_check())
+76 -4
View File
@@ -782,7 +782,7 @@ async def test_version_check_route_returns_stable_payload(
) -> None:
monkeypatch.setattr(
"nanobot.webui.settings_routes.check_for_update",
lambda: {"updateAvailable": update_info, "releaseStatus": {"state": "available" if update_info else "current"}},
AsyncMock(return_value={"updateAvailable": update_info, "releaseStatus": {"state": "available" if update_info else "current"}}),
)
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
@@ -793,11 +793,82 @@ async def test_version_check_route_returns_stable_payload(
assert json.loads(response.body) == expected
async def test_version_check_and_mcp_requests_share_the_gateway_loop(monkeypatch, tmp_path):
import httpx
from packaging.tags import Tag
import nanobot
from nanobot.release_feed import PYPI_URL, ReleaseFeed
from nanobot.releases import release_filenames
from nanobot.security import network
from nanobot.update_channel import UpdateChannel
from nanobot.webui import version_check
gateway_loop = asyncio.get_running_loop()
entered = asyncio.Event()
finish = asyncio.Event()
requests = []
def resolve(url, **_kwargs):
if url == f"{PYPI_URL}/json":
# Settle the gateway requests on the next tick of the checking loop,
# after discovery has tried to acquire the already-contended lock.
asyncio.get_running_loop().call_soon(gateway_loop.call_soon_threadsafe, finish.set)
return True, "", ("93.184.216.34",)
async def respond(request):
requests.append(str(request.url))
if request.url.host == "mcp.example":
entered.set()
await finish.wait()
return httpx.Response(200, json={})
assert str(request.url) == f"{PYPI_URL}/json"
return httpx.Response(200, json={
"info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"},
"urls": [{"filename": name, "size": 123, "yanked": False,
"digests": {"sha256": "c" * 64},
"url": f"https://files.pythonhosted.org/packages/{name}"}
for name in sorted(release_filenames("0.3.5"))
if name.endswith((".whl", ".tar.gz"))],
})
def transport():
return network.PinnedDNSAsyncTransport(inner=httpx.MockTransport(respond))
monkeypatch.setattr(network.PinnedDNSAsyncTransport, "_resolver_lock", asyncio.Lock())
monkeypatch.setattr(network, "resolve_url_target", resolve)
monkeypatch.setattr(nanobot, "__version__", "0.3.5")
monkeypatch.setattr(version_check, "read_update_channel", UpdateChannel)
monkeypatch.setattr(version_check, "installation_state_dir", lambda: tmp_path)
monkeypatch.setattr(version_check, "ReleaseFeed", lambda directory: ReleaseFeed(
directory, transport=transport(), supported_tags=[Tag("py3", "none", "win_amd64")],
))
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
async with httpx.AsyncClient(transport=transport(), trust_env=False) as client:
first = asyncio.create_task(client.get("https://mcp.example/first"))
await asyncio.wait_for(entered.wait(), timeout=5)
second = asyncio.create_task(client.get("https://mcp.example/second"))
await asyncio.sleep(0) # Let the second gateway request wait on the shared lock.
try:
response = await asyncio.wait_for(_router().dispatch(None, request, request.path), timeout=5)
finally:
finish.set()
await asyncio.gather(first, second)
subsequent = await client.get("https://mcp.example/subsequent")
assert response.status_code == 200
assert json.loads(response.body) == {"updateAvailable": None}
assert subsequent.status_code == 200
assert requests == ["https://mcp.example/first", "https://mcp.example/second",
f"{PYPI_URL}/json", "https://mcp.example/subsequent"]
@pytest.mark.asyncio
async def test_version_check_route_enforces_auth_and_bounds_failures(
monkeypatch: pytest.MonkeyPatch,
) -> None:
check = MagicMock(side_effect=RuntimeError("upstream secret body"))
check = AsyncMock(side_effect=RuntimeError("upstream secret body"))
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", check)
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
@@ -811,6 +882,7 @@ async def test_version_check_route_enforces_auth_and_bounds_failures(
assert failed.status_code == 500
assert json.loads(failed.body) == {"error": "version check failed"}
assert "upstream secret body" not in failed.body.decode()
check.assert_awaited_once_with()
@pytest.mark.parametrize("state", ["waiting_stable", "withdrawn", "unavailable", "publishing", "unsupported"])
@@ -818,7 +890,7 @@ async def test_channel_status_is_explicit_and_old_clients_never_report_false_suc
result = {"updateAvailable": None, "releaseStatus": {
"channel": "stable", "revision": 2, "currentVersion": "0.3.7.dev42", "state": state,
}}
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", lambda: result)
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", AsyncMock(return_value=result))
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
router = _router()
response = await router.dispatch(None, request, request.path)
@@ -834,7 +906,7 @@ async def test_version_check_owner_is_additive_read_only_and_failure_is_not_a_re
from nanobot.webui import settings_system
result = {"updateAvailable": None, "releaseStatus": {"state": "current"}}
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", lambda: result)
monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", AsyncMock(return_value=result))
inspect_owner = MagicMock(return_value=SimpleNamespace(owner="pipx", records={}))
monkeypatch.setattr(settings_system, "inspect_update_installation", inspect_owner)
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
+22 -22
View File
@@ -73,60 +73,60 @@ def select(channel):
return UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=current.revision))
def test_stable_preview_exit_wait_and_final_release(releases, monkeypatch):
assert version_check.check_for_update()["releaseStatus"]["state"] == "current"
async def test_stable_preview_exit_wait_and_final_release(releases, monkeypatch):
assert (await version_check.check_for_update())["releaseStatus"]["state"] == "current"
assert CATALOGUE_URL not in releases.requests
select("preview")
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["updateAvailable"]["latestVersion"] == "0.3.7.dev42"
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
releases.preview, releases.generation = "0.3.7.dev43", 2
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7.dev43"
assert (await version_check.check_for_update())["updateAvailable"]["latestVersion"] == "0.3.7.dev43"
select("stable")
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["releaseStatus"]["state"] == "waiting_stable"
assert result["updateAvailable"] is None
releases.stable, releases.generation = "0.3.7", 3
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7"
assert (await version_check.check_for_update())["updateAvailable"]["latestVersion"] == "0.3.7"
assert read_update_channel().channel == "stable"
def test_preview_subscription_survives_final_release_and_next_cycle(releases, monkeypatch):
async def test_preview_subscription_survives_final_release_and_next_cycle(releases, monkeypatch):
select("preview")
releases.stable = "0.3.7"
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7"
assert (await version_check.check_for_update())["updateAvailable"]["latestVersion"] == "0.3.7"
monkeypatch.setattr(nanobot, "__version__", "0.3.7")
assert version_check.check_for_update()["releaseStatus"]["state"] == "current"
assert (await version_check.check_for_update())["releaseStatus"]["state"] == "current"
assert read_update_channel().channel == "preview"
releases.preview, releases.generation = "0.3.8.dev1", 2
assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.8.dev1"
assert (await version_check.check_for_update())["updateAvailable"]["latestVersion"] == "0.3.8.dev1"
def test_leaving_preview_can_find_a_newer_stable_when_catalogue_is_unavailable(releases, monkeypatch):
async def test_leaving_preview_can_find_a_newer_stable_when_catalogue_is_unavailable(releases, monkeypatch):
select("preview")
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
select("stable")
releases.missing = True
releases.stable = "0.3.7"
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["updateAvailable"]["latestVersion"] == "0.3.7"
assert result["releaseStatus"]["state"] == "available"
assert read_update_channel().channel == "stable"
# A broken Preview index cannot authorize a partial release or a downgrade,
# or turn unverified withdrawal status into a green 'up to date'.
releases.partial = True
assert version_check.check_for_update()["updateAvailable"] is None
assert (await version_check.check_for_update())["updateAvailable"] is None
releases.partial = False
releases.stable = "0.3.6"
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["updateAvailable"] is None
assert result["releaseStatus"]["state"] == "unavailable"
@pytest.mark.parametrize("replacement", ["older", "newer", "incompatible"])
@pytest.mark.parametrize("channel", ["stable", "preview"])
def test_withdrawn_running_preview_is_not_reported_up_to_date(releases, monkeypatch, replacement, channel):
async def test_withdrawn_running_preview_is_not_reported_up_to_date(releases, monkeypatch, replacement, channel):
select(channel)
monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
releases.withdrawn = {"0.3.7.dev42": "Startup regression"}
@@ -134,30 +134,30 @@ def test_withdrawn_running_preview_is_not_reported_up_to_date(releases, monkeypa
releases.preview = "0.3.7.dev43"
releases.stable = "0.3.7"
releases.incompatible = replacement == "incompatible"
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["releaseStatus"]["state"] == "withdrawn"
assert (result["updateAvailable"] is not None) == (replacement == "newer")
@pytest.mark.parametrize("problem,state", [("partial", "publishing"), ("offline", "unavailable"),
("incompatible", "unsupported"), ("missing", "unavailable")])
def test_unavailable_checks_have_feedback_and_can_recover(releases, problem, state):
async def test_unavailable_checks_have_feedback_and_can_recover(releases, problem, state):
if problem == "missing":
select("preview")
setattr(releases, problem, True)
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["updateAvailable"] is None
assert result["releaseStatus"]["state"] == state
assert "credential" not in str(result)
setattr(releases, problem, False)
assert version_check.check_for_update()["releaseStatus"]["state"] in {"current", "available"}
assert (await version_check.check_for_update())["releaseStatus"]["state"] in {"current", "available"}
def test_current_dev_does_not_implicitly_opt_in_and_older_target_is_not_offered(releases, monkeypatch):
async def test_current_dev_does_not_implicitly_opt_in_and_older_target_is_not_offered(releases, monkeypatch):
monkeypatch.setattr(nanobot, "__version__", "0.3.8.dev1")
assert read_update_channel().channel == "stable"
assert version_check.check_for_update()["releaseStatus"]["state"] == "waiting_stable"
assert (await version_check.check_for_update())["releaseStatus"]["state"] == "waiting_stable"
select("preview")
result = version_check.check_for_update()
result = await version_check.check_for_update()
assert result["updateAvailable"] is None
assert result["releaseStatus"]["state"] == "ahead"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "This version is ahead of the selected channel. No downgrade will be installed.",
"waiting_stable": "Preview updates are off. Keep using this version until a newer stable release is available.",
"withdrawn": "This preview was withdrawn. Update to a newer release when available; do not downgrade over your current data.",
"unavailable": "Could not verify this channel. It may not be available yet. Check your connection and try again.",
"unavailable": "Could not check this update channel.",
"publishing": "The release is still being published. Check again later.",
"unsupported": "No compatible update is available for this Python version and platform.",
"releaseNotes": "Release notes"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "Esta versión es más reciente que la del canal seleccionado. No se instalará una versión anterior.",
"waiting_stable": "Las actualizaciones preliminares están desactivadas. Usa esta versión hasta que haya una versión estable más reciente.",
"withdrawn": "Esta versión preliminar fue retirada. Actualiza cuando haya una versión más reciente; no instales una anterior sobre tus datos actuales.",
"unavailable": "No se pudo verificar este canal. Puede que aún no esté disponible. Comprueba la conexión y vuelve a intentarlo.",
"unavailable": "No se pudieron comprobar las actualizaciones de este canal.",
"publishing": "La versión aún se está publicando. Vuelve a comprobarlo más tarde.",
"unsupported": "No hay una actualización compatible con esta versión de Python y plataforma.",
"releaseNotes": "Notas de la versión"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "Cette version est plus récente que celle du canal choisi. Aucune version antérieure ne sera installée.",
"waiting_stable": "Les préversions sont désactivées. Conservez cette version en attendant une version stable plus récente.",
"withdrawn": "Cette préversion a été retirée. Installez une version plus récente dès sa disponibilité ; ne rétrogradez pas avec vos données actuelles.",
"unavailable": "Impossible de vérifier ce canal. Il n’est peut-être pas encore disponible. Vérifiez votre connexion et réessayez.",
"unavailable": "Impossible de vérifier les mises à jour de ce canal.",
"publishing": "La publication est en cours. Réessayez plus tard.",
"unsupported": "Aucune mise à jour compatible avec cette version de Python et cette plateforme.",
"releaseNotes": "Notes de version"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "Versi ini lebih baru dari saluran yang dipilih. Versi lama tidak akan diinstal.",
"waiting_stable": "Pembaruan pratinjau dinonaktifkan. Gunakan versi ini sampai versi stabil yang lebih baru tersedia.",
"withdrawn": "Pratinjau ini ditarik. Perbarui saat versi baru tersedia; jangan turunkan versi dengan data saat ini.",
"unavailable": "Saluran ini belum dapat diverifikasi dan mungkin belum tersedia. Periksa koneksi lalu coba lagi.",
"unavailable": "Pembaruan di saluran ini tidak dapat diperiksa.",
"publishing": "Versi masih diterbitkan. Periksa lagi nanti.",
"unsupported": "Tidak ada pembaruan yang cocok untuk versi Python dan platform ini.",
"releaseNotes": "Catatan rilis"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "現在のバージョンは選択したチャンネルより新しいため、旧バージョンはインストールしません。",
"waiting_stable": "プレビュー更新を停止しました。新しい安定版が公開されるまで現在のバージョンを利用できます。",
"withdrawn": "このプレビュー版は撤回されました。修正版が公開されたら更新してください。現在のデータに旧版を上書きしないでください。",
"unavailable": "チャンネルを確認できません。まだ公開されていない可能性があります。接続を確認して再試行してください。",
"unavailable": "このチャンネルの更新を確認できません。",
"publishing": "リリースの公開中です。しばらくしてから再確認してください。",
"unsupported": "この Python バージョンとプラットフォームに対応する更新はありません。",
"releaseNotes": "リリースノート"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "현재 버전이 선택한 채널보다 최신입니다. 이전 버전을 설치하지 않습니다.",
"waiting_stable": "미리 보기 업데이트를 중단했습니다. 더 새로운 안정판이 나올 때까지 현재 버전을 사용하세요.",
"withdrawn": "이 미리 보기 버전은 철회되었습니다. 새 버전이 나오면 업데이트하세요. 현재 데이터에 이전 버전을 덮어쓰지 마세요.",
"unavailable": "채널을 확인할 수 없습니다. 아직 제공되지 않을 수 있습니다. 연결을 확인하고 다시 시도하세요.",
"unavailable": "이 채널의 업데이트를 확인할 수 없습니다.",
"publishing": "릴리스를 게시 중입니다. 나중에 다시 확인하세요.",
"unsupported": "이 Python 버전과 플랫폼에 맞는 업데이트가 없습니다.",
"releaseNotes": "릴리스 노트"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "Esta versão é mais recente que a do canal escolhido. Nenhuma versão anterior será instalada.",
"waiting_stable": "As atualizações prévias estão desativadas. Use esta versão até que haja uma versão estável mais recente.",
"withdrawn": "Esta prévia foi retirada. Atualize quando houver uma versão mais recente; não instale uma versão anterior sobre seus dados atuais.",
"unavailable": "Não foi possível verificar este canal. Ele pode ainda não estar disponível. Verifique a conexão e tente novamente.",
"unavailable": "Não foi possível verificar as atualizações deste canal.",
"publishing": "A versão ainda está sendo publicada. Verifique novamente mais tarde.",
"unsupported": "Não há atualização compatível com esta versão do Python e plataforma.",
"releaseNotes": "Notas da versão"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "Phiên bản này mới hơn kênh đã chọn. Sẽ không cài đặt phiên bản cũ hơn.",
"waiting_stable": "Đã tắt cập nhật xem trước. Tiếp tục dùng phiên bản này cho đến khi có bản ổn định mới hơn.",
"withdrawn": "Bản xem trước này đã bị thu hồi. Hãy cập nhật khi có phiên bản mới hơn; không hạ cấp đè lên dữ liệu hiện tại.",
"unavailable": "Không thể xác minh kênh này. Kênh có thể chưa được mở. Kiểm tra kết nối rồi thử lại.",
"unavailable": "Không thể kiểm tra bản cập nhật của kênh này.",
"publishing": "Phiên bản đang được phát hành. Vui lòng kiểm tra lại sau.",
"unsupported": "Không có bản cập nhật tương thích với phiên bản Python và nền tảng này.",
"releaseNotes": "Ghi chú phát hành"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "当前版本领先于所选频道,不会安装更旧的版本。",
"waiting_stable": "已退出预览更新。保留当前版本,等待更新的正式版。",
"withdrawn": "当前预览版已撤回。请在修复版可用时升级,不要直接降级覆盖当前数据。",
"unavailable": "暂时无法验证此频道,可能尚未开放。请检查网络后重试。",
"unavailable": "无法检查此频道的更新。",
"publishing": "新版本仍在发布中,请稍后再检查。",
"unsupported": "此 Python 版本或平台暂无兼容更新。",
"releaseNotes": "更新说明"
+1 -1
View File
@@ -54,7 +54,7 @@
"ahead": "目前版本領先於所選頻道,不會安裝較舊版本。",
"waiting_stable": "已退出預覽更新。保留目前版本,等待更新的正式版。",
"withdrawn": "目前預覽版已撤回。請在修正版可用時升級,不要直接降級覆寫目前資料。",
"unavailable": "暫時無法驗證此頻道,可能尚未開放。請檢查網路後重試。",
"unavailable": "無法檢查此頻道的更新。",
"publishing": "新版本仍在發布中,請稍後再檢查。",
"unsupported": "此 Python 版本或平台暫無相容更新。",
"releaseNotes": "更新說明"
+1 -1
View File
@@ -54,7 +54,7 @@ describe("Installation-owned release channels", () => {
expect(selector).toBeVisible();
expect(screen.queryByText("Saving…")).toBeNull();
expect(screen.queryByText("Update preference saved")).toBeNull();
expect(screen.getByText(/Could not verify/)).toBeVisible();
expect(screen.getByText("Could not check this update channel.")).toBeVisible();
expect(screen.queryByText("You're up to date")).toBeNull();
expect(screen.getByLabelText("Draft")).toHaveValue("Keep writing");
expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check?channel_status=1", expect.any(Object));