refactor: remove redundant comments and docstrings (#6527)
* refactor: remove redundant comments and docstrings * fix(signal): annotate async context manager as a generator
This commit is contained in:
1 parent
cb3ba45317
commit
a4d2430140
922 files changed
+406
-7738
No files matched your search
@@ -1,5 +1,3 @@
|
||||
"""Move a complete scheduled turn through the real authenticated gateway."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
@@ -88,10 +86,8 @@ async def test_durable_move_stale_edit_failed_save_and_old_action(tmp_path, monk
|
||||
assert CronService(cron.store_path).get_job(job.id) == moved
|
||||
with pytest.raises(ValueError, match="changed"):
|
||||
cron.change_binding(job.id, revision=revision, binding=target_binding(), message="Stale")
|
||||
# A CLI process can have read the old job before the WebUI commits.
|
||||
cron._append_action("update", asdict(old))
|
||||
assert cron.get_job(job.id) == moved
|
||||
# A directory-sync failure after replace must not report a false rollback.
|
||||
def committed_then_failed(path, content):
|
||||
write(path, content)
|
||||
raise OSError("directory sync failed")
|
||||
@@ -168,7 +164,6 @@ async def test_target_identity_scope_and_channel_lifecycle(tmp_path):
|
||||
offline = await automation_chats(job, sessions, workspaces, {})
|
||||
current = next(chat for chat in offline if chat.title == "Product team")
|
||||
assert current.public_payload()["unavailable"] is True
|
||||
# Only identical display names need a visible disambiguator.
|
||||
session = sessions.get_or_create("websocket:source")
|
||||
await sessions.state.update_metadata(session.key, {"title": "Product team"})
|
||||
duplicates = await automation_chats(job, sessions, workspaces, {})
|
||||
@@ -349,7 +344,6 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path, target
|
||||
return
|
||||
cron.change_binding(job.id, revision=binding_revision(moved),
|
||||
binding=CronBinding("websocket:source", "websocket", "source", {}), message="Back")
|
||||
# Moving back must not turn the external run's link into the current chat.
|
||||
history = serialize_automation_jobs([cron.get_job(job.id)], include_details=True)[0]["state"]["run_history"]
|
||||
assert [run["webui_session_key"] for run in history] == expected_history
|
||||
finally:
|
||||
@@ -363,7 +357,6 @@ async def test_real_gateway_move_run_reload_and_previous_result(tmp_path, target
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_late_subagent_result_stays_with_moved_task(tmp_path, monkeypatch):
|
||||
# A background result can arrive after the normal 300-second terminal wait.
|
||||
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.02)
|
||||
sessions, cron, job = seed(tmp_path)
|
||||
release = asyncio.Event()
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Published package versions never substitute for wire compatibility."""
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.webui.client_contract import assess_webui_contract, compatibility_error, webui_contract
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""The WebUI exposes only user-facing device data and owns cancellation."""
|
||||
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
@@ -84,8 +82,6 @@ def test_cancels_copilot_login_while_device_prompt_is_loading(monkeypatch, tmp_p
|
||||
else:
|
||||
replacement = login_oauth_provider(Config(), query, **kwargs)
|
||||
assert registry.get("github_copilot", replacement["flow_id"]) is not None
|
||||
# Cancellation must end the start request without waiting for the
|
||||
# outstanding GitHub device-code response to return.
|
||||
with pytest.raises(WebUISettingsError, match="GitHub sign-in failed"):
|
||||
started.result(timeout=1)
|
||||
assert saved == []
|
||||
|
||||
@@ -67,7 +67,6 @@ def test_file_reference_rejects_missing_files_and_directories(tmp_path, target)
|
||||
(b"RIFF\0\0\0\0WEBPexample", "image/webp"),
|
||||
])
|
||||
def test_raster_preview_uses_content_signature(tmp_path: Path, data: bytes, mime: str) -> None:
|
||||
# Extension must not determine the rendered MIME type.
|
||||
image = tmp_path / "figure.bin"
|
||||
image.write_bytes(data)
|
||||
scope = default_workspace_scope(tmp_path, restrict_to_workspace=True)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Terminal capability metadata is authenticated and does not allocate tokens."""
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Black-box smoke test for the real gateway WebUI transport."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -32,7 +30,6 @@ _BOOTSTRAP_SECRET = "smoke-secret"
|
||||
async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The auth proxy must preserve the actual gateway's WebUI mutation audience."""
|
||||
# Python CI runs from a clean source tree without a frontend build. Supply
|
||||
# this transport smoke's own local shell instead of relying on build leftovers.
|
||||
assets = tmp_path / "local-dist"
|
||||
@@ -354,7 +351,6 @@ async def test_gateway_recovers_private_children_and_deletes_them_with_parent(tm
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_path: Path) -> None:
|
||||
"""Two terminal clients exercise real authentication, framing and gateway lifetime."""
|
||||
ws_port, gateway_port = _free_port(), _free_port()
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
@@ -369,12 +365,11 @@ async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_pat
|
||||
unauthenticated = httpx.get(f"{base_url}/webui/terminal", trust_env=False)
|
||||
assert unauthenticated.status_code == 401
|
||||
probe = _get_bootstrap(f"{base_url}/webui/terminal")
|
||||
assert probe == terminal # Contains no token or config information.
|
||||
assert probe == terminal
|
||||
second = _get_bootstrap(f"{base_url}/webui/bootstrap")
|
||||
assert second["terminal"] == terminal
|
||||
identity_query = f'&terminal_protocol=1&terminal_instance={terminal["gatewayId"]}'
|
||||
first_url = f'{first["ws_url"]}?token={first["token"]}&client_id=terminal-one'
|
||||
# A rejected wrong-instance upgrade must not consume the one-use WS token.
|
||||
with pytest.raises(websockets.exceptions.InvalidStatus) as wrong:
|
||||
async with websockets.connect(first_url + "&terminal_protocol=1&terminal_instance=wrong"):
|
||||
pytest.fail("Wrong gateway identity accepted")
|
||||
@@ -394,7 +389,6 @@ async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_pat
|
||||
assert process.poll() is None
|
||||
after = _get_bootstrap(f"{base_url}/webui/bootstrap")
|
||||
assert after["terminal"] == terminal
|
||||
# The ordinary WebUI ready frame remains unchanged (no opt-in metadata).
|
||||
async with websockets.connect(f'{after["ws_url"]}?token={after["token"]}&client_id=browser') as browser:
|
||||
assert "terminal" not in await _recv_until(browser, "ready")
|
||||
finally:
|
||||
@@ -404,7 +398,6 @@ async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_pat
|
||||
def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Exercise recovery through two real gateway processes and durable files."""
|
||||
ws_port = _free_port()
|
||||
gateway_port = _free_port()
|
||||
workspace = tmp_path / "workspace"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for shared embedded WebUI HTTP helpers."""
|
||||
|
||||
import gzip
|
||||
import json
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Complete, lightweight navigation uses the same IDs and cursors as replay."""
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
@@ -33,11 +31,10 @@ def test_complete_index_and_bidirectional_pages_without_loading_model_messages(h
|
||||
assert page["events"][0]["text"] == "question 42"
|
||||
assert page["page"]["user_message_offset"] == 42
|
||||
assert page["page"]["has_more_before"] and page["page"]["has_more_after"]
|
||||
assert stats.parsed_records < 40 # Not the 360-record transcript.
|
||||
assert stats.parsed_records < 40
|
||||
newer = history.build(key, after=page["page"]["after_cursor"], limit=6)
|
||||
older = history.build(key, before=newer["page"]["before_cursor"], limit=6)
|
||||
assert older["events"] == page["events"]
|
||||
# Warm navigation uses the committed revision and cached summaries.
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr("nanobot.session.display_history.HistoryReader.navigation", lambda _: (_ for _ in ()).throw(AssertionError("replayed history")))
|
||||
assert history.prompts(key) == index
|
||||
@@ -106,7 +103,6 @@ def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(history
|
||||
assert appended["replaceFrom"] == 100
|
||||
assert len(appended["prompts"]) == 1
|
||||
assert [*initial["prompts"], *appended["prompts"]] == history.prompts(key)
|
||||
# A late answer changes the last preview; it must replace that prompt, not append it.
|
||||
history.append(key, {"event": "message", "text": "answer", "turn_id": "next"})
|
||||
changed = history.prompt_response(key, appended["revision"])
|
||||
assert changed["replaceFrom"] == 100
|
||||
@@ -116,7 +112,7 @@ def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(history
|
||||
replaced = history.prompt_response(key, changed["revision"])
|
||||
assert replaced["replaceFrom"] == 0
|
||||
assert len(replaced["prompts"]) == 1
|
||||
transcript._PROMPT_SNAPSHOTS.clear() # Restart/eviction sends a complete response.
|
||||
transcript._PROMPT_SNAPSHOTS.clear()
|
||||
assert history.prompt_response(key, replaced["revision"])["replaceFrom"] == 0
|
||||
history.sessions.delete_session(key)
|
||||
assert history.prompt_response(key, replaced["revision"])["prompts"] == ()
|
||||
@@ -183,8 +179,6 @@ async def test_recovered_public_index_and_page_validators_include_canonical_time
|
||||
Request(path, Headers([*auth, ("If-None-Match", response.headers["ETag"])])), path,
|
||||
)
|
||||
assert unchanged.status_code == 304
|
||||
# A canonical-only update must invalidate the recovered display even when
|
||||
# transcript artifacts and the session's updated_at are unchanged.
|
||||
session = await manager.state.get(key)
|
||||
session.messages[0]["timestamp"] = "2026-06-02T10:01:00+00:00"
|
||||
await manager.state.finish_turn(session)
|
||||
@@ -252,14 +246,12 @@ async def test_cached_history_routes_skip_replay_and_canonical_reads(history, tm
|
||||
Request(conditional, Headers([*auth, ("If-None-Match", previous.headers["ETag"])])), path.split("?")[0],
|
||||
)
|
||||
assert response.status_code == 304 and not response.body
|
||||
# An ordinary directory read also reuses the view, with or without `since`.
|
||||
for suffix in ("", "?since=" + prompts["revision"]):
|
||||
response = await gateway.http._dispatch_session_routes(Request(base + "/prompts" + suffix, Headers(auth)), base + "/prompts")
|
||||
assert response.status_code == 200
|
||||
data = json.loads(response.body)
|
||||
assert data["prompts"] == ([] if suffix else prompts["prompts"])
|
||||
assert data["replaceFrom"] == (3 if suffix else 0)
|
||||
# Eviction must not turn a valid conditional request into a replay either.
|
||||
transcript._PROMPT_SNAPSHOTS.clear()
|
||||
for path, previous in initial.items():
|
||||
response = await gateway.http._dispatch_session_routes(
|
||||
@@ -333,7 +325,6 @@ def test_indexed_backfill_preserves_unique_in_suffix_matching(history, tmp_path,
|
||||
history.append(key, {"event": "message", "text": answer})
|
||||
history.append(key, {"event": "turn_end"})
|
||||
prompts = history.prompts(key, session_messages_loader=lambda: messages)
|
||||
# A unique intervening answer advances the alignment past the first duplicate.
|
||||
assert len(prompts) == (len(answers) if with_anchor else 1)
|
||||
page = history.build(key, limit=1, session_messages=messages)
|
||||
users = [event for event in page["events"] if event["event"] == "user_message"]
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Remote setup discovers metadata, not secrets, and never invents sudo access."""
|
||||
|
||||
import asyncio
|
||||
import getpass
|
||||
import json
|
||||
@@ -46,7 +44,7 @@ def locate(monkeypatch, capsys, path, units="", properties=""):
|
||||
|
||||
def test_default_config_found_without_reading_contents(tmp_path, monkeypatch, capsys):
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text("model-secret") # Even invalid config content isn't read by discovery.
|
||||
path.write_text("model-secret")
|
||||
result, calls = locate(monkeypatch, capsys, path)
|
||||
assert result["candidates"] == [{"config_path": str(path), "runtime_user": "", "service": ""}]
|
||||
assert len(calls) == 1
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Connection boundaries: no deployment, copied model keys or remote shutdown."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
@@ -99,7 +97,6 @@ async def test_server_upgrade_rechecks_compatibility_without_new_pairing(manager
|
||||
ssh.state["identity"]["webui"] = {**webui_contract(), "version": "9.0.0"}
|
||||
await manager.action("connect", {"id": key})
|
||||
assert manager.snapshot()["profiles"][0]["compatibility"]["status"] == "compatible"
|
||||
# The stable saved host remains; only its reserved local origin is added.
|
||||
assert set(json.loads(manager.path.read_text(encoding="utf-8"))) == set(json.loads(saved))
|
||||
|
||||
|
||||
@@ -343,7 +340,6 @@ async def test_aliases_cannot_open_duplicate_views_but_distinct_instances_can(ma
|
||||
await manager.action("connect", {"id": first})
|
||||
first_connection = manager.connections[first]
|
||||
alias = await save(manager, host="another-alias", config_path="/srv/bot/config.json")
|
||||
# A genuinely separate tunnel/proxy, rather than the shared fixture handle.
|
||||
second_tunnel = SimpleNamespace(active=True, error="", port=23457, close=AsyncMock())
|
||||
second_proxy = SimpleNamespace(port=23458, origin="http://127.0.0.1:23458", secret="local-two")
|
||||
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=second_tunnel))
|
||||
@@ -386,8 +382,8 @@ async def test_offline_alias_does_not_block_replacement_connection(manager, ssh,
|
||||
assert first not in manager.connections
|
||||
assert manager.connections[alias].proxy is second_proxy
|
||||
ssh.tunnel.pause.assert_awaited_once()
|
||||
ssh.tunnel.close.assert_not_awaited() # Keep the old browser origin reserved.
|
||||
assert len(manager.snapshot()["profiles"]) == 2 # No saved routes/drafts were deleted.
|
||||
ssh.tunnel.close.assert_not_awaited()
|
||||
assert len(manager.snapshot()["profiles"]) == 2
|
||||
|
||||
|
||||
async def test_closing_local_manager_reaps_ssh(manager, ssh):
|
||||
@@ -486,8 +482,6 @@ async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh)
|
||||
await manager.action("disconnect", {"id": key})
|
||||
await manager.action("save", {"id": key, "profile": {"name": "Renamed", "host": "ubuntu@example.test"}})
|
||||
assert json.loads(manager.path.read_text())[key]["local_port"] == 23456
|
||||
# Editing display metadata must preserve the local-client origin marker,
|
||||
# not just its port: otherwise reconnect silently retires that origin.
|
||||
assert json.loads(manager.path.read_text())[key]["local_client_origin"] is True
|
||||
second = await manager.action("connect", {"id": key})
|
||||
assert second["url"] == first["url"]
|
||||
@@ -587,7 +581,7 @@ async def test_old_profile_origin_is_remembered_before_first_edit(manager, ssh):
|
||||
key = await save(manager)
|
||||
old = json.loads(manager.path.read_text())
|
||||
old[key]["local_port"] = 23456
|
||||
manager.path.write_text(json.dumps(old)) # Pre-ledger profile created by the previous build.
|
||||
manager.path.write_text(json.dumps(old))
|
||||
await manager.action("save", {"id": key, "profile": {
|
||||
"name": "Other", "host": "ubuntu@example.test", "runtime_user": "other-user",
|
||||
}})
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Private SSH master lifetime and guarded-bridge compatibility."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Pairing protocol, restricted authorization and local API regression tests."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -182,7 +180,6 @@ def test_paired_transport_cannot_fall_back_to_generic_probe_or_forwarding(pair,
|
||||
|
||||
@pytest.mark.parametrize("command", ["echo MUST-NOT-EXECUTE", "nanobot-remote-bridge-v2"])
|
||||
def test_fixed_bridge_streams_only_to_baked_in_loopback_port(tmp_path, command):
|
||||
# Real bidirectional bytes, no SSH_ORIGINAL_COMMAND interpolation.
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
@@ -228,7 +225,7 @@ def test_guarded_bridge_rejects_new_channels_without_connecting(tmp_path, reason
|
||||
result = subprocess.run([sys.executable, "-I", "-S", str(bridge)], capture_output=True, timeout=5,
|
||||
env={**os.environ, "SSH_ORIGINAL_COMMAND": "nanobot-remote-bridge-v2"})
|
||||
assert result.returncode == 1
|
||||
assert not result.stdout # No reuse capability or connection to the target.
|
||||
assert not result.stdout
|
||||
assert b"Permission denied" in result.stderr
|
||||
|
||||
|
||||
@@ -298,10 +295,10 @@ async def test_repeated_pairing_groups_one_instance_without_deleting_authorizati
|
||||
code = seal(second, renewed)
|
||||
preview = await manager.action("pair_preview", {"id": second.id, "code": code})
|
||||
assert preview["existing_connection"] == {"id": first.id, "name": "My team", "connected": False}
|
||||
assert len(manager.snapshot()["profiles"]) == 1 # Preview never saves or deletes.
|
||||
assert len(manager.snapshot()["profiles"]) == 1
|
||||
result = await manager.action("pair_finish", {"id": second.id, "code": code})
|
||||
assert result["id"] == second.id
|
||||
assert len(result["profiles"]) == 2 # Grants remain separately manageable.
|
||||
assert len(result["profiles"]) == 2
|
||||
assert {item["instance_id"] for item in result["profiles"]} == {first.id}
|
||||
assert {item["name"] for item in result["profiles"]} == {"My team"}
|
||||
assert manager.pairing.path(first.id).joinpath("identity").read_bytes() == before
|
||||
@@ -511,7 +508,6 @@ def test_expired_device_cannot_connect(pair, monkeypatch):
|
||||
monkeypatch.setattr(remote_pairing.time, "time", lambda: value.authorized_until + 1)
|
||||
with pytest.raises(RemoteError, match="pair_authorization_expired"):
|
||||
store.connection(request.id)
|
||||
# The UI can explain expiry without opening a path around connection().
|
||||
assert store.authorization_until(request.id) == value.authorized_until
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Real browser-side HTTP/WS, real gateway auth, and an owned SSH-pipe fixture."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
@@ -431,8 +429,6 @@ async def test_shutdown_replay_contains_only_dead_local_capabilities(remote):
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# The same browser retries after the local gateway exits. The new process
|
||||
# receives credentials that the actual remote gateway cannot authenticate.
|
||||
async with await asyncio.start_server(replacement, "127.0.0.1", remote.proxy.port):
|
||||
await remote.client.get(origin + "/webui/bootstrap", headers={"X-Nanobot-Auth": secret})
|
||||
await remote.client.get(origin + "/api/fixture", headers={"Authorization": "Bearer " + issued["api_token"]})
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""An optional host capability survives the authenticated bootstrap proxy."""
|
||||
|
||||
import json
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Real loopback sockets and subprocess pipes; no external host or credentials."""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import socket
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Linked-chat titles must use the same session metadata as the sidebar."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -61,7 +61,6 @@ def test_webui_session_list_surfaces_pending_recovery_state(tmp_path: Path) -> N
|
||||
"recovery_id": "recovery-123",
|
||||
"reason": "uncertain_tool_state",
|
||||
"attempts": 1,
|
||||
# Private checkpoint details must never leak into the sidebar index.
|
||||
"checkpoint": {"tool_args": "secret"},
|
||||
}
|
||||
manager.save(session)
|
||||
|
||||
@@ -2743,16 +2743,10 @@ def test_create_model_configuration_accepts_configured_oauth_provider(
|
||||
assert saved.model_presets["codex"].provider == "openai_codex"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Azure OpenAI: settings contract for static-key vs AAD (DefaultAzureCredential)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_settings_payload_azure_openai_with_api_key_is_configured(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Static-key mode: api_key + api_base both set -> configured."""
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.azure_openai.api_key = "k"
|
||||
@@ -2773,7 +2767,6 @@ def test_settings_payload_azure_openai_aad_mode_is_configured(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""AAD mode: only api_base set (no api_key) -> still configured."""
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.azure_openai.api_base = "https://r.openai.azure.com"
|
||||
@@ -2793,7 +2786,6 @@ def test_settings_payload_azure_openai_missing_base_not_configured(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""api_key alone (no api_base) is NOT a working config -> not configured."""
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.azure_openai.api_key = "k"
|
||||
@@ -2810,7 +2802,6 @@ def test_create_model_configuration_accepts_azure_openai_aad_mode(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Provider-validation accepts azure_openai with only api_base (AAD mode)."""
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.azure_openai.api_base = "https://r.openai.azure.com"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Model editing commits disk settings before admitting a refreshed runtime."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -94,7 +92,6 @@ async def test_model_save_commits_before_refreshing_next_session_admission(
|
||||
prior = await admit("prior")
|
||||
cached_preset = await admit("prior-preset", explicit_preset=True)
|
||||
draft = {"name": "chat", "context_window_tokens": 500_000}
|
||||
# A draft is just client-owned data, not disk or runtime state.
|
||||
assert disk_window() == 100_000
|
||||
assert prior.context_window_tokens == cached_preset.context_window_tokens == 100_000
|
||||
assert (await admit("draft-only")).context_window_tokens == 100_000
|
||||
@@ -114,8 +111,6 @@ async def test_model_save_commits_before_refreshing_next_session_admission(
|
||||
|
||||
allow_save.set()
|
||||
assert await asyncio.to_thread(disk_saved.wait, 5)
|
||||
# Disk can be committed while the route still owns a pending mutation;
|
||||
# admission uses the old snapshot until its synchronous refresh runs.
|
||||
assert not pending_save.done()
|
||||
assert disk_window() == 500_000
|
||||
assert (await admit("disk-committed-response-pending")).context_window_tokens == 100_000
|
||||
@@ -130,7 +125,6 @@ async def test_model_save_commits_before_refreshing_next_session_admission(
|
||||
assert next_preset.context_window_tokens == 500_000
|
||||
assert next_preset is not cached_preset
|
||||
assert agent.runtime_resolver.model_presets["chat"].context_window_tokens == 500_000
|
||||
# Refresh replaces admission values; already-admitted turns do not change.
|
||||
assert prior.context_window_tokens == during_save.context_window_tokens == 100_000
|
||||
assert cached_preset.context_window_tokens == 100_000
|
||||
finally:
|
||||
|
||||
@@ -110,7 +110,6 @@ def test_auto_routing_retains_same_connection_settings_but_new_connection_accept
|
||||
"name": ["primary"], "provider": ["auto"], "model": ["tenant_a/new"],
|
||||
}, oauth_status=_oauth_status)
|
||||
assert config.model_presets["primary"].extra_headers == {"X-Token": "private"}
|
||||
# A stale form must not restore the old connection's redacted credential.
|
||||
with pytest.raises(WebUISettingsError):
|
||||
update_model_configuration(config.model_copy(deep=True), {
|
||||
"name": ["primary"], "provider": ["tenant_b"],
|
||||
|
||||
@@ -176,7 +176,6 @@ async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeyp
|
||||
def login(*, storage, **_kwargs):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
# The actual SDK can finish its token exchange after start() timed out.
|
||||
storage.save(SimpleNamespace(access="late-fixture-token"))
|
||||
|
||||
monkeypatch.setattr(oauth, "login_oauth_interactive", login)
|
||||
@@ -814,8 +813,6 @@ async def test_version_check_and_mcp_requests_share_the_gateway_loop(monkeypatch
|
||||
|
||||
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",)
|
||||
|
||||
@@ -852,7 +849,7 @@ async def test_version_check_and_mcp_requests_share_the_gateway_loop(monkeypatch
|
||||
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.
|
||||
await asyncio.sleep(0)
|
||||
try:
|
||||
response = await asyncio.wait_for(_router().dispatch(None, request, request.path), timeout=5)
|
||||
finally:
|
||||
|
||||
@@ -321,8 +321,6 @@ def test_oauth_registry_keeps_flow_that_starts_while_cancellation_is_pending():
|
||||
removal.start()
|
||||
try:
|
||||
assert cancelling.wait(1)
|
||||
# Another request can register between register/start in the first login,
|
||||
# while its cancellation is waiting for the provider's commit lock.
|
||||
registry.register("xai_grok", "another", _Flow())
|
||||
flow.thread.start()
|
||||
allow_cancel.set()
|
||||
|
||||
@@ -115,7 +115,6 @@ def test_compaction_notice_webui_contract_and_config_round_trip(existing_key, tm
|
||||
})
|
||||
key = f"channels.{name}.showCompactionNotices"
|
||||
manager = ChannelManager.__new__(ChannelManager)
|
||||
# The generic settings route must preserve false, true and a return to inheritance.
|
||||
for submitted, expected in [("false", False), ("true", True), ("", None), (None, None)]:
|
||||
save_channel_config_values(
|
||||
config, name, {key: submitted}, load_channel_plugin=load_channel_plugin,
|
||||
@@ -129,7 +128,6 @@ def test_compaction_notice_webui_contract_and_config_round_trip(existing_key, tm
|
||||
assert instance.config.get("showCompactionNotices") is expected
|
||||
assert "show_compaction_notices" not in instance.config
|
||||
if expected is None:
|
||||
# Inheritance is persisted as absence, also readable by older QQ versions.
|
||||
assert "showCompactionNotices" not in instance.config
|
||||
assert manager._resolve_bool_override(
|
||||
instance.config, "show_compaction_notices", True,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Name discovery is passive; OpenSSH, not our index, interprets connection options."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
@@ -103,7 +101,7 @@ def test_include_read_budget_is_bounded_and_reported(ssh_home):
|
||||
(ssh_home / f"large-{index}").write_text(f"Host host-{index}\n#" + "x" * 250000)
|
||||
result = discover_hosts(str(config))
|
||||
assert result["incomplete"]
|
||||
assert len(result["files"]) == 5 # Root plus four complete included files.
|
||||
assert len(result["files"]) == 5
|
||||
assert result["hosts"][-1]["host"] == "final"
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""A restarted host replays task observations without recovering execution."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
@@ -247,7 +245,6 @@ async def test_child_activity_replays_real_tool_errors_and_file_diffs(tmp_path):
|
||||
await manager.spawn("Edit and inspect files", session_key="websocket:parent", runtime=runtime)
|
||||
task_id, = manager.statuses_for_session("websocket:parent")
|
||||
task = manager._running_tasks[task_id]
|
||||
# Each tool's persisted activity completes before the next model request.
|
||||
for _ in range(4):
|
||||
request = asyncio.create_task(model_requests.get())
|
||||
try:
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""The WebUI reads and cancels tasks through the session-owned lifecycle."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for WebUI transcription envelopes carried over the gateway socket."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Authenticated, refresh-safe review and job reads; no installer or server process runs."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
@@ -56,7 +54,6 @@ async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews(
|
||||
|
||||
fixture = preparation_gateway
|
||||
gateway, plan = await preparation_plan(fixture)
|
||||
# Plain HTTP cannot mutate; remote callers do not acquire install authority.
|
||||
response = await fetch(gateway, "/api/settings/nanobot-update/channel")
|
||||
assert response.status_code == 405
|
||||
response = await gateway.http.dispatch_webui_mutation(connection(), CHANNEL, {"channel": "preview", "revision": 0})
|
||||
@@ -71,7 +68,6 @@ async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews(
|
||||
prepared = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert prepared.status_code == 409
|
||||
assert not (fixture.directory / "jobs" / plan.id / "status.json").exists()
|
||||
# Stale tabs cannot overwrite the newer selection; native uses its distributor.
|
||||
assert (await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL,
|
||||
{"channel": "stable", "revision": 0})).status_code == 409
|
||||
assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), CHANNEL,
|
||||
@@ -108,7 +104,6 @@ async def test_review_uses_saved_channel_and_rejects_a_change_during_discovery(p
|
||||
observed.append(channel)
|
||||
if race:
|
||||
service.change_channel(UpdateChannelRequest(channel="stable", revision=1))
|
||||
# Preview subscriptions can receive a final release too.
|
||||
return stable.target
|
||||
|
||||
monkeypatch.setattr(update_plan, "ReleaseFeed", lambda _: Feed())
|
||||
@@ -440,7 +435,6 @@ async def test_preparation_is_durable_idempotent_and_independent_of_browser(prep
|
||||
directory = fixture.directory / "jobs" / plan.id
|
||||
assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
# A recreated router has no reference to the original browser's task.
|
||||
fresh = fixture.gateway()
|
||||
duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
|
||||
assert duplicate.status_code == 200
|
||||
@@ -804,8 +798,6 @@ async def test_job_reads_survive_refresh_expiry_and_unavailable_installation(rev
|
||||
assert not (directory / "request.json").exists(), "An early journal must not require committed staging"
|
||||
assert "webui.update-jobs.read.v1" in webui_contract()["capabilities"]
|
||||
|
||||
# A journal is recoverable without revalidating the expired plan or reading
|
||||
# package metadata; it is not permission to retry or proof a worker is live.
|
||||
monkeypatch.setattr(update_plan.time, "time", lambda: plan.expires_at + 1)
|
||||
JobStatus(plan_id, Phase.FAILED, 1, True, "https://user:secret@private.example", plan.expires_at).save(directory)
|
||||
pending = pending_update_path()
|
||||
@@ -819,16 +811,12 @@ async def test_job_reads_survive_refresh_expiry_and_unavailable_installation(rev
|
||||
assert job["recorded_phase"] == "failed" and job["mutation_started"] is True
|
||||
assert job["attempt"] == 1 and job["updated_at"] == plan.expires_at
|
||||
assert b"secret" not in response.body
|
||||
# Only the explicit recovery command exposes the launcher's exact location;
|
||||
# job diagnostics and profile paths must remain out of the status payload.
|
||||
assert job.pop("recovery_command") == recovery
|
||||
assert "private account" not in json.dumps(job)
|
||||
assert {"message", "running", "can_retry", "python", "url", "profiles"}.isdisjoint(job)
|
||||
assert len(fixture.requests) == 1
|
||||
assert not (directory / "approval.json").exists()
|
||||
|
||||
# A completed program restoration is not a successful installation. Keep
|
||||
# the legacy wire phase readable while exposing the precise new result.
|
||||
JobStatus(plan_id, Phase.RESTORED, 2, True, "Private recovery detail", plan.expires_at).save(directory)
|
||||
response = await fetch(fixture.gateway(), JOB + "?id=" + plan_id)
|
||||
job = json.loads(response.body)["job"]
|
||||
@@ -889,7 +877,6 @@ async def test_cancelled_request_keeps_probe_lease_until_native_work_exits(revie
|
||||
assert fixture.requests == []
|
||||
finally:
|
||||
release.set()
|
||||
# Wait for the probe's actual lease release before restoring Path.home.
|
||||
async with asyncio.timeout(5):
|
||||
while True:
|
||||
try:
|
||||
|
||||
@@ -113,8 +113,6 @@ async def test_leaving_preview_can_find_a_newer_stable_when_catalogue_is_unavail
|
||||
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 (await version_check.check_for_update())["updateAvailable"] is None
|
||||
releases.partial = False
|
||||
|
||||
Reference in new issue
Block a user