fix(ui): surface model retry status (NAN-34) (#5504)

This commit is contained in:
chengyongru authored and GitHub committed 2026-09-07 15:12:39 +08:00
1 parent 0b1fa0c3e4
commit b581a496a6
52 files changed
+1697 -55

No files matched your search

+6
View File
@@ -155,6 +155,7 @@ class TurnContext:
final_content: str | None = None
all_messages: list[dict[str, Any]] = field(default_factory=list)
stop_reason: str = ""
failure_error_kind: str | None = None
streamed_content: bool = False
input_persisted_early: bool = False
@@ -2012,6 +2013,7 @@ class AgentLoop:
ctx.summary_checkpoint = result.summary_checkpoint
ctx.provider_compaction_applied = result.provider_compaction_applied
ctx.stop_reason = result.stop_reason
ctx.failure_error_kind = result.failure_error_kind
if (
ctx.kind is TurnKind.USER
and (ctx.delivery.route.channel, ctx.delivery.route.chat_id) in message_sends
@@ -2073,6 +2075,10 @@ class AgentLoop:
)
async def _prepare_outbound(self, ctx: TurnContext) -> None:
ctx.delivery.record_stop_reason(
ctx.stop_reason,
failure_error_kind=ctx.failure_error_kind,
)
if ctx.suppress_response:
ctx.outbound = None
return
+4
View File
@@ -130,6 +130,7 @@ class AgentRunResult:
round_usages: list[LLMUsage] = field(default_factory=list)
stop_reason: str = "completed"
error: str | None = None
failure_error_kind: str | None = None
tool_events: list[dict[str, str]] = field(default_factory=list)
had_injections: bool = False
# Terminal tail to emit when the preceding final-content prefix was already streamed.
@@ -396,6 +397,7 @@ class AgentRunner:
usage: LLMUsage | None = None
round_usages: list[LLMUsage] = []
error: str | None = None
failure_error_kind: str | None = None
stop_reason = "completed"
tool_events: list[dict[str, str]] = []
external_lookup_counts: dict[str, int] = {}
@@ -730,6 +732,7 @@ class AgentRunner:
had_injections = True
length_recovery_parts.clear()
continue
failure_error_kind = LLMProvider.public_error_kind(response)
break
if is_blank_text(clean):
final_content = EMPTY_FINAL_RESPONSE_MESSAGE
@@ -827,6 +830,7 @@ class AgentRunner:
round_usages=round_usages,
stop_reason=stop_reason,
error=error,
failure_error_kind=failure_error_kind,
tool_events=tool_events,
had_injections=had_injections,
pending_stream_content=pending_stream_content,
+39 -1
View File
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, cast
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import notification_is_deliverable
from nanobot.bus.outbound_events import (
RetryStatusEvent,
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
@@ -61,6 +62,14 @@ def _bind_events(
return EventSink(publish, accepts)
def _turn_outcome(stop_reason: object) -> tuple[str, str | None]:
if stop_reason == "error":
return "failed", "model"
if stop_reason == "tool_error":
return "failed", "tool"
return "completed", None
class TurnDeliveryFactory:
"""Route turn delivery and session-level notifications."""
@@ -182,6 +191,9 @@ class TurnDelivery:
_stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False)
_routed_events: EventSink = field(init=False)
_stop_reason: str | None = field(init=False, default=None)
_failure_error_kind: str | None = field(init=False, default=None)
_retry_status: RetryStatusEvent | None = field(init=False, default=None)
def __post_init__(self) -> None:
self._routed_events = _bind_events(self.bus, self.route)
@@ -244,6 +256,15 @@ class TurnDelivery:
def record_usage(self, round_usages: list[LLMUsage]) -> None:
self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages)
def record_stop_reason(
self,
stop_reason: str,
*,
failure_error_kind: str | None = None,
) -> None:
self._stop_reason = stop_reason
self._failure_error_kind = failure_error_kind
def background_response(
self,
content: str | None,
@@ -276,12 +297,16 @@ class TurnDelivery:
*,
publish_completion: bool,
) -> None:
stop_reason = self._stop_reason
if stop_reason is None and response is not None:
stop_reason = cast(str | None, response.metadata.get("_stop_reason"))
completed_channel = self.lifecycle_message.channel
completed_chat_id = self.lifecycle_message.chat_id
if response is not None:
await self.bus.publish_outbound(response)
completed_channel = response.channel
completed_chat_id = response.chat_id
if response.channel != "websocket" or stop_reason != "error":
await self.bus.publish_outbound(response)
elif self.lifecycle_message.channel == "cli":
await self.bus.publish_outbound(
OutboundMessage(
@@ -292,11 +317,20 @@ class TurnDelivery:
)
)
if publish_completion:
outcome, failure_kind = _turn_outcome(stop_reason)
await self.runtime_event_publisher.turn_completed(
channel=completed_channel,
chat_id=completed_chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=(self._failure_error_kind or (
self._retry_status.error_kind if failure_kind == "model" and self._retry_status else None
)),
failure_attempts=(
self._retry_status.attempt if failure_kind == "model" and self._retry_status else None
),
)
async def fail(self, *, publish_completion: bool) -> None:
@@ -314,6 +348,8 @@ class TurnDelivery:
chat_id=self.lifecycle_message.chat_id,
session_key=self.session_key,
metadata=self.lifecycle_message.metadata,
outcome="failed",
failure_kind="internal",
)
async def idle(self) -> None:
@@ -329,6 +365,8 @@ class TurnDelivery:
return f"{self._stream_base_id}:{self._stream_segment}"
async def _publish_event(self, event: AgentEvent) -> None:
if isinstance(event, RetryStatusEvent):
self._retry_status = event if event.state == "exhausted" else None
if isinstance(event, StreamDeltaEvent | StreamEndEvent):
if not self.streaming:
return
+5 -1
View File
@@ -5,6 +5,7 @@ from typing import Literal
from nanobot.bus.outbound_events import (
FileEditEvent,
ProgressEvent,
RetryStatusEvent,
StreamDeltaEvent,
StreamEndEvent,
)
@@ -20,6 +21,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {
ContextCompactionEvent: "channel",
RetryWaitEvent: "lifecycle",
RecoveryStateEvent: "interactive",
RetryStatusEvent: "interactive",
}
@@ -33,5 +35,7 @@ def notification_is_deliverable(
if audience == "lifecycle":
return publish_lifecycle
if audience == "interactive":
return channel == "websocket"
return channel == "websocket" and (
event_type is not RetryStatusEvent or publish_lifecycle
)
return True
+6
View File
@@ -15,6 +15,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.events import AgentEvent
from nanobot.events import ContextCompactionEvent as ContextCompactionEvent
from nanobot.events import RecoveryStateEvent as RecoveryStateEvent
from nanobot.events import RetryStatusEvent as RetryStatusEvent
from nanobot.events import RetryWaitEvent as RetryWaitEvent
from nanobot.providers.base import LLMUsage
@@ -62,6 +63,11 @@ class TurnEndEvent(AgentEvent):
usage: LLMUsage | None = None
round_usages: tuple[LLMUsage, ...] = ()
context_window_tokens: int | None = None
outcome: str = "completed"
failure_kind: str | None = None
failure_error_kind: str | None = None
failure_attempts: int | None = None
failure_message: str | None = None
@dataclass(frozen=True)
+12
View File
@@ -67,6 +67,10 @@ class TurnCompleted(AgentEvent):
usage: LLMUsage | None = None
# Logical model rounds in display order; recovery dispatches are aggregated.
round_usages: tuple[LLMUsage, ...] = ()
outcome: str = "completed"
failure_kind: str | None = None
failure_error_kind: str | None = None
failure_attempts: int | None = None
@dataclass(frozen=True)
@@ -259,6 +263,10 @@ class RuntimeEventPublisher:
chat_id: str,
session_key: str,
metadata: dict[str, Any] | None,
outcome: str = "completed",
failure_kind: str | None = None,
failure_error_kind: str | None = None,
failure_attempts: int | None = None,
) -> None:
await self.bus.publish(
TurnCompleted(
@@ -272,6 +280,10 @@ class RuntimeEventPublisher:
runtime=self._turn_runtime.pop(session_key, None),
usage=self._turn_usage.pop(session_key, None),
round_usages=self._turn_round_usages.pop(session_key, ()),
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=failure_error_kind,
failure_attempts=failure_attempts,
)
)
@@ -29,6 +29,8 @@ from nanobot.bus.outbound_events import (
GoalStatusEvent,
ProgressEvent,
RecoveryStateEvent,
RetryStatusEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent,
SessionUpdatedEvent,
TurnEndEvent,
@@ -2806,6 +2808,106 @@ async def test_send_turn_end_emits_turn_end_event() -> None:
]
@pytest.mark.asyncio
async def test_retry_status_is_transient_and_turn_scoped(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr("nanobot.webui.outbound_wire.time.time", lambda: 120.0)
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
gateway=_basic_handler(bus),
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
await channel.send(OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={WEBUI_TURN_METADATA_KEY: "turn-1"},
event=RetryStatusEvent(
state="waiting",
attempt=2,
max_attempts=4,
error_kind="connection",
next_retry_at=123.5,
),
))
assert _sent_ws_payloads(mock_ws) == [{
"event": "retry_status",
"chat_id": "chat-1",
"turn_id": "turn-1",
"state": "waiting",
"attempt": 2,
"max_attempts": 4,
"error_kind": "connection",
"retry_after_s": 3.5,
}]
@pytest.mark.asyncio
async def test_legacy_retry_wait_is_not_sent_or_persisted() -> None:
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
gateway=_basic_handler(bus),
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
channel._persist_turn_transcript_event = MagicMock(return_value=True)
await channel.send(OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="Model request failed, retry in 2s (attempt 1).",
event=RetryWaitEvent(
content="Model request failed, retry in 2s (attempt 1).",
),
))
assert _sent_ws_payloads(mock_ws) == []
channel._persist_turn_transcript_event.assert_not_called()
@pytest.mark.asyncio
async def test_failed_turn_end_exposes_safe_terminal_outcome() -> None:
bus = MagicMock()
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
gateway=_basic_handler(bus),
)
mock_ws = AsyncMock()
channel._attach(mock_ws, "chat-1")
await channel.send(OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
event=TurnEndEvent(
outcome="failed",
failure_kind="model",
failure_error_kind="connection",
failure_attempts=4,
failure_message="Model provider request failed.",
),
))
assert _sent_ws_payloads(mock_ws)[0] == {
"event": "turn_end",
"chat_id": "chat-1",
"outcome": "failed",
"failure_kind": "model",
"failure_error_kind": "connection",
"failure_attempts": 4,
"failure_message": "Model provider request failed.",
}
@pytest.mark.asyncio
async def test_context_compaction_started_is_live_only() -> None:
bus = MagicMock()
+11
View File
@@ -24,6 +24,17 @@ class RetryWaitEvent(AgentEvent):
content: str = ""
@dataclass(frozen=True)
class RetryStatusEvent(AgentEvent):
"""Sanitized retry lifecycle for one model request chain."""
state: Literal["waiting", "recovered", "cleared", "exhausted"]
attempt: int
max_attempts: int | None
error_kind: str
next_retry_at: float | None = None
@dataclass(frozen=True)
class RecoveryStateEvent(AgentEvent):
status: str
+94 -9
View File
@@ -19,7 +19,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
import json_repair
from loguru import logger
from nanobot.events import NO_EVENTS, EventSink, RetryWaitEvent
from nanobot.events import NO_EVENTS, EventSink, RetryStatusEvent, RetryWaitEvent
from nanobot.utils.helpers import sanitize_surrogates_deep
if TYPE_CHECKING:
@@ -33,6 +33,7 @@ RETRY_AFTER_BUFFER = 1
RetryEventCallback = Callable[[str], Awaitable[None]]
LLMCallObserver = Callable[["LLMCallRecord"], None]
ProviderCompactionScope = Literal["prior_context", "current_request"]
RetryStatusCallback = Callable[[RetryStatusEvent], Awaitable[None]]
def resolve_stream_idle_timeout_s(
@@ -1453,6 +1454,7 @@ class LLMProvider(ABC):
on_retry_wait: RetryEventCallback | None = None,
provider_context: ProviderCallContext | None = None,
on_retry_exhausted: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> LLMResponse:
"""Call chat_stream() with retry on transient provider failures."""
if max_tokens is self._SENTINEL or max_tokens is None:
@@ -1489,8 +1491,8 @@ class LLMProvider(ABC):
kw["provider_context"] = provider_context
if on_stream_recover and getattr(self, "supports_stream_recover_callback", False):
kw["on_stream_recover"] = _recover_stream
on_retry_wait, on_retry_exhausted = self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted,
on_retry_wait, on_retry_exhausted, on_retry_status = await self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted, on_retry_status,
)
return await self._run_chat_with_retry(
kw,
@@ -1499,6 +1501,7 @@ class LLMProvider(ABC):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=lambda: not has_streamed_content,
on_stream_recover=_recover_stream if on_stream_recover else None,
)
@@ -1516,6 +1519,7 @@ class LLMProvider(ABC):
on_retry_wait: RetryEventCallback | None = None,
provider_context: ProviderCallContext | None = None,
on_retry_exhausted: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> LLMResponse:
"""Call chat() with retry on transient provider failures.
@@ -1540,8 +1544,8 @@ class LLMProvider(ABC):
)
if provider_context is not None:
kw["provider_context"] = provider_context
on_retry_wait, on_retry_exhausted = self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted,
on_retry_wait, on_retry_exhausted, on_retry_status = await self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted, on_retry_status,
)
return await self._run_chat_with_retry(
kw,
@@ -1550,14 +1554,16 @@ class LLMProvider(ABC):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
)
@staticmethod
def _retry_notifications(
async def _retry_notifications(
context: ProviderCallContext | None,
on_wait: RetryEventCallback | None,
on_exhausted: RetryEventCallback | None,
) -> tuple[RetryEventCallback | None, RetryEventCallback | None]:
on_status: RetryStatusCallback | None,
) -> tuple[RetryEventCallback | None, RetryEventCallback | None, RetryStatusCallback | None]:
"""Adapt once at the retry-chain boundary, before candidate callbacks.
Explicit callbacks retain precedence. In particular a fallback candidate
@@ -1568,7 +1574,12 @@ class LLMProvider(ABC):
await context.events.emit(RetryWaitEvent(content))
on_wait = publish
return on_wait, on_exhausted or on_wait
if on_status is None and context is not None and context.events.accepts(RetryStatusEvent):
on_status = context.events.emit
# A turn may continue after an exhausted request; the new chain owns
# its own retry state, including when its first attempt is terminal.
await on_status(RetryStatusEvent("cleared", 1, None, "unknown"))
return on_wait, on_exhausted or on_wait, on_status
async def _run_chat_with_retry(
self,
@@ -1579,6 +1590,7 @@ class LLMProvider(ABC):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
@@ -1591,6 +1603,7 @@ class LLMProvider(ABC):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=should_retry_guard,
on_stream_recover=on_stream_recover,
)
@@ -1676,8 +1689,12 @@ class LLMProvider(ABC):
*,
attempt: int,
persistent: bool,
on_retry_wait: Callable[[str], Awaitable[None]] | None = None,
error_kind: str,
max_attempts: int | None,
on_retry_wait: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> None:
next_retry_at = time.time() + max(0.0, delay)
remaining = max(0.0, delay)
while remaining > 0:
if on_retry_wait:
@@ -1686,10 +1703,34 @@ class LLMProvider(ABC):
f"Model request failed, {kind} in {max(1, int(round(remaining)))}s "
f"(attempt {attempt})."
)
if on_retry_status:
await on_retry_status(
RetryStatusEvent(
state="waiting",
attempt=attempt,
max_attempts=max_attempts,
error_kind=error_kind,
next_retry_at=next_retry_at,
)
)
chunk = min(remaining, self._RETRY_HEARTBEAT_CHUNK)
await asyncio.sleep(chunk)
remaining -= chunk
@classmethod
def public_error_kind(cls, response: LLMResponse) -> str:
"""Return a stable public category without exposing provider details."""
if cls.is_arrearage_response(response):
return "billing"
kind = (response.error_kind or "").strip().lower()
if kind in {"connection", "timeout"}:
return kind
if response.error_status_code == 429:
return "rate_limit"
if response.error_status_code is not None and response.error_status_code >= 500:
return "server"
return "unknown"
async def _run_with_retry(
self,
call: Callable[..., Awaitable[LLMResponse]],
@@ -1699,6 +1740,7 @@ class LLMProvider(ABC):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
@@ -1708,10 +1750,26 @@ class LLMProvider(ABC):
last_response: LLMResponse | None = None
last_error_key: str | None = None
identical_error_count = 0
async def _finish_retry_status(
state: Literal["recovered", "cleared"],
response: LLMResponse,
) -> None:
if attempt > 1 and on_retry_status:
await on_retry_status(
RetryStatusEvent(
state=state,
attempt=attempt,
max_attempts=None if persistent else len(delays) + 1,
error_kind=self.public_error_kind(response),
)
)
while True:
attempt += 1
response = await call(**kw)
if response.finish_reason != "error":
await _finish_retry_status("recovered", response)
return response
last_response = response
if should_retry_guard is not None and not should_retry_guard():
@@ -1737,6 +1795,7 @@ class LLMProvider(ABC):
logger.warning(
"LLM stream failed after content was emitted; skipping retry"
)
await _finish_retry_status("cleared", response)
return response
error_key = ((response.content or "").strip().lower() or None)
if error_key and error_key == last_error_key:
@@ -1779,7 +1838,12 @@ class LLMProvider(ABC):
# subsequent iterations do not repeat the error-retry cycle.
if result.finish_reason != "error":
self._strip_image_content_inplace(original_messages)
await _finish_retry_status(
"recovered" if result.finish_reason != "error" else "cleared",
result,
)
return result
await _finish_retry_status("cleared", response)
return response
if persistent and identical_error_count >= self._PERSISTENT_IDENTICAL_ERROR_LIMIT:
@@ -1792,6 +1856,15 @@ class LLMProvider(ABC):
await on_retry_exhausted(
f"Persistent retry stopped after {identical_error_count} identical errors."
)
if on_retry_status:
await on_retry_status(
RetryStatusEvent(
state="exhausted",
attempt=attempt,
max_attempts=None,
error_kind=self.public_error_kind(response),
)
)
return response
if not persistent and attempt > len(delays):
@@ -1804,6 +1877,15 @@ class LLMProvider(ABC):
await on_retry_exhausted(
f"Model request failed after {attempt} attempts, giving up."
)
if on_retry_status:
await on_retry_status(
RetryStatusEvent(
state="exhausted",
attempt=attempt,
max_attempts=len(delays) + 1,
error_kind=self.public_error_kind(response),
)
)
break
retry_after = self._extract_retry_after_from_response(response)
@@ -1823,7 +1905,10 @@ class LLMProvider(ABC):
delay,
attempt=attempt,
persistent=persistent,
error_kind=self.public_error_kind(response),
max_attempts=None if persistent else len(delays) + 1,
on_retry_wait=on_retry_wait,
on_retry_status=on_retry_status,
)
return last_response if last_response is not None else await call(**kw) # pyright: ignore[reportUnnecessaryComparison]
+37 -8
View File
@@ -12,6 +12,7 @@ from typing import Any
from loguru import logger
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import (
GenerationSettings,
LLMCallObserver,
@@ -20,6 +21,7 @@ from nanobot.providers.base import (
ProviderCallContext,
ProviderConversationState,
RetryEventCallback,
RetryStatusCallback,
)
# Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker.
@@ -213,6 +215,7 @@ class FallbackProvider(LLMProvider):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
@@ -229,6 +232,7 @@ class FallbackProvider(LLMProvider):
"retry_mode": retry_mode,
"on_retry_wait": on_retry_wait,
"on_retry_exhausted": on_retry_exhausted,
"on_retry_status": on_retry_status,
})
if stream:
return await self._primary.chat_stream_with_retry(**call_kwargs)
@@ -273,6 +277,7 @@ class FallbackProvider(LLMProvider):
retry_mode=retry_mode,
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
has_streamed=has_streamed,
on_stream_recover=recover_stream,
persistent_retry_guard=should_retry_guard,
@@ -328,6 +333,7 @@ class FallbackProvider(LLMProvider):
retry_mode: str,
on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
has_streamed: list[bool] | None,
on_stream_recover: Callable[[], Awaitable[None]] | None,
persistent_retry_guard: Callable[[], bool] | None,
@@ -336,22 +342,42 @@ class FallbackProvider(LLMProvider):
async def _call_chain(**chain_kwargs: Any) -> LLMResponse:
last_exhausted_message: str | None = None
last_exhausted_status: RetryStatusEvent | None = None
async def _capture_exhaustion(message: str) -> None:
nonlocal last_exhausted_message
last_exhausted_message = message
async def _capture_status(status: RetryStatusEvent) -> None:
nonlocal last_exhausted_status
if status.state == "exhausted":
last_exhausted_status = status
elif on_retry_status:
await on_retry_status(status)
async def _clear_status_for_fallback() -> None:
if last_exhausted_status is not None and on_retry_status is not None:
await on_retry_status(
replace(
last_exhausted_status,
state="cleared",
next_retry_at=None,
)
)
async def _call_candidate(
provider: LLMProvider,
candidate_kwargs: dict[str, Any],
) -> LLMResponse:
nonlocal last_exhausted_message
nonlocal last_exhausted_message, last_exhausted_status
last_exhausted_message = None
last_exhausted_status = None
return await call(provider, {
**candidate_kwargs,
"retry_mode": "standard",
"on_retry_wait": on_retry_wait,
"on_retry_exhausted": _capture_exhaustion,
"on_retry_status": _capture_status,
})
response = await self._try_with_fallback(
@@ -359,14 +385,13 @@ class FallbackProvider(LLMProvider):
chain_kwargs,
has_streamed=has_streamed,
on_stream_recover=on_stream_recover,
on_fallback_attempt=_clear_status_for_fallback,
)
if (
retry_mode != "persistent"
and response.finish_reason == "error"
and last_exhausted_message
and on_retry_exhausted
):
await on_retry_exhausted(last_exhausted_message)
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)
return response
if retry_mode != "persistent":
@@ -378,6 +403,7 @@ class FallbackProvider(LLMProvider):
retry_mode="persistent",
on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=persistent_retry_guard,
on_stream_recover=on_stream_recover,
)
@@ -420,6 +446,7 @@ class FallbackProvider(LLMProvider):
kwargs: dict[str, Any],
has_streamed: list[bool] | None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
on_fallback_attempt: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse:
primary_model = kwargs.get("model") or self._primary.get_default_model()
primary_was_attempted = False
@@ -517,6 +544,8 @@ class FallbackProvider(LLMProvider):
"Fallback '{}' also failed, trying next fallback '{}'",
self._fallback_presets[idx - 1].model, fallback_model,
)
if on_fallback_attempt is not None:
await on_fallback_attempt()
try:
fallback_provider = self._provider_factory(fallback)
fallback_provider.set_llm_call_observer(self._llm_call_observer)
+20 -1
View File
@@ -558,7 +558,6 @@ class WebuiTurnCoordinator:
sessions: SessionManager
schedule_background: Callable[[Awaitable[None]], None]
recovery: RecoveryCoordinator | None = None
def subscribe(self) -> Callable[[], None]:
"""Subscribe this coordinator to runtime events."""
unsubscribe = [
@@ -710,6 +709,10 @@ class WebuiTurnCoordinator:
context_window_tokens=(
event.runtime.context_window_tokens if event.runtime is not None else None
),
outcome=event.outcome,
failure_kind=event.failure_kind,
failure_error_kind=event.failure_error_kind,
failure_attempts=event.failure_attempts,
)
if self.recovery is not None:
await self.recovery.turn_completed(event.context.session_key)
@@ -753,6 +756,10 @@ class WebuiTurnCoordinator:
usage: LLMUsage | None = None,
round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None,
outcome: str = "completed",
failure_kind: str | None = None,
failure_error_kind: str | None = None,
failure_attempts: int | None = None,
) -> None:
if msg.channel != "websocket":
return
@@ -768,6 +775,18 @@ class WebuiTurnCoordinator:
usage=usage,
round_usages=round_usages,
context_window_tokens=context_window_tokens,
outcome=outcome,
failure_kind=failure_kind,
failure_error_kind=failure_error_kind,
failure_attempts=failure_attempts,
failure_message=(
"Model provider request failed. Check the provider configuration or "
"service status, then try again."
if failure_kind == "model"
else "This turn failed and has ended."
if outcome == "failed"
else None
),
),
metadata=msg.metadata,
)
+6 -1
View File
@@ -12,6 +12,8 @@ from nanobot.bus.outbound_events import (
GoalStateSyncEvent,
GoalStatusEvent,
ProgressEvent,
RetryStatusEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent,
SessionUpdatedEvent,
TurnEndEvent,
@@ -134,6 +136,8 @@ class WebUIOutboundProjector:
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, RetryWaitEvent):
return
progress_event = event if isinstance(event, ProgressEvent) else None
if isinstance(event, RuntimeModelUpdatedEvent):
await self._transport.send_runtime_model_updated(
@@ -146,6 +150,7 @@ class WebUIOutboundProjector:
if not conns:
quiet_events = (
ProgressEvent,
RetryStatusEvent,
UserInputEvent,
TurnEndEvent,
SessionUpdatedEvent,
@@ -179,7 +184,7 @@ class WebUIOutboundProjector:
provenance=event.provenance,
)
return
notification = project_notification(msg.chat_id, event)
notification = project_notification(msg.chat_id, event, msg.metadata)
if notification is not None:
if conns or notification.deliver_offline:
kwargs: dict[str, Any] = (
+53 -2
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import time
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
@@ -9,6 +10,7 @@ from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
from nanobot.bus.outbound_events import (
ContextCompactionEvent,
RecoveryStateEvent,
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.events import AgentEvent
@@ -29,6 +31,15 @@ class RecoveryStateWirePayload(_ChatWirePayload):
can_continue: NotRequired[bool]
class RetryStatusWirePayload(_ChatWirePayload):
event: Literal["retry_status"]
state: str
attempt: int
max_attempts: NotRequired[int]
error_kind: str
retry_after_s: NotRequired[float]
class TurnEndWirePayload(_ChatWirePayload):
event: Literal["turn_end"]
latency_ms: NotRequired[int]
@@ -36,6 +47,11 @@ class TurnEndWirePayload(_ChatWirePayload):
usage: NotRequired[dict[str, int]]
round_usages: NotRequired[list[dict[str, int]]]
context_window_tokens: NotRequired[int]
outcome: NotRequired[str]
failure_kind: NotRequired[str]
failure_error_kind: NotRequired[str]
failure_attempts: NotRequired[int]
failure_message: NotRequired[str]
class ContextCompactionWirePayload(_ChatWirePayload):
@@ -45,7 +61,7 @@ class ContextCompactionWirePayload(_ChatWirePayload):
WebUIWirePayload: TypeAlias = (
ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
)
WebUIWirePersistence: TypeAlias = Literal[
"transient",
@@ -97,7 +113,9 @@ class NotificationProjection:
attach_turn_metadata: bool = False
def project_notification(chat_id: str, event: AgentEvent | None) -> NotificationProjection | None:
def project_notification(
chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None,
) -> NotificationProjection | None:
"""Keep notification serialization and persistence decisions at one boundary."""
if isinstance(event, ContextCompactionEvent):
return NotificationProjection(
@@ -106,11 +124,34 @@ def project_notification(chat_id: str, event: AgentEvent | None) -> Notification
deliver_offline=True,
attach_turn_metadata=True,
)
if isinstance(event, RetryStatusEvent):
return NotificationProjection(encode_retry_status(chat_id, event, metadata))
if isinstance(event, RecoveryStateEvent):
return NotificationProjection(encode_recovery_state(chat_id, event))
return None
def encode_retry_status(
chat_id: str,
event: RetryStatusEvent,
metadata: Mapping[str, object] | None = None,
) -> RetryStatusWirePayload:
"""Project one transient retry transition onto its stable wire shape."""
payload: RetryStatusWirePayload = {
"event": "retry_status",
"chat_id": chat_id,
"state": event.state,
"attempt": event.attempt,
"error_kind": event.error_kind,
}
turn_id = (metadata or {}).get(WEBUI_TURN_METADATA_KEY)
if isinstance(turn_id, str) and turn_id:
payload["turn_id"] = turn_id
if event.max_attempts is not None:
payload["max_attempts"] = event.max_attempts
if event.next_retry_at is not None:
payload["retry_after_s"] = max(0.0, event.next_retry_at - time.time())
return payload
def encode_turn_end(
chat_id: str,
event: TurnEndEvent,
@@ -134,4 +175,14 @@ def encode_turn_end(
payload["round_usages"] = [item.to_turn_dict() for item in event.round_usages]
if event.context_window_tokens is not None:
payload["context_window_tokens"] = int(event.context_window_tokens)
if event.outcome != "completed":
payload["outcome"] = event.outcome
if event.failure_kind is not None:
payload["failure_kind"] = event.failure_kind
if event.failure_error_kind is not None:
payload["failure_error_kind"] = event.failure_error_kind
if event.failure_attempts is not None:
payload["failure_attempts"] = int(event.failure_attempts)
if event.failure_message is not None:
payload["failure_message"] = event.failure_message
return payload
+5 -1
View File
@@ -6,5 +6,9 @@
{"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":"recovered","recovery_id":"r1","attempts":1},
{"event":"recovery_state","chat_id":"chat","status":"failed","recovery_id":"r1","attempts":2}
{"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},
{"event":"retry_status","chat_id":"chat","state":"recovered","attempt":2,"max_attempts":4,"error_kind":"connection"},
{"event":"retry_status","chat_id":"chat","state":"cleared","attempt":2,"max_attempts":4,"error_kind":"connection"},
{"event":"retry_status","chat_id":"chat","state":"exhausted","attempt":4,"max_attempts":4,"error_kind":"connection"}
]
+30 -1
View File
@@ -14,7 +14,16 @@ export interface ContextCompaction {
phase: "started" | "succeeded" | "failed" | "cancelled"
}
export interface RetryStatus {
state: "waiting" | "recovered" | "cleared" | "exhausted"
attempt: number
max_attempts?: number
error_kind: string
retry_after_s?: number
}
export type NotificationEvent =
| ({ event: "retry_status"; chat_id: string; turn_id?: string } & RetryStatus)
| ({ event: "recovery_state"; chat_id: string; turn_id?: string } & RecoveryState)
| {
event: "context_compaction"
@@ -49,8 +58,11 @@ export function isRecoveryState(value: unknown): value is RecoveryState {
/** Undefined means another protocol family; null means a malformed notification. */
export function decodeNotification(value: unknown): NotificationEvent | null | undefined {
if (!isRecord(value)) return undefined
if (value.event !== "recovery_state" && value.event !== "context_compaction") return undefined
if (!["recovery_state", "context_compaction", "retry_status"].includes(String(value.event))) return undefined
if (typeof value.chat_id !== "string" || !optional(value.turn_id, "string")) return null
if (value.event === "retry_status") {
return isRetryStatus(value) ? value as unknown as NotificationEvent : null
}
if (value.event === "recovery_state") {
return isRecoveryState(value) ? value as unknown as NotificationEvent : null
}
@@ -58,6 +70,23 @@ export function decodeNotification(value: unknown): NotificationEvent | null | u
&& isCompactionPhase(value.phase) ? value as unknown as NotificationEvent : null
}
function isRetryStatus(value: Record<string, unknown>): boolean {
return typeof value.state === "string"
&& ["waiting", "recovered", "cleared", "exhausted"].includes(value.state)
&& typeof value.attempt === "number"
&& Number.isInteger(value.attempt)
&& value.attempt >= 1
&& (value.max_attempts === undefined
|| (typeof value.max_attempts === "number"
&& Number.isInteger(value.max_attempts)
&& value.max_attempts >= value.attempt))
&& typeof value.error_kind === "string"
&& (value.retry_after_s === undefined
|| (typeof value.retry_after_s === "number"
&& Number.isFinite(value.retry_after_s)
&& value.retry_after_s >= 0))
}
/** A terminal history row must not regress when an older live event arrives. */
export function acceptsCompactionPhase(
current: ContextCompaction["phase"] | undefined,
+55 -1
View File
@@ -10,9 +10,17 @@ import pytest
from nanobot.agent.context import TranscriptInput
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.tools.context import RequestContext
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import StreamedResponseEvent
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import (
GenerationSettings,
LLMProvider,
LLMResponse,
ToolCallRequest,
)
from nanobot.runtime_context import (
RUNTIME_CONTEXT_INPUT_META,
WEBUI_QUOTE_METADATA,
@@ -45,6 +53,52 @@ def _make_loop(tmp_path):
return loop
@pytest.mark.asyncio
async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
from nanobot.agent.loop import AgentLoop
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
captured: dict[str, object] = {}
async def chat_with_retry(**kwargs):
captured.update(kwargs)
retry_status = kwargs["provider_context"].events.emit
assert retry_status is not None
await retry_status(RetryStatusEvent(
state="waiting",
attempt=1,
max_attempts=4,
error_kind="connection",
next_retry_at=123.5,
))
return LLMResponse(content="done", tool_calls=[], usage=None)
provider.chat_with_retry = chat_with_retry
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
loop.tools.get_definitions = MagicMock(return_value=[])
result = await loop._process_message(
InboundMessage(
channel="websocket",
sender_id="user",
chat_id="chat-a",
content="hello",
),
ephemeral=True,
)
assert result is not None
assert captured["provider_context"].events.accepts(RetryStatusEvent)
assert bus.outbound_size == 1
outbound = bus.outbound.get_nowait()
assert isinstance(outbound.event, RetryStatusEvent)
assert outbound.event.state == "waiting"
assert outbound.chat_id == "chat-a"
@pytest.mark.asyncio
async def test_ephemeral_runner_enters_and_restores_turn_scopes(tmp_path):
loop = _make_loop(tmp_path)
+1
View File
@@ -157,6 +157,7 @@ async def test_llm_arrearage_error_surfaces_clear_message():
assert result.stop_reason == "error"
assert result.final_content == _ARREARAGE_ERROR_MESSAGE
assert result.failure_error_kind == "billing"
@pytest.mark.asyncio
+36 -5
View File
@@ -11,6 +11,7 @@ import pytest
from loguru import logger
from nanobot.config.schema import ModelPresetConfig
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import (
LLMProvider,
LLMResponse,
@@ -1086,12 +1087,14 @@ class TestRetryBeforeFailover:
)
assert result.content == "fallback ok"
events = [call.args[0] for call in observe.await_args_list]
assert len(events) == 3
assert all(isinstance(event, RetryWaitEvent) for event in events)
assert not any("giving up" in event.content for event in events)
notices = [event for event in events if isinstance(event, RetryWaitEvent)]
assert len(notices) == 3
assert not any("giving up" in event.content for event in notices)
statuses = [event.state for event in events if isinstance(event, RetryStatusEvent)]
assert statuses == ["cleared", "waiting", "waiting", "waiting", "cleared"]
async def test_scoped_persistent_retry_includes_chain_wait_and_one_terminal(self):
from nanobot.events import EventSink
from nanobot.events import EventSink, RetryWaitEvent
primary = _FakeProvider("primary", _retryable_error("primary unavailable"))
fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))
@@ -1105,11 +1108,15 @@ class TestRetryBeforeFailover:
provider_context=ProviderCallContext(events=EventSink(observe)),
)
assert result.finish_reason == "error"
notices = [call.args[0].content for call in observe.await_args_list]
events = [call.args[0] for call in observe.await_args_list]
notices = [event.content for event in events if isinstance(event, RetryWaitEvent)]
# Two candidates, three waits each, for two chains, plus one chain wait.
assert len(notices) == 14
assert sum("Persistent retry stopped" in text for text in notices) == 1
assert not any("giving up" in text for text in notices)
statuses = [event for event in events if isinstance(event, RetryStatusEvent)]
assert sum(event.state == "exhausted" for event in statuses) == 1
assert statuses[-1].state == "exhausted"
@pytest.mark.asyncio
@pytest.mark.parametrize("retry_mode", ["standard", "persistent"])
@@ -1140,17 +1147,34 @@ class TestRetryBeforeFailover:
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
factory = MagicMock(return_value=fallback)
retry_events = AsyncMock()
retry_statuses: list[RetryStatusEvent] = []
provider = FallbackProvider(primary, [_fallback("fallback-a")], factory)
async def _record_status(status: RetryStatusEvent) -> None:
retry_statuses.append(status)
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await provider.chat_with_retry(
[{"role": "user", "content": "hi"}],
on_retry_wait=retry_events,
on_retry_status=_record_status,
)
assert result.content == "fallback ok"
assert len(primary.chat_calls) == 4
assert not any("giving up" in call.args[0] for call in retry_events.await_args_list)
assert [status.state for status in retry_statuses] == [
"waiting",
"waiting",
"waiting",
"cleared",
]
assert retry_statuses[-1] == RetryStatusEvent(
state="cleared",
attempt=4,
max_attempts=4,
error_kind="server",
)
factory.assert_called_once_with(_fallback("fallback-a"))
@pytest.mark.asyncio
@@ -1159,17 +1183,22 @@ class TestRetryBeforeFailover:
fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))
retry_events = AsyncMock()
terminal_event = AsyncMock()
retry_statuses: list[RetryStatusEvent] = []
provider = FallbackProvider(
primary,
[_fallback("fallback-a")],
MagicMock(return_value=fallback),
)
async def _record_status(status: RetryStatusEvent) -> None:
retry_statuses.append(status)
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await provider.chat_with_retry(
[{"role": "user", "content": "hi"}],
on_retry_wait=retry_events,
on_retry_exhausted=terminal_event,
on_retry_status=_record_status,
)
assert result.finish_reason == "error"
@@ -1178,6 +1207,8 @@ class TestRetryBeforeFailover:
terminal_event.assert_awaited_once_with(
"Model request failed after 4 attempts, giving up."
)
assert "cleared" in [status.state for status in retry_statuses]
assert retry_statuses[-1].state == "exhausted"
@pytest.mark.asyncio
@pytest.mark.parametrize("factory_fails", [False, True])
+141 -1
View File
@@ -3,9 +3,12 @@ from pathlib import Path
import pytest
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import TurnCompleted
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import LLMProvider, ProviderCallContext
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.webui.metadata import (
@@ -88,6 +91,143 @@ async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> No
assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event)
@pytest.mark.asyncio
async def test_retry_event_uses_scoped_channel_delivery() -> None:
bus = MessageBus()
msg = InboundMessage(
channel="websocket",
sender_id="user",
chat_id="chat-a",
content="hello",
metadata={WEBUI_TURN_METADATA_KEY: "turn-1"},
)
delivery = TurnDeliveryFactory(bus).create(msg, msg.session_key)
await delivery.events.emit(RetryStatusEvent(
state="waiting",
attempt=1,
max_attempts=4,
error_kind="connection",
next_retry_at=123.5,
))
assert bus.outbound_size == 1
outbound = bus.outbound.get_nowait()
assert isinstance(outbound.event, RetryStatusEvent)
assert outbound.event.error_kind == "connection"
assert outbound.event.next_retry_at == 123.5
assert outbound.metadata[WEBUI_TURN_METADATA_KEY] == "turn-1"
@pytest.mark.asyncio
async def test_delivery_maps_model_error_to_failed_turn_completion() -> None:
bus = MessageBus()
seen: list[TurnCompleted] = []
bus.subscribe(seen.append, TurnCompleted)
msg = InboundMessage(
channel="websocket",
sender_id="user",
chat_id="chat-a",
content="hello",
)
delivery = TurnDeliveryFactory(bus).create(msg, msg.session_key)
delivery.record_stop_reason("error", failure_error_kind="billing")
await delivery.complete(
OutboundMessage(
channel="websocket",
chat_id="chat-a",
content="Sorry, I encountered an error calling the AI model.",
),
publish_completion=True,
)
assert len(seen) == 1
assert seen[0].outcome == "failed"
assert seen[0].failure_kind == "model"
assert seen[0].failure_error_kind == "billing"
assert bus.outbound_size == 0
@pytest.mark.asyncio
async def test_delivery_keeps_model_error_message_for_ordinary_channels() -> None:
bus = MessageBus()
msg = InboundMessage(
channel="telegram",
sender_id="user",
chat_id="chat-a",
content="hello",
)
delivery = TurnDeliveryFactory(bus).create(msg, msg.session_key)
delivery.record_stop_reason("error")
response = OutboundMessage(
channel="telegram",
chat_id="chat-a",
content="Sorry, I encountered an error calling the AI model.",
)
await delivery.complete(response, publish_completion=True)
assert await bus.consume_outbound() is response
@pytest.mark.parametrize("channel", ["telegram", "cli", "websocket"])
async def test_background_retry_status_is_quiet(channel) -> None:
factory = TurnDeliveryFactory(MessageBus())
delivery = factory.create(InboundMessage(
channel="system", sender_id="job", chat_id=f"{channel}:chat", content="",
), f"{channel}:chat")
assert not delivery.events.accepts(RetryStatusEvent)
await delivery.events.emit(RetryStatusEvent("waiting", 1, 4, "connection"))
assert factory.bus.outbound.empty()
async def test_retry_completion_is_isolated_between_turns_in_one_session() -> None:
bus = MessageBus()
seen: list[TurnCompleted] = []
bus.subscribe(seen.append, TurnCompleted)
factory = TurnDeliveryFactory(bus)
deliveries = [factory.create(InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="",
metadata={WEBUI_TURN_METADATA_KEY: turn},
), "websocket:chat") for turn in ("first", "second")]
await deliveries[0].events.emit(RetryStatusEvent("exhausted", 4, 4, "connection"))
for delivery in reversed(deliveries):
delivery.record_stop_reason("error")
await delivery.complete(None, publish_completion=True)
assert [(event.context.metadata[WEBUI_TURN_METADATA_KEY], event.failure_attempts)
for event in seen] == [("second", None), ("first", 4)]
async def test_next_model_request_clears_exhaustion_within_the_same_turn() -> None:
from unittest.mock import AsyncMock, patch
from nanobot.providers.base import LLMResponse
class Provider(LLMProvider):
async def chat(self, **kwargs):
return LLMResponse(content="payment required", finish_reason="error", error_status_code=402)
def get_default_model(self):
return "test"
bus = MessageBus()
completed: list[TurnCompleted] = []
bus.subscribe(completed.append, TurnCompleted)
msg = InboundMessage(channel="websocket", sender_id="user", chat_id="chat", content="")
delivery = TurnDeliveryFactory(bus).create(msg, msg.session_key)
await delivery.events.emit(RetryStatusEvent("exhausted", 4, 4, "connection"))
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
response = await Provider(provider_name="test").chat_with_retry(
[{"role": "user", "content": "continue"}],
provider_context=ProviderCallContext(events=delivery.events),
)
delivery.record_stop_reason("error", failure_error_kind=LLMProvider.public_error_kind(response))
await delivery.complete(None, publish_completion=True)
assert completed[0].failure_error_kind == "billing"
assert completed[0].failure_attempts is None
def test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None:
factory = TurnDeliveryFactory(
MessageBus(),
+6
View File
@@ -205,6 +205,9 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
chat_id="direct",
session_key="cli:direct",
metadata={"source": "test"},
outcome="failed",
failure_kind="model",
failure_error_kind="billing",
)
await publisher.turn_completed(
channel="cli",
@@ -221,6 +224,9 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
assert first.runtime == "runtime"
assert first.usage == first_round + second_round
assert first.round_usages == (first_round, second_round)
assert first.outcome == "failed"
assert first.failure_kind == "model"
assert first.failure_error_kind == "billing"
assert isinstance(second, TurnCompleted)
assert second.latency_ms is None
assert second.runtime is None
+89 -1
View File
@@ -3,6 +3,7 @@ import copy
import pytest
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import (
RETRY_AFTER_BUFFER,
GenerationSettings,
@@ -64,6 +65,78 @@ async def test_chat_with_retry_retries_transient_error_then_succeeds(monkeypatch
assert delays == [1]
@pytest.mark.asyncio
async def test_chat_with_retry_emits_structured_retry_lifecycle(monkeypatch) -> None:
provider = ScriptedProvider([
LLMResponse(
content="network connection failed",
finish_reason="error",
error_kind="connection",
),
LLMResponse(content="ok"),
])
statuses: list[RetryStatusEvent] = []
async def _fake_sleep(_delay: float) -> None:
return None
async def _status(status: RetryStatusEvent) -> None:
statuses.append(status)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}],
on_retry_status=_status,
)
assert response.content == "ok"
assert [status.state for status in statuses] == ["waiting", "recovered"]
assert statuses[0].attempt == 1
assert statuses[0].max_attempts == 4
assert statuses[0].error_kind == "connection"
assert statuses[0].next_retry_at is not None
assert statuses[1].attempt == 2
@pytest.mark.asyncio
async def test_chat_with_retry_clears_waiting_status_on_terminal_non_transient_error(
monkeypatch,
) -> None:
provider = ScriptedProvider([
LLMResponse(
content="network connection failed",
finish_reason="error",
error_kind="connection",
),
LLMResponse(
content="401 unauthorized",
finish_reason="error",
error_status_code=401,
error_should_retry=False,
),
])
statuses: list[RetryStatusEvent] = []
async def _fake_sleep(_delay: float) -> None:
return None
async def _status(status: RetryStatusEvent) -> None:
statuses.append(status)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}],
on_retry_status=_status,
)
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"
@pytest.mark.asyncio
async def test_chat_with_retry_does_not_retry_non_transient_error(monkeypatch) -> None:
provider = ScriptedProvider([
@@ -111,9 +184,14 @@ async def test_chat_with_retry_emits_terminal_progress_when_standard_retries_exh
LLMResponse(content="429 rate limit a", finish_reason="error"),
LLMResponse(content="429 rate limit b", finish_reason="error"),
LLMResponse(content="429 rate limit c", finish_reason="error"),
LLMResponse(content="503 final server error", finish_reason="error"),
LLMResponse(
content="503 final server error",
finish_reason="error",
error_status_code=503,
),
])
progress: list[str] = []
statuses: list[RetryStatusEvent] = []
async def _fake_sleep(delay: int) -> None:
return None
@@ -121,15 +199,25 @@ async def test_chat_with_retry_emits_terminal_progress_when_standard_retries_exh
async def _progress(msg: str) -> None:
progress.append(msg)
async def _status(status: RetryStatusEvent) -> None:
statuses.append(status)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}],
on_retry_wait=_progress,
on_retry_status=_status,
)
assert response.content == "503 final server error"
assert progress[-1] == "Model request failed after 4 attempts, giving up."
assert statuses[-1] == RetryStatusEvent(
state="exhausted",
attempt=4,
max_attempts=4,
error_kind="server",
)
@pytest.mark.asyncio
+44 -1
View File
@@ -5,8 +5,15 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import GoalStatusEvent, TurnModelUpdatedEvent, UserInputEvent
from nanobot.bus.outbound_events import (
GoalStatusEvent,
RetryStatusEvent,
TurnEndEvent,
TurnModelUpdatedEvent,
UserInputEvent,
)
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import (
RuntimeEventContext,
@@ -242,6 +249,42 @@ async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path)
assert outbound.event.model_preset == "Codex"
@pytest.mark.asyncio
@pytest.mark.parametrize(("states", "terminal_kind", "expected_kind", "attempts"), [
(("exhausted",), None, "connection", 4),
(("waiting", "recovered"), None, None, None),
(("waiting",), "billing", "billing", None),
(("exhausted", "cleared"), "billing", "billing", None),
])
async def test_turn_retry_cause_survives_only_actual_exhaustion(
tmp_path, states, terminal_kind, expected_kind, attempts,
) -> None:
bus = MessageBus()
coordinator = wth.WebuiTurnCoordinator(
bus=bus, sessions=SessionManager(tmp_path),
schedule_background=lambda coro: coro.close(),
)
with coordinator.connected():
msg = InboundMessage(
channel="websocket", sender_id="user", chat_id="chat-retry", content="hello",
metadata={"webui": True, "webui_turn_id": "turn-1"},
)
delivery = TurnDeliveryFactory(bus).create(msg, msg.session_key)
for state in states:
await delivery.events.emit(RetryStatusEvent(
state=state, attempt=4, max_attempts=4, error_kind="connection",
))
delivery.record_stop_reason("error", failure_error_kind=terminal_kind)
await delivery.complete(None, publish_completion=True)
outbounds = [bus.outbound.get_nowait() for _ in range(bus.outbound_size)]
retry_events = [out.event for out in outbounds if isinstance(out.event, RetryStatusEvent)]
assert [event.state for event in retry_events] == list(states)
completed = next(out.event for out in outbounds if isinstance(out.event, TurnEndEvent))
assert completed.failure_error_kind == expected_kind
assert completed.failure_attempts == attempts
@pytest.mark.asyncio
async def test_session_input_is_projected_by_the_webui_coordinator(
tmp_path,
+10 -5
View File
@@ -4,19 +4,24 @@ import json
import tarfile
from pathlib import Path
from nanobot.events import ContextCompactionEvent, RecoveryStateEvent
from nanobot.events import ContextCompactionEvent, RecoveryStateEvent, RetryStatusEvent
from nanobot.webui.outbound_wire import project_notification
ROOT = Path(__file__).resolve().parents[2]
def test_wire_fixtures_are_real_python_projections():
def test_wire_fixtures_are_real_python_projections(monkeypatch):
monkeypatch.setattr("nanobot.webui.outbound_wire.time.time", lambda: 100.0)
fixtures = json.loads((ROOT / "packages/client-events/fixtures.json").read_text())
for expected in fixtures:
fields = {key: value for key, value in expected.items() if key not in {"event", "chat_id"}}
event_type = (
ContextCompactionEvent if expected["event"] == "context_compaction" else RecoveryStateEvent
)
event_type = {
"context_compaction": ContextCompactionEvent,
"recovery_state": RecoveryStateEvent,
"retry_status": RetryStatusEvent,
}[expected["event"]]
if "retry_after_s" in fields:
fields["next_retry_at"] = 100.0 + fields.pop("retry_after_s")
projection = project_notification(expected["chat_id"], event_type(**fields))
assert projection is not None
assert projection.payload == expected
+43
View File
@@ -1,8 +1,11 @@
from __future__ import annotations
import pytest
from nanobot.bus.outbound_events import (
ContextCompactionEvent,
RecoveryStateEvent,
RetryStatusEvent,
TurnEndEvent,
)
from nanobot.providers.base import LLMUsage
@@ -10,6 +13,7 @@ from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
from nanobot.webui.outbound_wire import (
encode_context_compaction,
encode_recovery_state,
encode_retry_status,
encode_turn_end,
)
@@ -74,6 +78,35 @@ def test_encode_recovery_state_preserves_false_can_continue() -> None:
}
def test_encode_retry_status_projects_relative_wait_and_turn_id(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr("nanobot.webui.outbound_wire.time.time", lambda: 120.0)
payload = encode_retry_status(
"chat-1",
RetryStatusEvent(
state="waiting",
attempt=2,
max_attempts=4,
error_kind="connection",
next_retry_at=123.5,
),
{WEBUI_TURN_METADATA_KEY: "turn-1", "private": "must-not-leak"},
)
assert payload == {
"event": "retry_status",
"chat_id": "chat-1",
"turn_id": "turn-1",
"state": "waiting",
"attempt": 2,
"max_attempts": 4,
"error_kind": "connection",
"retry_after_s": 3.5,
}
def test_encode_turn_end_omits_absent_fields_and_private_metadata() -> None:
payload = encode_turn_end(
"chat-1",
@@ -100,6 +133,11 @@ def test_encode_turn_end_projects_complete_wire_contract() -> None:
usage=usage,
round_usages=(usage,),
context_window_tokens=128_000,
outcome="error",
failure_kind="provider",
failure_error_kind="connection",
failure_attempts=4,
failure_message="Connection refused",
),
{WEBUI_TURN_METADATA_KEY: "turn-1", "private": "must-not-leak"},
)
@@ -113,4 +151,9 @@ def test_encode_turn_end_projects_complete_wire_contract() -> None:
"usage": usage.to_turn_dict(),
"round_usages": [usage.to_turn_dict()],
"context_window_tokens": 128_000,
"outcome": "error",
"failure_kind": "provider",
"failure_error_kind": "connection",
"failure_attempts": 4,
"failure_message": "Connection refused",
}
+87 -1
View File
@@ -14,7 +14,12 @@ import {
type TestRendererSetup,
} from "@opentui/core/testing"
import { NanobotTui, sessionExitMessage, type AppOptions } from "./app"
import {
NanobotTui,
sessionExitMessage,
terminalModelFailureLine,
type AppOptions,
} from "./app"
import type {
MessageOptions,
RecoveryState,
@@ -60,6 +65,16 @@ test("formats a reusable session ID after exit", () => {
)
})
test("formats actionable terminal model failures without inventing retries", () => {
expect(terminalModelFailureLine("billing")).toBe(
"Model provider quota is unavailable. "
+ "Add credit or check billing for the provider account, then try again.",
)
expect(terminalModelFailureLine("unknown")).toBe(
"Model provider request failed. "
+ "Check the provider configuration or service status, then try again.",
)
})
function contrastRatio(foreground: string, background: string): number {
const luminance = (color: string) => {
const channel = (offset: number) => {
@@ -2602,6 +2617,77 @@ describe("NanobotTui layout", () => {
expect(ui.composer.placeholder).toBe("Ask nanobot anything")
})
test("updates retry state in place and ends failed turns explicitly", async () => {
setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })
const app = mount(setup)
app.accept({ event: "attached", chat_id: "chat" })
app.accept({
event: "goal_status",
chat_id: "chat",
status: "running",
turn_id: "turn-1",
})
const ui = app as unknown as { status: { plainText: string } }
app.accept({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "waiting",
attempt: 1,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 5,
})
expect(ui.status.plainText).toMatch(
/^Could not connect to the model provider · retrying in [45]s · attempt 1\/4/u,
)
app.accept({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 3,
})
expect(ui.status.plainText).toContain("attempt 2/4")
app.accept({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "cleared",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
})
expect(ui.status.plainText).not.toContain("retrying")
app.accept({
event: "turn_end",
chat_id: "chat",
turn_id: "turn-1",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Unlocalized server failure",
})
await setup.renderOnce()
const frame = setup.captureCharFrame()
const terminalFailure = "Could not connect to the model provider. The request still failed "
+ "on attempt 4, so retries stopped. Check the provider configuration or service status, "
+ "then try again."
expect(frame).toContain("Could not connect to the model provider.")
expect(frame.replace(/\s+/gu, " ")).toContain(terminalFailure)
expect(frame).not.toContain("Unlocalized server failure")
expect(frame).not.toContain("Last turn failed")
expect(ui.status.plainText).toBe("Ready")
})
test("folds long tool traces without discarding their details", async () => {
setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })
const app = mount(setup)
+86 -2
View File
@@ -39,6 +39,7 @@ import {
type MentionCandidate,
type MessageOptions,
type RecoveryState,
type RetryStatus,
type SkillCandidate,
type SlashCommand,
type SessionSummary,
@@ -402,6 +403,45 @@ function connectionStatusText(
return "Session ended"
}
function retryFailureLabel(errorKind: string): string {
if (errorKind === "billing") return "Model provider quota is unavailable"
if (errorKind === "connection") return "Could not connect to the model provider"
if (errorKind === "timeout") return "Model provider request timed out"
if (errorKind === "rate_limit") return "Model provider rate limit reached"
if (errorKind === "server") return "Model provider service error"
return "Model provider request failed"
}
export function terminalModelFailureLine(errorKind?: string, attempts?: number): string {
const reason = retryFailureLabel(errorKind || "unknown")
if (errorKind === "billing") {
return `${reason}. Add credit or check billing for the provider account, then try again.`
}
const retryResult = typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0
? ` The request still failed on attempt ${attempts}, so retries stopped.`
: ""
return `${reason}.${retryResult} Check the provider configuration or service status, then try again.`
}
interface RenderedRetryStatus extends RetryStatus {
nextRetryAtMs?: number
}
export function retryStatusLine(status: RenderedRetryStatus, nowMs = Date.now()): string {
const label = retryFailureLabel(status.error_kind)
if (status.state === "exhausted") return `${label} · ending turn`
if (status.state === "recovered") return "Connection restored"
if (status.state === "cleared") return "Retry status cleared"
const remaining = Math.max(
0,
Math.ceil(((status.nextRetryAtMs ?? nowMs) - nowMs) / 1000),
)
const attempt = status.max_attempts
? `${status.attempt}/${status.max_attempts}`
: String(status.attempt)
return `${label} · retrying in ${remaining}s · attempt ${attempt}`
}
export function sessionExitMessage(chatId: string): string {
const sessionId = `websocket:${chatId}`
return `Resume with: nanobot agent --session ${sessionId}\n`
@@ -457,6 +497,7 @@ export class NanobotTui {
private activeTurn = false
private activeTurnId: string | null = null
private activeLabel = "Thinking"
private retryStatus: RenderedRetryStatus | null = null
private activeStartedAt = 0
private finalMessage = ""
private turnHadAnswer = false
@@ -999,6 +1040,7 @@ export class NanobotTui {
this.finalMessage = ""
this.turnHadAnswer = false
this.activeLabel = "Thinking"
this.retryStatus = null
this.currentFileEdits = []
this.setActive(true, startedAt)
}
@@ -1082,6 +1124,7 @@ export class NanobotTui {
return
}
case "delta":
this.retryStatus = null
this.setActive(true)
this.activeLabel = "Writing"
this.turnHadAnswer = true
@@ -1102,6 +1145,7 @@ export class NanobotTui {
}
}
if (event.kind) {
this.retryStatus = null
this.activeLabel = event.kind === "tool_hint" ? "Working" : "Thinking"
this.transcript.progress(event.text, event.tool_events)
this.setActive(true)
@@ -1110,6 +1154,7 @@ export class NanobotTui {
}
return
case "file_edit":
this.retryStatus = null
this.activeLabel = "Editing"
this.currentFileEdits = mergeFileEdits(this.currentFileEdits, event.edits)
if (this.diffViewer.visible) this.diffViewer.update(this.currentFileEdits)
@@ -1117,6 +1162,7 @@ export class NanobotTui {
this.setActive(true)
return
case "reasoning_delta":
this.retryStatus = null
this.activeLabel = "Thinking"
this.setActive(true)
return
@@ -1130,19 +1176,50 @@ export class NanobotTui {
this.transcript.finishStream(event.text || "")
}
return
case "retry_status":
if (event.turn_id && this.activeTurnId && event.turn_id !== this.activeTurnId) return
if (event.state === "recovered" || event.state === "cleared") {
this.retryStatus = null
if (this.activeTurn) this.renderActiveStatus()
return
}
const retryAfterSeconds = typeof event.retry_after_s === "number"
&& Number.isFinite(event.retry_after_s)
&& event.retry_after_s >= 0
? event.retry_after_s
: undefined
this.retryStatus = {
...event,
...(retryAfterSeconds !== undefined
? { nextRetryAtMs: Date.now() + retryAfterSeconds * 1000 }
: {}),
}
this.setActive(true)
this.renderActiveStatus()
return
case "turn_end":
if (event.turn_id && this.activeTurnId && event.turn_id !== this.activeTurnId) return
if (event.turn_id) {
this.commandTurns.delete(event.turn_id)
this.modelCommandTurns.delete(event.turn_id)
}
this.transcript.finishStream(this.turnHadAnswer ? "" : this.finalMessage)
const failed = event.outcome === "failed"
this.transcript.finishStream(failed || this.turnHadAnswer ? "" : this.finalMessage)
if (failed) {
this.transcript.notice(
event.failure_kind === "model"
? terminalModelFailureLine(event.failure_error_kind, event.failure_attempts)
: event.failure_message || "This turn failed and has ended.",
true,
)
}
this.transcript.finishActivity()
if (this.currentFileEdits.length) this.lastFileEdits = this.currentFileEdits
this.currentFileEdits = []
if (this.diffViewer.visible) this.diffViewer.update(this.lastFileEdits)
this.finalMessage = ""
this.turnHadAnswer = false
this.retryStatus = null
this.activeTurnId = null
if (event.usage) this.lastUsage = event.usage
if (typeof event.context_window_tokens === "number") {
@@ -1153,7 +1230,7 @@ export class NanobotTui {
// A synthetic/rehydrated turn may already be idle, in which case
// setActive(false) intentionally does not repaint the footer.
this.updateMeta()
this.readyDetail = typeof event.latency_ms === "number"
this.readyDetail = !failed && typeof event.latency_ms === "number"
? `${(event.latency_ms / 1000).toFixed(1)}s`
: ""
this.status.content = this.readyStatus()
@@ -1450,11 +1527,18 @@ export class NanobotTui {
}
if (this.shimmerTimer) clearInterval(this.shimmerTimer)
this.shimmerTimer = null
this.retryStatus = null
this.status.content = this.readyStatus()
}
private renderActiveStatus(): void {
if (this.sessionLoading || this.sessionMenu.visible) return
if (this.retryStatus) {
const navigation = this.transcriptNavigation.awayFromBottom ? " · Ctrl+End latest" : ""
const queued = this.promptQueue.length ? ` · ${this.promptQueue.length} queued` : ""
this.status.content = `${retryStatusLine(this.retryStatus)}${queued}${navigation}`
return
}
const elapsed = formatElapsed(Date.now() - this.activeStartedAt)
const navigation = this.transcriptNavigation.awayFromBottom ? " · Ctrl+End latest" : ""
const queued = this.promptQueue.length ? ` · ${this.promptQueue.length} queued` : ""
+78
View File
@@ -805,6 +805,84 @@ describe("gateway protocol", () => {
}
})
test("validates structured retry and failed turn events", () => {
const original = globalThis.WebSocket
let socket: FakeSocket | undefined
Object.defineProperty(globalThis, "WebSocket", {
configurable: true,
value: class extends FakeSocket {
constructor() {
super()
socket = this
}
},
})
try {
const events: InboundEvent[] = []
const statuses: string[] = []
const client = new NanobotClient({
url: "ws://nanobot.test/ws",
onEvent: (event) => events.push(event),
onStatus: (status, detail) => statuses.push(`${status}:${detail || ""}`),
})
client.connect()
if (!socket) throw new Error("socket was not created")
socket.emit("message", { data: JSON.stringify({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 3.5,
}) })
socket.emit("message", { data: JSON.stringify({
event: "retry_status",
chat_id: "chat",
turn_id: "turn-1",
state: "cleared",
attempt: 4,
max_attempts: 4,
error_kind: "connection",
}) })
socket.emit("message", { data: JSON.stringify({
event: "turn_end",
chat_id: "chat",
turn_id: "turn-1",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Model provider request failed.",
}) })
socket.emit("message", { data: JSON.stringify({
event: "retry_status",
chat_id: "chat",
state: "waiting",
attempt: 0,
error_kind: "connection",
}) })
socket.emit("message", { data: JSON.stringify({
event: "turn_end",
chat_id: "chat",
outcome: "failed",
failure_kind: "model",
failure_attempts: 0,
}) })
expect(events).toHaveLength(3)
expect(events[0]?.event).toBe("retry_status")
expect(events[1]?.event).toBe("retry_status")
expect(events[2]?.event).toBe("turn_end")
expect(statuses).toContain("error:gateway sent an invalid event")
client.close()
} finally {
Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original })
}
})
test("reattaches the same generated chat after a transient disconnect", async () => {
const original = globalThis.WebSocket
const sockets: FakeSocket[] = []
+17 -2
View File
@@ -1,6 +1,6 @@
import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications"
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications"
export type { ContextCompaction, RecoveryState, RecoveryStatus } from "../../packages/client-events/notifications"
export type { ContextCompaction, RecoveryState, RecoveryStatus, RetryStatus } from "../../packages/client-events/notifications"
export type ConnectionStatus =
| "starting"
@@ -136,6 +136,11 @@ export type InboundEvent =
usage?: TokenUsage
context_window_tokens?: number
goal_state?: Record<string, unknown>
outcome?: "completed" | "failed" | "cancelled" | "interrupted"
failure_kind?: string
failure_error_kind?: string
failure_attempts?: number
failure_message?: string
}
| {
event: "goal_status"
@@ -347,6 +352,7 @@ const CHAT_EVENTS = new Set([
"stream_end",
"reasoning_delta",
"reasoning_end",
"retry_status",
"turn_end",
"goal_status",
"goal_state",
@@ -526,7 +532,16 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {
&& (!optional(record.latency_ms, "number")
|| !optional(record.context_window_tokens, "number")
|| (record.usage !== undefined && !isTokenUsage(record.usage))
|| (record.goal_state !== undefined && !isRecord(record.goal_state)))
|| (record.goal_state !== undefined && !isRecord(record.goal_state))
|| (record.outcome !== undefined
&& !["completed", "failed", "cancelled", "interrupted"].includes(String(record.outcome)))
|| !optional(record.failure_kind, "string")
|| !optional(record.failure_error_kind, "string")
|| (record.failure_attempts !== undefined
&& (typeof record.failure_attempts !== "number"
|| !Number.isInteger(record.failure_attempts)
|| record.failure_attempts < 1))
|| !optional(record.failure_message, "string"))
) return null
if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null
if (name === "goal_state" && !isRecord(record.goal_state)) return null
@@ -57,7 +57,14 @@ import type { FileEditDisplayMode } from "@/lib/local-preferences";
import { logoFallbackUrls } from "@/lib/provider-brand";
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, ToolProgressEvent, UIFileEdit, UIMessage } from "@/lib/types";
import type {
CliAppInfo,
McpPresetInfo,
RetryStatus,
ToolProgressEvent,
UIFileEdit,
UIMessage,
} from "@/lib/types";
const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;
@@ -143,6 +150,7 @@ interface AgentActivityClusterProps {
turnLatencyMs?: number;
/** User turn start timestamp for live activity before the first trace/reasoning row. */
startedAtMs?: number;
retryStatus?: RetryStatus | null;
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
onOpenFilePreview?: (path: string) => void;
@@ -158,6 +166,7 @@ export function AgentActivityCluster({
hasBodyBelow,
turnLatencyMs,
startedAtMs,
retryStatus = null,
cliApps = [],
mcpPresets = [],
onOpenFilePreview,
@@ -219,7 +228,34 @@ export function AgentActivityCluster({
startedAtMs,
);
const activityDuration = formatActivityDuration(durationMs);
const activityLabel = isTurnStreaming
const retryError = retryStatus?.error_kind === "connection"
? t("message.retryConnection", { defaultValue: "Connection failed" })
: retryStatus?.error_kind === "timeout"
? t("message.retryTimeout", { defaultValue: "Model timed out" })
: retryStatus?.error_kind === "rate_limit"
? t("message.retryRateLimit", { defaultValue: "Rate limited" })
: retryStatus?.error_kind === "server"
? t("message.retryServer", { defaultValue: "Model unavailable" })
: t("message.retryUnknown", { defaultValue: "Model request failed" });
const retryAttempt = retryStatus?.max_attempts
? `${retryStatus.attempt}/${retryStatus.max_attempts}`
: String(retryStatus?.attempt ?? "");
const retrySeconds = retryStatus?.next_retry_at === undefined
? 0
: Math.max(0, Math.ceil(retryStatus.next_retry_at - now / 1000));
const activityLabel = retryStatus?.state === "exhausted"
? t("message.retryExhausted", {
error: retryError,
defaultValue: "{{error}} · ending turn",
})
: retryStatus?.state === "waiting"
? t("message.retryWaiting", {
error: retryError,
seconds: retrySeconds,
attempt: retryAttempt,
defaultValue: "{{error}} · retrying in {{seconds}}s · attempt {{attempt}}",
})
: isTurnStreaming
? t("message.activityWorkingFor", {
duration: activityDuration,
defaultValue: "Working for {{duration}}",
@@ -1,7 +1,9 @@
import { AlertTriangle, X } from "lucide-react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
import { cn } from "@/lib/utils";
import type { StreamError } from "@/lib/nanobot-client";
@@ -53,7 +55,7 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
function resolveCopy(
error: StreamError,
t: (key: string) => string,
t: TFunction,
): { title: string; body: string } {
switch (error.kind) {
case "message_too_big":
@@ -71,6 +73,8 @@ function resolveCopy(
title: t("errors.turnRejected.title"),
body: t("errors.turnRejected.body"),
};
case "model_request_failed":
return resolveModelRequestFailureCopy(error, t);
default: {
// Exhaustiveness guard: if a new StreamError kind is added, TS will
// complain here until we add a corresponding i18n branch.
+14 -2
View File
@@ -4,7 +4,7 @@ import { MessageBubble } from "@/components/MessageBubble";
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import type { CliAppInfo, McpPresetInfo, SlashCommand, UIMessage } from "@/lib/types";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
interface ThreadMessagesProps {
messages: UIMessage[];
@@ -14,6 +14,7 @@ interface ThreadMessagesProps {
activeTurnId?: string | null;
/** Optimistic or canonical active-turn start, in unix seconds. */
runStartedAt?: number | null;
retryStatus?: RetryStatus | null;
hiddenUserMessageCount?: number;
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
@@ -63,6 +64,7 @@ export function ThreadMessages({
isStreaming = false,
activeTurnId = null,
runStartedAt = null,
retryStatus = null,
hiddenUserMessageCount = 0,
cliApps = [],
mcpPresets = [],
@@ -97,7 +99,7 @@ export function ThreadMessages({
isStreaming
&& liveActivityClusterIndices.size === 0
&& pendingTurn !== null
&& !pendingTurn.hasVisibleOutput
&& (retryStatus !== null || !pendingTurn.hasVisibleOutput)
) ? pendingTurn : null;
const currentTurnStartIndex = isStreaming
? activeTurnStartIndex(units, activeTurnId)
@@ -161,6 +163,11 @@ export function ThreadMessages({
: index > currentTurnStartIndex
)
}
retryStatus={
unit.type === "activity" && liveActivityClusterIndices.has(index)
? retryStatus
: null
}
forkIndex={forkIndex}
showForkBoundary={index === forkBoundaryAfterUnitIndex}
forkBoundaryLabel={t("thread.forkedFromHistory")}
@@ -179,6 +186,7 @@ export function ThreadMessages({
messages={[]}
isTurnStreaming
hasBodyBelow={false}
retryStatus={retryStatus}
startedAtMs={
runStartedAt != null
? runStartedAt * 1000
@@ -243,6 +251,7 @@ interface ThreadDisplayUnitProps {
hasBodyBelow: boolean;
deferOffscreenRender: boolean;
isTurnStreaming: boolean;
retryStatus: RetryStatus | null;
forkIndex?: number;
showForkBoundary: boolean;
forkBoundaryLabel: string;
@@ -262,6 +271,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
hasBodyBelow,
deferOffscreenRender,
isTurnStreaming,
retryStatus,
forkIndex,
showForkBoundary,
forkBoundaryLabel,
@@ -293,6 +303,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
<AgentActivityCluster
messages={unit.messages}
isTurnStreaming={isTurnStreaming}
retryStatus={retryStatus}
hasBodyBelow={hasBodyBelow}
turnLatencyMs={unit.turnLatencyMs}
startedAtMs={unit.startedAtMs}
@@ -329,6 +340,7 @@ function threadDisplayUnitPropsEqual(
&& previous.hasBodyBelow === next.hasBodyBelow
&& previous.deferOffscreenRender === next.deferOffscreenRender
&& previous.isTurnStreaming === next.isTurnStreaming
&& previous.retryStatus === next.retryStatus
&& previous.forkIndex === next.forkIndex
&& previous.showForkBoundary === next.showForkBoundary
&& previous.forkBoundaryLabel === next.forkBoundaryLabel
@@ -820,6 +820,7 @@ export function ThreadShell({
messagesReady,
isStreaming,
runStartedAt,
retryStatus,
goalState,
recoveryState,
continueRecovery,
@@ -1726,6 +1727,7 @@ export function ThreadShell({
temporary={temporary}
isStreaming={turnActive}
runStartedAt={currentRunStartedAt}
retryStatus={retryStatus}
emptyState={emptyState}
composer={composerPortalTarget === undefined ? composer : null}
activeTurnId={viewportTurnId}
@@ -26,7 +26,7 @@ import {
promptTop,
} from "@/components/thread/promptNavigation";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, SlashCommand, UIMessage } from "@/lib/types";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
export interface ThreadViewportHandle {
jumpToUserPrompt: (promptId: string) => void;
@@ -39,6 +39,7 @@ interface ThreadViewportProps {
isStreaming: boolean;
/** Optimistic or canonical start time for the active turn, in unix seconds. */
runStartedAt?: number | null;
retryStatus?: RetryStatus | null;
composer?: ReactNode;
emptyState?: ReactNode;
scrollToBottomSignal?: number;
@@ -221,6 +222,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
temporary = false,
isStreaming,
runStartedAt = null,
retryStatus = null,
composer,
emptyState,
scrollToBottomSignal = 0,
@@ -878,6 +880,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
isStreaming={isStreaming}
activeTurnId={activeTurnId}
runStartedAt={runStartedAt}
retryStatus={retryStatus}
hiddenUserMessageCount={hiddenUserMessageCount}
cliApps={cliApps}
mcpPresets={mcpPresets}
+78 -1
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { useClient } from "@/providers/ClientProvider";
import { toMediaAttachment } from "@/lib/media";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
import {
mergeToolProgressEvents,
mergeToolProgressTraceLines,
@@ -39,6 +40,7 @@ import type {
GoalStateWsPayload,
MessageDeliveryStatus,
RecoveryState,
RetryStatus,
UIMediaAttachment,
UIMessage,
WorkspaceScopePayload,
@@ -247,6 +249,8 @@ export function useNanobotStream(
isStreaming: boolean;
/** Unix epoch seconds when the current user turn started (WebSocket ``goal_status``). */
runStartedAt: number | null;
/** Transient model retry state for the active turn. */
retryStatus: RetryStatus | null;
/** Latest sustained goal for this ``chatId`` (``goal_state`` WS events). */
goalState: GoalStateWsPayload | undefined;
recoveryState: RecoveryState | null;
@@ -281,6 +285,7 @@ export function useNanobotStream(
);
/** Unix epoch seconds when the current user turn started; cleared on ``idle``. */
const [runStartedAt, setRunStartedAt] = useState<number | null>(initialRunStartedAt);
const [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
const [streamError, setStreamError] = useState<StreamError | null>(null);
@@ -366,6 +371,7 @@ export function useNanobotStream(
// still be shown in the mounted thread, but cannot roll back any turn.
if (!chatId || (err.chatId && err.chatId !== chatId)) return;
setStreamError(err);
if (err.kind === "model_request_failed") return;
if (!err.turnId) return;
const rejectedTurnId = err.turnId;
@@ -680,6 +686,7 @@ export function useNanobotStream(
);
setStreamError(null);
setRunStartedAt(restoredRunStartedAt);
setRetryStatus(null);
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null);
buffer.current = null;
@@ -802,6 +809,13 @@ export function useNanobotStream(
});
return;
}
if (
ev.event === "delta"
|| ev.event === "message"
|| ev.event === "file_edit"
|| ev.event === "reasoning_delta"
|| ev.event === "stream_end"
) setRetryStatus(null);
if (ev.event === "delta") {
if (suppressStreamUntilTurnEndRef.current) return;
const chunk = typeof ev.text === "string" ? ev.text : "";
@@ -875,11 +889,42 @@ export function useNanobotStream(
if (ev.event === "goal_status") {
if (ev.status === "running" && typeof ev.started_at === "number") {
setStreamError(null);
setRunStartedAt(ev.started_at);
setIsStreaming(true);
} else {
setRunStartedAt(null);
setIsStreaming(false);
setRetryStatus(null);
}
return;
}
if (ev.event === "retry_status") {
const activeTurnId = client.getRunTurnId(chatId);
if (ev.turn_id && activeTurnId && ev.turn_id !== activeTurnId) return;
if (ev.state === "recovered" || ev.state === "cleared") {
setRetryStatus(null);
} else {
const retryAfterSeconds =
typeof ev.retry_after_s === "number" &&
Number.isFinite(ev.retry_after_s) &&
ev.retry_after_s >= 0
? ev.retry_after_s
: undefined;
setRetryStatus({
state: ev.state,
attempt: ev.attempt,
error_kind: ev.error_kind,
...(typeof ev.max_attempts === "number"
? { max_attempts: ev.max_attempts }
: {}),
...(retryAfterSeconds !== undefined
? { next_retry_at: Date.now() / 1000 + retryAfterSeconds }
: {}),
...(ev.turn_id ? { turn_id: ev.turn_id } : {}),
});
setIsStreaming(true);
}
return;
}
@@ -890,9 +935,29 @@ export function useNanobotStream(
setGoalState(ev.goal_state);
}
setRunStartedAt(null);
setRetryStatus(null);
// Definitive signal that the turn is fully complete, so stop the
// loading indicator immediately.
setIsStreaming(false);
const modelRequestFailed = ev.outcome === "failed" && ev.failure_kind === "model";
const failureAttempts =
typeof ev.failure_attempts === "number"
&& Number.isInteger(ev.failure_attempts)
&& ev.failure_attempts > 0
? ev.failure_attempts
: undefined;
const modelFailure = modelRequestFailed
? {
kind: "model_request_failed" as const,
chatId,
...(ev.turn_id ? { turnId: ev.turn_id } : {}),
...(typeof ev.failure_error_kind === "string"
? { errorKind: ev.failure_error_kind }
: {}),
...(failureAttempts !== undefined ? { attempts: failureAttempts } : {}),
}
: null;
if (modelFailure) setStreamError(modelFailure);
const completedAt = Date.now();
setMessages((prev) => {
let finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
@@ -920,7 +985,13 @@ export function useNanobotStream(
return finalized;
});
suppressStreamUntilTurnEndRef.current = false;
notifyInBackground(t("recovery.completed", { defaultValue: "Task completed" }));
notifyInBackground(
modelFailure
? resolveModelRequestFailureCopy(modelFailure, t).body
: ev.outcome === "failed"
? ev.failure_message || "This turn failed and has ended."
: t("recovery.completed", { defaultValue: "Task completed" }),
);
onTurnEnd?.();
return;
}
@@ -945,6 +1016,7 @@ export function useNanobotStream(
|| ev.status === "recovered"
|| ev.status === "failed"
) {
setRetryStatus(null);
// Recovery is an explicit boundary. The interrupted turn is no
// longer running, so do not let the stale start time keep the
// activity clock (or composer stop state) alive underneath the
@@ -1211,6 +1283,7 @@ export function useNanobotStream(
// them via ``media`` paths.
if (!hasAttachments && !content.trim()) return null;
setStreamError(null);
const sideChannel = options?.sideChannel === true;
const finalizeActiveTurn = options?.finalizeActiveTurn === true;
const continueActiveTurn = options?.continueActiveTurn === true;
@@ -1220,6 +1293,7 @@ export function useNanobotStream(
flushPendingStreamEvents();
if (finalizeActiveTurn) {
setIsStreaming(false);
setRetryStatus(null);
}
const turnId = crypto.randomUUID();
const userMessageId = crypto.randomUUID();
@@ -1280,6 +1354,7 @@ export function useNanobotStream(
if (!chatId) return;
flushPendingStreamEvents();
setIsStreaming(false);
setRetryStatus(null);
setMessages((prev) => {
buffer.current = null;
activeAssistantRef.current = null;
@@ -1301,6 +1376,7 @@ export function useNanobotStream(
clearActivitySegment();
suppressStreamUntilTurnEndRef.current = false;
setRunStartedAt(null);
setRetryStatus(null);
setIsStreaming(false);
}, [clearActivitySegment, clearPendingStreamWork]);
@@ -1332,6 +1408,7 @@ export function useNanobotStream(
messagesReady: messageOwnerChatId === chatId,
isStreaming,
runStartedAt,
retryStatus,
goalState,
recoveryState,
continueRecovery,
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "Working for {{duration}}",
"activityWorked": "Worked",
"activityWorkedFor": "Worked for {{duration}}",
"retryConnection": "Connection failed",
"retryTimeout": "Model timed out",
"retryRateLimit": "Rate limited",
"retryServer": "Model unavailable",
"retryUnknown": "Model request failed",
"retryWaiting": "{{error}} · retrying in {{seconds}}s · attempt {{attempt}}",
"retryExhausted": "{{error}} · ending turn",
"cliActivityRunningOne": "Using {{name}}",
"cliActivityRanOne": "Used {{name}}",
"cliActivityFailedOne": "{{name}} failed",
@@ -1546,6 +1553,17 @@
"turnRejected": {
"title": "Message was not sent",
"body": "The gateway rejected this message. Review its text or attachments, then try again."
},
"modelRequestFailed": {
"billingTitle": "Model provider quota is unavailable",
"billingBody": "Add credit or check billing for the provider account, then try again.",
"connectionTitle": "Could not connect to the model provider",
"timeoutTitle": "Model provider request timed out",
"rateLimitTitle": "Model provider rate limit reached",
"serverTitle": "Model provider service error",
"unknownTitle": "Model provider request failed",
"bodyWithAttempt": "The request still failed on attempt {{attempts}}, so retries stopped. Check the provider configuration or service status, then try again.",
"body": "Check the provider configuration or service status, then try again."
}
},
"workspace": {
+18
View File
@@ -1435,6 +1435,13 @@
"activityWorkingFor": "Trabajando durante {{duration}}",
"activityWorked": "Trabajo completado",
"activityWorkedFor": "Trabajó durante {{duration}}",
"retryConnection": "Error de conexión",
"retryTimeout": "Se agotó el tiempo de espera del modelo",
"retryRateLimit": "Límite de solicitudes alcanzado",
"retryServer": "Modelo no disponible",
"retryUnknown": "La solicitud al modelo falló",
"retryWaiting": "{{error}} · reintentando en {{seconds}} s · intento {{attempt}}",
"retryExhausted": "{{error}} · finalizando el turno",
"cliActivityRunningOne": "Usando {{name}}",
"cliActivityRanOne": "Usó {{name}}",
"cliActivityFailedOne": "Falló {{name}}",
@@ -1533,6 +1540,17 @@
"turnRejected": {
"title": "El mensaje no se envió",
"body": "El gateway rechazó este mensaje. Revisa el texto o los archivos adjuntos e inténtalo de nuevo."
},
"modelRequestFailed": {
"billingTitle": "La cuota del proveedor del modelo no está disponible",
"billingBody": "Añade crédito o revisa la facturación de la cuenta del proveedor y vuelve a intentarlo.",
"connectionTitle": "No se pudo conectar con el proveedor del modelo",
"timeoutTitle": "La solicitud al proveedor del modelo agotó el tiempo de espera",
"rateLimitTitle": "Se alcanzó el límite de solicitudes del proveedor del modelo",
"serverTitle": "Error del servicio del proveedor del modelo",
"unknownTitle": "La solicitud al proveedor del modelo falló",
"bodyWithAttempt": "La solicitud siguió fallando en el intento {{attempts}}, por lo que se detuvieron los reintentos. Revisa la configuración o el estado del proveedor y vuelve a intentarlo.",
"body": "Revisa la configuración o el estado del proveedor y vuelve a intentarlo."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Travail en cours depuis {{duration}}",
"activityWorked": "Travail terminé",
"activityWorkedFor": "Travail terminé en {{duration}}",
"retryConnection": "Échec de la connexion",
"retryTimeout": "Délai d’attente du modèle dépassé",
"retryRateLimit": "Limite de requêtes atteinte",
"retryServer": "Modèle indisponible",
"retryUnknown": "Échec de la requête au modèle",
"retryWaiting": "{{error}} · nouvelle tentative dans {{seconds}} s · tentative {{attempt}}",
"retryExhausted": "{{error}} · fin du tour",
"cliActivityRunningOne": "Utilisation de {{name}}",
"cliActivityRanOne": "{{name}} utilisé",
"cliActivityFailedOne": "Échec de {{name}}",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "Le message n’a pas été envoyé",
"body": "La passerelle a refusé ce message. Vérifiez le texte ou les pièces jointes, puis réessayez."
},
"modelRequestFailed": {
"billingTitle": "Quota du fournisseur du modèle indisponible",
"billingBody": "Ajoutez du crédit ou vérifiez la facturation du compte fournisseur, puis réessayez.",
"connectionTitle": "Impossible de se connecter au fournisseur du modèle",
"timeoutTitle": "La requête au fournisseur du modèle a expiré",
"rateLimitTitle": "Limite de requêtes du fournisseur du modèle atteinte",
"serverTitle": "Erreur du service du fournisseur du modèle",
"unknownTitle": "Échec de la requête au fournisseur du modèle",
"bodyWithAttempt": "La requête a encore échoué à la tentative {{attempts}} ; les nouvelles tentatives ont donc été arrêtées. Vérifiez la configuration ou l’état du fournisseur, puis réessayez.",
"body": "Vérifiez la configuration ou l’état du fournisseur, puis réessayez."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Memproses selama {{duration}}",
"activityWorked": "Selesai memproses",
"activityWorkedFor": "Diproses selama {{duration}}",
"retryConnection": "Koneksi gagal",
"retryTimeout": "Waktu respons model habis",
"retryRateLimit": "Batas permintaan tercapai",
"retryServer": "Model tidak tersedia",
"retryUnknown": "Permintaan model gagal",
"retryWaiting": "{{error}} · mencoba lagi dalam {{seconds}} dtk · percobaan {{attempt}}",
"retryExhausted": "{{error}} · mengakhiri giliran",
"cliActivityRunningOne": "Menggunakan {{name}}",
"cliActivityRanOne": "Menggunakan {{name}} selesai",
"cliActivityFailedOne": "{{name}} gagal",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "Pesan tidak terkirim",
"body": "Gateway menolak pesan ini. Periksa teks atau lampiran, lalu coba lagi."
},
"modelRequestFailed": {
"billingTitle": "Kuota penyedia model tidak tersedia",
"billingBody": "Tambahkan kredit atau periksa tagihan akun penyedia, lalu coba lagi.",
"connectionTitle": "Tidak dapat terhubung ke penyedia model",
"timeoutTitle": "Permintaan ke penyedia model kehabisan waktu",
"rateLimitTitle": "Batas permintaan penyedia model tercapai",
"serverTitle": "Kesalahan layanan penyedia model",
"unknownTitle": "Permintaan ke penyedia model gagal",
"bodyWithAttempt": "Permintaan masih gagal pada percobaan ke-{{attempts}}, sehingga percobaan ulang dihentikan. Periksa konfigurasi atau status layanan penyedia, lalu coba lagi.",
"body": "Periksa konfigurasi atau status layanan penyedia, lalu coba lagi."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "{{duration}}作業中",
"activityWorked": "作業しました",
"activityWorkedFor": "{{duration}}作業しました",
"retryConnection": "接続に失敗しました",
"retryTimeout": "モデルがタイムアウトしました",
"retryRateLimit": "リクエスト制限に達しました",
"retryServer": "モデルを利用できません",
"retryUnknown": "モデルリクエストに失敗しました",
"retryWaiting": "{{error}} · {{seconds}}秒後に再試行 · 試行 {{attempt}}",
"retryExhausted": "{{error}} · ターンを終了します",
"cliActivityRunningOne": "{{name}} を使用中",
"cliActivityRanOne": "{{name}} を使用しました",
"cliActivityFailedOne": "{{name}} が失敗しました",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "メッセージは送信されませんでした",
"body": "ゲートウェイがこのメッセージを拒否しました。本文または添付ファイルを確認して、もう一度お試しください。"
},
"modelRequestFailed": {
"billingTitle": "モデルプロバイダーの利用枠を使用できません",
"billingBody": "プロバイダーアカウントにクレジットを追加するか、請求状況を確認してから、もう一度お試しください。",
"connectionTitle": "モデルプロバイダーに接続できません",
"timeoutTitle": "モデルプロバイダーへのリクエストがタイムアウトしました",
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
"bodyWithAttempt": "{{attempts}} 回目の試行でもリクエストに失敗したため、再試行を停止しました。プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。",
"body": "プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。"
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "{{duration}} 동안 작업 중",
"activityWorked": "작업함",
"activityWorkedFor": "{{duration}} 동안 작업함",
"retryConnection": "연결 실패",
"retryTimeout": "모델 응답 시간 초과",
"retryRateLimit": "요청 한도 초과",
"retryServer": "모델을 사용할 수 없음",
"retryUnknown": "모델 요청 실패",
"retryWaiting": "{{error}} · {{seconds}}초 후 재시도 · 시도 {{attempt}}",
"retryExhausted": "{{error}} · 턴 종료 중",
"cliActivityRunningOne": "{{name}} 사용 중",
"cliActivityRanOne": "{{name}} 사용함",
"cliActivityFailedOne": "{{name}} 실패",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "메시지가 전송되지 않았습니다",
"body": "게이트웨이가 이 메시지를 거부했습니다. 텍스트나 첨부 파일을 확인한 후 다시 시도하세요."
},
"modelRequestFailed": {
"billingTitle": "모델 제공업체 할당량을 사용할 수 없음",
"billingBody": "제공업체 계정에 크레딧을 추가하거나 결제 상태를 확인한 후 다시 시도하세요.",
"connectionTitle": "모델 제공업체에 연결할 수 없음",
"timeoutTitle": "모델 제공업체 요청 시간 초과",
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
"serverTitle": "모델 제공업체 서비스 오류",
"unknownTitle": "모델 제공업체 요청 실패",
"bodyWithAttempt": "{{attempts}}번째 시도에서도 요청이 실패하여 재시도를 중지했습니다. 제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요.",
"body": "제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요."
}
},
"workspace": {
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "Trabalhando por {{duration}}",
"activityWorked": "Trabalhou",
"activityWorkedFor": "Trabalhou por {{duration}}",
"retryConnection": "Falha na conexão",
"retryTimeout": "O modelo excedeu o tempo limite",
"retryRateLimit": "Limite de solicitações atingido",
"retryServer": "Modelo indisponível",
"retryUnknown": "Falha na solicitação ao modelo",
"retryWaiting": "{{error}} · tentando novamente em {{seconds}} s · tentativa {{attempt}}",
"retryExhausted": "{{error}} · encerrando o turno",
"cliActivityRunningOne": "Usando {{name}}",
"cliActivityRanOne": "Usou {{name}}",
"cliActivityFailedOne": "Falhou em {{name}}",
@@ -1546,6 +1553,17 @@
"turnRejected": {
"title": "A mensagem não foi enviada",
"body": "O gateway rejeitou esta mensagem. Revise o texto ou os anexos e tente novamente."
},
"modelRequestFailed": {
"billingTitle": "A cota do provedor do modelo está indisponível",
"billingBody": "Adicione créditos ou verifique o faturamento da conta do provedor e tente novamente.",
"connectionTitle": "Não foi possível conectar ao provedor do modelo",
"timeoutTitle": "A solicitação ao provedor do modelo expirou",
"rateLimitTitle": "Limite de solicitações do provedor do modelo atingido",
"serverTitle": "Erro no serviço do provedor do modelo",
"unknownTitle": "Falha na solicitação ao provedor do modelo",
"bodyWithAttempt": "A solicitação ainda falhou na tentativa {{attempts}}, então as novas tentativas foram interrompidas. Verifique a configuração ou o status do provedor e tente novamente.",
"body": "Verifique a configuração ou o status do provedor e tente novamente."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Đang xử lý trong {{duration}}",
"activityWorked": "Đã xử lý",
"activityWorkedFor": "Đã xử lý trong {{duration}}",
"retryConnection": "Kết nối thất bại",
"retryTimeout": "Mô hình đã hết thời gian chờ",
"retryRateLimit": "Đã đạt giới hạn yêu cầu",
"retryServer": "Mô hình không khả dụng",
"retryUnknown": "Yêu cầu mô hình thất bại",
"retryWaiting": "{{error}} · thử lại sau {{seconds}} giây · lần thử {{attempt}}",
"retryExhausted": "{{error}} · đang kết thúc lượt",
"cliActivityRunningOne": "Đang dùng {{name}}",
"cliActivityRanOne": "Đã dùng {{name}}",
"cliActivityFailedOne": "{{name}} thất bại",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "Tin nhắn chưa được gửi",
"body": "Gateway đã từ chối tin nhắn này. Hãy kiểm tra nội dung hoặc tệp đính kèm rồi thử lại."
},
"modelRequestFailed": {
"billingTitle": "Hạn mức của nhà cung cấp mô hình không khả dụng",
"billingBody": "Hãy nạp thêm tín dụng hoặc kiểm tra thanh toán của tài khoản nhà cung cấp rồi thử lại.",
"connectionTitle": "Không thể kết nối với nhà cung cấp mô hình",
"timeoutTitle": "Yêu cầu tới nhà cung cấp mô hình đã hết thời gian chờ",
"rateLimitTitle": "Đã đạt giới hạn yêu cầu của nhà cung cấp mô hình",
"serverTitle": "Lỗi dịch vụ nhà cung cấp mô hình",
"unknownTitle": "Yêu cầu tới nhà cung cấp mô hình không thành công",
"bodyWithAttempt": "Yêu cầu vẫn thất bại ở lần thử {{attempts}}, nên hệ thống đã dừng thử lại. Hãy kiểm tra cấu hình hoặc trạng thái dịch vụ của nhà cung cấp rồi thử lại.",
"body": "Hãy kiểm tra cấu hình hoặc trạng thái dịch vụ của nhà cung cấp rồi thử lại."
}
},
"workspace": {
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "处理中 {{duration}}",
"activityWorked": "已处理",
"activityWorkedFor": "处理了 {{duration}}",
"retryConnection": "连接失败",
"retryTimeout": "模型响应超时",
"retryRateLimit": "请求频率受限",
"retryServer": "模型服务不可用",
"retryUnknown": "模型请求失败",
"retryWaiting": "{{error}} · {{seconds}} 秒后重试 · 第 {{attempt}} 次",
"retryExhausted": "{{error}} · 正在结束本次任务",
"cliActivityRunningOne": "正在使用 {{name}}",
"cliActivityRanOne": "已使用 {{name}}",
"cliActivityFailedOne": "使用 {{name}} 失败",
@@ -1546,6 +1553,17 @@
"turnRejected": {
"title": "消息未发送",
"body": "网关拒绝了这条消息。请检查消息内容或附件后重试。"
},
"modelRequestFailed": {
"billingTitle": "模型提供商账户额度不足",
"billingBody": "请为提供商账户充值或检查账单状态后重试。",
"connectionTitle": "无法连接模型提供商",
"timeoutTitle": "模型提供商请求超时",
"rateLimitTitle": "模型提供商请求受限",
"serverTitle": "模型提供商服务异常",
"unknownTitle": "模型提供商请求失败",
"bodyWithAttempt": "模型提供商请求在第 {{attempts}} 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
"body": "请检查提供商配置或服务状态后重试。"
}
},
"workspace": {
+18
View File
@@ -1433,6 +1433,13 @@
"activityWorkingFor": "處理中,已 {{duration}}",
"activityWorked": "已處理",
"activityWorkedFor": "已處理 {{duration}}",
"retryConnection": "連線失敗",
"retryTimeout": "模型回應逾時",
"retryRateLimit": "請求頻率受限",
"retryServer": "模型服務無法使用",
"retryUnknown": "模型請求失敗",
"retryWaiting": "{{error}} · {{seconds}} 秒後重試 · 第 {{attempt}} 次",
"retryExhausted": "{{error}} · 正在結束本輪",
"cliActivityRunningOne": "正在使用 @{{name}}",
"cliActivityRanOne": "已使用 @{{name}}",
"cliActivityFailedOne": "使用 @{{name}} 失敗",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "訊息未傳送",
"body": "閘道拒絕了這則訊息。請檢查內容或附件後再試一次。"
},
"modelRequestFailed": {
"billingTitle": "模型供應商帳戶額度不足",
"billingBody": "請為供應商帳戶儲值或檢查帳單狀態後再試。",
"connectionTitle": "無法連線至模型供應商",
"timeoutTitle": "模型供應商請求逾時",
"rateLimitTitle": "模型供應商請求受到限制",
"serverTitle": "模型供應商服務發生錯誤",
"unknownTitle": "模型供應商請求失敗",
"bodyWithAttempt": "模型供應商請求在第 {{attempts}} 次嘗試後仍然失敗,已停止重試。請檢查供應商設定或服務狀態後再試。",
"body": "請檢查供應商設定或服務狀態後再試。"
}
},
"workspace": {
+36
View File
@@ -0,0 +1,36 @@
import type { TFunction } from "i18next";
export interface ModelRequestFailureDetails {
errorKind?: string;
attempts?: number;
}
export function resolveModelRequestFailureCopy(
details: ModelRequestFailureDetails,
t: TFunction,
): { title: string; body: string } {
let titleKey = "errors.modelRequestFailed.unknownTitle";
if (details.errorKind === "billing") {
titleKey = "errors.modelRequestFailed.billingTitle";
} else if (details.errorKind === "connection") {
titleKey = "errors.modelRequestFailed.connectionTitle";
} else if (details.errorKind === "timeout") {
titleKey = "errors.modelRequestFailed.timeoutTitle";
} else if (details.errorKind === "rate_limit") {
titleKey = "errors.modelRequestFailed.rateLimitTitle";
} else if (details.errorKind === "server") {
titleKey = "errors.modelRequestFailed.serverTitle";
}
const attempts = details.attempts;
let bodyKey = "errors.modelRequestFailed.body";
if (details.errorKind === "billing") {
bodyKey = "errors.modelRequestFailed.billingBody";
} else if (typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0) {
bodyKey = "errors.modelRequestFailed.bodyWithAttempt";
}
return {
title: t(titleKey),
body: t(bodyKey, { attempts }),
};
}
+10 -3
View File
@@ -79,9 +79,9 @@ type RunStatusHandler = (chatId: string, startedAt: number | null) => void;
/** Structured errors surfaced to the UI.
*
* Most entries are transport-level or protocol-level faults. Workspace scope
* rejections are server application errors promoted here because they affect
* controls outside the message stream and must be visible immediately.
* Most entries are transport-level or protocol-level faults. Runtime and
* workspace failures are promoted here when they must remain visible outside
* the message stream.
*/
export type StreamError =
/** Server rejected the inbound frame as too large (WS close code 1009).
@@ -100,6 +100,13 @@ export type StreamError =
reason?: string;
chatId: string;
turnId: string;
}
| {
kind: "model_request_failed";
chatId: string;
turnId?: string;
errorKind?: string;
attempts?: number;
};
type ErrorHandler = (error: StreamError) => void;
+10 -1
View File
@@ -1,4 +1,4 @@
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../../packages/client-events/notifications";
import type { ContextCompaction, NotificationEvent, RecoveryState, RetryStatus as WireRetryStatus } from "../../../packages/client-events/notifications";
export type { RecoveryState, RecoveryStatus } from "../../../packages/client-events/notifications";
type Role = "user" | "assistant" | "tool" | "system";
@@ -64,6 +64,10 @@ export interface TurnUsage {
export type RoundUsage = TurnUsage;
export interface RetryStatus extends WireRetryStatus {
next_retry_at?: number;
turn_id?: string;
}
export interface UIMessage {
id: string;
role: Role;
@@ -1422,6 +1426,11 @@ export type InboundEvent =
context_window_tokens?: number;
/** Authoritative sustained-goal snapshot for this chat (same shape as ``goal_state`` events). */
goal_state?: GoalStateWsPayload;
outcome?: "completed" | "failed" | "cancelled" | "interrupted";
failure_kind?: string;
failure_error_kind?: string;
failure_attempts?: number;
failure_message?: string;
} & InboundTurnMetadata)
| ({
event: "goal_status";
@@ -140,6 +140,27 @@ function installReducedMotion() {
}
describe("AgentActivityCluster", () => {
it("shows model retries in the existing live activity header", () => {
render(
<AgentActivityCluster
messages={[]}
isTurnStreaming
hasBodyBelow={false}
retryStatus={{
state: "waiting",
attempt: 1,
max_attempts: 4,
error_kind: "connection",
next_retry_at: Date.now() / 1000 + 5,
}}
/>,
);
expect(
screen.getByText("Connection failed · retrying in 5s · attempt 1/4"),
).toBeInTheDocument();
});
it("keeps intermediate assistant output as normal Markdown inside live activity", async () => {
await act(async () => {
await preloadMarkdownText();
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import i18n from "@/i18n";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
describe("model request failure copy", () => {
it("maps every sanitized provider error category to a specific cause", () => {
const titles = ["billing", "connection", "timeout", "rate_limit", "server", "unknown"].map(
(errorKind) => resolveModelRequestFailureCopy({ errorKind }, i18n.t).title,
);
expect(titles).toEqual([
"Model provider quota is unavailable",
"Could not connect to the model provider",
"Model provider request timed out",
"Model provider rate limit reached",
"Model provider service error",
"Model provider request failed",
]);
});
it("reports the final attempt and a concrete recovery action", () => {
expect(resolveModelRequestFailureCopy(
{ errorKind: "connection", attempts: 4 },
i18n.t,
).body).toBe(
"The request still failed on attempt 4, so retries stopped. "
+ "Check the provider configuration or service status, then try again.",
);
});
it("provides billing recovery without claiming a retry occurred", () => {
expect(resolveModelRequestFailureCopy(
{ errorKind: "billing" },
i18n.t,
).body).toBe(
"Add credit or check billing for the provider account, then try again.",
);
});
it("does not claim retries stopped without an attempt count", () => {
const body = resolveModelRequestFailureCopy({ errorKind: "unknown" }, i18n.t).body;
expect(body).toBe(
"Check the provider configuration or service status, then try again.",
);
});
});
+8
View File
@@ -3,6 +3,14 @@ import fixtures from "../../../packages/client-events/fixtures.json";
import { acceptsCompactionPhase, decodeNotification } from "../../../packages/client-events/notifications";
describe("shared notification contract", () => {
it("rejects malformed retry counters and relative delays", () => {
const retry = { event: "retry_status", chat_id: "chat", state: "waiting",
attempt: 1, max_attempts: 4, error_kind: "connection", retry_after_s: 2 };
for (const invalid of [
{ attempt: 0 }, { attempt: 1.5 }, { max_attempts: 0 }, { max_attempts: NaN },
{ retry_after_s: -1 }, { retry_after_s: Infinity }, { state: "unknown" },
]) expect(decodeNotification({ ...retry, ...invalid })).toBeNull();
});
it.each(fixtures)("accepts the Python wire fixture %#", (event) => {
expect(decodeNotification(event)).toEqual(event);
expect(decodeNotification({ ...event, turn_id: "turn" })).toMatchObject(event);
+51
View File
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { ThreadCameraController } from "@/components/thread/thread-camera";
import { ThreadShell } from "@/components/thread/ThreadShell";
import i18n from "@/i18n";
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
@@ -3793,6 +3794,56 @@ describe("ThreadShell", () => {
});
});
it("keeps a terminal model failure visible until the next user action", async () => {
const client = makeClient();
await act(async () => {
await i18n.changeLanguage("zh-CN");
});
render(
wrap(
client,
<ThreadShell
session={session("chat-model-failure")}
title="Chat model failure"
onToggleSidebar={() => {}}
onGoHome={() => {}}
onNewChat={() => {}}
/>,
),
);
await act(async () => {});
act(() => {
client._emitChat("chat-model-failure", {
event: "turn_end",
chat_id: "chat-model-failure",
turn_id: "turn-model-failure",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Unlocalized server failure",
});
});
const banner = await screen.findByRole("alert");
expect(banner).toHaveTextContent("无法连接模型提供商");
expect(banner).toHaveTextContent(
"模型提供商请求在第 4 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
);
expect(banner).not.toHaveTextContent("Unlocalized server failure");
fireEvent.change(screen.getByLabelText("消息输入框"), {
target: { value: "try again" },
});
fireEvent.click(screen.getByRole("button", { name: "发送消息" }));
await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
it("moves a correlated delivery error from the banner into the failed message tooltip", async () => {
const client = makeClient();
+69
View File
@@ -125,6 +125,9 @@ function fakeClient() {
const v = runStartedAtByChatId.get(chatId);
return v === undefined ? null : v;
},
getRunTurnId() {
return null;
},
getGoalState(chatId: string) {
return goalStateByChatId.get(chatId);
},
@@ -3227,6 +3230,72 @@ describe("useNanobotStream", () => {
expect(result.current.isStreaming).toBe(false);
});
it("clears retry status and exposes a terminal model failure at turn end", () => {
const dateNow = vi.spyOn(Date, "now").mockReturnValue(120_000);
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-retry", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
fake.emit("chat-retry", {
event: "retry_status",
chat_id: "chat-retry",
turn_id: "turn-1",
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 3.5,
});
});
expect(result.current.retryStatus).toEqual({
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
next_retry_at: 123.5,
turn_id: "turn-1",
});
expect(result.current.isStreaming).toBe(true);
act(() => {
fake.emit("chat-retry", {
event: "retry_status",
chat_id: "chat-retry",
turn_id: "turn-1",
state: "cleared",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
});
});
expect(result.current.retryStatus).toBeNull();
act(() => {
fake.emit("chat-retry", {
event: "turn_end",
chat_id: "chat-retry",
turn_id: "turn-1",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Unlocalized server failure",
});
});
expect(result.current.retryStatus).toBeNull();
expect(result.current.isStreaming).toBe(false);
expect(result.current.streamError).toEqual({
kind: "model_request_failed",
chatId: "chat-retry",
turnId: "turn-1",
errorKind: "connection",
attempts: 4,
});
dateNow.mockRestore();
});
it("clears runStartedAt on turn_end even without idle", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-g", EMPTY_MESSAGES), {