fix(webui): recover model failures and align chat controls
This commit is contained in:
1 parent
688976bcb9
commit
28f6c26946
42 files changed
+646
-82
No files matched your search
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
@@ -11,7 +12,7 @@ from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
RECOVERY_METADATA_KEY,
|
||||
@@ -23,6 +24,75 @@ from nanobot.webui.recovery import RecoveryCoordinator
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_committed_model_failure_continues_with_tool_results_without_resending(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
|
||||
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: tmp_path / "webui")
|
||||
bus = MessageBus()
|
||||
sessions = SessionManager(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.metadata["title"] = "Saved recovery"
|
||||
sessions.save(session)
|
||||
recovery = RecoveryCoordinator(sessions, bus)
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.can_resume_conversation_state.return_value = False
|
||||
requests: list[dict] = []
|
||||
responses = iter([
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
"read-once", "read_file", {"path": str(tmp_path / "note.txt")},
|
||||
)]),
|
||||
LLMResponse(content="private failure", finish_reason="error", error_kind="connection"),
|
||||
LLMResponse(content="Finished from the saved result."),
|
||||
])
|
||||
|
||||
async def respond(**kwargs):
|
||||
requests.append(deepcopy({
|
||||
"messages": LLMProvider._sanitize_empty_content(kwargs["messages"]),
|
||||
"tools": kwargs["tools"],
|
||||
}))
|
||||
return next(responses)
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
|
||||
(tmp_path / "note.txt").write_text("saved evidence", encoding="utf-8")
|
||||
loop = AgentLoop(
|
||||
bus=bus, provider=provider, workspace=tmp_path, model="test-model",
|
||||
session_manager=sessions, recovery_admission=recovery,
|
||||
)
|
||||
loop.turn_delivery_factory = TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions))
|
||||
coordinator = WebuiTurnCoordinator(bus, sessions, loop.schedule_background, recovery=recovery)
|
||||
read_tool = loop.tools.get("read_file")
|
||||
assert read_tool is not None
|
||||
execute = AsyncMock(wraps=read_tool.execute)
|
||||
monkeypatch.setattr(read_tool, "execute", execute)
|
||||
request = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="Read the note and summarize it",
|
||||
metadata={"webui": True, "webui_turn_id": "request-1"},
|
||||
)
|
||||
try:
|
||||
with coordinator.connected():
|
||||
await loop._dispatch_one(request, asyncio.Queue())
|
||||
state = (await sessions.state.get(request.session_key)).metadata[RECOVERY_METADATA_KEY]
|
||||
assert state["status"] == "awaiting_user"
|
||||
assert bus.inbound.empty()
|
||||
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})
|
||||
await loop._dispatch_one(bus.inbound.get_nowait(), asyncio.Queue())
|
||||
final = await sessions.state.get(request.session_key)
|
||||
assert final.metadata[RECOVERY_METADATA_KEY]["status"] == "recovered"
|
||||
assert execute.await_count == 1
|
||||
assert sum(message.get("role") == "user" for message in final.messages) == 1
|
||||
assert any(message.get("role") == "tool" and "saved evidence" in message["content"] for message in requests[-1]["messages"])
|
||||
assert requests[0]["messages"][0] == requests[-1]["messages"][0]
|
||||
assert requests[0]["tools"] == requests[-1]["tools"]
|
||||
assert requests[-1]["messages"][:len(requests[1]["messages"])] == requests[1]["messages"]
|
||||
assert len(requests) == 3
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovery_continuation_runs_without_a_sustained_goal(
|
||||
tmp_path: Path,
|
||||
|
||||
@@ -1281,6 +1281,34 @@ class TestRetryBeforeFailover:
|
||||
assert "cleared" in [status.state for status in retry_statuses]
|
||||
assert retry_statuses[-1].state == "exhausted"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_auth_error_preserves_primary_diagnosis_and_exhaustion(self) -> None:
|
||||
primary = _FakeProvider("primary", _make_response(
|
||||
"private network detail", finish_reason="error", error_kind="connection",
|
||||
))
|
||||
fallback = _FakeProvider("fallback", _make_response(
|
||||
"private auth detail", finish_reason="error", error_status_code=401,
|
||||
))
|
||||
provider = FallbackProvider(primary, [_fallback("backup")], MagicMock(return_value=fallback))
|
||||
statuses: list[RetryStatusEvent] = []
|
||||
|
||||
async def record(status: RetryStatusEvent) -> None:
|
||||
statuses.append(status)
|
||||
|
||||
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
|
||||
result = await provider.chat_with_retry(
|
||||
[{"role": "user", "content": "hello"}], on_retry_status=record,
|
||||
)
|
||||
|
||||
assert len(primary.chat_calls) == 4
|
||||
assert len(fallback.chat_calls) == 1
|
||||
assert LLMProvider.public_error_kind(result) == "connection"
|
||||
assert result.preserve_provider_state_on_error is True
|
||||
assert not LLMProvider.is_transient_response(result) # Retry policy is still terminal.
|
||||
assert statuses[-1] == RetryStatusEvent(
|
||||
state="exhausted", attempt=4, max_attempts=4, error_kind="connection",
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("factory_fails", [False, True])
|
||||
async def test_persistent_mode_repeats_the_whole_chain(
|
||||
|
||||
@@ -44,6 +44,20 @@ class ScriptedProvider(LLMProvider):
|
||||
return "test-model"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("response", "expected"), [
|
||||
(LLMResponse(content=None, finish_reason="error", error_kind="oauth_auth_required"), "authentication"),
|
||||
(LLMResponse(content=None, finish_reason="error", error_status_code=401), "authentication"),
|
||||
(LLMResponse(content=None, finish_reason="error", error_status_code=403), "unknown"),
|
||||
(LLMResponse(
|
||||
content=None, finish_reason="error", error_status_code=403, error_code="content_filter",
|
||||
), "unknown"),
|
||||
])
|
||||
def test_public_authentication_diagnosis_requires_credential_evidence(
|
||||
response: LLMResponse, expected: str,
|
||||
) -> None:
|
||||
assert LLMProvider.public_error_kind(response) == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_with_retry_retries_transient_error_then_succeeds(monkeypatch) -> None:
|
||||
provider = ScriptedProvider([
|
||||
@@ -134,7 +148,7 @@ async def test_chat_with_retry_clears_waiting_status_on_terminal_non_transient_e
|
||||
assert response.content == "401 unauthorized"
|
||||
assert [status.state for status in statuses] == ["waiting", "cleared"]
|
||||
assert statuses[-1].attempt == 2
|
||||
assert statuses[-1].error_kind == "unknown"
|
||||
assert statuses[-1].error_kind == "authentication"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -403,6 +417,36 @@ async def test_chat_with_retry_explicit_override_beats_defaults() -> None:
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Image fallback tests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("error", [
|
||||
LLMResponse(content="unauthorized", finish_reason="error", error_status_code=401),
|
||||
LLMResponse(content="login expired", finish_reason="error", error_kind="authentication"),
|
||||
LLMResponse(
|
||||
content="Sign in again.", finish_reason="error",
|
||||
error_kind="oauth_auth_required", error_should_retry=False,
|
||||
),
|
||||
LLMResponse(content="billing", finish_reason="error", error_status_code=402),
|
||||
])
|
||||
async def test_account_failure_does_not_retry_without_images(error: LLMResponse) -> None:
|
||||
provider = ScriptedProvider([error])
|
||||
messages = copy.deepcopy(_IMAGE_MSG)
|
||||
original = copy.deepcopy(messages)
|
||||
state = ProviderConversationState(
|
||||
provider="scripted", model="test-model", kind="test", version=1, payload={},
|
||||
)
|
||||
context = ProviderCallContext(conversation_state=state)
|
||||
|
||||
response = await provider.chat_with_retry(messages=messages, provider_context=context)
|
||||
|
||||
assert response is error
|
||||
assert provider.calls == 1
|
||||
assert messages == original
|
||||
assert context.conversation_state is state
|
||||
assert LLMProvider.public_error_kind(response) in {"authentication", "billing"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_IMAGE_MSG = [
|
||||
|
||||
@@ -8,6 +8,7 @@ import pytest
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import RecoveryStateEvent, SessionUpdatedEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import ProviderConversationState
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUPS_KEY,
|
||||
@@ -735,6 +736,58 @@ async def test_dismiss_does_not_queue_work(tmp_path: Path) -> None:
|
||||
assert bus.inbound.empty()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_model_failure_waits_across_restart_and_rejects_duplicate_continue(tmp_path: Path) -> None:
|
||||
coordinator, bus, sessions = _coordinator(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.messages = [{"role": "user", "content": "finish this"}]
|
||||
_persist(sessions, session)
|
||||
|
||||
await coordinator.turn_completed("websocket:chat", failure_kind="model", failure_error_kind="connection")
|
||||
assert bus.inbound.empty()
|
||||
coordinator, bus, sessions = _coordinator(tmp_path)
|
||||
await coordinator.scan()
|
||||
assert bus.inbound.empty()
|
||||
state = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]
|
||||
assert state["failure_error_kind"] == "connection"
|
||||
assert state["status"] == "awaiting_user"
|
||||
payload = {"chat_id": "chat", "recovery_id": state["recovery_id"]}
|
||||
await coordinator.handle_action("continue", payload)
|
||||
with pytest.raises(RecoveryActionError):
|
||||
await coordinator.handle_action("continue", payload)
|
||||
continuation = bus.inbound.get_nowait()
|
||||
assert continuation.metadata["_skip_user_persist"] is True
|
||||
assert bus.inbound.empty()
|
||||
await coordinator.turn_completed("websocket:chat", failure_kind="model", failure_error_kind="authentication")
|
||||
failed_again = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]
|
||||
assert failed_again["status"] == "awaiting_user"
|
||||
assert failed_again["failure_error_kind"] == "authentication"
|
||||
with pytest.raises(RecoveryActionError, match="stale"):
|
||||
await coordinator.handle_action("continue", payload)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_new_input_after_model_failure_does_not_change_saved_context(tmp_path: Path) -> None:
|
||||
coordinator, _, sessions = _coordinator(tmp_path)
|
||||
session = sessions.get_or_create("websocket:chat")
|
||||
session.messages = [{"role": "user", "content": "finish this"}]
|
||||
session.provider_state = ProviderConversationState(
|
||||
kind="openai_responses", provider="openai_codex", model="test-model", version=1,
|
||||
payload={"response_id": "saved-response"},
|
||||
)
|
||||
_persist(sessions, session)
|
||||
await coordinator.turn_completed("websocket:chat", failure_kind="model")
|
||||
before = sessions.get_or_create("websocket:chat")
|
||||
assert before.provider_state is not None
|
||||
await coordinator.admit(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="new request",
|
||||
))
|
||||
after = sessions.get_or_create("websocket:chat")
|
||||
assert after.messages == before.messages
|
||||
assert after.provider_state == before.provider_state
|
||||
assert after.metadata[RECOVERY_METADATA_KEY]["reason"] == "superseded"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scan_failure_is_visible_instead_of_aborting_other_sessions(
|
||||
tmp_path: Path,
|
||||
|
||||
Reference in new issue
Block a user