diff --git a/docs/webui.md b/docs/webui.md index 5cd6cc15c..4a98862ab 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -153,6 +153,10 @@ Open the context indicator beside the composer model badge to see how much of th When nanobot compacts context, the timeline shows its progress and outcome. The model continues with a summary and any messages after it; messages covered by the summary remain in your chat history but are no longer sent to the model verbatim. Use `/compact` to compact the current topic's context manually. See [Memory](./memory.md) for compaction and Dream consolidation. +### Model failures + +After a model request fails and automatic retries stop, the WebUI shows the failure category. Use **Continue** to resume from the saved conversation, or open model settings to change the model or correct its authorization. Review completed work before continuing: saved tool results are retained, but the model can choose to call tools again. Continuing does not resend the original message. Sending a new message or dismissing the notice clears the pending decision. Saved recovery decisions remain available after a refresh or gateway restart; temporary chats still follow their normal lifetime. + ### Delegated work When nanobot delegates work to subagents, a work group appears under the request that started it. Progress continues to update after the main reply finishes. Completed tasks stay available for inspection, and refreshing or reopening the WebUI restores saved progress and results without restarting the work. diff --git a/nanobot/events.py b/nanobot/events.py index 7d5397308..3200a6923 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -65,6 +65,7 @@ class RecoveryStateEvent(AgentEvent): reason: str | None = None attempts: int = 0 can_continue: bool | None = None + failure_error_kind: str | None = None @dataclass(frozen=True) diff --git a/nanobot/providers/base.py b/nanobot/providers/base.py index 9c8328da4..da8bbbc32 100644 --- a/nanobot/providers/base.py +++ b/nanobot/providers/base.py @@ -324,6 +324,9 @@ class LLMResponse: error_code: str | None = None # Provider/code semantic, e.g. rate_limit_exceeded. error_retry_after_s: float | None = None error_should_retry: bool | None = None + # A failed fallback must not replace the selected model's public diagnosis. + # Keep this separate from the last response's retry policy. + primary_error_kind: str | None = field(default=None, repr=False) is_fallback: bool = field(default=False, repr=False) @property @@ -1556,9 +1559,14 @@ class LLMProvider(ABC): @classmethod def public_error_kind(cls, response: LLMResponse) -> str: """Return a stable public category without exposing provider details.""" + if response.primary_error_kind is not None: + return response.primary_error_kind if cls.is_arrearage_response(response): return "billing" kind = (response.error_kind or "").strip().lower() + # A plain 403 can be a policy or permission rejection, not bad credentials. + if kind in {"authentication", "oauth_auth_required"} or response.error_status_code == 401: + return "authentication" if kind in {"connection", "timeout"}: return kind if response.error_status_code == 429: @@ -1641,6 +1649,15 @@ class LLMProvider(ABC): identical_error_count = 1 if error_key else 0 if not self.is_transient_response(response): + # Removing the user's images cannot repair account access. + # Do not rebuild native provider state for an unrelated failure. + if ( + (response.error_kind or "").lower() in {"authentication", "oauth_auth_required"} + or response.error_status_code in {401, 403} + or self.is_arrearage_response(response) + ): + await _finish_retry_status("cleared", response) + return response stripped = self._strip_image_content(kw["messages"]) provider_context = kw.get("provider_context") stripped_context: ProviderCallContext | None = None diff --git a/nanobot/providers/fallback_provider.py b/nanobot/providers/fallback_provider.py index ecb041f2f..400e3c9e2 100644 --- a/nanobot/providers/fallback_provider.py +++ b/nanobot/providers/fallback_provider.py @@ -361,6 +361,9 @@ class FallbackProvider(LLMProvider): async def _call_chain(**chain_kwargs: Any) -> LLMResponse: last_exhausted_message: str | None = None last_exhausted_status: RetryStatusEvent | None = None + primary_attempted = False + primary_exhausted_message: str | None = None + primary_exhausted_status: RetryStatusEvent | None = None async def _capture_exhaustion(message: str) -> None: nonlocal last_exhausted_message @@ -388,15 +391,22 @@ class FallbackProvider(LLMProvider): candidate_kwargs: dict[str, Any], ) -> LLMResponse: nonlocal last_exhausted_message, last_exhausted_status + nonlocal primary_attempted, primary_exhausted_message, primary_exhausted_status last_exhausted_message = None last_exhausted_status = None - return await call(provider, { + if provider is self._primary: + primary_attempted = True + response = await call(provider, { **candidate_kwargs, "retry_mode": "standard", "on_retry_wait": on_retry_wait, "on_retry_exhausted": _capture_exhaustion, "on_retry_status": _capture_status, }) + if provider is self._primary: + primary_exhausted_message = last_exhausted_message + primary_exhausted_status = last_exhausted_status + return response response = await self._try_with_fallback( _call_candidate, @@ -406,10 +416,12 @@ class FallbackProvider(LLMProvider): on_fallback_attempt=_clear_status_for_fallback, ) if retry_mode != "persistent" and response.finish_reason == "error": - if last_exhausted_message and on_retry_exhausted: - await on_retry_exhausted(last_exhausted_message) - if last_exhausted_status and on_retry_status: - await on_retry_status(last_exhausted_status) + terminal_message = primary_exhausted_message if primary_attempted else last_exhausted_message + terminal_status = primary_exhausted_status if primary_attempted else last_exhausted_status + if terminal_message and on_retry_exhausted: + await on_retry_exhausted(terminal_message) + if terminal_status and on_retry_status: + await on_retry_status(terminal_status) return response if retry_mode != "persistent": @@ -656,6 +668,9 @@ class FallbackProvider(LLMProvider): return replace( last_response, preserve_provider_state_on_error=preserve_primary_state, + primary_error_kind=( + self.public_error_kind(primary_response) if primary_response is not None else None + ), ) # Primary was skipped and no fallback returned a response. Keep the result # transient until the primary circuit is eligible for another probe. diff --git a/nanobot/session/recovery.py b/nanobot/session/recovery.py index 36076ba13..bea08000a 100644 --- a/nanobot/session/recovery.py +++ b/nanobot/session/recovery.py @@ -447,4 +447,9 @@ def recovery_state_from_metadata(metadata: Mapping[str, Any] | None) -> dict[str can_continue = state.get("can_continue") if isinstance(can_continue, bool): payload["can_continue"] = can_continue + failure_error_kind = state.get("failure_error_kind") + if isinstance(failure_error_kind, str) and failure_error_kind in { + "authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown", + }: + payload["failure_error_kind"] = failure_error_kind return payload diff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.py index c990aeabd..76328bf18 100644 --- a/nanobot/session/webui_turns.py +++ b/nanobot/session/webui_turns.py @@ -733,7 +733,11 @@ class WebuiTurnCoordinator: failure_attempts=event.failure_attempts, ) if self.recovery is not None: - await self.recovery.turn_completed(event.context.session_key) + await self.recovery.turn_completed( + event.context.session_key, + failure_kind=event.failure_kind, + failure_error_kind=event.failure_error_kind, + ) if event.outcome == "completed" and is_webui_session_key(event.context.session_key): turn_id = event.context.metadata.get(WEBUI_TURN_METADATA_KEY) if isinstance(turn_id, str) and turn_id: diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index c693decb3..577c8bd38 100644 --- a/nanobot/webui/outbound_wire.py +++ b/nanobot/webui/outbound_wire.py @@ -72,6 +72,7 @@ class RecoveryStateWirePayload(_ChatWirePayload): attempts: int reason: NotRequired[str] can_continue: NotRequired[bool] + failure_error_kind: NotRequired[str] class RetryStatusWirePayload(_ChatWirePayload): @@ -135,6 +136,8 @@ def encode_recovery_state( payload["reason"] = event.reason if event.can_continue is not None: payload["can_continue"] = event.can_continue + if event.failure_error_kind is not None: + payload["failure_error_kind"] = event.failure_error_kind return payload diff --git a/nanobot/webui/recovery.py b/nanobot/webui/recovery.py index 2d33d7042..962e6b667 100644 --- a/nanobot/webui/recovery.py +++ b/nanobot/webui/recovery.py @@ -166,9 +166,10 @@ class RecoveryCoordinator: state = recovery_state_from_metadata(session.metadata) if state and state["status"] in {"resuming", "awaiting_user", "failed"}: await self._cancel_active_recovery(message.session_key) - restore_runtime_checkpoint(session) - if not restore_pending_interruption(session, superseded=True): - append_recovery_interruption(session, superseded=True) + if state.get("reason") != "model_request_failed": + restore_runtime_checkpoint(session) + if not restore_pending_interruption(session, superseded=True): + append_recovery_interruption(session, superseded=True) recovered = self._set_state( session, status="recovered", @@ -180,15 +181,33 @@ class RecoveryCoordinator: await self._publish(message.chat_id, recovered) return True - async def turn_completed(self, session_key: str) -> None: - """Resolve a resuming state after the recovered turn commits.""" + async def turn_completed( + self, session_key: str, *, failure_kind: str | None = None, + failure_error_kind: str | None = None, + ) -> None: + """Offer explicit continuation of committed model failures or resolve recovery.""" session = await self.sessions.state.get(session_key) state = recovery_state_from_metadata(session.metadata) - if not state or state["status"] != "resuming": - return route = self._websocket_route(session) if route is None: return + if failure_kind == "model": + # The turn has already saved its transcript and tool results. Use + # that context, never resend the user's message or replay tools. + waiting = self._set_state( + session, + status="awaiting_user", + recovery_id=uuid4().hex, + attempts=cast(int, state.get("attempts", 0)) if state else 0, + reason="model_request_failed", + can_continue=any(message.get("role") == "user" for message in session.messages), + ) + waiting["failure_error_kind"] = failure_error_kind or "unknown" + await self.sessions.state.restore_interruption(session) + await self._publish(route[1], waiting) + return + if not state or state["status"] != "resuming": + return recovered = self._set_state( session, status="recovered", @@ -445,6 +464,7 @@ class RecoveryCoordinator: reason=cast(str | None, state.get("reason")), attempts=cast(int, state.get("attempts", 0)), can_continue=cast(bool | None, state.get("can_continue")), + failure_error_kind=cast(str | None, state.get("failure_error_kind")), ), ) ) diff --git a/packages/client-events/fixtures.json b/packages/client-events/fixtures.json index a89d8a704..ad31ca789 100644 --- a/packages/client-events/fixtures.json +++ b/packages/client-events/fixtures.json @@ -5,6 +5,7 @@ {"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"cancelled"}, {"event":"recovery_state","chat_id":"chat","status":"resuming","recovery_id":"r1","attempts":0}, {"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r1","attempts":1,"reason":"tool_state_unknown","can_continue":false}, + {"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r2","attempts":0,"reason":"model_request_failed","failure_error_kind":"connection"}, {"event":"recovery_state","chat_id":"chat","status":"recovered","recovery_id":"r1","attempts":1}, {"event":"recovery_state","chat_id":"chat","status":"failed","recovery_id":"r1","attempts":2}, {"event":"retry_status","chat_id":"chat","state":"waiting","attempt":1,"max_attempts":4,"error_kind":"connection","retry_after_s":2}, diff --git a/packages/client-events/notifications.ts b/packages/client-events/notifications.ts index 2800e6c05..d3e59972b 100644 --- a/packages/client-events/notifications.ts +++ b/packages/client-events/notifications.ts @@ -7,6 +7,7 @@ export interface RecoveryState { reason?: string attempts?: number can_continue?: boolean + failure_error_kind?: string } export interface ContextCompaction { @@ -53,6 +54,7 @@ export function isRecoveryState(value: unknown): value is RecoveryState { && optional(value.reason, "string") && optional(value.attempts, "number") && optional(value.can_continue, "boolean") + && optional(value.failure_error_kind, "string") } /** Undefined means another protocol family; null means a malformed notification. */ diff --git a/tests/agent/test_loop_recovery.py b/tests/agent/test_loop_recovery.py index 509e17240..689bc5c3e 100644 --- a/tests/agent/test_loop_recovery.py +++ b/tests/agent/test_loop_recovery.py @@ -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, diff --git a/tests/agent/test_runner_fallback.py b/tests/agent/test_runner_fallback.py index 701a955e3..6eff3a41e 100644 --- a/tests/agent/test_runner_fallback.py +++ b/tests/agent/test_runner_fallback.py @@ -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( diff --git a/tests/providers/test_provider_retry.py b/tests/providers/test_provider_retry.py index 6e34c6976..8799793ec 100644 --- a/tests/providers/test_provider_retry.py +++ b/tests/providers/test_provider_retry.py @@ -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 = [ diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.py index 249f713b6..b81481bd5 100644 --- a/tests/session/test_recovery.py +++ b/tests/session/test_recovery.py @@ -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, diff --git a/webui/browser/chat-failure-fixture.tsx b/webui/browser/chat-failure-fixture.tsx new file mode 100644 index 000000000..ae24f6623 --- /dev/null +++ b/webui/browser/chat-failure-fixture.tsx @@ -0,0 +1,47 @@ +import { useState } from "react"; + +import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice"; +import { RecoveryNotice } from "@/components/thread/RecoveryNotice"; +import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice"; +import { ThreadComposer } from "@/components/thread/ThreadComposer"; +import { ThreadMessages } from "@/components/thread/ThreadMessages"; +import { useReadingTypography } from "@/hooks/useReadingTypography"; +import { formatQuotedUserMessage } from "@/lib/user-message-quote"; +import type { UIMessage } from "@/lib/types"; + +const messages: UIMessage[] = [{ + id: "failed-question", + role: "user" as const, + content: formatQuotedUserMessage("Please explain this failure. 请解释这个错误。", "Earlier context / 之前的上下文"), + images: [{ url: "data:image/svg+xml," + encodeURIComponent(''), name: "Failure screenshot" }], + createdAt: 1_700_000_000_000, +}]; + +// Real components with controlled state. No model calls or saved user data. +export function ChatFailureFixture({ parameters }: { parameters: URLSearchParams }) { + useReadingTypography(); + const [visible, setVisible] = useState(true); + const [action, setAction] = useState(""); + const variant = parameters.get("variant") === "hero" ? "hero" : "thread"; + const dismiss = () => { setVisible(false); setAction("dismissed"); }; + const settings = () => setAction("settings"); + return
+
+ +
+
+ {visible && (parameters.get("notice") === "stream" + ? + : parameters.get("notice") === "fallback" + ? + : { setVisible(false); setAction("continued"); }} + onDismiss={async () => dismiss()} + onOpenSettings={settings} + />)} + {}} workspaceControlsHidden /> +
+ {action} +
; +} diff --git a/webui/browser/chat-failure.spec.ts b/webui/browser/chat-failure.spec.ts new file mode 100644 index 000000000..fe4110681 --- /dev/null +++ b/webui/browser/chat-failure.spec.ts @@ -0,0 +1,95 @@ +import { expect, test } from "@playwright/test"; + +for (const width of [1440, 390]) { + for (const variant of ["thread", "hero"]) { + for (const notice of ["recovery", "stream", "fallback"]) { + test(`${notice} aligns with ${variant} composer at ${width}px`, async ({ page }) => { + await page.setViewportSize({ width, height: 1000 }); + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.addInitScript(({ dark, locale }) => { + localStorage.setItem("nanobot.locale", locale); + localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({ schemaVersion: 1, readingTextSize: "large" })); + document.addEventListener("DOMContentLoaded", () => { + document.documentElement.classList.toggle("dark", dark); + }); + }, { dark: variant === "hero", locale: width === 390 ? "zh-CN" : "en" }); + await page.goto(`/browser/fixture.html?case=chat-failure¬ice=${notice}&variant=${variant}`); + const alert = page.locator(".thread-composer-notice"); + const composer = page.locator(".thread-composer-surface"); + await expect(alert).toBeVisible(); + await expect(composer).toBeVisible(); + const noticeBox = (await alert.boundingBox())!; + const composerBox = (await composer.boundingBox())!; + expect(Math.abs(noticeBox.x - composerBox.x)).toBeLessThan(1); + expect(Math.abs(noticeBox.width - composerBox.width)).toBeLessThan(1); + for (const button of await alert.getByRole("button").all()) { + await expect(button).toBeInViewport({ ratio: 1 }); + const box = (await button.boundingBox())!; + expect(box.x).toBeGreaterThanOrEqual(noticeBox.x); + expect(box.x + box.width).toBeLessThanOrEqual(noticeBox.x + noticeBox.width); + } + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width); + if (notice === "recovery") { + await expect(alert).toContainText(width === 390 ? "模型提供商验证失败" : "Model provider authorization failed"); + await alert.getByRole("button").first().click(); + await expect(page.getByLabel("Fixture action")).toHaveText("settings"); + await alert.getByRole("button").last().click(); + await expect(alert).toBeHidden(); + await expect(page.getByLabel("Fixture action")).toHaveText("continued"); + } else { + await alert.getByRole("button").last().click(); + await expect(alert).toBeHidden(); + await expect(page.getByLabel("Fixture action")).toHaveText("dismissed"); + } + }); + } + } +} + +for (const width of [1440, 390]) { + for (const size of ["small", "standard", "large"] as const) { + test(`image and quote retain the responsive message actions: ${size}, ${width}px`, async ({ page }, info) => { + await page.setViewportSize({ width, height: 1000 }); + await page.addInitScript(({ size, locale }) => { + localStorage.setItem("nanobot.locale", locale); + localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({ schemaVersion: 1, readingTextSize: size })); + }, { size, locale: width === 390 ? "zh-CN" : "en" }); + await page.goto("/browser/fixture.html?case=chat-failure"); + const image = page.getByAltText("Failure screenshot"); + await expect(image).toBeVisible(); + await expect(page.getByText("Earlier context / 之前的上下文")).toBeVisible(); + const bubble = page.locator("[data-user-text-bubble]"); + const text = bubble.locator("p"); + const trigger = page.locator("[data-message-block-menu-trigger]"); + const fontSize = width === 390 + ? { small: 15, standard: 16, large: 18 }[size] + : { small: 16, standard: 18, large: 20 }[size]; + await expect(text).toHaveCSS("font-size", `${fontSize}px`); + await bubble.hover(); + await expect(trigger).toBeVisible(); + const bubbleBox = (await bubble.boundingBox())!; + const triggerBox = (await trigger.boundingBox())!; + const imageBox = (await image.boundingBox())!; + expect(imageBox.y + imageBox.height).toBeLessThan(bubbleBox.y); + if (width === 390) { + // Narrow screens use a touch action row below the message, not a hover rail. + await expect(page.locator("[data-message-mobile-actions]")).toBeVisible(); + expect(triggerBox.y).toBeGreaterThanOrEqual(bubbleBox.y + bubbleBox.height); + expect(triggerBox.height).toBeGreaterThanOrEqual(44); + await expect(trigger).toBeInViewport({ ratio: 1 }); + } else { + const firstLineCenter = await text.evaluate(node => { + const style = getComputedStyle(node); + return node.getBoundingClientRect().y + parseFloat(style.paddingTop) + parseFloat(style.lineHeight) / 2; + }); + expect(Math.abs(triggerBox.y + triggerBox.height / 2 - firstLineCenter)).toBeLessThan(1); + } + await trigger.click(); + await expect(page.locator("[data-message-block-menu]")).toBeVisible(); + if (width === 390) { + await expect(page.locator("[data-message-mobile-sheet]")).toBeInViewport({ ratio: 1 }); + } + await page.screenshot({ path: info.outputPath("message-menu.png") }); + }); + } +} diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 45d4b0f5c..ee370d674 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -24,6 +24,7 @@ import "../src/globals.css"; import { DiagramFixture } from "./diagram-fixture"; import { TypographyFixture } from "./typography-fixture"; import { HistoryBoundaryFixture } from "./history-boundary-fixture"; +import { ChatFailureFixture } from "./chat-failure-fixture"; import { ThreadLoadingFixture } from "./thread-loading-fixture"; const history: UIMessage[] = [ @@ -146,7 +147,9 @@ function AppsFixture() { if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi(); await initializeI18n(); createRoot(document.getElementById("root")!).render( - {parameters.get("case") === "typography" + {parameters.get("case") === "chat-failure" + ? + : parameters.get("case") === "typography" ? : parameters.get("case") === "history-boundary" ? diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 899224625..8136fc26a 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -483,10 +483,9 @@ export function MessageBubble({ ); return (
- {contextMenu} + {!hasText ? contextMenu : null} {hasImages ? : null} {!hasImages && hasMedia ? ( @@ -498,18 +497,21 @@ export function MessageBubble({ /> ) : null} {hasText ? ( -

- {messageText} -

+
+ {contextMenu} +

+ {messageText} +

+
) : null} {showDeliveryStatus ? (
diff --git a/webui/src/components/thread/ModelFallbackNotice.tsx b/webui/src/components/thread/ModelFallbackNotice.tsx index c0691a701..d2c6a7b89 100644 --- a/webui/src/components/thread/ModelFallbackNotice.tsx +++ b/webui/src/components/thread/ModelFallbackNotice.tsx @@ -16,7 +16,7 @@ export function ModelFallbackNotice({ model, reauthProvider, reauthProviderLabel return (
Promise; onDismiss: () => Promise; + onOpenSettings?: () => void; } -export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeProps) { +export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }: RecoveryNoticeProps) { const { t } = useTranslation(); const [pending, setPending] = useState<"continue" | "dismiss" | null>(null); const [error, setError] = useState(null); @@ -33,14 +35,17 @@ export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeP if (!waiting || hiddenRecoveryId === state.recovery_id) return null; const contextUnavailable = state.can_continue === false; - const title = state.status === "failed" + const modelFailure = state.reason === "model_request_failed" + ? resolveModelRequestFailureCopy({ errorKind: state.failure_error_kind }, t) + : null; + const title = modelFailure?.title ?? (state.status === "failed" ? t("recovery.failed", { defaultValue: "Task recovery failed" }) - : t("recovery.interrupted", { defaultValue: "Task interrupted" }); - const detail = state.status === "failed" || contextUnavailable + : t("recovery.interrupted", { defaultValue: "Task interrupted" })); + const detail = contextUnavailable || state.status === "failed" ? t("recovery.failedHelp", { defaultValue: "The saved task could not be restored safely. Review it before continuing.", }) - : t("recovery.review", { defaultValue: "Review the task before continuing. Tools will not be replayed automatically." }); + : modelFailure?.body ?? t("recovery.review", { defaultValue: "Review the task before continuing. Tools will not be replayed automatically." }); const run = (action: "continue" | "dismiss") => { setPending(action); setError(null); @@ -60,13 +65,18 @@ export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeP role="alert" aria-live="assertive" data-recovery-status={state.status} - className="mx-auto mb-2 flex w-full max-w-[49.5rem] items-center gap-3 rounded-control border border-border/70 bg-muted/35 px-3 py-2 text-sm transition-[background-color,border-color,opacity,transform] duration-200 ease-out motion-reduce:transition-none animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none" + className="thread-composer-notice mb-2 flex flex-wrap items-center gap-3 rounded-control border border-border/70 bg-muted/35 px-3 py-2 text-sm transition-[background-color,border-color,opacity,transform] duration-200 ease-out motion-reduce:transition-none animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none" > -
+

{title}

+ {modelFailure && onOpenSettings ? ( + + ) : null}

-
+
+ ) : null}