refactor(webui): separate gateway mutations and UI state (#6727)
This commit is contained in:
1 parent
ce12bfdd0d
commit
5537bdabd3
70 files changed
+4058
-3650
No files matched your search
@@ -37,7 +37,6 @@ async def test_background_auth_and_staged_upload(tmp_path):
|
||||
handler.tokens = SimpleNamespace(check_api_token=lambda request: request.headers.get("Authorization") == "Bearer valid")
|
||||
router = WebUICommandRouter.__new__(WebUICommandRouter)
|
||||
router._background_lock = asyncio.Lock()
|
||||
router._background_references = set()
|
||||
router._http_router = handler
|
||||
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
|
||||
router.request_locks = {}
|
||||
@@ -106,7 +105,6 @@ async def test_background_style_persistence_and_validation(tmp_path):
|
||||
handler.tokens = SimpleNamespace(check_api_token=lambda request: request.headers.get("Authorization") == "Bearer valid")
|
||||
router = WebUICommandRouter.__new__(WebUICommandRouter)
|
||||
router._background_lock = asyncio.Lock()
|
||||
router._background_references = set()
|
||||
router._http_router = handler
|
||||
router.request_locks = {}
|
||||
path = "/api/settings/background-style"
|
||||
@@ -173,8 +171,6 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from nanobot.webui import background
|
||||
|
||||
store = AttachmentStore(tmp_path / "staging")
|
||||
body = image_bytes()
|
||||
|
||||
@@ -184,24 +180,28 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk
|
||||
ref = await store.upload(chunks(), owner="alice", mime="image/png", size=len(body))
|
||||
router = WebUICommandRouter.__new__(WebUICommandRouter)
|
||||
router._background_lock = asyncio.Lock()
|
||||
router._background_references = set()
|
||||
router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace(
|
||||
config=SimpleNamespace(path=tmp_path / "config.json")))
|
||||
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
|
||||
router.request_locks = {}
|
||||
staged_path = store.inspect([ref], owner="alice")[0].path
|
||||
started, release = threading.Event(), threading.Event()
|
||||
original = background.save_background
|
||||
original_open = type(staged_path).open
|
||||
event_loop_thread = threading.get_ident()
|
||||
|
||||
def slow(*args):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
original(*args)
|
||||
def slow_read(path, mode="r", *args, **kwargs):
|
||||
if path == staged_path and mode == "rb":
|
||||
assert threading.get_ident() != event_loop_thread
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return original_open(path, mode, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(background, "save_background", slow)
|
||||
monkeypatch.setattr(type(staged_path), "open", slow_read)
|
||||
task = asyncio.create_task(router.execute_webui_request("alice", "background.update", {"reference": ref}))
|
||||
assert await asyncio.to_thread(started.wait, 3)
|
||||
# The event loop remains responsive, and disconnect cannot invalidate the worker's descriptor.
|
||||
# Disconnect cannot remove the staged source even before the worker opens it.
|
||||
store.discard_owner("alice")
|
||||
assert staged_path.exists()
|
||||
task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not task.done()
|
||||
@@ -209,6 +209,7 @@ async def test_background_worker_cancellation_survives_disconnect(tmp_path, monk
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert (tmp_path / "webui" / "background.png").exists()
|
||||
assert not staged_path.exists()
|
||||
|
||||
|
||||
async def test_background_worker_failure_releases_upload_for_retry(tmp_path, monkeypatch):
|
||||
@@ -223,7 +224,6 @@ async def test_background_worker_failure_releases_upload_for_retry(tmp_path, mon
|
||||
ref = await store.upload(chunks(), owner="alice", mime="image/png", size=len(body))
|
||||
router = WebUICommandRouter.__new__(WebUICommandRouter)
|
||||
router._background_lock = asyncio.Lock()
|
||||
router._background_references = set()
|
||||
router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace(
|
||||
config=SimpleNamespace(path=tmp_path / "config.json")))
|
||||
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
|
||||
@@ -251,7 +251,6 @@ async def test_invalid_background_releases_upload_for_retry(tmp_path):
|
||||
|
||||
router = WebUICommandRouter.__new__(WebUICommandRouter)
|
||||
router._background_lock = asyncio.Lock()
|
||||
router._background_references = set()
|
||||
router._http_router = SimpleNamespace(bus=MessageBus(), settings=SimpleNamespace(
|
||||
config=SimpleNamespace(path=tmp_path / "config.json")))
|
||||
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
|
||||
@@ -281,7 +280,6 @@ async def test_background_waiter_cancelled_does_not_write(tmp_path, monkeypatch)
|
||||
bus = MessageBus()
|
||||
router = WebUICommandRouter.__new__(WebUICommandRouter)
|
||||
router._background_lock = asyncio.Lock()
|
||||
router._background_references = set()
|
||||
router._http_router = SimpleNamespace(bus=bus, settings=SimpleNamespace(
|
||||
config=SimpleNamespace(path=tmp_path / "config.json")))
|
||||
router._uploads = SimpleNamespace(store=store, owner=lambda connection: connection)
|
||||
|
||||
@@ -10,16 +10,17 @@ from nanobot.webui.gateway_tokens import GatewayTokenStore
|
||||
from nanobot.webui.ws_http import GatewayHTTPHandler
|
||||
|
||||
|
||||
def test_terminal_probe_is_private_stable_and_does_not_issue_credentials():
|
||||
async def test_terminal_probe_is_private_stable_and_does_not_issue_credentials():
|
||||
handler = object.__new__(GatewayHTTPHandler)
|
||||
handler.config = WebSocketConfig(token_issue_secret="fixture-secret")
|
||||
handler.tokens = GatewayTokenStore(max_tokens=0)
|
||||
connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
|
||||
request = Request("/webui/terminal", Headers({"Host": "127.0.0.1:8765"}))
|
||||
assert handler._handle_bootstrap(connection, request, terminal_probe=True).status_code == 401
|
||||
denied = await handler._handle_bootstrap(connection, request, terminal_probe=True)
|
||||
assert denied.status_code == 401
|
||||
request.headers["X-Nanobot-Auth"] = "fixture-secret"
|
||||
for _ in range(3):
|
||||
response = handler._handle_bootstrap(connection, request, terminal_probe=True)
|
||||
response = await handler._handle_bootstrap(connection, request, terminal_probe=True)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body) == gateway_identity(handler.tokens.instance_id)
|
||||
assert "no-store" in response.headers["Cache-Control"]
|
||||
|
||||
@@ -10,7 +10,7 @@ from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.session.display_history import HistoryFact
|
||||
from nanobot.session.history_graph import history_record_size
|
||||
from nanobot.webui import transcript
|
||||
from nanobot.webui import transcript, transcript_replay
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
from nanobot.webui.history import fact_from_record
|
||||
|
||||
@@ -594,3 +594,57 @@ async def test_http_fragment_recovery_reads_persisted_canonical_history(history,
|
||||
assert pages[-1]["completed_turn_ids"] == ["t"]
|
||||
assert pages[-1]["has_pending_tool_calls"] is False
|
||||
assert history.read(key) == original
|
||||
|
||||
|
||||
def test_selected_bytes_are_measured_once_for_the_compacted_source_page(history, monkeypatch):
|
||||
key = "websocket:replay-metrics"
|
||||
for record in (
|
||||
{"event": "user", "text": "question"},
|
||||
{"event": "delta", "text": "partial"},
|
||||
{"event": "stream_end", "text": "answer 日本語"},
|
||||
{"event": "turn_end"},
|
||||
):
|
||||
history.append(key, record)
|
||||
|
||||
measured = []
|
||||
measure = transcript_replay._records_bytes
|
||||
|
||||
def track_measure(records):
|
||||
measured.append(records)
|
||||
return measure(records)
|
||||
|
||||
monkeypatch.setattr(transcript_replay, "_records_bytes", track_measure)
|
||||
stats = transcript.TranscriptReplayStats()
|
||||
page = history.build(key, stats=stats)
|
||||
assert page is not None
|
||||
assert stats.parsed_records == 4
|
||||
assert stats.selected_records == 3
|
||||
assert stats.compacted_delta_records == 1
|
||||
assert not measured
|
||||
selected_bytes = stats.selected_bytes
|
||||
assert stats.selected_bytes == selected_bytes > 0
|
||||
assert len(measured) == 1
|
||||
assert [record["event"] for record in measured[0]] == ["user", "stream_end", "turn_end"]
|
||||
assert selected_bytes == sum(
|
||||
len(json.dumps(record, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) + 1
|
||||
for record in measured[0]
|
||||
)
|
||||
|
||||
|
||||
def test_cached_inline_trace_uses_message_augmentation(history):
|
||||
key = "websocket:cached-trace-augmentation"
|
||||
history.append(key, {"event": "user", "text": "question"})
|
||||
history.append(key, {
|
||||
"event": "message", "kind": "progress", "text": "",
|
||||
"media": ["private.png"], "media_urls": [{"url": "/api/media/old", "name": "private.png"}],
|
||||
})
|
||||
history.append(key, {"event": "message", "kind": "progress", "text": "plain text", "render_as": "text"})
|
||||
|
||||
result = history.build(
|
||||
key,
|
||||
augment_assistant_text=lambda text: f"augmented:{text}",
|
||||
augment_assistant_media=lambda _paths: [],
|
||||
)
|
||||
progress = [event for event in result["events"] if event.get("kind") == "progress"]
|
||||
assert [event["text"] for event in progress] == ["augmented:", "plain text"]
|
||||
assert "media_urls" not in progress[0]
|
||||
@@ -989,6 +989,7 @@ async def test_remote_clients_cannot_open_local_file_picker(gateway, monkeypatch
|
||||
))
|
||||
result = await gateway.http.dispatch_webui_mutation(connection, "remote.pick_file", {})
|
||||
assert result.status_code == 403
|
||||
assert result.message == "remote_connections_local_only"
|
||||
choose.assert_not_awaited()
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -18,6 +17,7 @@ from nanobot.providers.factory import load_provider_snapshot
|
||||
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
|
||||
from nanobot.webui import settings_api
|
||||
from nanobot.webui.http_utils import http_json_response
|
||||
from nanobot.webui.settings_contracts import MutationParams
|
||||
from nanobot.webui.settings_routes import WebUISettingsRouter
|
||||
from nanobot.webui.settings_services import WebUISettingsServices
|
||||
|
||||
@@ -96,12 +96,9 @@ async def test_model_save_commits_before_refreshing_next_session_admission(
|
||||
assert prior.context_window_tokens == cached_preset.context_window_tokens == 100_000
|
||||
assert (await admit("draft-only")).context_window_tokens == 100_000
|
||||
|
||||
path = "/api/settings/model-configurations/update"
|
||||
request = SimpleNamespace(path=path, headers=Headers())
|
||||
request._nanobot_webui_mutation_request = True
|
||||
request._nanobot_webui_mutation_payload = draft
|
||||
request._nanobot_trusted_proxy_authenticated = True
|
||||
pending_save = asyncio.create_task(router.dispatch(None, request, path))
|
||||
pending_save = asyncio.create_task(router.dispatch_mutation(
|
||||
None, Headers(), "settings.model_configuration.update", MutationParams(draft),
|
||||
))
|
||||
assert await asyncio.to_thread(before_save.wait, 5)
|
||||
assert not pending_save.done()
|
||||
assert disk_window() == 100_000
|
||||
@@ -117,7 +114,7 @@ async def test_model_save_commits_before_refreshing_next_session_admission(
|
||||
|
||||
allow_return.set()
|
||||
response = await asyncio.wait_for(pending_save, 5)
|
||||
assert response.status_code == 200, json.loads(response.body)
|
||||
assert response.status_code == 200, response.message
|
||||
assert agent.runtime_resolver.runtime.context_window_tokens == 500_000
|
||||
next_runtime = await admit("after-success")
|
||||
next_preset = await admit("after-success-preset", explicit_preset=True)
|
||||
|
||||
@@ -8,12 +8,14 @@ import pytest
|
||||
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.providers.registry import find_by_name
|
||||
from nanobot.webui.settings_contracts import MutationParams
|
||||
from nanobot.webui.settings_models import (
|
||||
WebUISettingsError,
|
||||
create_model_configuration,
|
||||
model_settings_payload,
|
||||
provider_models_payload,
|
||||
update_agent_model_settings,
|
||||
update_model_call_order,
|
||||
update_model_configuration,
|
||||
update_provider_settings,
|
||||
)
|
||||
@@ -367,3 +369,54 @@ def test_known_reasoning_efforts_preserve_default_none_and_custom_roundtrips() -
|
||||
if row["name"] == unknown)
|
||||
assert row["reasoning_effort"] == "future-effort"
|
||||
assert row["reasoning_effort_values"] == ["", "low", "medium", "high"]
|
||||
|
||||
|
||||
def test_model_call_order_accepts_json_request_and_legacy_alias() -> None:
|
||||
config = Config.model_validate({
|
||||
"providers": {"openai": {"apiKey": "fixture"}},
|
||||
"modelPresets": {name: {"model": "gpt-4o", "provider": "openai"} for name in ("alpha", "beta")},
|
||||
})
|
||||
assert update_model_call_order(
|
||||
config, MutationParams({"order": [" beta ", "alpha"]}), oauth_status=_oauth_status,
|
||||
)
|
||||
assert config.agents.defaults.model_preset == "beta"
|
||||
assert config.agents.defaults.fallback_models == ["alpha"]
|
||||
assert not update_model_call_order(
|
||||
config, {"presetNames": ['["beta", "alpha"]']}, oauth_status=_oauth_status,
|
||||
)
|
||||
|
||||
with pytest.raises(WebUISettingsError, match="model call order must contain at least one preset"):
|
||||
update_model_call_order(
|
||||
config, MutationParams({"order": ["alpha", 5]}), oauth_status=_oauth_status,
|
||||
)
|
||||
with pytest.raises(WebUISettingsError, match="model call order must be a JSON array"):
|
||||
update_model_call_order(config, {"order": ["broken"]}, oauth_status=_oauth_status)
|
||||
assert config.agents.defaults.model_preset == "beta"
|
||||
assert config.agents.defaults.fallback_models == ["alpha"]
|
||||
|
||||
|
||||
def test_structured_api_declarations_can_be_set_and_cleared() -> None:
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "fixture"
|
||||
api = {"supportedApis": ["responses"], "preferredApi": "responses"}
|
||||
changed, _ = update_provider_settings(config, MutationParams({"provider": "openai", "api": api}))
|
||||
assert changed
|
||||
assert config.providers.openai.api is not None
|
||||
assert config.providers.openai.api.preferred_api == "responses"
|
||||
|
||||
name = create_model_configuration(
|
||||
config, MutationParams({"name": "custom", "provider": "openai", "model": "gpt-4o", "api": api}),
|
||||
oauth_status=_oauth_status,
|
||||
)
|
||||
saved_api = config.model_presets[name].api
|
||||
assert saved_api is not None
|
||||
assert saved_api.model_dump(by_alias=True, mode="json") == api
|
||||
with pytest.raises(WebUISettingsError, match="api must declare supportedApis"):
|
||||
update_model_configuration(
|
||||
config, MutationParams({"name": name, "api": []}), oauth_status=_oauth_status,
|
||||
)
|
||||
assert config.model_presets[name].api == saved_api
|
||||
assert update_model_configuration(
|
||||
config, MutationParams({"name": name, "api": None}), oauth_status=_oauth_status,
|
||||
)
|
||||
assert config.model_presets[name].api is None
|
||||
@@ -20,7 +20,8 @@ from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.webui.http_utils import http_json_response
|
||||
from nanobot.webui.mcp_presets_api import custom_mcp_action
|
||||
from nanobot.webui.settings_routes import WebUISettingsRouter
|
||||
from nanobot.webui.settings_contracts import MutationParams
|
||||
from nanobot.webui.settings_routes import _SETTINGS_ROUTES, WebUISettingsRouter
|
||||
from nanobot.webui.settings_services import WebUISettingsServices
|
||||
|
||||
|
||||
@@ -58,21 +59,27 @@ def _router(
|
||||
)
|
||||
|
||||
|
||||
def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace:
|
||||
request = SimpleNamespace(path=path, headers=Headers())
|
||||
request._nanobot_webui_mutation_request = True
|
||||
request._nanobot_webui_mutation_payload = payload
|
||||
request._nanobot_trusted_proxy_authenticated = True
|
||||
return request
|
||||
def _mutation_request(path: str, payload: dict[str, object]) -> tuple[str, MutationParams]:
|
||||
if path.startswith("/api/settings/channels/") and "/connect/" in path:
|
||||
_, channel, _, operation = path.rsplit("/", 3)
|
||||
return f"settings.channel.connect.{operation}", MutationParams({"channel": channel, **payload})
|
||||
action = _SETTINGS_ROUTES[path].mutation
|
||||
assert action is not None
|
||||
return action, MutationParams(payload)
|
||||
|
||||
|
||||
async def test_sandbox_check_is_authenticated_explicit_and_serialized(tmp_path, monkeypatch):
|
||||
async def _mutate(
|
||||
router: WebUISettingsRouter, request: tuple[str, MutationParams],
|
||||
):
|
||||
action, params = request
|
||||
return await router.dispatch_mutation(None, Headers(), action, params)
|
||||
|
||||
|
||||
async def test_sandbox_check_is_websocket_only_and_serialized(tmp_path, monkeypatch):
|
||||
path = "/api/settings/sandbox/check"
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
response = await router.dispatch(None, SimpleNamespace(path=path, headers=Headers()), path)
|
||||
assert response.status_code == 405
|
||||
unauthorized = _router(authorized=False, config_path=tmp_path / "config.json")
|
||||
assert (await unauthorized.dispatch(None, _mutation_request(path, {}), path)).status_code == 401
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def probe(config, workspace):
|
||||
@@ -81,33 +88,30 @@ async def test_sandbox_check_is_authenticated_explicit_and_serialized(tmp_path,
|
||||
return {"state": "passed", "reason": "", "launcher": "/usr/bin/bwrap", "revision": "test", "supported_backend": "bwrap"}
|
||||
|
||||
monkeypatch.setattr("nanobot.webui.settings_system.check_sandbox", probe)
|
||||
first = asyncio.create_task(router.dispatch(None, _mutation_request(path, {}), path))
|
||||
first = asyncio.create_task(_mutate(router, _mutation_request(path, {})))
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
try:
|
||||
assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 409
|
||||
assert (await _mutate(router, _mutation_request(path, {}))).status_code == 409
|
||||
finally:
|
||||
release.set()
|
||||
assert (await first).status_code == 200
|
||||
assert (await router.dispatch(None, _mutation_request(path, {}), path)).status_code == 200
|
||||
assert (await _mutate(router, _mutation_request(path, {}))).status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nanobot_update_requires_auth_local_permission_and_websocket(tmp_path, monkeypatch):
|
||||
async def test_nanobot_update_requires_local_permission_and_websocket(tmp_path, monkeypatch):
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
path = "/api/settings/nanobot-update/job/prepare"
|
||||
request = SimpleNamespace(path=path, headers=Headers())
|
||||
response = await router.dispatch(None, request, path)
|
||||
assert response.status_code == 405
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {}))
|
||||
assert response.status_code == 403
|
||||
unauthorized = _router(authorized=False, config_path=tmp_path / "config.json")
|
||||
response = await unauthorized.dispatch(None, _mutation_request(path, {}), path)
|
||||
assert response.status_code == 401
|
||||
monkeypatch.setattr(router._system, "allow_feature_package_install", lambda _: True)
|
||||
response = await router.dispatch(None, _mutation_request(path, {"id": "invalid"}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {"id": "invalid"}))
|
||||
assert response.status_code == 400
|
||||
router._runtime_surface = "native"
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {}))
|
||||
assert response.status_code == 409
|
||||
|
||||
|
||||
@@ -155,9 +159,9 @@ async def test_provider_login_keeps_maintenance_busy_until_worker_exits(tmp_path
|
||||
))
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {})
|
||||
path = "/api/settings/provider/oauth-login"
|
||||
response = await router.dispatch(None, _mutation_request(path, {"provider": "github_copilot"}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {"provider": "github_copilot"}))
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
payload = response.result
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("The authorization prompt still has a live worker")
|
||||
try:
|
||||
@@ -172,9 +176,9 @@ async def test_provider_login_keeps_maintenance_busy_until_worker_exits(tmp_path
|
||||
"/api/settings/provider/oauth-logout" if finish == "logout"
|
||||
else "/api/settings/provider/oauth-login/complete"
|
||||
)
|
||||
response = await router.dispatch(None, _mutation_request(path, {
|
||||
response = await _mutate(router, _mutation_request(path, {
|
||||
"provider": "github_copilot", "flow_id": payload["flow_id"], "cancel": "true",
|
||||
}), path)
|
||||
}))
|
||||
assert response.status_code == 200
|
||||
assert await asyncio.to_thread(stopping.wait, 1)
|
||||
assert router.settings.oauth_flows.get("github_copilot", payload["flow_id"]) is None
|
||||
@@ -207,9 +211,9 @@ async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeyp
|
||||
monkeypatch.setattr(oauth, "login_oauth_interactive", login)
|
||||
path = "/api/settings/provider/oauth-login"
|
||||
try:
|
||||
response = await router.dispatch(None, _mutation_request(path, {
|
||||
response = await _mutate(router, _mutation_request(path, {
|
||||
"provider": "openai_codex", "remote_browser": "true",
|
||||
}), path)
|
||||
}))
|
||||
assert response.status_code == 502
|
||||
assert entered.is_set()
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
@@ -227,7 +231,6 @@ async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeyp
|
||||
async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
|
||||
tmp_path, monkeypatch, close_fails,
|
||||
) -> None:
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
|
||||
|
||||
class Connector:
|
||||
@@ -248,10 +251,11 @@ async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
|
||||
"nanobot.webui.settings_routes.load_channel_plugin",
|
||||
lambda _: SimpleNamespace(load_connector=lambda: connector),
|
||||
)
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
path = "/api/settings/channels/whatsapp/connect/start"
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {}))
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["status"] == "pending"
|
||||
assert response.result["status"] == "pending"
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Returning a QR code does not finish its connection")
|
||||
shutdown = asyncio.create_task(router.close())
|
||||
@@ -275,14 +279,14 @@ async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_connector_can_connect_but_cannot_claim_maintenance_idle(tmp_path, monkeypatch):
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
connector = SimpleNamespace(handle=AsyncMock(return_value={"status": "pending"}))
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.load_channel_plugin",
|
||||
lambda _: SimpleNamespace(load_connector=lambda: connector),
|
||||
)
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
path = "/api/settings/channels/custom/connect/start"
|
||||
response = await router.dispatch(None, _mutation_request(path, {}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {}))
|
||||
assert response.status_code == 200
|
||||
await router.close()
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
@@ -457,9 +461,9 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admiss
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
|
||||
router = _router(config_path=tmp_path / "config.json")
|
||||
path = "/api/settings/mcp-oauth/start"
|
||||
response = await router.dispatch(None, _mutation_request(path, {"name": "linear"}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {"name": "linear"}))
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["status"] == "authorization_required"
|
||||
assert response.result["status"] == "authorization_required"
|
||||
with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
|
||||
pytest.fail("Settings returned, but authorization has not finished")
|
||||
|
||||
@@ -477,7 +481,7 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admiss
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monkeypatch) -> None:
|
||||
async def test_mcp_oauth_start_uses_gateway_callback_and_sanitizes_errors(monkeypatch) -> None:
|
||||
config = SimpleNamespace(
|
||||
type="streamableHttp",
|
||||
auth="oauth",
|
||||
@@ -501,11 +505,11 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
|
||||
{"name": "xmind"},
|
||||
)
|
||||
|
||||
response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start")
|
||||
response = await _mutate(router, request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["flow_id"] == "flow-123"
|
||||
assert response.result["flow_id"] == "flow-123"
|
||||
start.assert_awaited_once_with(
|
||||
"xmind",
|
||||
config,
|
||||
@@ -515,20 +519,15 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
|
||||
reset_credentials=False,
|
||||
)
|
||||
|
||||
denied = _router(authorized=False)
|
||||
denied_response = await denied.dispatch(None, request, "/api/settings/mcp-oauth/start")
|
||||
assert denied_response is not None
|
||||
assert denied_response.status_code == 401
|
||||
|
||||
failed = _router()
|
||||
failed._mcp_oauth = SimpleNamespace(
|
||||
start=AsyncMock(side_effect=RuntimeError("upstream secret response"))
|
||||
)
|
||||
failed_response = await failed.dispatch(None, request, "/api/settings/mcp-oauth/start")
|
||||
failed_response = await _mutate(failed, request)
|
||||
assert failed_response is not None
|
||||
assert failed_response.status_code == 500
|
||||
assert json.loads(failed_response.body) == {"error": "MCP OAuth start failed"}
|
||||
assert b"upstream secret response" not in failed_response.body
|
||||
assert failed_response.message == "MCP OAuth start failed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -575,22 +574,14 @@ async def test_mcp_oauth_manual_completion_reads_websocket_payload() -> None:
|
||||
{"flow_id": "flow-123", "callback_url": callback_url},
|
||||
)
|
||||
|
||||
response = await router.dispatch(None, request, "/api/settings/mcp-oauth/complete")
|
||||
response = await _mutate(router, request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["status"] == "connecting"
|
||||
assert b"oauth-code" not in response.body
|
||||
assert response.result["status"] == "connecting"
|
||||
assert "oauth-code" not in json.dumps(response.result)
|
||||
submit.assert_called_once_with(flow_id="flow-123", callback_url=callback_url)
|
||||
|
||||
denied = _router(authorized=False)
|
||||
denied_response = await denied.dispatch(
|
||||
None,
|
||||
request,
|
||||
"/api/settings/mcp-oauth/complete",
|
||||
)
|
||||
assert denied_response is not None
|
||||
assert denied_response.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -636,71 +627,58 @@ async def test_oauth_completion_reads_websocket_payload(
|
||||
},
|
||||
)
|
||||
|
||||
response = await router.dispatch(
|
||||
None,
|
||||
request,
|
||||
"/api/settings/provider/oauth-login/complete",
|
||||
)
|
||||
response = await _mutate(router, request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body) == {
|
||||
assert response.result == {
|
||||
"status": "pending",
|
||||
"provider": provider,
|
||||
"flow_id": "flow-123",
|
||||
}
|
||||
assert captured == {
|
||||
"query": {"provider": [provider], "flow_id": ["flow-123"]},
|
||||
"query": MutationParams({"provider": provider, "flow_id": "flow-123", "authorization_response": authorization_response}),
|
||||
"authorization_response": authorization_response,
|
||||
}
|
||||
assert request.path == "/api/settings/provider/oauth-login/complete"
|
||||
assert not request.headers
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("route_path", "function_name", "payload", "expected_query"),
|
||||
("route_path", "function_name", "payload"),
|
||||
[
|
||||
(
|
||||
"/api/settings/update",
|
||||
"update_agent_settings",
|
||||
{"model_preset": "Codex"},
|
||||
{"model_preset": ["Codex"]},
|
||||
),
|
||||
(
|
||||
"/api/settings/model-configurations/create",
|
||||
"create_model_configuration",
|
||||
{"name": "Codex", "model": "openai-codex/gpt-5.6"},
|
||||
{"name": ["Codex"], "model": ["openai-codex/gpt-5.6"]},
|
||||
),
|
||||
(
|
||||
"/api/settings/model-configurations/delete",
|
||||
"delete_model_configuration",
|
||||
{"name": "spare"},
|
||||
{"name": ["spare"]},
|
||||
),
|
||||
(
|
||||
"/api/settings/model-configurations/migrate",
|
||||
"migrate_model_configurations",
|
||||
{},
|
||||
{},
|
||||
),
|
||||
(
|
||||
"/api/settings/model-call-order/update",
|
||||
"update_model_call_order",
|
||||
{"order": ["backup"]},
|
||||
{"order": ['["backup"]']},
|
||||
),
|
||||
(
|
||||
"/api/settings/provider/create",
|
||||
"create_provider_settings",
|
||||
{"name": "team", "api_base": "https://llm.example/v1"},
|
||||
{"name": ["team"], "api_base": ["https://llm.example/v1"]},
|
||||
),
|
||||
(
|
||||
"/api/settings/provider/update",
|
||||
"update_provider_settings",
|
||||
{"provider": "team", "api_base": "https://llm.example/v2"},
|
||||
{"provider": ["team"], "api_base": ["https://llm.example/v2"]},
|
||||
),
|
||||
],
|
||||
)
|
||||
@@ -710,7 +688,6 @@ async def test_runtime_config_mutation_routes_refresh_live_runtime(
|
||||
route_path: str,
|
||||
function_name: str,
|
||||
payload: dict[str, object],
|
||||
expected_query: dict[str, list[str]],
|
||||
) -> None:
|
||||
captured: dict[str, object] = {}
|
||||
refresh_runtime_config = MagicMock()
|
||||
@@ -722,14 +699,14 @@ async def test_runtime_config_mutation_routes_refresh_live_runtime(
|
||||
monkeypatch.setattr(f"nanobot.webui.settings_routes.{function_name}", mutate)
|
||||
request = _mutation_request(route_path, payload)
|
||||
|
||||
response = await _router(
|
||||
response = await _mutate(_router(
|
||||
refresh_runtime_config=refresh_runtime_config,
|
||||
).dispatch(None, request, route_path)
|
||||
), request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["routed"] == function_name
|
||||
assert captured["query"] == expected_query
|
||||
assert response.result["routed"] == function_name
|
||||
assert captured["query"] == MutationParams(payload)
|
||||
refresh_runtime_config.assert_called_once_with()
|
||||
|
||||
|
||||
@@ -747,19 +724,15 @@ async def test_model_update_route_forwards_session_rename_dependency(monkeypatch
|
||||
path = "/api/settings/model-configurations/update"
|
||||
request = _mutation_request(path, {"name": "openai", "new_name": "Codex"})
|
||||
|
||||
response = await _router(
|
||||
response = await _mutate(_router(
|
||||
rename_model_preset=rename_model_preset,
|
||||
refresh_runtime_config=refresh_runtime_config,
|
||||
).dispatch(
|
||||
None,
|
||||
request,
|
||||
path,
|
||||
)
|
||||
), request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert captured == {
|
||||
"query": {"name": ["openai"], "new_name": ["Codex"]},
|
||||
"query": MutationParams({"name": "openai", "new_name": "Codex"}),
|
||||
"rename_model_preset": rename_model_preset,
|
||||
}
|
||||
refresh_runtime_config.assert_called_once_with()
|
||||
@@ -775,11 +748,11 @@ async def test_older_client_does_not_partially_update_provider_settings(tmp_path
|
||||
path = "/api/settings/provider/update"
|
||||
request = _mutation_request(path, {"provider": "openai", "apiType": "auto", "apiBase": "https://example.test/v1"})
|
||||
|
||||
response = await router.dispatch(None, request, path)
|
||||
response = await _mutate(router, request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 400
|
||||
assert "Update the client" in json.loads(response.body)["error"]
|
||||
assert "Update the client" in response.message
|
||||
assert config_path.read_text(encoding="utf-8") == before
|
||||
refresh.assert_not_called()
|
||||
|
||||
@@ -969,25 +942,23 @@ async def test_version_check_owner_is_additive_read_only_and_failure_is_not_a_re
|
||||
assert "secret" not in unavailable.body.decode()
|
||||
|
||||
|
||||
async def test_runtime_config_route_authentication_validation_and_restart(tmp_path):
|
||||
async def test_runtime_config_requires_websocket_and_tracks_restart(tmp_path):
|
||||
from nanobot.config.loader import load_config
|
||||
|
||||
path = "/api/settings/runtime-config/update"
|
||||
config_path = tmp_path / "config.json"
|
||||
request = _mutation_request(path, {"values": {"tools.exec.timeout": 19}})
|
||||
unauthorized = await _router(authorized=False, config_path=config_path).dispatch(None, request, path)
|
||||
assert unauthorized.status_code == 401
|
||||
assert not config_path.exists()
|
||||
router = _router(config_path=config_path)
|
||||
http_request = SimpleNamespace(path=path, headers=Headers())
|
||||
assert (await router.dispatch(None, http_request, path)).status_code == 405
|
||||
invalid = _mutation_request(path, {"values": {"channels.send_progress": False}})
|
||||
assert (await router.dispatch(None, invalid, path)).status_code == 400
|
||||
assert not config_path.exists()
|
||||
result = await router.dispatch(None, request, path)
|
||||
invalid = _mutation_request(path, {"values": {"channels.send_progress": False}})
|
||||
assert (await _mutate(router, invalid)).status_code == 400
|
||||
assert not config_path.exists()
|
||||
result = await _mutate(router, request)
|
||||
assert result.status_code == 200
|
||||
assert load_config(config_path).tools.exec.timeout == 19
|
||||
body = json.loads(result.body)
|
||||
body = result.result
|
||||
assert body["runtime_config"]["tools.exec.timeout"] == 19
|
||||
assert body["restart_required_sections"] == ["runtime"]
|
||||
refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")
|
||||
@@ -998,11 +969,11 @@ async def test_runtime_settings_only_save_without_refreshing_or_rebinding(tmp_pa
|
||||
refresh = MagicMock()
|
||||
router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh)
|
||||
path = "/api/settings/runtime-config/update"
|
||||
response = await router.dispatch(None, _mutation_request(path, {
|
||||
response = await _mutate(router, _mutation_request(path, {
|
||||
"values": {"agents.defaults.dream.enabled": False, "gateway.port": 19001},
|
||||
}), path)
|
||||
}))
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["requires_restart"]
|
||||
assert response.result["requires_restart"]
|
||||
refresh.assert_not_called()
|
||||
|
||||
|
||||
@@ -1014,9 +985,9 @@ async def test_reverting_runtime_switch_clears_restart_but_preserves_other_chang
|
||||
path = "/api/settings/runtime-config/update"
|
||||
|
||||
async def update(values):
|
||||
response = await router.dispatch(None, _mutation_request(path, {"values": values}), path)
|
||||
response = await _mutate(router, _mutation_request(path, {"values": values}))
|
||||
assert response.status_code == 200
|
||||
return json.loads(response.body)
|
||||
return response.result
|
||||
|
||||
assert (await update({"agents.defaults.dream.enabled": not original_memory}))["requires_restart"]
|
||||
await update({"tools.web.enable": not original_web})
|
||||
@@ -1034,31 +1005,31 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
|
||||
original_reader = config.tools.web.fetch.use_jina_reader
|
||||
original_port = config.gateway.port
|
||||
path = "/api/settings/web-search/update"
|
||||
first = await router.dispatch(None, _mutation_request(path, {
|
||||
first = await _mutate(router, _mutation_request(path, {
|
||||
"provider": "duckduckgo", "use_jina_reader": not original_reader,
|
||||
}), path)
|
||||
}))
|
||||
assert first.status_code == 200
|
||||
assert json.loads(first.body)["restart_required_sections"] == ["browser"]
|
||||
assert first.result["restart_required_sections"] == ["browser"]
|
||||
|
||||
runtime_path = "/api/settings/runtime-config/update"
|
||||
changed = await router.dispatch(None, _mutation_request(runtime_path, {
|
||||
changed = await _mutate(router, _mutation_request(runtime_path, {
|
||||
"values": {"gateway.port": original_port + 1},
|
||||
}), runtime_path)
|
||||
}))
|
||||
assert changed.status_code == 200
|
||||
assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"}
|
||||
assert set(changed.result["restart_required_sections"]) == {"browser", "runtime"}
|
||||
|
||||
restored = await router.dispatch(None, _mutation_request(path, {
|
||||
restored = await _mutate(router, _mutation_request(path, {
|
||||
"provider": "duckduckgo", "use_jina_reader": original_reader,
|
||||
}), path)
|
||||
}))
|
||||
assert restored.status_code == 200
|
||||
assert json.loads(restored.body)["restart_required_sections"] == ["runtime"]
|
||||
assert restored.result["restart_required_sections"] == ["runtime"]
|
||||
refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")
|
||||
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]
|
||||
reverted = await router.dispatch(None, _mutation_request(runtime_path, {
|
||||
reverted = await _mutate(router, _mutation_request(runtime_path, {
|
||||
"values": {"gateway.port": original_port},
|
||||
}), runtime_path)
|
||||
}))
|
||||
assert reverted.status_code == 200
|
||||
assert json.loads(reverted.body)["restart_required_sections"] == []
|
||||
assert reverted.result["restart_required_sections"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True])
|
||||
@@ -1077,11 +1048,11 @@ async def test_image_switch_round_trip_clears_restart(tmp_path, enabled):
|
||||
)
|
||||
router.logger.warning = MagicMock()
|
||||
path = "/api/settings/image-generation/update"
|
||||
changed = await router.dispatch(None, _mutation_request(path, {"enabled": not enabled}), path)
|
||||
assert json.loads(changed.body)["requires_restart"] is True
|
||||
reverted = await router.dispatch(None, _mutation_request(path, {"enabled": enabled}), path)
|
||||
assert json.loads(reverted.body)["requires_restart"] is False
|
||||
assert json.loads(reverted.body)["restart_required_sections"] == []
|
||||
changed = await _mutate(router, _mutation_request(path, {"enabled": not enabled}))
|
||||
assert changed.result["requires_restart"] is True
|
||||
reverted = await _mutate(router, _mutation_request(path, {"enabled": enabled}))
|
||||
assert reverted.result["requires_restart"] is False
|
||||
assert reverted.result["restart_required_sections"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1111,11 +1082,11 @@ async def test_first_mcp_oauth_request_saves_proxy_flag_before_starting_flow(tmp
|
||||
"/api/settings/mcp-oauth/start",
|
||||
{"name": "xmind", "use_proxy": True},
|
||||
)
|
||||
response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start")
|
||||
response = await _mutate(router, request)
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["flow_id"] == "first-flow"
|
||||
assert response.result["flow_id"] == "first-flow"
|
||||
assert captured == {"network": "http://shared.example:8080"}
|
||||
|
||||
|
||||
@@ -1172,7 +1143,7 @@ async def test_mcp_proxy_mutation_persists_reloads_and_keeps_oauth_credentials(
|
||||
connection, "settings.mcp.proxy", {"name": "team-docs", "use_proxy": str(use_proxy).lower()},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
payload = response.result
|
||||
assert payload["hot_reload"]["ok"] is True
|
||||
assert payload["requires_restart"] is False
|
||||
row = next(row for row in payload["presets"] if row["name"] == "team-docs")
|
||||
|
||||
@@ -765,7 +765,7 @@ async def test_webui_deletion_cancels_parent_work_and_removes_child_sessions(tmp
|
||||
connection, "session.delete", {"key": "websocket:parent"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["deleted"] is True
|
||||
assert response.result == {"deleted": True}
|
||||
gateway.http.discard_session.assert_awaited_once_with("websocket:parent")
|
||||
assert sessions.read_session_file("websocket:parent") is None
|
||||
assert sessions.read_session_file(child_key) is None
|
||||
|
||||
@@ -71,8 +71,8 @@ async def test_webui_task_access_and_targeted_idempotent_cancel(tmp_path):
|
||||
connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": task_id},
|
||||
)
|
||||
assert result.status_code == 404
|
||||
errors.append(result.body)
|
||||
assert errors[0] == errors[1]
|
||||
errors.append(result.message)
|
||||
assert errors == ["task unavailable", "task unavailable"]
|
||||
assert manager.check(foreign, "websocket:b").state == "running"
|
||||
|
||||
for _ in range(2):
|
||||
@@ -80,7 +80,8 @@ async def test_webui_task_access_and_targeted_idempotent_cancel(tmp_path):
|
||||
connection, "subagent.cancel", {"session_key": "websocket:a", "task_id": first},
|
||||
)
|
||||
assert result.status_code == 200
|
||||
assert json.loads(result.body)["state"] == "cancelled"
|
||||
assert result.result is not None
|
||||
assert result.result["state"] == "cancelled"
|
||||
assert manager.check(sibling, "websocket:a").state == "running"
|
||||
assert manager.check(foreign, "websocket:b").state == "running"
|
||||
assert bus.inbound_size == 1
|
||||
|
||||
@@ -60,8 +60,8 @@ async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews(
|
||||
assert response.status_code == 403
|
||||
assert read_update_channel().revision == 0
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, {"channel": "preview", "revision": 0})
|
||||
assert response.status_code == 200, response.body
|
||||
assert json.loads(response.body) == {"channel": "preview", "revision": 1}
|
||||
assert response.status_code == 200, response.message
|
||||
assert response.result == {"channel": "preview", "revision": 1}
|
||||
assert "webui.update-channels.v1" in webui_contract()["capabilities"]
|
||||
reviewed = await fetch(gateway, READ + "?id=" + plan.id)
|
||||
assert json.loads(reviewed.body)["plan"]["validity"] == "channel_changed"
|
||||
@@ -109,7 +109,7 @@ async def test_review_uses_saved_channel_and_rejects_a_change_during_discovery(p
|
||||
monkeypatch.setattr(update_plan, "ReleaseFeed", lambda _: Feed())
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
|
||||
assert response.status_code == 200
|
||||
saved = UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"])
|
||||
saved = UpdatePlans(fixture.directory / "plans").load(response.result["plan"]["id"])
|
||||
assert (saved.channel, saved.channel_revision) == ("preview", 1)
|
||||
race = True
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
|
||||
@@ -206,8 +206,8 @@ async def preparation_plan(fixture):
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection(local=True), "settings.nanobot.update.plan", {"extras": []},
|
||||
)
|
||||
assert response.status_code == 200, response.body
|
||||
return gateway, UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"])
|
||||
assert response.status_code == 200, response.message
|
||||
return gateway, UpdatePlans(fixture.directory / "plans").load(response.result["plan"]["id"])
|
||||
|
||||
|
||||
async def execution_plan(fixture):
|
||||
@@ -256,12 +256,12 @@ async def test_execution_consent_survives_cancelled_response_and_duplicate_reque
|
||||
assert not operation.done(), "A lost requester cannot abandon a still-running launch thread"
|
||||
fresh = fixture.gateway()
|
||||
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload)
|
||||
assert duplicate.status_code == 200, duplicate.body
|
||||
assert duplicate.headers["Cache-Control"] == "no-store"
|
||||
saved = json.loads(duplicate.body)["job"]
|
||||
assert duplicate.status_code == 200, duplicate.message
|
||||
saved = duplicate.result["job"]
|
||||
assert saved["execution_confirmation_id"] == confirmation.id
|
||||
assert saved["recorded_phase"] == "checking" and not saved["mutation_started"]
|
||||
restored = await fetch(fresh, JOB + "?id=" + plan.id)
|
||||
assert restored.headers["Cache-Control"] == "no-store"
|
||||
assert json.loads(restored.body)["job"] == saved
|
||||
finally:
|
||||
release.set()
|
||||
@@ -326,13 +326,12 @@ async def test_retry_is_explicit_authorized_and_old_submissions_only_read_histor
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, bad)).status_code == 400
|
||||
assert not calls
|
||||
first = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, payload)
|
||||
assert first.status_code == 200, first.body
|
||||
assert first.headers["Cache-Control"] == "no-store"
|
||||
assert json.loads(first.body)["job"]["execution_confirmation_id"] == current.id
|
||||
assert first.status_code == 200, first.message
|
||||
assert first.result["job"]["execution_confirmation_id"] == current.id
|
||||
fresh = fixture.gateway()
|
||||
for action, body in ((RETRY, payload), (EXECUTE, {"id": plan.id, "confirm_restart": True})):
|
||||
repeated = await fresh.http.dispatch_webui_mutation(connection(local=True), action, body)
|
||||
assert repeated.status_code == 200 and json.loads(repeated.body) == json.loads(first.body)
|
||||
assert repeated.status_code == 200 and repeated.result == first.result
|
||||
assert calls == [previous.id]
|
||||
assert "webui.update-jobs.retry-handoff.v1" in webui_contract()["capabilities"]
|
||||
|
||||
@@ -349,7 +348,8 @@ async def test_busy_retry_does_not_look_like_an_accepted_new_confirmation(prepar
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY,
|
||||
{"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True})
|
||||
assert response.status_code == 409
|
||||
assert b"private lease" not in response.body
|
||||
assert response.message is not None
|
||||
assert "private lease" not in response.message
|
||||
assert ExecutionConfirmation.read(directory) == previous
|
||||
|
||||
|
||||
@@ -373,10 +373,11 @@ async def test_handoff_settlement_route_preserves_permission_and_reads_cancelled
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(), SETTLE, {"id": plan.id})).status_code == 403
|
||||
assert calls == []
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
|
||||
assert response.status_code == 200, response.body
|
||||
assert json.loads(response.body)["job"]["recorded_phase"] == "cancelled"
|
||||
assert json.loads(response.body)["job"]["execution_confirmation_id"] == previous.id
|
||||
assert (await fetch(gateway, JOB + "?id=" + plan.id)).body == response.body
|
||||
assert response.status_code == 200, response.message
|
||||
assert response.result["job"]["recorded_phase"] == "cancelled"
|
||||
assert response.result["job"]["execution_confirmation_id"] == previous.id
|
||||
restored = await fetch(gateway, JOB + "?id=" + plan.id)
|
||||
assert json.loads(restored.body) == response.result
|
||||
assert calls == [directory]
|
||||
assert "webui.update-jobs.settle-handoff.v1" in webui_contract()["capabilities"]
|
||||
|
||||
@@ -402,7 +403,7 @@ async def test_execution_refuses_unreviewed_gateway_lifecycle(preparation_gatewa
|
||||
monkeypatch.setattr(update_service, "start_handoff", forbidden)
|
||||
result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE,
|
||||
{"id": plan.id, "confirm_restart": True})
|
||||
assert result.status_code == 409, result.body
|
||||
assert result.status_code == 409, result.message
|
||||
assert ExecutionConfirmation.read(directory) is None
|
||||
|
||||
|
||||
@@ -429,17 +430,18 @@ async def test_preparation_is_durable_idempotent_and_independent_of_browser(prep
|
||||
close = None
|
||||
try:
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert response.status_code == 200, response.body
|
||||
assert json.loads(response.body)["job"]["recorded_phase"] == "preparation_requested"
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
assert response.status_code == 200, response.message
|
||||
assert response.result["job"]["recorded_phase"] == "preparation_requested"
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
fresh = fixture.gateway()
|
||||
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert duplicate.status_code == 200
|
||||
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparing"
|
||||
assert (await fetch(fresh, JOB + "?id=" + plan.id)).status_code == 200
|
||||
assert duplicate.result["job"]["recorded_phase"] == "preparing"
|
||||
restored = await fetch(fresh, JOB + "?id=" + plan.id)
|
||||
assert restored.status_code == 200
|
||||
assert restored.headers["Cache-Control"] == "no-store"
|
||||
assert (await fresh.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})).status_code == 409
|
||||
other = plan.model_copy(update={"id": str(uuid4())})
|
||||
UpdatePlans(fixture.directory / "plans").save(other)
|
||||
@@ -494,8 +496,8 @@ async def test_preparation_revalidation_failure_is_saved_and_never_retried_by_re
|
||||
await gateway.http.settings_routes.close()
|
||||
duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert duplicate.status_code == 200
|
||||
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed"
|
||||
assert b"secret" not in duplicate.body
|
||||
assert duplicate.result["job"]["recorded_phase"] == "preparation_failed"
|
||||
assert "secret" not in json.dumps(duplicate.result)
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
assert "secret" not in (directory / "status.json").read_text()
|
||||
assert targets == [plan.target]
|
||||
@@ -555,20 +557,20 @@ async def test_explicit_settlement_checks_ownership_and_does_not_retry(preparati
|
||||
|
||||
monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", forbidden)
|
||||
restored = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert json.loads(restored.body)["job"]["recorded_phase"] == phase.value
|
||||
assert restored.result["job"]["recorded_phase"] == phase.value
|
||||
lock = "prepare-native.lock" if phase == Phase.PREPARING else "preparation-controller.lock"
|
||||
with file_access(fixture.directory / lock, exclusive=True):
|
||||
blocked = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
|
||||
assert blocked.status_code == 409
|
||||
assert JobStatus.read(directory).phase == phase
|
||||
settled = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
|
||||
assert settled.status_code == 200, settled.body
|
||||
assert json.loads(settled.body)["job"]["recorded_phase"] == "preparation_failed"
|
||||
assert settled.status_code == 200, settled.message
|
||||
assert settled.result["job"]["recorded_phase"] == "preparation_failed"
|
||||
if phase == Phase.PREPARING:
|
||||
assert PreparationProcess.load(directory).active is False
|
||||
assert not (directory / "request.json").exists()
|
||||
duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed"
|
||||
assert duplicate.result["job"]["recorded_phase"] == "preparation_failed"
|
||||
|
||||
|
||||
async def test_exact_review_survives_router_recreation_without_reselection_or_install(review_gateway):
|
||||
@@ -581,9 +583,8 @@ async def test_exact_review_survives_router_recreation_without_reselection_or_in
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection(), "settings.nanobot.update.plan", {"channel": "stable", "restart_running": True},
|
||||
)
|
||||
assert response.status_code == 200, response.body
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
payload = json.loads(response.body)
|
||||
assert response.status_code == 200, response.message
|
||||
payload = response.result
|
||||
review = payload["plan"]
|
||||
assert payload["installation_allowed"] is False
|
||||
assert payload["execution_available"] is False
|
||||
@@ -618,7 +619,7 @@ async def test_live_update_review_requires_this_gateway_and_preserves_owner_poli
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
|
||||
)
|
||||
payload = json.loads(response.body)
|
||||
payload = response.result
|
||||
assert payload["installation_allowed"] is True
|
||||
assert payload["execution_available"] is (os.name == "posix")
|
||||
assert payload["plan"]["extras"] == ["webui"]
|
||||
@@ -641,7 +642,7 @@ async def test_review_routes_unverified_uv_versions_to_the_installation_owner(re
|
||||
connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
payload = response.result
|
||||
assert payload["execution_available"] is False
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"])
|
||||
assert update_plan.inline_update_blocked_reason(plan) == "installation_owner"
|
||||
@@ -653,7 +654,7 @@ async def test_review_reports_profile_and_installation_changes_without_replacing
|
||||
gateway = fixture.gateway()
|
||||
created = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {})
|
||||
assert created.status_code == 200
|
||||
payload = json.loads(created.body)
|
||||
payload = created.result
|
||||
assert payload["installation_allowed"] is True
|
||||
review = payload["plan"]
|
||||
assert not any(item["stop"] or item["restart"] for item in review["profiles"])
|
||||
@@ -691,7 +692,7 @@ async def test_expired_unknown_and_foreign_plans_have_explicit_results(review_ga
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
review = json.loads(response.body)["plan"]
|
||||
review = response.result["plan"]
|
||||
now = time.time()
|
||||
monkeypatch.setattr(update_plan.time, "time", lambda: now + 901)
|
||||
response = await fetch(gateway, READ + "?id=" + review["id"])
|
||||
@@ -719,7 +720,8 @@ async def test_desktop_and_failed_discovery_do_not_claim_executable_or_current(r
|
||||
monkeypatch.setattr(update_plan, "inspect_installation", failed_probe)
|
||||
failed = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
assert failed.status_code == 409
|
||||
assert b"secret" not in failed.body
|
||||
assert failed.message is not None
|
||||
assert "secret" not in failed.message
|
||||
assert not (fixture.directory / "plans").exists()
|
||||
|
||||
|
||||
@@ -739,7 +741,7 @@ async def test_environment_replaced_during_discovery_does_not_return_a_valid_rev
|
||||
connection(), "settings.nanobot.update.plan", {},
|
||||
)
|
||||
assert response.status_code == 409
|
||||
assert response.body == b"Could not verify an update plan for this installation. No update was started."
|
||||
assert response.message == "Could not verify an update plan for this installation. No update was started."
|
||||
assert calls == 2
|
||||
assert not (fixture.directory / "jobs").exists()
|
||||
|
||||
@@ -748,7 +750,7 @@ async def test_missing_interpreter_is_not_misreported_as_a_missing_plan(review_g
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
plan_id = json.loads(response.body)["plan"]["id"]
|
||||
plan_id = response.result["plan"]["id"]
|
||||
|
||||
def removed_python():
|
||||
raise FileNotFoundError("/private/installation/bin/python")
|
||||
@@ -764,7 +766,7 @@ async def test_job_reads_survive_refresh_expiry_and_unavailable_installation(rev
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
plan_id = json.loads(response.body)["plan"]["id"]
|
||||
plan_id = response.result["plan"]["id"]
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
|
||||
directory = fixture.directory / "jobs" / plan_id
|
||||
directory.mkdir(parents=True)
|
||||
@@ -828,7 +830,7 @@ async def test_job_reads_reject_missing_foreign_and_corrupt_records(review_gatew
|
||||
fixture = review_gateway
|
||||
gateway = fixture.gateway()
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
|
||||
plan_id = json.loads(response.body)["plan"]["id"]
|
||||
plan_id = response.result["plan"]["id"]
|
||||
plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
|
||||
monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment)
|
||||
for query in ("", "?id=../../config", "?id=not-a-uuid"):
|
||||
@@ -904,7 +906,7 @@ async def test_plan_cannot_invent_restart_ownership_or_replace_manager_extras(re
|
||||
assert not (fixture.directory / "plans").exists()
|
||||
else:
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
payload = response.result
|
||||
assert payload["execution_available"] is False
|
||||
assert payload["plan"]["execution_blocked_reason"] == (
|
||||
"external_restart" if os.name == "posix" else "installation_owner"
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import cast
|
||||
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request as WsRequest
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.ws_http import GatewayHTTPHandler
|
||||
@@ -16,14 +12,10 @@ def _handler(config: WebSocketConfig) -> GatewayHTTPHandler:
|
||||
return handler
|
||||
|
||||
|
||||
def _request(**headers: str) -> WsRequest:
|
||||
return cast(WsRequest, SimpleNamespace(headers=Headers(headers)))
|
||||
|
||||
|
||||
def test_mcp_oauth_callback_uses_configured_public_websocket_origin() -> None:
|
||||
handler = _handler(WebSocketConfig(path="/ws", public_ws_url="wss://agent.example/ws"))
|
||||
|
||||
redirect_uri = handler._mcp_oauth_redirect_uri(_request(Host="ignored.example"))
|
||||
redirect_uri = handler._mcp_oauth_redirect_uri(Headers({"Host": "ignored.example"}))
|
||||
|
||||
assert redirect_uri == "https://agent.example/auth/mcp/callback"
|
||||
|
||||
@@ -32,7 +24,7 @@ def test_mcp_oauth_callback_uses_safe_forwarded_request_origin() -> None:
|
||||
handler = _handler(WebSocketConfig(path="/ws", host="127.0.0.1", port=8765))
|
||||
|
||||
redirect_uri = handler._mcp_oauth_redirect_uri(
|
||||
_request(Host="nanobot.example:9443", **{"X-Forwarded-Proto": "https"})
|
||||
Headers({"Host": "nanobot.example:9443", "X-Forwarded-Proto": "https"})
|
||||
)
|
||||
|
||||
assert redirect_uri == "https://nanobot.example:9443/auth/mcp/callback"
|
||||
Reference in new issue
Block a user