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 final_content: str | None = None
all_messages: list[dict[str, Any]] = field(default_factory=list) all_messages: list[dict[str, Any]] = field(default_factory=list)
stop_reason: str = "" stop_reason: str = ""
failure_error_kind: str | None = None
streamed_content: bool = False streamed_content: bool = False
input_persisted_early: bool = False input_persisted_early: bool = False
@@ -2012,6 +2013,7 @@ class AgentLoop:
ctx.summary_checkpoint = result.summary_checkpoint ctx.summary_checkpoint = result.summary_checkpoint
ctx.provider_compaction_applied = result.provider_compaction_applied ctx.provider_compaction_applied = result.provider_compaction_applied
ctx.stop_reason = result.stop_reason ctx.stop_reason = result.stop_reason
ctx.failure_error_kind = result.failure_error_kind
if ( if (
ctx.kind is TurnKind.USER ctx.kind is TurnKind.USER
and (ctx.delivery.route.channel, ctx.delivery.route.chat_id) in message_sends 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: 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: if ctx.suppress_response:
ctx.outbound = None ctx.outbound = None
return return
+4
View File
@@ -130,6 +130,7 @@ class AgentRunResult:
round_usages: list[LLMUsage] = field(default_factory=list) round_usages: list[LLMUsage] = field(default_factory=list)
stop_reason: str = "completed" stop_reason: str = "completed"
error: str | None = None error: str | None = None
failure_error_kind: str | None = None
tool_events: list[dict[str, str]] = field(default_factory=list) tool_events: list[dict[str, str]] = field(default_factory=list)
had_injections: bool = False had_injections: bool = False
# Terminal tail to emit when the preceding final-content prefix was already streamed. # Terminal tail to emit when the preceding final-content prefix was already streamed.
@@ -396,6 +397,7 @@ class AgentRunner:
usage: LLMUsage | None = None usage: LLMUsage | None = None
round_usages: list[LLMUsage] = [] round_usages: list[LLMUsage] = []
error: str | None = None error: str | None = None
failure_error_kind: str | None = None
stop_reason = "completed" stop_reason = "completed"
tool_events: list[dict[str, str]] = [] tool_events: list[dict[str, str]] = []
external_lookup_counts: dict[str, int] = {} external_lookup_counts: dict[str, int] = {}
@@ -730,6 +732,7 @@ class AgentRunner:
had_injections = True had_injections = True
length_recovery_parts.clear() length_recovery_parts.clear()
continue continue
failure_error_kind = LLMProvider.public_error_kind(response)
break break
if is_blank_text(clean): if is_blank_text(clean):
final_content = EMPTY_FINAL_RESPONSE_MESSAGE final_content = EMPTY_FINAL_RESPONSE_MESSAGE
@@ -827,6 +830,7 @@ class AgentRunner:
round_usages=round_usages, round_usages=round_usages,
stop_reason=stop_reason, stop_reason=stop_reason,
error=error, error=error,
failure_error_kind=failure_error_kind,
tool_events=tool_events, tool_events=tool_events,
had_injections=had_injections, had_injections=had_injections,
pending_stream_content=pending_stream_content, 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.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import notification_is_deliverable from nanobot.bus.notification_delivery import notification_is_deliverable
from nanobot.bus.outbound_events import ( from nanobot.bus.outbound_events import (
RetryStatusEvent,
StreamDeltaEvent, StreamDeltaEvent,
StreamedResponseEvent, StreamedResponseEvent,
StreamEndEvent, StreamEndEvent,
@@ -61,6 +62,14 @@ def _bind_events(
return EventSink(publish, accepts) 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: class TurnDeliveryFactory:
"""Route turn delivery and session-level notifications.""" """Route turn delivery and session-level notifications."""
@@ -182,6 +191,9 @@ class TurnDelivery:
_stream_open: bool = field(init=False, default=False) _stream_open: bool = field(init=False, default=False)
events: EventSink = field(init=False) events: EventSink = field(init=False)
_routed_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: def __post_init__(self) -> None:
self._routed_events = _bind_events(self.bus, self.route) self._routed_events = _bind_events(self.bus, self.route)
@@ -244,6 +256,15 @@ class TurnDelivery:
def record_usage(self, round_usages: list[LLMUsage]) -> None: def record_usage(self, round_usages: list[LLMUsage]) -> None:
self.runtime_event_publisher.record_turn_usage(self.session_key, round_usages) 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( def background_response(
self, self,
content: str | None, content: str | None,
@@ -276,12 +297,16 @@ class TurnDelivery:
*, *,
publish_completion: bool, publish_completion: bool,
) -> None: ) -> 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_channel = self.lifecycle_message.channel
completed_chat_id = self.lifecycle_message.chat_id completed_chat_id = self.lifecycle_message.chat_id
if response is not None: if response is not None:
await self.bus.publish_outbound(response)
completed_channel = response.channel completed_channel = response.channel
completed_chat_id = response.chat_id 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": elif self.lifecycle_message.channel == "cli":
await self.bus.publish_outbound( await self.bus.publish_outbound(
OutboundMessage( OutboundMessage(
@@ -292,11 +317,20 @@ class TurnDelivery:
) )
) )
if publish_completion: if publish_completion:
outcome, failure_kind = _turn_outcome(stop_reason)
await self.runtime_event_publisher.turn_completed( await self.runtime_event_publisher.turn_completed(
channel=completed_channel, channel=completed_channel,
chat_id=completed_chat_id, chat_id=completed_chat_id,
session_key=self.session_key, session_key=self.session_key,
metadata=self.lifecycle_message.metadata, 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: async def fail(self, *, publish_completion: bool) -> None:
@@ -314,6 +348,8 @@ class TurnDelivery:
chat_id=self.lifecycle_message.chat_id, chat_id=self.lifecycle_message.chat_id,
session_key=self.session_key, session_key=self.session_key,
metadata=self.lifecycle_message.metadata, metadata=self.lifecycle_message.metadata,
outcome="failed",
failure_kind="internal",
) )
async def idle(self) -> None: async def idle(self) -> None:
@@ -329,6 +365,8 @@ class TurnDelivery:
return f"{self._stream_base_id}:{self._stream_segment}" return f"{self._stream_base_id}:{self._stream_segment}"
async def _publish_event(self, event: AgentEvent) -> None: 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 isinstance(event, StreamDeltaEvent | StreamEndEvent):
if not self.streaming: if not self.streaming:
return return
+5 -1
View File
@@ -5,6 +5,7 @@ from typing import Literal
from nanobot.bus.outbound_events import ( from nanobot.bus.outbound_events import (
FileEditEvent, FileEditEvent,
ProgressEvent, ProgressEvent,
RetryStatusEvent,
StreamDeltaEvent, StreamDeltaEvent,
StreamEndEvent, StreamEndEvent,
) )
@@ -20,6 +21,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = {
ContextCompactionEvent: "channel", ContextCompactionEvent: "channel",
RetryWaitEvent: "lifecycle", RetryWaitEvent: "lifecycle",
RecoveryStateEvent: "interactive", RecoveryStateEvent: "interactive",
RetryStatusEvent: "interactive",
} }
@@ -33,5 +35,7 @@ def notification_is_deliverable(
if audience == "lifecycle": if audience == "lifecycle":
return publish_lifecycle return publish_lifecycle
if audience == "interactive": if audience == "interactive":
return channel == "websocket" return channel == "websocket" and (
event_type is not RetryStatusEvent or publish_lifecycle
)
return True return True
+6
View File
@@ -15,6 +15,7 @@ from nanobot.bus.events import OutboundMessage
from nanobot.events import AgentEvent from nanobot.events import AgentEvent
from nanobot.events import ContextCompactionEvent as ContextCompactionEvent from nanobot.events import ContextCompactionEvent as ContextCompactionEvent
from nanobot.events import RecoveryStateEvent as RecoveryStateEvent from nanobot.events import RecoveryStateEvent as RecoveryStateEvent
from nanobot.events import RetryStatusEvent as RetryStatusEvent
from nanobot.events import RetryWaitEvent as RetryWaitEvent from nanobot.events import RetryWaitEvent as RetryWaitEvent
from nanobot.providers.base import LLMUsage from nanobot.providers.base import LLMUsage
@@ -62,6 +63,11 @@ class TurnEndEvent(AgentEvent):
usage: LLMUsage | None = None usage: LLMUsage | None = None
round_usages: tuple[LLMUsage, ...] = () round_usages: tuple[LLMUsage, ...] = ()
context_window_tokens: int | None = None 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) @dataclass(frozen=True)
+12
View File
@@ -67,6 +67,10 @@ class TurnCompleted(AgentEvent):
usage: LLMUsage | None = None usage: LLMUsage | None = None
# Logical model rounds in display order; recovery dispatches are aggregated. # Logical model rounds in display order; recovery dispatches are aggregated.
round_usages: tuple[LLMUsage, ...] = () 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) @dataclass(frozen=True)
@@ -259,6 +263,10 @@ class RuntimeEventPublisher:
chat_id: str, chat_id: str,
session_key: str, session_key: str,
metadata: dict[str, Any] | None, 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: ) -> None:
await self.bus.publish( await self.bus.publish(
TurnCompleted( TurnCompleted(
@@ -272,6 +280,10 @@ class RuntimeEventPublisher:
runtime=self._turn_runtime.pop(session_key, None), runtime=self._turn_runtime.pop(session_key, None),
usage=self._turn_usage.pop(session_key, None), usage=self._turn_usage.pop(session_key, None),
round_usages=self._turn_round_usages.pop(session_key, ()), 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, GoalStatusEvent,
ProgressEvent, ProgressEvent,
RecoveryStateEvent, RecoveryStateEvent,
RetryStatusEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent, RuntimeModelUpdatedEvent,
SessionUpdatedEvent, SessionUpdatedEvent,
TurnEndEvent, 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 @pytest.mark.asyncio
async def test_context_compaction_started_is_live_only() -> None: async def test_context_compaction_started_is_live_only() -> None:
bus = MagicMock() bus = MagicMock()
+11
View File
@@ -24,6 +24,17 @@ class RetryWaitEvent(AgentEvent):
content: str = "" 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) @dataclass(frozen=True)
class RecoveryStateEvent(AgentEvent): class RecoveryStateEvent(AgentEvent):
status: str status: str
+94 -9
View File
@@ -19,7 +19,7 @@ from typing import TYPE_CHECKING, Any, Literal, cast
import json_repair import json_repair
from loguru import logger 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 from nanobot.utils.helpers import sanitize_surrogates_deep
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -33,6 +33,7 @@ RETRY_AFTER_BUFFER = 1
RetryEventCallback = Callable[[str], Awaitable[None]] RetryEventCallback = Callable[[str], Awaitable[None]]
LLMCallObserver = Callable[["LLMCallRecord"], None] LLMCallObserver = Callable[["LLMCallRecord"], None]
ProviderCompactionScope = Literal["prior_context", "current_request"] ProviderCompactionScope = Literal["prior_context", "current_request"]
RetryStatusCallback = Callable[[RetryStatusEvent], Awaitable[None]]
def resolve_stream_idle_timeout_s( def resolve_stream_idle_timeout_s(
@@ -1453,6 +1454,7 @@ class LLMProvider(ABC):
on_retry_wait: RetryEventCallback | None = None, on_retry_wait: RetryEventCallback | None = None,
provider_context: ProviderCallContext | None = None, provider_context: ProviderCallContext | None = None,
on_retry_exhausted: RetryEventCallback | None = None, on_retry_exhausted: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> LLMResponse: ) -> LLMResponse:
"""Call chat_stream() with retry on transient provider failures.""" """Call chat_stream() with retry on transient provider failures."""
if max_tokens is self._SENTINEL or max_tokens is None: if max_tokens is self._SENTINEL or max_tokens is None:
@@ -1489,8 +1491,8 @@ class LLMProvider(ABC):
kw["provider_context"] = provider_context kw["provider_context"] = provider_context
if on_stream_recover and getattr(self, "supports_stream_recover_callback", False): if on_stream_recover and getattr(self, "supports_stream_recover_callback", False):
kw["on_stream_recover"] = _recover_stream kw["on_stream_recover"] = _recover_stream
on_retry_wait, on_retry_exhausted = self._retry_notifications( on_retry_wait, on_retry_exhausted, on_retry_status = await self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted, provider_context, on_retry_wait, on_retry_exhausted, on_retry_status,
) )
return await self._run_chat_with_retry( return await self._run_chat_with_retry(
kw, kw,
@@ -1499,6 +1501,7 @@ class LLMProvider(ABC):
retry_mode=retry_mode, retry_mode=retry_mode,
on_retry_wait=on_retry_wait, on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted, on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=lambda: not has_streamed_content, should_retry_guard=lambda: not has_streamed_content,
on_stream_recover=_recover_stream if on_stream_recover else None, on_stream_recover=_recover_stream if on_stream_recover else None,
) )
@@ -1516,6 +1519,7 @@ class LLMProvider(ABC):
on_retry_wait: RetryEventCallback | None = None, on_retry_wait: RetryEventCallback | None = None,
provider_context: ProviderCallContext | None = None, provider_context: ProviderCallContext | None = None,
on_retry_exhausted: RetryEventCallback | None = None, on_retry_exhausted: RetryEventCallback | None = None,
on_retry_status: RetryStatusCallback | None = None,
) -> LLMResponse: ) -> LLMResponse:
"""Call chat() with retry on transient provider failures. """Call chat() with retry on transient provider failures.
@@ -1540,8 +1544,8 @@ class LLMProvider(ABC):
) )
if provider_context is not None: if provider_context is not None:
kw["provider_context"] = provider_context kw["provider_context"] = provider_context
on_retry_wait, on_retry_exhausted = self._retry_notifications( on_retry_wait, on_retry_exhausted, on_retry_status = await self._retry_notifications(
provider_context, on_retry_wait, on_retry_exhausted, provider_context, on_retry_wait, on_retry_exhausted, on_retry_status,
) )
return await self._run_chat_with_retry( return await self._run_chat_with_retry(
kw, kw,
@@ -1550,14 +1554,16 @@ class LLMProvider(ABC):
retry_mode=retry_mode, retry_mode=retry_mode,
on_retry_wait=on_retry_wait, on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted, on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
) )
@staticmethod @staticmethod
def _retry_notifications( async def _retry_notifications(
context: ProviderCallContext | None, context: ProviderCallContext | None,
on_wait: RetryEventCallback | None, on_wait: RetryEventCallback | None,
on_exhausted: 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. """Adapt once at the retry-chain boundary, before candidate callbacks.
Explicit callbacks retain precedence. In particular a fallback candidate Explicit callbacks retain precedence. In particular a fallback candidate
@@ -1568,7 +1574,12 @@ class LLMProvider(ABC):
await context.events.emit(RetryWaitEvent(content)) await context.events.emit(RetryWaitEvent(content))
on_wait = publish 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( async def _run_chat_with_retry(
self, self,
@@ -1579,6 +1590,7 @@ class LLMProvider(ABC):
retry_mode: str, retry_mode: str,
on_retry_wait: RetryEventCallback | None, on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None, on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None, should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None, on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse: ) -> LLMResponse:
@@ -1591,6 +1603,7 @@ class LLMProvider(ABC):
retry_mode=retry_mode, retry_mode=retry_mode,
on_retry_wait=on_retry_wait, on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted, on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=should_retry_guard, should_retry_guard=should_retry_guard,
on_stream_recover=on_stream_recover, on_stream_recover=on_stream_recover,
) )
@@ -1676,8 +1689,12 @@ class LLMProvider(ABC):
*, *,
attempt: int, attempt: int,
persistent: bool, 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: ) -> None:
next_retry_at = time.time() + max(0.0, delay)
remaining = max(0.0, delay) remaining = max(0.0, delay)
while remaining > 0: while remaining > 0:
if on_retry_wait: if on_retry_wait:
@@ -1686,10 +1703,34 @@ class LLMProvider(ABC):
f"Model request failed, {kind} in {max(1, int(round(remaining)))}s " f"Model request failed, {kind} in {max(1, int(round(remaining)))}s "
f"(attempt {attempt})." 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) chunk = min(remaining, self._RETRY_HEARTBEAT_CHUNK)
await asyncio.sleep(chunk) await asyncio.sleep(chunk)
remaining -= 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( async def _run_with_retry(
self, self,
call: Callable[..., Awaitable[LLMResponse]], call: Callable[..., Awaitable[LLMResponse]],
@@ -1699,6 +1740,7 @@ class LLMProvider(ABC):
retry_mode: str, retry_mode: str,
on_retry_wait: RetryEventCallback | None, on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None, on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None, should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None, on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse: ) -> LLMResponse:
@@ -1708,10 +1750,26 @@ class LLMProvider(ABC):
last_response: LLMResponse | None = None last_response: LLMResponse | None = None
last_error_key: str | None = None last_error_key: str | None = None
identical_error_count = 0 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: while True:
attempt += 1 attempt += 1
response = await call(**kw) response = await call(**kw)
if response.finish_reason != "error": if response.finish_reason != "error":
await _finish_retry_status("recovered", response)
return response return response
last_response = response last_response = response
if should_retry_guard is not None and not should_retry_guard(): if should_retry_guard is not None and not should_retry_guard():
@@ -1737,6 +1795,7 @@ class LLMProvider(ABC):
logger.warning( logger.warning(
"LLM stream failed after content was emitted; skipping retry" "LLM stream failed after content was emitted; skipping retry"
) )
await _finish_retry_status("cleared", response)
return response return response
error_key = ((response.content or "").strip().lower() or None) error_key = ((response.content or "").strip().lower() or None)
if error_key and error_key == last_error_key: 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. # subsequent iterations do not repeat the error-retry cycle.
if result.finish_reason != "error": if result.finish_reason != "error":
self._strip_image_content_inplace(original_messages) self._strip_image_content_inplace(original_messages)
await _finish_retry_status(
"recovered" if result.finish_reason != "error" else "cleared",
result,
)
return result return result
await _finish_retry_status("cleared", response)
return response return response
if persistent and identical_error_count >= self._PERSISTENT_IDENTICAL_ERROR_LIMIT: if persistent and identical_error_count >= self._PERSISTENT_IDENTICAL_ERROR_LIMIT:
@@ -1792,6 +1856,15 @@ class LLMProvider(ABC):
await on_retry_exhausted( await on_retry_exhausted(
f"Persistent retry stopped after {identical_error_count} identical errors." 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 return response
if not persistent and attempt > len(delays): if not persistent and attempt > len(delays):
@@ -1804,6 +1877,15 @@ class LLMProvider(ABC):
await on_retry_exhausted( await on_retry_exhausted(
f"Model request failed after {attempt} attempts, giving up." 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 break
retry_after = self._extract_retry_after_from_response(response) retry_after = self._extract_retry_after_from_response(response)
@@ -1823,7 +1905,10 @@ class LLMProvider(ABC):
delay, delay,
attempt=attempt, attempt=attempt,
persistent=persistent, 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_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] 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 loguru import logger
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import ( from nanobot.providers.base import (
GenerationSettings, GenerationSettings,
LLMCallObserver, LLMCallObserver,
@@ -20,6 +21,7 @@ from nanobot.providers.base import (
ProviderCallContext, ProviderCallContext,
ProviderConversationState, ProviderConversationState,
RetryEventCallback, RetryEventCallback,
RetryStatusCallback,
) )
# Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker. # Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker.
@@ -213,6 +215,7 @@ class FallbackProvider(LLMProvider):
retry_mode: str, retry_mode: str,
on_retry_wait: RetryEventCallback | None, on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None, on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
should_retry_guard: Callable[[], bool] | None = None, should_retry_guard: Callable[[], bool] | None = None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None, on_stream_recover: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse: ) -> LLMResponse:
@@ -229,6 +232,7 @@ class FallbackProvider(LLMProvider):
"retry_mode": retry_mode, "retry_mode": retry_mode,
"on_retry_wait": on_retry_wait, "on_retry_wait": on_retry_wait,
"on_retry_exhausted": on_retry_exhausted, "on_retry_exhausted": on_retry_exhausted,
"on_retry_status": on_retry_status,
}) })
if stream: if stream:
return await self._primary.chat_stream_with_retry(**call_kwargs) return await self._primary.chat_stream_with_retry(**call_kwargs)
@@ -273,6 +277,7 @@ class FallbackProvider(LLMProvider):
retry_mode=retry_mode, retry_mode=retry_mode,
on_retry_wait=on_retry_wait, on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted, on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
has_streamed=has_streamed, has_streamed=has_streamed,
on_stream_recover=recover_stream, on_stream_recover=recover_stream,
persistent_retry_guard=should_retry_guard, persistent_retry_guard=should_retry_guard,
@@ -328,6 +333,7 @@ class FallbackProvider(LLMProvider):
retry_mode: str, retry_mode: str,
on_retry_wait: RetryEventCallback | None, on_retry_wait: RetryEventCallback | None,
on_retry_exhausted: RetryEventCallback | None, on_retry_exhausted: RetryEventCallback | None,
on_retry_status: RetryStatusCallback | None,
has_streamed: list[bool] | None, has_streamed: list[bool] | None,
on_stream_recover: Callable[[], Awaitable[None]] | None, on_stream_recover: Callable[[], Awaitable[None]] | None,
persistent_retry_guard: Callable[[], bool] | None, persistent_retry_guard: Callable[[], bool] | None,
@@ -336,22 +342,42 @@ class FallbackProvider(LLMProvider):
async def _call_chain(**chain_kwargs: Any) -> LLMResponse: async def _call_chain(**chain_kwargs: Any) -> LLMResponse:
last_exhausted_message: str | None = None last_exhausted_message: str | None = None
last_exhausted_status: RetryStatusEvent | None = None
async def _capture_exhaustion(message: str) -> None: async def _capture_exhaustion(message: str) -> None:
nonlocal last_exhausted_message nonlocal last_exhausted_message
last_exhausted_message = 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( async def _call_candidate(
provider: LLMProvider, provider: LLMProvider,
candidate_kwargs: dict[str, Any], candidate_kwargs: dict[str, Any],
) -> LLMResponse: ) -> LLMResponse:
nonlocal last_exhausted_message nonlocal last_exhausted_message, last_exhausted_status
last_exhausted_message = None last_exhausted_message = None
last_exhausted_status = None
return await call(provider, { return await call(provider, {
**candidate_kwargs, **candidate_kwargs,
"retry_mode": "standard", "retry_mode": "standard",
"on_retry_wait": on_retry_wait, "on_retry_wait": on_retry_wait,
"on_retry_exhausted": _capture_exhaustion, "on_retry_exhausted": _capture_exhaustion,
"on_retry_status": _capture_status,
}) })
response = await self._try_with_fallback( response = await self._try_with_fallback(
@@ -359,14 +385,13 @@ class FallbackProvider(LLMProvider):
chain_kwargs, chain_kwargs,
has_streamed=has_streamed, has_streamed=has_streamed,
on_stream_recover=on_stream_recover, on_stream_recover=on_stream_recover,
on_fallback_attempt=_clear_status_for_fallback,
) )
if ( if retry_mode != "persistent" and response.finish_reason == "error":
retry_mode != "persistent" if last_exhausted_message and on_retry_exhausted:
and response.finish_reason == "error" await on_retry_exhausted(last_exhausted_message)
and last_exhausted_message if last_exhausted_status and on_retry_status:
and on_retry_exhausted await on_retry_status(last_exhausted_status)
):
await on_retry_exhausted(last_exhausted_message)
return response return response
if retry_mode != "persistent": if retry_mode != "persistent":
@@ -378,6 +403,7 @@ class FallbackProvider(LLMProvider):
retry_mode="persistent", retry_mode="persistent",
on_retry_wait=on_retry_wait, on_retry_wait=on_retry_wait,
on_retry_exhausted=on_retry_exhausted, on_retry_exhausted=on_retry_exhausted,
on_retry_status=on_retry_status,
should_retry_guard=persistent_retry_guard, should_retry_guard=persistent_retry_guard,
on_stream_recover=on_stream_recover, on_stream_recover=on_stream_recover,
) )
@@ -420,6 +446,7 @@ class FallbackProvider(LLMProvider):
kwargs: dict[str, Any], kwargs: dict[str, Any],
has_streamed: list[bool] | None, has_streamed: list[bool] | None,
on_stream_recover: Callable[[], Awaitable[None]] | None = None, on_stream_recover: Callable[[], Awaitable[None]] | None = None,
on_fallback_attempt: Callable[[], Awaitable[None]] | None = None,
) -> LLMResponse: ) -> LLMResponse:
primary_model = kwargs.get("model") or self._primary.get_default_model() primary_model = kwargs.get("model") or self._primary.get_default_model()
primary_was_attempted = False primary_was_attempted = False
@@ -517,6 +544,8 @@ class FallbackProvider(LLMProvider):
"Fallback '{}' also failed, trying next fallback '{}'", "Fallback '{}' also failed, trying next fallback '{}'",
self._fallback_presets[idx - 1].model, fallback_model, self._fallback_presets[idx - 1].model, fallback_model,
) )
if on_fallback_attempt is not None:
await on_fallback_attempt()
try: try:
fallback_provider = self._provider_factory(fallback) fallback_provider = self._provider_factory(fallback)
fallback_provider.set_llm_call_observer(self._llm_call_observer) fallback_provider.set_llm_call_observer(self._llm_call_observer)
+20 -1
View File
@@ -558,7 +558,6 @@ class WebuiTurnCoordinator:
sessions: SessionManager sessions: SessionManager
schedule_background: Callable[[Awaitable[None]], None] schedule_background: Callable[[Awaitable[None]], None]
recovery: RecoveryCoordinator | None = None recovery: RecoveryCoordinator | None = None
def subscribe(self) -> Callable[[], None]: def subscribe(self) -> Callable[[], None]:
"""Subscribe this coordinator to runtime events.""" """Subscribe this coordinator to runtime events."""
unsubscribe = [ unsubscribe = [
@@ -710,6 +709,10 @@ class WebuiTurnCoordinator:
context_window_tokens=( context_window_tokens=(
event.runtime.context_window_tokens if event.runtime is not None else None 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: if self.recovery is not None:
await self.recovery.turn_completed(event.context.session_key) await self.recovery.turn_completed(event.context.session_key)
@@ -753,6 +756,10 @@ class WebuiTurnCoordinator:
usage: LLMUsage | None = None, usage: LLMUsage | None = None,
round_usages: tuple[LLMUsage, ...] = (), round_usages: tuple[LLMUsage, ...] = (),
context_window_tokens: int | None = None, 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: ) -> None:
if msg.channel != "websocket": if msg.channel != "websocket":
return return
@@ -768,6 +775,18 @@ class WebuiTurnCoordinator:
usage=usage, usage=usage,
round_usages=round_usages, round_usages=round_usages,
context_window_tokens=context_window_tokens, 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, metadata=msg.metadata,
) )
+6 -1
View File
@@ -12,6 +12,8 @@ from nanobot.bus.outbound_events import (
GoalStateSyncEvent, GoalStateSyncEvent,
GoalStatusEvent, GoalStatusEvent,
ProgressEvent, ProgressEvent,
RetryStatusEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent, RuntimeModelUpdatedEvent,
SessionUpdatedEvent, SessionUpdatedEvent,
TurnEndEvent, TurnEndEvent,
@@ -134,6 +136,8 @@ class WebUIOutboundProjector:
async def send(self, msg: OutboundMessage) -> None: async def send(self, msg: OutboundMessage) -> None:
event = msg.event event = msg.event
if isinstance(event, RetryWaitEvent):
return
progress_event = event if isinstance(event, ProgressEvent) else None progress_event = event if isinstance(event, ProgressEvent) else None
if isinstance(event, RuntimeModelUpdatedEvent): if isinstance(event, RuntimeModelUpdatedEvent):
await self._transport.send_runtime_model_updated( await self._transport.send_runtime_model_updated(
@@ -146,6 +150,7 @@ class WebUIOutboundProjector:
if not conns: if not conns:
quiet_events = ( quiet_events = (
ProgressEvent, ProgressEvent,
RetryStatusEvent,
UserInputEvent, UserInputEvent,
TurnEndEvent, TurnEndEvent,
SessionUpdatedEvent, SessionUpdatedEvent,
@@ -179,7 +184,7 @@ class WebUIOutboundProjector:
provenance=event.provenance, provenance=event.provenance,
) )
return return
notification = project_notification(msg.chat_id, event) notification = project_notification(msg.chat_id, event, msg.metadata)
if notification is not None: if notification is not None:
if conns or notification.deliver_offline: if conns or notification.deliver_offline:
kwargs: dict[str, Any] = ( kwargs: dict[str, Any] = (
+53 -2
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import time
from collections.abc import Mapping from collections.abc import Mapping
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Literal, NotRequired, TypeAlias, TypedDict 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 ( from nanobot.bus.outbound_events import (
ContextCompactionEvent, ContextCompactionEvent,
RecoveryStateEvent, RecoveryStateEvent,
RetryStatusEvent,
TurnEndEvent, TurnEndEvent,
) )
from nanobot.events import AgentEvent from nanobot.events import AgentEvent
@@ -29,6 +31,15 @@ class RecoveryStateWirePayload(_ChatWirePayload):
can_continue: NotRequired[bool] 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): class TurnEndWirePayload(_ChatWirePayload):
event: Literal["turn_end"] event: Literal["turn_end"]
latency_ms: NotRequired[int] latency_ms: NotRequired[int]
@@ -36,6 +47,11 @@ class TurnEndWirePayload(_ChatWirePayload):
usage: NotRequired[dict[str, int]] usage: NotRequired[dict[str, int]]
round_usages: NotRequired[list[dict[str, int]]] round_usages: NotRequired[list[dict[str, int]]]
context_window_tokens: NotRequired[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): class ContextCompactionWirePayload(_ChatWirePayload):
@@ -45,7 +61,7 @@ class ContextCompactionWirePayload(_ChatWirePayload):
WebUIWirePayload: TypeAlias = ( WebUIWirePayload: TypeAlias = (
ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
) )
WebUIWirePersistence: TypeAlias = Literal[ WebUIWirePersistence: TypeAlias = Literal[
"transient", "transient",
@@ -97,7 +113,9 @@ class NotificationProjection:
attach_turn_metadata: bool = False 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.""" """Keep notification serialization and persistence decisions at one boundary."""
if isinstance(event, ContextCompactionEvent): if isinstance(event, ContextCompactionEvent):
return NotificationProjection( return NotificationProjection(
@@ -106,11 +124,34 @@ def project_notification(chat_id: str, event: AgentEvent | None) -> Notification
deliver_offline=True, deliver_offline=True,
attach_turn_metadata=True, attach_turn_metadata=True,
) )
if isinstance(event, RetryStatusEvent):
return NotificationProjection(encode_retry_status(chat_id, event, metadata))
if isinstance(event, RecoveryStateEvent): if isinstance(event, RecoveryStateEvent):
return NotificationProjection(encode_recovery_state(chat_id, event)) return NotificationProjection(encode_recovery_state(chat_id, event))
return None 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( def encode_turn_end(
chat_id: str, chat_id: str,
event: TurnEndEvent, event: TurnEndEvent,
@@ -134,4 +175,14 @@ def encode_turn_end(
payload["round_usages"] = [item.to_turn_dict() for item in event.round_usages] payload["round_usages"] = [item.to_turn_dict() for item in event.round_usages]
if event.context_window_tokens is not None: if event.context_window_tokens is not None:
payload["context_window_tokens"] = int(event.context_window_tokens) 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 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":"resuming","recovery_id":"r1","attempts":0},
{"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r1","attempts":1,"reason":"tool_state_unknown","can_continue":false}, {"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"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":"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" 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 = export type NotificationEvent =
| ({ event: "retry_status"; chat_id: string; turn_id?: string } & RetryStatus)
| ({ event: "recovery_state"; chat_id: string; turn_id?: string } & RecoveryState) | ({ event: "recovery_state"; chat_id: string; turn_id?: string } & RecoveryState)
| { | {
event: "context_compaction" 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. */ /** Undefined means another protocol family; null means a malformed notification. */
export function decodeNotification(value: unknown): NotificationEvent | null | undefined { export function decodeNotification(value: unknown): NotificationEvent | null | undefined {
if (!isRecord(value)) return 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 (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") { if (value.event === "recovery_state") {
return isRecoveryState(value) ? value as unknown as NotificationEvent : null 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 && 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. */ /** A terminal history row must not regress when an older live event arrives. */
export function acceptsCompactionPhase( export function acceptsCompactionPhase(
current: ContextCompaction["phase"] | undefined, current: ContextCompaction["phase"] | undefined,
+55 -1
View File
@@ -10,9 +10,17 @@ import pytest
from nanobot.agent.context import TranscriptInput from nanobot.agent.context import TranscriptInput
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.tools.context import RequestContext from nanobot.agent.tools.context import RequestContext
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import StreamedResponseEvent from nanobot.bus.outbound_events import StreamedResponseEvent
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import AgentDefaults 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 ( from nanobot.runtime_context import (
RUNTIME_CONTEXT_INPUT_META, RUNTIME_CONTEXT_INPUT_META,
WEBUI_QUOTE_METADATA, WEBUI_QUOTE_METADATA,
@@ -45,6 +53,52 @@ def _make_loop(tmp_path):
return loop 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 @pytest.mark.asyncio
async def test_ephemeral_runner_enters_and_restores_turn_scopes(tmp_path): async def test_ephemeral_runner_enters_and_restores_turn_scopes(tmp_path):
loop = _make_loop(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.stop_reason == "error"
assert result.final_content == _ARREARAGE_ERROR_MESSAGE assert result.final_content == _ARREARAGE_ERROR_MESSAGE
assert result.failure_error_kind == "billing"
@pytest.mark.asyncio @pytest.mark.asyncio
+36 -5
View File
@@ -11,6 +11,7 @@ import pytest
from loguru import logger from loguru import logger
from nanobot.config.schema import ModelPresetConfig from nanobot.config.schema import ModelPresetConfig
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import ( from nanobot.providers.base import (
LLMProvider, LLMProvider,
LLMResponse, LLMResponse,
@@ -1086,12 +1087,14 @@ class TestRetryBeforeFailover:
) )
assert result.content == "fallback ok" assert result.content == "fallback ok"
events = [call.args[0] for call in observe.await_args_list] events = [call.args[0] for call in observe.await_args_list]
assert len(events) == 3 notices = [event for event in events if isinstance(event, RetryWaitEvent)]
assert all(isinstance(event, RetryWaitEvent) for event in events) assert len(notices) == 3
assert not any("giving up" in event.content for event in events) 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): 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")) primary = _FakeProvider("primary", _retryable_error("primary unavailable"))
fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable")) fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))
@@ -1105,11 +1108,15 @@ class TestRetryBeforeFailover:
provider_context=ProviderCallContext(events=EventSink(observe)), provider_context=ProviderCallContext(events=EventSink(observe)),
) )
assert result.finish_reason == "error" 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. # Two candidates, three waits each, for two chains, plus one chain wait.
assert len(notices) == 14 assert len(notices) == 14
assert sum("Persistent retry stopped" in text for text in notices) == 1 assert sum("Persistent retry stopped" in text for text in notices) == 1
assert not any("giving up" in text for text in notices) 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.asyncio
@pytest.mark.parametrize("retry_mode", ["standard", "persistent"]) @pytest.mark.parametrize("retry_mode", ["standard", "persistent"])
@@ -1140,17 +1147,34 @@ class TestRetryBeforeFailover:
fallback = _FakeProvider("fallback", _make_response("fallback ok")) fallback = _FakeProvider("fallback", _make_response("fallback ok"))
factory = MagicMock(return_value=fallback) factory = MagicMock(return_value=fallback)
retry_events = AsyncMock() retry_events = AsyncMock()
retry_statuses: list[RetryStatusEvent] = []
provider = FallbackProvider(primary, [_fallback("fallback-a")], factory) 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): with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await provider.chat_with_retry( result = await provider.chat_with_retry(
[{"role": "user", "content": "hi"}], [{"role": "user", "content": "hi"}],
on_retry_wait=retry_events, on_retry_wait=retry_events,
on_retry_status=_record_status,
) )
assert result.content == "fallback ok" assert result.content == "fallback ok"
assert len(primary.chat_calls) == 4 assert len(primary.chat_calls) == 4
assert not any("giving up" in call.args[0] for call in retry_events.await_args_list) 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")) factory.assert_called_once_with(_fallback("fallback-a"))
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -1159,17 +1183,22 @@ class TestRetryBeforeFailover:
fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable")) fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))
retry_events = AsyncMock() retry_events = AsyncMock()
terminal_event = AsyncMock() terminal_event = AsyncMock()
retry_statuses: list[RetryStatusEvent] = []
provider = FallbackProvider( provider = FallbackProvider(
primary, primary,
[_fallback("fallback-a")], [_fallback("fallback-a")],
MagicMock(return_value=fallback), 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): with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await provider.chat_with_retry( result = await provider.chat_with_retry(
[{"role": "user", "content": "hi"}], [{"role": "user", "content": "hi"}],
on_retry_wait=retry_events, on_retry_wait=retry_events,
on_retry_exhausted=terminal_event, on_retry_exhausted=terminal_event,
on_retry_status=_record_status,
) )
assert result.finish_reason == "error" assert result.finish_reason == "error"
@@ -1178,6 +1207,8 @@ class TestRetryBeforeFailover:
terminal_event.assert_awaited_once_with( terminal_event.assert_awaited_once_with(
"Model request failed after 4 attempts, giving up." "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.asyncio
@pytest.mark.parametrize("factory_fails", [False, True]) @pytest.mark.parametrize("factory_fails", [False, True])
+141 -1
View File
@@ -3,9 +3,12 @@ from pathlib import Path
import pytest import pytest
from nanobot.agent.turn_delivery import TurnDeliveryFactory 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.outbound_events import ContextCompactionEvent
from nanobot.bus.queue import MessageBus 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.manager import SessionManager
from nanobot.session.webui_turns import WebuiTurnRoutePolicy from nanobot.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.webui.metadata import ( 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) 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: def test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None:
factory = TurnDeliveryFactory( factory = TurnDeliveryFactory(
MessageBus(), MessageBus(),
+6
View File
@@ -205,6 +205,9 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
chat_id="direct", chat_id="direct",
session_key="cli:direct", session_key="cli:direct",
metadata={"source": "test"}, metadata={"source": "test"},
outcome="failed",
failure_kind="model",
failure_error_kind="billing",
) )
await publisher.turn_completed( await publisher.turn_completed(
channel="cli", channel="cli",
@@ -221,6 +224,9 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
assert first.runtime == "runtime" assert first.runtime == "runtime"
assert first.usage == first_round + second_round assert first.usage == first_round + second_round
assert first.round_usages == (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 isinstance(second, TurnCompleted)
assert second.latency_ms is None assert second.latency_ms is None
assert second.runtime is None assert second.runtime is None
+89 -1
View File
@@ -3,6 +3,7 @@ import copy
import pytest import pytest
from nanobot.events import RetryStatusEvent
from nanobot.providers.base import ( from nanobot.providers.base import (
RETRY_AFTER_BUFFER, RETRY_AFTER_BUFFER,
GenerationSettings, GenerationSettings,
@@ -64,6 +65,78 @@ async def test_chat_with_retry_retries_transient_error_then_succeeds(monkeypatch
assert delays == [1] 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 @pytest.mark.asyncio
async def test_chat_with_retry_does_not_retry_non_transient_error(monkeypatch) -> None: async def test_chat_with_retry_does_not_retry_non_transient_error(monkeypatch) -> None:
provider = ScriptedProvider([ 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 a", finish_reason="error"),
LLMResponse(content="429 rate limit b", finish_reason="error"), LLMResponse(content="429 rate limit b", finish_reason="error"),
LLMResponse(content="429 rate limit c", 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] = [] progress: list[str] = []
statuses: list[RetryStatusEvent] = []
async def _fake_sleep(delay: int) -> None: async def _fake_sleep(delay: int) -> None:
return 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: async def _progress(msg: str) -> None:
progress.append(msg) progress.append(msg)
async def _status(status: RetryStatusEvent) -> None:
statuses.append(status)
monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep) monkeypatch.setattr("nanobot.providers.base.asyncio.sleep", _fake_sleep)
response = await provider.chat_with_retry( response = await provider.chat_with_retry(
messages=[{"role": "user", "content": "hello"}], messages=[{"role": "user", "content": "hello"}],
on_retry_wait=_progress, on_retry_wait=_progress,
on_retry_status=_status,
) )
assert response.content == "503 final server error" assert response.content == "503 final server error"
assert progress[-1] == "Model request failed after 4 attempts, giving up." 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 @pytest.mark.asyncio
+44 -1
View File
@@ -5,8 +5,15 @@ from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from nanobot.agent.tools.context import RequestContext, request_context 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.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.queue import MessageBus
from nanobot.bus.runtime_events import ( from nanobot.bus.runtime_events import (
RuntimeEventContext, RuntimeEventContext,
@@ -242,6 +249,42 @@ async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path)
assert outbound.event.model_preset == "Codex" 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 @pytest.mark.asyncio
async def test_session_input_is_projected_by_the_webui_coordinator( async def test_session_input_is_projected_by_the_webui_coordinator(
tmp_path, tmp_path,
+10 -5
View File
@@ -4,19 +4,24 @@ import json
import tarfile import tarfile
from pathlib import Path 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 from nanobot.webui.outbound_wire import project_notification
ROOT = Path(__file__).resolve().parents[2] 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()) fixtures = json.loads((ROOT / "packages/client-events/fixtures.json").read_text())
for expected in fixtures: for expected in fixtures:
fields = {key: value for key, value in expected.items() if key not in {"event", "chat_id"}} fields = {key: value for key, value in expected.items() if key not in {"event", "chat_id"}}
event_type = ( event_type = {
ContextCompactionEvent if expected["event"] == "context_compaction" else RecoveryStateEvent "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)) projection = project_notification(expected["chat_id"], event_type(**fields))
assert projection is not None assert projection is not None
assert projection.payload == expected assert projection.payload == expected
+43
View File
@@ -1,8 +1,11 @@
from __future__ import annotations from __future__ import annotations
import pytest
from nanobot.bus.outbound_events import ( from nanobot.bus.outbound_events import (
ContextCompactionEvent, ContextCompactionEvent,
RecoveryStateEvent, RecoveryStateEvent,
RetryStatusEvent,
TurnEndEvent, TurnEndEvent,
) )
from nanobot.providers.base import LLMUsage 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 ( from nanobot.webui.outbound_wire import (
encode_context_compaction, encode_context_compaction,
encode_recovery_state, encode_recovery_state,
encode_retry_status,
encode_turn_end, 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: def test_encode_turn_end_omits_absent_fields_and_private_metadata() -> None:
payload = encode_turn_end( payload = encode_turn_end(
"chat-1", "chat-1",
@@ -100,6 +133,11 @@ def test_encode_turn_end_projects_complete_wire_contract() -> None:
usage=usage, usage=usage,
round_usages=(usage,), round_usages=(usage,),
context_window_tokens=128_000, 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"}, {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(), "usage": usage.to_turn_dict(),
"round_usages": [usage.to_turn_dict()], "round_usages": [usage.to_turn_dict()],
"context_window_tokens": 128_000, "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, type TestRendererSetup,
} from "@opentui/core/testing" } from "@opentui/core/testing"
import { NanobotTui, sessionExitMessage, type AppOptions } from "./app" import {
NanobotTui,
sessionExitMessage,
terminalModelFailureLine,
type AppOptions,
} from "./app"
import type { import type {
MessageOptions, MessageOptions,
RecoveryState, 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 { function contrastRatio(foreground: string, background: string): number {
const luminance = (color: string) => { const luminance = (color: string) => {
const channel = (offset: number) => { const channel = (offset: number) => {
@@ -2602,6 +2617,77 @@ describe("NanobotTui layout", () => {
expect(ui.composer.placeholder).toBe("Ask nanobot anything") 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 () => { test("folds long tool traces without discarding their details", async () => {
setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" }) setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })
const app = mount(setup) const app = mount(setup)
+86 -2
View File
@@ -39,6 +39,7 @@ import {
type MentionCandidate, type MentionCandidate,
type MessageOptions, type MessageOptions,
type RecoveryState, type RecoveryState,
type RetryStatus,
type SkillCandidate, type SkillCandidate,
type SlashCommand, type SlashCommand,
type SessionSummary, type SessionSummary,
@@ -402,6 +403,45 @@ function connectionStatusText(
return "Session ended" 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 { export function sessionExitMessage(chatId: string): string {
const sessionId = `websocket:${chatId}` const sessionId = `websocket:${chatId}`
return `Resume with: nanobot agent --session ${sessionId}\n` return `Resume with: nanobot agent --session ${sessionId}\n`
@@ -457,6 +497,7 @@ export class NanobotTui {
private activeTurn = false private activeTurn = false
private activeTurnId: string | null = null private activeTurnId: string | null = null
private activeLabel = "Thinking" private activeLabel = "Thinking"
private retryStatus: RenderedRetryStatus | null = null
private activeStartedAt = 0 private activeStartedAt = 0
private finalMessage = "" private finalMessage = ""
private turnHadAnswer = false private turnHadAnswer = false
@@ -999,6 +1040,7 @@ export class NanobotTui {
this.finalMessage = "" this.finalMessage = ""
this.turnHadAnswer = false this.turnHadAnswer = false
this.activeLabel = "Thinking" this.activeLabel = "Thinking"
this.retryStatus = null
this.currentFileEdits = [] this.currentFileEdits = []
this.setActive(true, startedAt) this.setActive(true, startedAt)
} }
@@ -1082,6 +1124,7 @@ export class NanobotTui {
return return
} }
case "delta": case "delta":
this.retryStatus = null
this.setActive(true) this.setActive(true)
this.activeLabel = "Writing" this.activeLabel = "Writing"
this.turnHadAnswer = true this.turnHadAnswer = true
@@ -1102,6 +1145,7 @@ export class NanobotTui {
} }
} }
if (event.kind) { if (event.kind) {
this.retryStatus = null
this.activeLabel = event.kind === "tool_hint" ? "Working" : "Thinking" this.activeLabel = event.kind === "tool_hint" ? "Working" : "Thinking"
this.transcript.progress(event.text, event.tool_events) this.transcript.progress(event.text, event.tool_events)
this.setActive(true) this.setActive(true)
@@ -1110,6 +1154,7 @@ export class NanobotTui {
} }
return return
case "file_edit": case "file_edit":
this.retryStatus = null
this.activeLabel = "Editing" this.activeLabel = "Editing"
this.currentFileEdits = mergeFileEdits(this.currentFileEdits, event.edits) this.currentFileEdits = mergeFileEdits(this.currentFileEdits, event.edits)
if (this.diffViewer.visible) this.diffViewer.update(this.currentFileEdits) if (this.diffViewer.visible) this.diffViewer.update(this.currentFileEdits)
@@ -1117,6 +1162,7 @@ export class NanobotTui {
this.setActive(true) this.setActive(true)
return return
case "reasoning_delta": case "reasoning_delta":
this.retryStatus = null
this.activeLabel = "Thinking" this.activeLabel = "Thinking"
this.setActive(true) this.setActive(true)
return return
@@ -1130,19 +1176,50 @@ export class NanobotTui {
this.transcript.finishStream(event.text || "") this.transcript.finishStream(event.text || "")
} }
return 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": case "turn_end":
if (event.turn_id && this.activeTurnId && event.turn_id !== this.activeTurnId) return if (event.turn_id && this.activeTurnId && event.turn_id !== this.activeTurnId) return
if (event.turn_id) { if (event.turn_id) {
this.commandTurns.delete(event.turn_id) this.commandTurns.delete(event.turn_id)
this.modelCommandTurns.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() this.transcript.finishActivity()
if (this.currentFileEdits.length) this.lastFileEdits = this.currentFileEdits if (this.currentFileEdits.length) this.lastFileEdits = this.currentFileEdits
this.currentFileEdits = [] this.currentFileEdits = []
if (this.diffViewer.visible) this.diffViewer.update(this.lastFileEdits) if (this.diffViewer.visible) this.diffViewer.update(this.lastFileEdits)
this.finalMessage = "" this.finalMessage = ""
this.turnHadAnswer = false this.turnHadAnswer = false
this.retryStatus = null
this.activeTurnId = null this.activeTurnId = null
if (event.usage) this.lastUsage = event.usage if (event.usage) this.lastUsage = event.usage
if (typeof event.context_window_tokens === "number") { 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 // A synthetic/rehydrated turn may already be idle, in which case
// setActive(false) intentionally does not repaint the footer. // setActive(false) intentionally does not repaint the footer.
this.updateMeta() this.updateMeta()
this.readyDetail = typeof event.latency_ms === "number" this.readyDetail = !failed && typeof event.latency_ms === "number"
? `${(event.latency_ms / 1000).toFixed(1)}s` ? `${(event.latency_ms / 1000).toFixed(1)}s`
: "" : ""
this.status.content = this.readyStatus() this.status.content = this.readyStatus()
@@ -1450,11 +1527,18 @@ export class NanobotTui {
} }
if (this.shimmerTimer) clearInterval(this.shimmerTimer) if (this.shimmerTimer) clearInterval(this.shimmerTimer)
this.shimmerTimer = null this.shimmerTimer = null
this.retryStatus = null
this.status.content = this.readyStatus() this.status.content = this.readyStatus()
} }
private renderActiveStatus(): void { private renderActiveStatus(): void {
if (this.sessionLoading || this.sessionMenu.visible) return 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 elapsed = formatElapsed(Date.now() - this.activeStartedAt)
const navigation = this.transcriptNavigation.awayFromBottom ? " · Ctrl+End latest" : "" const navigation = this.transcriptNavigation.awayFromBottom ? " · Ctrl+End latest" : ""
const queued = this.promptQueue.length ? ` · ${this.promptQueue.length} queued` : "" 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 () => { test("reattaches the same generated chat after a transient disconnect", async () => {
const original = globalThis.WebSocket const original = globalThis.WebSocket
const sockets: FakeSocket[] = [] const sockets: FakeSocket[] = []
+17 -2
View File
@@ -1,6 +1,6 @@
import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications" import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications"
import type { ContextCompaction, NotificationEvent, RecoveryState } 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 = export type ConnectionStatus =
| "starting" | "starting"
@@ -136,6 +136,11 @@ export type InboundEvent =
usage?: TokenUsage usage?: TokenUsage
context_window_tokens?: number context_window_tokens?: number
goal_state?: Record<string, unknown> 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" event: "goal_status"
@@ -347,6 +352,7 @@ const CHAT_EVENTS = new Set([
"stream_end", "stream_end",
"reasoning_delta", "reasoning_delta",
"reasoning_end", "reasoning_end",
"retry_status",
"turn_end", "turn_end",
"goal_status", "goal_status",
"goal_state", "goal_state",
@@ -526,7 +532,16 @@ function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {
&& (!optional(record.latency_ms, "number") && (!optional(record.latency_ms, "number")
|| !optional(record.context_window_tokens, "number") || !optional(record.context_window_tokens, "number")
|| (record.usage !== undefined && !isTokenUsage(record.usage)) || (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 ) return null
if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null
if (name === "goal_state" && !isRecord(record.goal_state)) 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 { logoFallbackUrls } from "@/lib/provider-brand";
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces"; import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
import { cn } from "@/lib/utils"; 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; const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;
@@ -143,6 +150,7 @@ interface AgentActivityClusterProps {
turnLatencyMs?: number; turnLatencyMs?: number;
/** User turn start timestamp for live activity before the first trace/reasoning row. */ /** User turn start timestamp for live activity before the first trace/reasoning row. */
startedAtMs?: number; startedAtMs?: number;
retryStatus?: RetryStatus | null;
cliApps?: CliAppInfo[]; cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[]; mcpPresets?: McpPresetInfo[];
onOpenFilePreview?: (path: string) => void; onOpenFilePreview?: (path: string) => void;
@@ -158,6 +166,7 @@ export function AgentActivityCluster({
hasBodyBelow, hasBodyBelow,
turnLatencyMs, turnLatencyMs,
startedAtMs, startedAtMs,
retryStatus = null,
cliApps = [], cliApps = [],
mcpPresets = [], mcpPresets = [],
onOpenFilePreview, onOpenFilePreview,
@@ -219,7 +228,34 @@ export function AgentActivityCluster({
startedAtMs, startedAtMs,
); );
const activityDuration = formatActivityDuration(durationMs); 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", { ? t("message.activityWorkingFor", {
duration: activityDuration, duration: activityDuration,
defaultValue: "Working for {{duration}}", defaultValue: "Working for {{duration}}",
@@ -1,7 +1,9 @@
import { AlertTriangle, X } from "lucide-react"; import { AlertTriangle, X } from "lucide-react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import type { StreamError } from "@/lib/nanobot-client"; import type { StreamError } from "@/lib/nanobot-client";
@@ -53,7 +55,7 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
function resolveCopy( function resolveCopy(
error: StreamError, error: StreamError,
t: (key: string) => string, t: TFunction,
): { title: string; body: string } { ): { title: string; body: string } {
switch (error.kind) { switch (error.kind) {
case "message_too_big": case "message_too_big":
@@ -71,6 +73,8 @@ function resolveCopy(
title: t("errors.turnRejected.title"), title: t("errors.turnRejected.title"),
body: t("errors.turnRejected.body"), body: t("errors.turnRejected.body"),
}; };
case "model_request_failed":
return resolveModelRequestFailureCopy(error, t);
default: { default: {
// Exhaustiveness guard: if a new StreamError kind is added, TS will // Exhaustiveness guard: if a new StreamError kind is added, TS will
// complain here until we add a corresponding i18n branch. // 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 { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction"; import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline"; 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 { interface ThreadMessagesProps {
messages: UIMessage[]; messages: UIMessage[];
@@ -14,6 +14,7 @@ interface ThreadMessagesProps {
activeTurnId?: string | null; activeTurnId?: string | null;
/** Optimistic or canonical active-turn start, in unix seconds. */ /** Optimistic or canonical active-turn start, in unix seconds. */
runStartedAt?: number | null; runStartedAt?: number | null;
retryStatus?: RetryStatus | null;
hiddenUserMessageCount?: number; hiddenUserMessageCount?: number;
cliApps?: CliAppInfo[]; cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[]; mcpPresets?: McpPresetInfo[];
@@ -63,6 +64,7 @@ export function ThreadMessages({
isStreaming = false, isStreaming = false,
activeTurnId = null, activeTurnId = null,
runStartedAt = null, runStartedAt = null,
retryStatus = null,
hiddenUserMessageCount = 0, hiddenUserMessageCount = 0,
cliApps = [], cliApps = [],
mcpPresets = [], mcpPresets = [],
@@ -97,7 +99,7 @@ export function ThreadMessages({
isStreaming isStreaming
&& liveActivityClusterIndices.size === 0 && liveActivityClusterIndices.size === 0
&& pendingTurn !== null && pendingTurn !== null
&& !pendingTurn.hasVisibleOutput && (retryStatus !== null || !pendingTurn.hasVisibleOutput)
) ? pendingTurn : null; ) ? pendingTurn : null;
const currentTurnStartIndex = isStreaming const currentTurnStartIndex = isStreaming
? activeTurnStartIndex(units, activeTurnId) ? activeTurnStartIndex(units, activeTurnId)
@@ -161,6 +163,11 @@ export function ThreadMessages({
: index > currentTurnStartIndex : index > currentTurnStartIndex
) )
} }
retryStatus={
unit.type === "activity" && liveActivityClusterIndices.has(index)
? retryStatus
: null
}
forkIndex={forkIndex} forkIndex={forkIndex}
showForkBoundary={index === forkBoundaryAfterUnitIndex} showForkBoundary={index === forkBoundaryAfterUnitIndex}
forkBoundaryLabel={t("thread.forkedFromHistory")} forkBoundaryLabel={t("thread.forkedFromHistory")}
@@ -179,6 +186,7 @@ export function ThreadMessages({
messages={[]} messages={[]}
isTurnStreaming isTurnStreaming
hasBodyBelow={false} hasBodyBelow={false}
retryStatus={retryStatus}
startedAtMs={ startedAtMs={
runStartedAt != null runStartedAt != null
? runStartedAt * 1000 ? runStartedAt * 1000
@@ -243,6 +251,7 @@ interface ThreadDisplayUnitProps {
hasBodyBelow: boolean; hasBodyBelow: boolean;
deferOffscreenRender: boolean; deferOffscreenRender: boolean;
isTurnStreaming: boolean; isTurnStreaming: boolean;
retryStatus: RetryStatus | null;
forkIndex?: number; forkIndex?: number;
showForkBoundary: boolean; showForkBoundary: boolean;
forkBoundaryLabel: string; forkBoundaryLabel: string;
@@ -262,6 +271,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
hasBodyBelow, hasBodyBelow,
deferOffscreenRender, deferOffscreenRender,
isTurnStreaming, isTurnStreaming,
retryStatus,
forkIndex, forkIndex,
showForkBoundary, showForkBoundary,
forkBoundaryLabel, forkBoundaryLabel,
@@ -293,6 +303,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
<AgentActivityCluster <AgentActivityCluster
messages={unit.messages} messages={unit.messages}
isTurnStreaming={isTurnStreaming} isTurnStreaming={isTurnStreaming}
retryStatus={retryStatus}
hasBodyBelow={hasBodyBelow} hasBodyBelow={hasBodyBelow}
turnLatencyMs={unit.turnLatencyMs} turnLatencyMs={unit.turnLatencyMs}
startedAtMs={unit.startedAtMs} startedAtMs={unit.startedAtMs}
@@ -329,6 +340,7 @@ function threadDisplayUnitPropsEqual(
&& previous.hasBodyBelow === next.hasBodyBelow && previous.hasBodyBelow === next.hasBodyBelow
&& previous.deferOffscreenRender === next.deferOffscreenRender && previous.deferOffscreenRender === next.deferOffscreenRender
&& previous.isTurnStreaming === next.isTurnStreaming && previous.isTurnStreaming === next.isTurnStreaming
&& previous.retryStatus === next.retryStatus
&& previous.forkIndex === next.forkIndex && previous.forkIndex === next.forkIndex
&& previous.showForkBoundary === next.showForkBoundary && previous.showForkBoundary === next.showForkBoundary
&& previous.forkBoundaryLabel === next.forkBoundaryLabel && previous.forkBoundaryLabel === next.forkBoundaryLabel
@@ -820,6 +820,7 @@ export function ThreadShell({
messagesReady, messagesReady,
isStreaming, isStreaming,
runStartedAt, runStartedAt,
retryStatus,
goalState, goalState,
recoveryState, recoveryState,
continueRecovery, continueRecovery,
@@ -1726,6 +1727,7 @@ export function ThreadShell({
temporary={temporary} temporary={temporary}
isStreaming={turnActive} isStreaming={turnActive}
runStartedAt={currentRunStartedAt} runStartedAt={currentRunStartedAt}
retryStatus={retryStatus}
emptyState={emptyState} emptyState={emptyState}
composer={composerPortalTarget === undefined ? composer : null} composer={composerPortalTarget === undefined ? composer : null}
activeTurnId={viewportTurnId} activeTurnId={viewportTurnId}
@@ -26,7 +26,7 @@ import {
promptTop, promptTop,
} from "@/components/thread/promptNavigation"; } from "@/components/thread/promptNavigation";
import { cn } from "@/lib/utils"; 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 { export interface ThreadViewportHandle {
jumpToUserPrompt: (promptId: string) => void; jumpToUserPrompt: (promptId: string) => void;
@@ -39,6 +39,7 @@ interface ThreadViewportProps {
isStreaming: boolean; isStreaming: boolean;
/** Optimistic or canonical start time for the active turn, in unix seconds. */ /** Optimistic or canonical start time for the active turn, in unix seconds. */
runStartedAt?: number | null; runStartedAt?: number | null;
retryStatus?: RetryStatus | null;
composer?: ReactNode; composer?: ReactNode;
emptyState?: ReactNode; emptyState?: ReactNode;
scrollToBottomSignal?: number; scrollToBottomSignal?: number;
@@ -221,6 +222,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
temporary = false, temporary = false,
isStreaming, isStreaming,
runStartedAt = null, runStartedAt = null,
retryStatus = null,
composer, composer,
emptyState, emptyState,
scrollToBottomSignal = 0, scrollToBottomSignal = 0,
@@ -878,6 +880,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
isStreaming={isStreaming} isStreaming={isStreaming}
activeTurnId={activeTurnId} activeTurnId={activeTurnId}
runStartedAt={runStartedAt} runStartedAt={runStartedAt}
retryStatus={retryStatus}
hiddenUserMessageCount={hiddenUserMessageCount} hiddenUserMessageCount={hiddenUserMessageCount}
cliApps={cliApps} cliApps={cliApps}
mcpPresets={mcpPresets} mcpPresets={mcpPresets}
+78 -1
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { useClient } from "@/providers/ClientProvider"; import { useClient } from "@/providers/ClientProvider";
import { toMediaAttachment } from "@/lib/media"; import { toMediaAttachment } from "@/lib/media";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
import { import {
mergeToolProgressEvents, mergeToolProgressEvents,
mergeToolProgressTraceLines, mergeToolProgressTraceLines,
@@ -39,6 +40,7 @@ import type {
GoalStateWsPayload, GoalStateWsPayload,
MessageDeliveryStatus, MessageDeliveryStatus,
RecoveryState, RecoveryState,
RetryStatus,
UIMediaAttachment, UIMediaAttachment,
UIMessage, UIMessage,
WorkspaceScopePayload, WorkspaceScopePayload,
@@ -247,6 +249,8 @@ export function useNanobotStream(
isStreaming: boolean; isStreaming: boolean;
/** Unix epoch seconds when the current user turn started (WebSocket ``goal_status``). */ /** Unix epoch seconds when the current user turn started (WebSocket ``goal_status``). */
runStartedAt: number | null; runStartedAt: number | null;
/** Transient model retry state for the active turn. */
retryStatus: RetryStatus | null;
/** Latest sustained goal for this ``chatId`` (``goal_state`` WS events). */ /** Latest sustained goal for this ``chatId`` (``goal_state`` WS events). */
goalState: GoalStateWsPayload | undefined; goalState: GoalStateWsPayload | undefined;
recoveryState: RecoveryState | null; recoveryState: RecoveryState | null;
@@ -281,6 +285,7 @@ export function useNanobotStream(
); );
/** Unix epoch seconds when the current user turn started; cleared on ``idle``. */ /** Unix epoch seconds when the current user turn started; cleared on ``idle``. */
const [runStartedAt, setRunStartedAt] = useState<number | null>(initialRunStartedAt); const [runStartedAt, setRunStartedAt] = useState<number | null>(initialRunStartedAt);
const [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined); const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null); const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
const [streamError, setStreamError] = useState<StreamError | 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. // still be shown in the mounted thread, but cannot roll back any turn.
if (!chatId || (err.chatId && err.chatId !== chatId)) return; if (!chatId || (err.chatId && err.chatId !== chatId)) return;
setStreamError(err); setStreamError(err);
if (err.kind === "model_request_failed") return;
if (!err.turnId) return; if (!err.turnId) return;
const rejectedTurnId = err.turnId; const rejectedTurnId = err.turnId;
@@ -680,6 +686,7 @@ export function useNanobotStream(
); );
setStreamError(null); setStreamError(null);
setRunStartedAt(restoredRunStartedAt); setRunStartedAt(restoredRunStartedAt);
setRetryStatus(null);
setGoalState(chatId ? client.getGoalState(chatId) : undefined); setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null); setRecoveryState(null);
buffer.current = null; buffer.current = null;
@@ -802,6 +809,13 @@ export function useNanobotStream(
}); });
return; 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 (ev.event === "delta") {
if (suppressStreamUntilTurnEndRef.current) return; if (suppressStreamUntilTurnEndRef.current) return;
const chunk = typeof ev.text === "string" ? ev.text : ""; const chunk = typeof ev.text === "string" ? ev.text : "";
@@ -875,11 +889,42 @@ export function useNanobotStream(
if (ev.event === "goal_status") { if (ev.event === "goal_status") {
if (ev.status === "running" && typeof ev.started_at === "number") { if (ev.status === "running" && typeof ev.started_at === "number") {
setStreamError(null);
setRunStartedAt(ev.started_at); setRunStartedAt(ev.started_at);
setIsStreaming(true); setIsStreaming(true);
} else { } else {
setRunStartedAt(null); setRunStartedAt(null);
setIsStreaming(false); 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; return;
} }
@@ -890,9 +935,29 @@ export function useNanobotStream(
setGoalState(ev.goal_state); setGoalState(ev.goal_state);
} }
setRunStartedAt(null); setRunStartedAt(null);
setRetryStatus(null);
// Definitive signal that the turn is fully complete, so stop the // Definitive signal that the turn is fully complete, so stop the
// loading indicator immediately. // loading indicator immediately.
setIsStreaming(false); 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(); const completedAt = Date.now();
setMessages((prev) => { setMessages((prev) => {
let finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); let finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
@@ -920,7 +985,13 @@ export function useNanobotStream(
return finalized; return finalized;
}); });
suppressStreamUntilTurnEndRef.current = false; 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?.(); onTurnEnd?.();
return; return;
} }
@@ -945,6 +1016,7 @@ export function useNanobotStream(
|| ev.status === "recovered" || ev.status === "recovered"
|| ev.status === "failed" || ev.status === "failed"
) { ) {
setRetryStatus(null);
// Recovery is an explicit boundary. The interrupted turn is no // Recovery is an explicit boundary. The interrupted turn is no
// longer running, so do not let the stale start time keep the // longer running, so do not let the stale start time keep the
// activity clock (or composer stop state) alive underneath the // activity clock (or composer stop state) alive underneath the
@@ -1211,6 +1283,7 @@ export function useNanobotStream(
// them via ``media`` paths. // them via ``media`` paths.
if (!hasAttachments && !content.trim()) return null; if (!hasAttachments && !content.trim()) return null;
setStreamError(null);
const sideChannel = options?.sideChannel === true; const sideChannel = options?.sideChannel === true;
const finalizeActiveTurn = options?.finalizeActiveTurn === true; const finalizeActiveTurn = options?.finalizeActiveTurn === true;
const continueActiveTurn = options?.continueActiveTurn === true; const continueActiveTurn = options?.continueActiveTurn === true;
@@ -1220,6 +1293,7 @@ export function useNanobotStream(
flushPendingStreamEvents(); flushPendingStreamEvents();
if (finalizeActiveTurn) { if (finalizeActiveTurn) {
setIsStreaming(false); setIsStreaming(false);
setRetryStatus(null);
} }
const turnId = crypto.randomUUID(); const turnId = crypto.randomUUID();
const userMessageId = crypto.randomUUID(); const userMessageId = crypto.randomUUID();
@@ -1280,6 +1354,7 @@ export function useNanobotStream(
if (!chatId) return; if (!chatId) return;
flushPendingStreamEvents(); flushPendingStreamEvents();
setIsStreaming(false); setIsStreaming(false);
setRetryStatus(null);
setMessages((prev) => { setMessages((prev) => {
buffer.current = null; buffer.current = null;
activeAssistantRef.current = null; activeAssistantRef.current = null;
@@ -1301,6 +1376,7 @@ export function useNanobotStream(
clearActivitySegment(); clearActivitySegment();
suppressStreamUntilTurnEndRef.current = false; suppressStreamUntilTurnEndRef.current = false;
setRunStartedAt(null); setRunStartedAt(null);
setRetryStatus(null);
setIsStreaming(false); setIsStreaming(false);
}, [clearActivitySegment, clearPendingStreamWork]); }, [clearActivitySegment, clearPendingStreamWork]);
@@ -1332,6 +1408,7 @@ export function useNanobotStream(
messagesReady: messageOwnerChatId === chatId, messagesReady: messageOwnerChatId === chatId,
isStreaming, isStreaming,
runStartedAt, runStartedAt,
retryStatus,
goalState, goalState,
recoveryState, recoveryState,
continueRecovery, continueRecovery,
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "Working for {{duration}}", "activityWorkingFor": "Working for {{duration}}",
"activityWorked": "Worked", "activityWorked": "Worked",
"activityWorkedFor": "Worked for {{duration}}", "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}}", "cliActivityRunningOne": "Using {{name}}",
"cliActivityRanOne": "Used {{name}}", "cliActivityRanOne": "Used {{name}}",
"cliActivityFailedOne": "{{name}} failed", "cliActivityFailedOne": "{{name}} failed",
@@ -1546,6 +1553,17 @@
"turnRejected": { "turnRejected": {
"title": "Message was not sent", "title": "Message was not sent",
"body": "The gateway rejected this message. Review its text or attachments, then try again." "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": { "workspace": {
+18
View File
@@ -1435,6 +1435,13 @@
"activityWorkingFor": "Trabajando durante {{duration}}", "activityWorkingFor": "Trabajando durante {{duration}}",
"activityWorked": "Trabajo completado", "activityWorked": "Trabajo completado",
"activityWorkedFor": "Trabajó durante {{duration}}", "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}}", "cliActivityRunningOne": "Usando {{name}}",
"cliActivityRanOne": "Usó {{name}}", "cliActivityRanOne": "Usó {{name}}",
"cliActivityFailedOne": "Falló {{name}}", "cliActivityFailedOne": "Falló {{name}}",
@@ -1533,6 +1540,17 @@
"turnRejected": { "turnRejected": {
"title": "El mensaje no se envió", "title": "El mensaje no se envió",
"body": "El gateway rechazó este mensaje. Revisa el texto o los archivos adjuntos e inténtalo de nuevo." "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": { "workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Travail en cours depuis {{duration}}", "activityWorkingFor": "Travail en cours depuis {{duration}}",
"activityWorked": "Travail terminé", "activityWorked": "Travail terminé",
"activityWorkedFor": "Travail terminé en {{duration}}", "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}}", "cliActivityRunningOne": "Utilisation de {{name}}",
"cliActivityRanOne": "{{name}} utilisé", "cliActivityRanOne": "{{name}} utilisé",
"cliActivityFailedOne": "Échec de {{name}}", "cliActivityFailedOne": "Échec de {{name}}",
@@ -1532,6 +1539,17 @@
"turnRejected": { "turnRejected": {
"title": "Le message n’a pas été envoyé", "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." "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": { "workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Memproses selama {{duration}}", "activityWorkingFor": "Memproses selama {{duration}}",
"activityWorked": "Selesai memproses", "activityWorked": "Selesai memproses",
"activityWorkedFor": "Diproses selama {{duration}}", "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}}", "cliActivityRunningOne": "Menggunakan {{name}}",
"cliActivityRanOne": "Menggunakan {{name}} selesai", "cliActivityRanOne": "Menggunakan {{name}} selesai",
"cliActivityFailedOne": "{{name}} gagal", "cliActivityFailedOne": "{{name}} gagal",
@@ -1532,6 +1539,17 @@
"turnRejected": { "turnRejected": {
"title": "Pesan tidak terkirim", "title": "Pesan tidak terkirim",
"body": "Gateway menolak pesan ini. Periksa teks atau lampiran, lalu coba lagi." "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": { "workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "{{duration}}作業中", "activityWorkingFor": "{{duration}}作業中",
"activityWorked": "作業しました", "activityWorked": "作業しました",
"activityWorkedFor": "{{duration}}作業しました", "activityWorkedFor": "{{duration}}作業しました",
"retryConnection": "接続に失敗しました",
"retryTimeout": "モデルがタイムアウトしました",
"retryRateLimit": "リクエスト制限に達しました",
"retryServer": "モデルを利用できません",
"retryUnknown": "モデルリクエストに失敗しました",
"retryWaiting": "{{error}} · {{seconds}}秒後に再試行 · 試行 {{attempt}}",
"retryExhausted": "{{error}} · ターンを終了します",
"cliActivityRunningOne": "{{name}} を使用中", "cliActivityRunningOne": "{{name}} を使用中",
"cliActivityRanOne": "{{name}} を使用しました", "cliActivityRanOne": "{{name}} を使用しました",
"cliActivityFailedOne": "{{name}} が失敗しました", "cliActivityFailedOne": "{{name}} が失敗しました",
@@ -1532,6 +1539,17 @@
"turnRejected": { "turnRejected": {
"title": "メッセージは送信されませんでした", "title": "メッセージは送信されませんでした",
"body": "ゲートウェイがこのメッセージを拒否しました。本文または添付ファイルを確認して、もう一度お試しください。" "body": "ゲートウェイがこのメッセージを拒否しました。本文または添付ファイルを確認して、もう一度お試しください。"
},
"modelRequestFailed": {
"billingTitle": "モデルプロバイダーの利用枠を使用できません",
"billingBody": "プロバイダーアカウントにクレジットを追加するか、請求状況を確認してから、もう一度お試しください。",
"connectionTitle": "モデルプロバイダーに接続できません",
"timeoutTitle": "モデルプロバイダーへのリクエストがタイムアウトしました",
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
"bodyWithAttempt": "{{attempts}} 回目の試行でもリクエストに失敗したため、再試行を停止しました。プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。",
"body": "プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。"
} }
}, },
"workspace": { "workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "{{duration}} 동안 작업 중", "activityWorkingFor": "{{duration}} 동안 작업 중",
"activityWorked": "작업함", "activityWorked": "작업함",
"activityWorkedFor": "{{duration}} 동안 작업함", "activityWorkedFor": "{{duration}} 동안 작업함",
"retryConnection": "연결 실패",
"retryTimeout": "모델 응답 시간 초과",
"retryRateLimit": "요청 한도 초과",
"retryServer": "모델을 사용할 수 없음",
"retryUnknown": "모델 요청 실패",
"retryWaiting": "{{error}} · {{seconds}}초 후 재시도 · 시도 {{attempt}}",
"retryExhausted": "{{error}} · 턴 종료 중",
"cliActivityRunningOne": "{{name}} 사용 중", "cliActivityRunningOne": "{{name}} 사용 중",
"cliActivityRanOne": "{{name}} 사용함", "cliActivityRanOne": "{{name}} 사용함",
"cliActivityFailedOne": "{{name}} 실패", "cliActivityFailedOne": "{{name}} 실패",
@@ -1532,6 +1539,17 @@
"turnRejected": { "turnRejected": {
"title": "메시지가 전송되지 않았습니다", "title": "메시지가 전송되지 않았습니다",
"body": "게이트웨이가 이 메시지를 거부했습니다. 텍스트나 첨부 파일을 확인한 후 다시 시도하세요." "body": "게이트웨이가 이 메시지를 거부했습니다. 텍스트나 첨부 파일을 확인한 후 다시 시도하세요."
},
"modelRequestFailed": {
"billingTitle": "모델 제공업체 할당량을 사용할 수 없음",
"billingBody": "제공업체 계정에 크레딧을 추가하거나 결제 상태를 확인한 후 다시 시도하세요.",
"connectionTitle": "모델 제공업체에 연결할 수 없음",
"timeoutTitle": "모델 제공업체 요청 시간 초과",
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
"serverTitle": "모델 제공업체 서비스 오류",
"unknownTitle": "모델 제공업체 요청 실패",
"bodyWithAttempt": "{{attempts}}번째 시도에서도 요청이 실패하여 재시도를 중지했습니다. 제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요.",
"body": "제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요."
} }
}, },
"workspace": { "workspace": {
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "Trabalhando por {{duration}}", "activityWorkingFor": "Trabalhando por {{duration}}",
"activityWorked": "Trabalhou", "activityWorked": "Trabalhou",
"activityWorkedFor": "Trabalhou por {{duration}}", "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}}", "cliActivityRunningOne": "Usando {{name}}",
"cliActivityRanOne": "Usou {{name}}", "cliActivityRanOne": "Usou {{name}}",
"cliActivityFailedOne": "Falhou em {{name}}", "cliActivityFailedOne": "Falhou em {{name}}",
@@ -1546,6 +1553,17 @@
"turnRejected": { "turnRejected": {
"title": "A mensagem não foi enviada", "title": "A mensagem não foi enviada",
"body": "O gateway rejeitou esta mensagem. Revise o texto ou os anexos e tente novamente." "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": { "workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Đang xử lý trong {{duration}}", "activityWorkingFor": "Đang xử lý trong {{duration}}",
"activityWorked": "Đã xử lý", "activityWorked": "Đã xử lý",
"activityWorkedFor": "Đã xử lý trong {{duration}}", "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}}", "cliActivityRunningOne": "Đang dùng {{name}}",
"cliActivityRanOne": "Đã dùng {{name}}", "cliActivityRanOne": "Đã dùng {{name}}",
"cliActivityFailedOne": "{{name}} thất bại", "cliActivityFailedOne": "{{name}} thất bại",
@@ -1532,6 +1539,17 @@
"turnRejected": { "turnRejected": {
"title": "Tin nhắn chưa được gửi", "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." "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": { "workspace": {
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "处理中 {{duration}}", "activityWorkingFor": "处理中 {{duration}}",
"activityWorked": "已处理", "activityWorked": "已处理",
"activityWorkedFor": "处理了 {{duration}}", "activityWorkedFor": "处理了 {{duration}}",
"retryConnection": "连接失败",
"retryTimeout": "模型响应超时",
"retryRateLimit": "请求频率受限",
"retryServer": "模型服务不可用",
"retryUnknown": "模型请求失败",
"retryWaiting": "{{error}} · {{seconds}} 秒后重试 · 第 {{attempt}} 次",
"retryExhausted": "{{error}} · 正在结束本次任务",
"cliActivityRunningOne": "正在使用 {{name}}", "cliActivityRunningOne": "正在使用 {{name}}",
"cliActivityRanOne": "已使用 {{name}}", "cliActivityRanOne": "已使用 {{name}}",
"cliActivityFailedOne": "使用 {{name}} 失败", "cliActivityFailedOne": "使用 {{name}} 失败",
@@ -1546,6 +1553,17 @@
"turnRejected": { "turnRejected": {
"title": "消息未发送", "title": "消息未发送",
"body": "网关拒绝了这条消息。请检查消息内容或附件后重试。" "body": "网关拒绝了这条消息。请检查消息内容或附件后重试。"
},
"modelRequestFailed": {
"billingTitle": "模型提供商账户额度不足",
"billingBody": "请为提供商账户充值或检查账单状态后重试。",
"connectionTitle": "无法连接模型提供商",
"timeoutTitle": "模型提供商请求超时",
"rateLimitTitle": "模型提供商请求受限",
"serverTitle": "模型提供商服务异常",
"unknownTitle": "模型提供商请求失败",
"bodyWithAttempt": "模型提供商请求在第 {{attempts}} 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
"body": "请检查提供商配置或服务状态后重试。"
} }
}, },
"workspace": { "workspace": {
+18
View File
@@ -1433,6 +1433,13 @@
"activityWorkingFor": "處理中,已 {{duration}}", "activityWorkingFor": "處理中,已 {{duration}}",
"activityWorked": "已處理", "activityWorked": "已處理",
"activityWorkedFor": "已處理 {{duration}}", "activityWorkedFor": "已處理 {{duration}}",
"retryConnection": "連線失敗",
"retryTimeout": "模型回應逾時",
"retryRateLimit": "請求頻率受限",
"retryServer": "模型服務無法使用",
"retryUnknown": "模型請求失敗",
"retryWaiting": "{{error}} · {{seconds}} 秒後重試 · 第 {{attempt}} 次",
"retryExhausted": "{{error}} · 正在結束本輪",
"cliActivityRunningOne": "正在使用 @{{name}}", "cliActivityRunningOne": "正在使用 @{{name}}",
"cliActivityRanOne": "已使用 @{{name}}", "cliActivityRanOne": "已使用 @{{name}}",
"cliActivityFailedOne": "使用 @{{name}} 失敗", "cliActivityFailedOne": "使用 @{{name}} 失敗",
@@ -1532,6 +1539,17 @@
"turnRejected": { "turnRejected": {
"title": "訊息未傳送", "title": "訊息未傳送",
"body": "閘道拒絕了這則訊息。請檢查內容或附件後再試一次。" "body": "閘道拒絕了這則訊息。請檢查內容或附件後再試一次。"
},
"modelRequestFailed": {
"billingTitle": "模型供應商帳戶額度不足",
"billingBody": "請為供應商帳戶儲值或檢查帳單狀態後再試。",
"connectionTitle": "無法連線至模型供應商",
"timeoutTitle": "模型供應商請求逾時",
"rateLimitTitle": "模型供應商請求受到限制",
"serverTitle": "模型供應商服務發生錯誤",
"unknownTitle": "模型供應商請求失敗",
"bodyWithAttempt": "模型供應商請求在第 {{attempts}} 次嘗試後仍然失敗,已停止重試。請檢查供應商設定或服務狀態後再試。",
"body": "請檢查供應商設定或服務狀態後再試。"
} }
}, },
"workspace": { "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. /** Structured errors surfaced to the UI.
* *
* Most entries are transport-level or protocol-level faults. Workspace scope * Most entries are transport-level or protocol-level faults. Runtime and
* rejections are server application errors promoted here because they affect * workspace failures are promoted here when they must remain visible outside
* controls outside the message stream and must be visible immediately. * the message stream.
*/ */
export type StreamError = export type StreamError =
/** Server rejected the inbound frame as too large (WS close code 1009). /** Server rejected the inbound frame as too large (WS close code 1009).
@@ -100,6 +100,13 @@ export type StreamError =
reason?: string; reason?: string;
chatId: string; chatId: string;
turnId: string; turnId: string;
}
| {
kind: "model_request_failed";
chatId: string;
turnId?: string;
errorKind?: string;
attempts?: number;
}; };
type ErrorHandler = (error: StreamError) => void; 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"; export type { RecoveryState, RecoveryStatus } from "../../../packages/client-events/notifications";
type Role = "user" | "assistant" | "tool" | "system"; type Role = "user" | "assistant" | "tool" | "system";
@@ -64,6 +64,10 @@ export interface TurnUsage {
export type RoundUsage = TurnUsage; export type RoundUsage = TurnUsage;
export interface RetryStatus extends WireRetryStatus {
next_retry_at?: number;
turn_id?: string;
}
export interface UIMessage { export interface UIMessage {
id: string; id: string;
role: Role; role: Role;
@@ -1422,6 +1426,11 @@ export type InboundEvent =
context_window_tokens?: number; context_window_tokens?: number;
/** Authoritative sustained-goal snapshot for this chat (same shape as ``goal_state`` events). */ /** Authoritative sustained-goal snapshot for this chat (same shape as ``goal_state`` events). */
goal_state?: GoalStateWsPayload; goal_state?: GoalStateWsPayload;
outcome?: "completed" | "failed" | "cancelled" | "interrupted";
failure_kind?: string;
failure_error_kind?: string;
failure_attempts?: number;
failure_message?: string;
} & InboundTurnMetadata) } & InboundTurnMetadata)
| ({ | ({
event: "goal_status"; event: "goal_status";
@@ -140,6 +140,27 @@ function installReducedMotion() {
} }
describe("AgentActivityCluster", () => { 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 () => { it("keeps intermediate assistant output as normal Markdown inside live activity", async () => {
await act(async () => { await act(async () => {
await preloadMarkdownText(); 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"; import { acceptsCompactionPhase, decodeNotification } from "../../../packages/client-events/notifications";
describe("shared notification contract", () => { 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) => { it.each(fixtures)("accepts the Python wire fixture %#", (event) => {
expect(decodeNotification(event)).toEqual(event); expect(decodeNotification(event)).toEqual(event);
expect(decodeNotification({ ...event, turn_id: "turn" })).toMatchObject(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 { preloadMarkdownText } from "@/components/MarkdownText";
import { ThreadCameraController } from "@/components/thread/thread-camera"; import { ThreadCameraController } from "@/components/thread/thread-camera";
import { ThreadShell } from "@/components/thread/ThreadShell"; import { ThreadShell } from "@/components/thread/ThreadShell";
import i18n from "@/i18n";
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events"; import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client"; import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider"; 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 () => { it("moves a correlated delivery error from the banner into the failed message tooltip", async () => {
const client = makeClient(); const client = makeClient();
+69
View File
@@ -125,6 +125,9 @@ function fakeClient() {
const v = runStartedAtByChatId.get(chatId); const v = runStartedAtByChatId.get(chatId);
return v === undefined ? null : v; return v === undefined ? null : v;
}, },
getRunTurnId() {
return null;
},
getGoalState(chatId: string) { getGoalState(chatId: string) {
return goalStateByChatId.get(chatId); return goalStateByChatId.get(chatId);
}, },
@@ -3227,6 +3230,72 @@ describe("useNanobotStream", () => {
expect(result.current.isStreaming).toBe(false); 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", () => { it("clears runStartedAt on turn_end even without idle", () => {
const fake = fakeClient(); const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-g", EMPTY_MESSAGES), { const { result } = renderHook(() => useNanobotStream("chat-g", EMPTY_MESSAGES), {