fix(webui): recover model failures and align chat controls

This commit is contained in:
Xubin Ren committed 2026-10-21 02:34:09 +08:00
1 parent 688976bcb9
commit 28f6c26946
42 files changed
+646 -82

No files matched your search

+1
View File
@@ -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)
+17
View File
@@ -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
+20 -5
View File
@@ -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.
+5
View File
@@ -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
+5 -1
View File
@@ -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:
+3
View File
@@ -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
+27 -7
View File
@@ -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")),
),
)
)