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

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

No files matched your search

+4
View File
@@ -153,6 +153,10 @@ Open the context indicator beside the composer model badge to see how much of th
When nanobot compacts context, the timeline shows its progress and outcome. The model continues with a summary and any messages after it; messages covered by the summary remain in your chat history but are no longer sent to the model verbatim. Use `/compact` to compact the current topic's context manually. See [Memory](./memory.md) for compaction and Dream consolidation.
### Model failures
After a model request fails and automatic retries stop, the WebUI shows the failure category. Use **Continue** to resume from the saved conversation, or open model settings to change the model or correct its authorization. Review completed work before continuing: saved tool results are retained, but the model can choose to call tools again. Continuing does not resend the original message. Sending a new message or dismissing the notice clears the pending decision. Saved recovery decisions remain available after a refresh or gateway restart; temporary chats still follow their normal lifetime.
### Delegated work
When nanobot delegates work to subagents, a work group appears under the request that started it. Progress continues to update after the main reply finishes. Completed tasks stay available for inspection, and refreshing or reopening the WebUI restores saved progress and results without restarting the work.
+1
View File
@@ -65,6 +65,7 @@ class RecoveryStateEvent(AgentEvent):
reason: str | None = None
attempts: int = 0
can_continue: bool | None = None
failure_error_kind: str | None = None
@dataclass(frozen=True)
+17
View File
@@ -324,6 +324,9 @@ class LLMResponse:
error_code: str | None = None # Provider/code semantic, e.g. rate_limit_exceeded.
error_retry_after_s: float | None = None
error_should_retry: bool | None = None
# A failed fallback must not replace the selected model's public diagnosis.
# Keep this separate from the last response's retry policy.
primary_error_kind: str | None = field(default=None, repr=False)
is_fallback: bool = field(default=False, repr=False)
@property
@@ -1556,9 +1559,14 @@ class LLMProvider(ABC):
@classmethod
def public_error_kind(cls, response: LLMResponse) -> str:
"""Return a stable public category without exposing provider details."""
if response.primary_error_kind is not None:
return response.primary_error_kind
if cls.is_arrearage_response(response):
return "billing"
kind = (response.error_kind or "").strip().lower()
# A plain 403 can be a policy or permission rejection, not bad credentials.
if kind in {"authentication", "oauth_auth_required"} or response.error_status_code == 401:
return "authentication"
if kind in {"connection", "timeout"}:
return kind
if response.error_status_code == 429:
@@ -1641,6 +1649,15 @@ class LLMProvider(ABC):
identical_error_count = 1 if error_key else 0
if not self.is_transient_response(response):
# Removing the user's images cannot repair account access.
# Do not rebuild native provider state for an unrelated failure.
if (
(response.error_kind or "").lower() in {"authentication", "oauth_auth_required"}
or response.error_status_code in {401, 403}
or self.is_arrearage_response(response)
):
await _finish_retry_status("cleared", response)
return response
stripped = self._strip_image_content(kw["messages"])
provider_context = kw.get("provider_context")
stripped_context: ProviderCallContext | None = None
+20 -5
View File
@@ -361,6 +361,9 @@ class FallbackProvider(LLMProvider):
async def _call_chain(**chain_kwargs: Any) -> LLMResponse:
last_exhausted_message: str | None = None
last_exhausted_status: RetryStatusEvent | None = None
primary_attempted = False
primary_exhausted_message: str | None = None
primary_exhausted_status: RetryStatusEvent | None = None
async def _capture_exhaustion(message: str) -> None:
nonlocal last_exhausted_message
@@ -388,15 +391,22 @@ class FallbackProvider(LLMProvider):
candidate_kwargs: dict[str, Any],
) -> LLMResponse:
nonlocal last_exhausted_message, last_exhausted_status
nonlocal primary_attempted, primary_exhausted_message, primary_exhausted_status
last_exhausted_message = None
last_exhausted_status = None
return await call(provider, {
if provider is self._primary:
primary_attempted = True
response = await call(provider, {
**candidate_kwargs,
"retry_mode": "standard",
"on_retry_wait": on_retry_wait,
"on_retry_exhausted": _capture_exhaustion,
"on_retry_status": _capture_status,
})
if provider is self._primary:
primary_exhausted_message = last_exhausted_message
primary_exhausted_status = last_exhausted_status
return response
response = await self._try_with_fallback(
_call_candidate,
@@ -406,10 +416,12 @@ class FallbackProvider(LLMProvider):
on_fallback_attempt=_clear_status_for_fallback,
)
if retry_mode != "persistent" and response.finish_reason == "error":
if last_exhausted_message and on_retry_exhausted:
await on_retry_exhausted(last_exhausted_message)
if last_exhausted_status and on_retry_status:
await on_retry_status(last_exhausted_status)
terminal_message = primary_exhausted_message if primary_attempted else last_exhausted_message
terminal_status = primary_exhausted_status if primary_attempted else last_exhausted_status
if terminal_message and on_retry_exhausted:
await on_retry_exhausted(terminal_message)
if terminal_status and on_retry_status:
await on_retry_status(terminal_status)
return response
if retry_mode != "persistent":
@@ -656,6 +668,9 @@ class FallbackProvider(LLMProvider):
return replace(
last_response,
preserve_provider_state_on_error=preserve_primary_state,
primary_error_kind=(
self.public_error_kind(primary_response) if primary_response is not None else None
),
)
# Primary was skipped and no fallback returned a response. Keep the result
# transient until the primary circuit is eligible for another probe.
+5
View File
@@ -447,4 +447,9 @@ def recovery_state_from_metadata(metadata: Mapping[str, Any] | None) -> dict[str
can_continue = state.get("can_continue")
if isinstance(can_continue, bool):
payload["can_continue"] = can_continue
failure_error_kind = state.get("failure_error_kind")
if isinstance(failure_error_kind, str) and failure_error_kind in {
"authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown",
}:
payload["failure_error_kind"] = failure_error_kind
return payload
+5 -1
View File
@@ -733,7 +733,11 @@ class WebuiTurnCoordinator:
failure_attempts=event.failure_attempts,
)
if self.recovery is not None:
await self.recovery.turn_completed(event.context.session_key)
await self.recovery.turn_completed(
event.context.session_key,
failure_kind=event.failure_kind,
failure_error_kind=event.failure_error_kind,
)
if event.outcome == "completed" and is_webui_session_key(event.context.session_key):
turn_id = event.context.metadata.get(WEBUI_TURN_METADATA_KEY)
if isinstance(turn_id, str) and turn_id:
+3
View File
@@ -72,6 +72,7 @@ class RecoveryStateWirePayload(_ChatWirePayload):
attempts: int
reason: NotRequired[str]
can_continue: NotRequired[bool]
failure_error_kind: NotRequired[str]
class RetryStatusWirePayload(_ChatWirePayload):
@@ -135,6 +136,8 @@ def encode_recovery_state(
payload["reason"] = event.reason
if event.can_continue is not None:
payload["can_continue"] = event.can_continue
if event.failure_error_kind is not None:
payload["failure_error_kind"] = event.failure_error_kind
return payload
+27 -7
View File
@@ -166,9 +166,10 @@ class RecoveryCoordinator:
state = recovery_state_from_metadata(session.metadata)
if state and state["status"] in {"resuming", "awaiting_user", "failed"}:
await self._cancel_active_recovery(message.session_key)
restore_runtime_checkpoint(session)
if not restore_pending_interruption(session, superseded=True):
append_recovery_interruption(session, superseded=True)
if state.get("reason") != "model_request_failed":
restore_runtime_checkpoint(session)
if not restore_pending_interruption(session, superseded=True):
append_recovery_interruption(session, superseded=True)
recovered = self._set_state(
session,
status="recovered",
@@ -180,15 +181,33 @@ class RecoveryCoordinator:
await self._publish(message.chat_id, recovered)
return True
async def turn_completed(self, session_key: str) -> None:
"""Resolve a resuming state after the recovered turn commits."""
async def turn_completed(
self, session_key: str, *, failure_kind: str | None = None,
failure_error_kind: str | None = None,
) -> None:
"""Offer explicit continuation of committed model failures or resolve recovery."""
session = await self.sessions.state.get(session_key)
state = recovery_state_from_metadata(session.metadata)
if not state or state["status"] != "resuming":
return
route = self._websocket_route(session)
if route is None:
return
if failure_kind == "model":
# The turn has already saved its transcript and tool results. Use
# that context, never resend the user's message or replay tools.
waiting = self._set_state(
session,
status="awaiting_user",
recovery_id=uuid4().hex,
attempts=cast(int, state.get("attempts", 0)) if state else 0,
reason="model_request_failed",
can_continue=any(message.get("role") == "user" for message in session.messages),
)
waiting["failure_error_kind"] = failure_error_kind or "unknown"
await self.sessions.state.restore_interruption(session)
await self._publish(route[1], waiting)
return
if not state or state["status"] != "resuming":
return
recovered = self._set_state(
session,
status="recovered",
@@ -445,6 +464,7 @@ class RecoveryCoordinator:
reason=cast(str | None, state.get("reason")),
attempts=cast(int, state.get("attempts", 0)),
can_continue=cast(bool | None, state.get("can_continue")),
failure_error_kind=cast(str | None, state.get("failure_error_kind")),
),
)
)
+1
View File
@@ -5,6 +5,7 @@
{"event":"context_compaction","chat_id":"chat","compaction_id":"c1","phase":"cancelled"},
{"event":"recovery_state","chat_id":"chat","status":"resuming","recovery_id":"r1","attempts":0},
{"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r1","attempts":1,"reason":"tool_state_unknown","can_continue":false},
{"event":"recovery_state","chat_id":"chat","status":"awaiting_user","recovery_id":"r2","attempts":0,"reason":"model_request_failed","failure_error_kind":"connection"},
{"event":"recovery_state","chat_id":"chat","status":"recovered","recovery_id":"r1","attempts":1},
{"event":"recovery_state","chat_id":"chat","status":"failed","recovery_id":"r1","attempts":2},
{"event":"retry_status","chat_id":"chat","state":"waiting","attempt":1,"max_attempts":4,"error_kind":"connection","retry_after_s":2},
+2
View File
@@ -7,6 +7,7 @@ export interface RecoveryState {
reason?: string
attempts?: number
can_continue?: boolean
failure_error_kind?: string
}
export interface ContextCompaction {
@@ -53,6 +54,7 @@ export function isRecoveryState(value: unknown): value is RecoveryState {
&& optional(value.reason, "string")
&& optional(value.attempts, "number")
&& optional(value.can_continue, "boolean")
&& optional(value.failure_error_kind, "string")
}
/** Undefined means another protocol family; null means a malformed notification. */
+71 -1
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
from copy import deepcopy
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
@@ -11,7 +12,7 @@ from nanobot.agent.loop import AgentLoop
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.session.manager import SessionManager
from nanobot.session.recovery import (
RECOVERY_METADATA_KEY,
@@ -23,6 +24,75 @@ from nanobot.webui.recovery import RecoveryCoordinator
from nanobot.webui.transcript import WebUITranscriptRecorder
@pytest.mark.asyncio
async def test_committed_model_failure_continues_with_tool_results_without_resending(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: tmp_path / "webui")
bus = MessageBus()
sessions = SessionManager(tmp_path)
session = sessions.get_or_create("websocket:chat")
session.metadata["title"] = "Saved recovery"
sessions.save(session)
recovery = RecoveryCoordinator(sessions, bus)
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.can_resume_conversation_state.return_value = False
requests: list[dict] = []
responses = iter([
LLMResponse(content=None, tool_calls=[ToolCallRequest(
"read-once", "read_file", {"path": str(tmp_path / "note.txt")},
)]),
LLMResponse(content="private failure", finish_reason="error", error_kind="connection"),
LLMResponse(content="Finished from the saved result."),
])
async def respond(**kwargs):
requests.append(deepcopy({
"messages": LLMProvider._sanitize_empty_content(kwargs["messages"]),
"tools": kwargs["tools"],
}))
return next(responses)
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
(tmp_path / "note.txt").write_text("saved evidence", encoding="utf-8")
loop = AgentLoop(
bus=bus, provider=provider, workspace=tmp_path, model="test-model",
session_manager=sessions, recovery_admission=recovery,
)
loop.turn_delivery_factory = TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions))
coordinator = WebuiTurnCoordinator(bus, sessions, loop.schedule_background, recovery=recovery)
read_tool = loop.tools.get("read_file")
assert read_tool is not None
execute = AsyncMock(wraps=read_tool.execute)
monkeypatch.setattr(read_tool, "execute", execute)
request = InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="Read the note and summarize it",
metadata={"webui": True, "webui_turn_id": "request-1"},
)
try:
with coordinator.connected():
await loop._dispatch_one(request, asyncio.Queue())
state = (await sessions.state.get(request.session_key)).metadata[RECOVERY_METADATA_KEY]
assert state["status"] == "awaiting_user"
assert bus.inbound.empty()
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})
await loop._dispatch_one(bus.inbound.get_nowait(), asyncio.Queue())
final = await sessions.state.get(request.session_key)
assert final.metadata[RECOVERY_METADATA_KEY]["status"] == "recovered"
assert execute.await_count == 1
assert sum(message.get("role") == "user" for message in final.messages) == 1
assert any(message.get("role") == "tool" and "saved evidence" in message["content"] for message in requests[-1]["messages"])
assert requests[0]["messages"][0] == requests[-1]["messages"][0]
assert requests[0]["tools"] == requests[-1]["tools"]
assert requests[-1]["messages"][:len(requests[1]["messages"])] == requests[1]["messages"]
assert len(requests) == 3
finally:
await loop.aclose()
@pytest.mark.asyncio
async def test_recovery_continuation_runs_without_a_sustained_goal(
tmp_path: Path,
+28
View File
@@ -1281,6 +1281,34 @@ class TestRetryBeforeFailover:
assert "cleared" in [status.state for status in retry_statuses]
assert retry_statuses[-1].state == "exhausted"
@pytest.mark.asyncio
async def test_fallback_auth_error_preserves_primary_diagnosis_and_exhaustion(self) -> None:
primary = _FakeProvider("primary", _make_response(
"private network detail", finish_reason="error", error_kind="connection",
))
fallback = _FakeProvider("fallback", _make_response(
"private auth detail", finish_reason="error", error_status_code=401,
))
provider = FallbackProvider(primary, [_fallback("backup")], MagicMock(return_value=fallback))
statuses: list[RetryStatusEvent] = []
async def record(status: RetryStatusEvent) -> None:
statuses.append(status)
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await provider.chat_with_retry(
[{"role": "user", "content": "hello"}], on_retry_status=record,
)
assert len(primary.chat_calls) == 4
assert len(fallback.chat_calls) == 1
assert LLMProvider.public_error_kind(result) == "connection"
assert result.preserve_provider_state_on_error is True
assert not LLMProvider.is_transient_response(result) # Retry policy is still terminal.
assert statuses[-1] == RetryStatusEvent(
state="exhausted", attempt=4, max_attempts=4, error_kind="connection",
)
@pytest.mark.asyncio
@pytest.mark.parametrize("factory_fails", [False, True])
async def test_persistent_mode_repeats_the_whole_chain(
+45 -1
View File
@@ -44,6 +44,20 @@ class ScriptedProvider(LLMProvider):
return "test-model"
@pytest.mark.parametrize(("response", "expected"), [
(LLMResponse(content=None, finish_reason="error", error_kind="oauth_auth_required"), "authentication"),
(LLMResponse(content=None, finish_reason="error", error_status_code=401), "authentication"),
(LLMResponse(content=None, finish_reason="error", error_status_code=403), "unknown"),
(LLMResponse(
content=None, finish_reason="error", error_status_code=403, error_code="content_filter",
), "unknown"),
])
def test_public_authentication_diagnosis_requires_credential_evidence(
response: LLMResponse, expected: str,
) -> None:
assert LLMProvider.public_error_kind(response) == expected
@pytest.mark.asyncio
async def test_chat_with_retry_retries_transient_error_then_succeeds(monkeypatch) -> None:
provider = ScriptedProvider([
@@ -134,7 +148,7 @@ async def test_chat_with_retry_clears_waiting_status_on_terminal_non_transient_e
assert response.content == "401 unauthorized"
assert [status.state for status in statuses] == ["waiting", "cleared"]
assert statuses[-1].attempt == 2
assert statuses[-1].error_kind == "unknown"
assert statuses[-1].error_kind == "authentication"
@pytest.mark.asyncio
@@ -403,6 +417,36 @@ async def test_chat_with_retry_explicit_override_beats_defaults() -> None:
# ---------------------------------------------------------------------------
# Image fallback tests
@pytest.mark.asyncio
@pytest.mark.parametrize("error", [
LLMResponse(content="unauthorized", finish_reason="error", error_status_code=401),
LLMResponse(content="login expired", finish_reason="error", error_kind="authentication"),
LLMResponse(
content="Sign in again.", finish_reason="error",
error_kind="oauth_auth_required", error_should_retry=False,
),
LLMResponse(content="billing", finish_reason="error", error_status_code=402),
])
async def test_account_failure_does_not_retry_without_images(error: LLMResponse) -> None:
provider = ScriptedProvider([error])
messages = copy.deepcopy(_IMAGE_MSG)
original = copy.deepcopy(messages)
state = ProviderConversationState(
provider="scripted", model="test-model", kind="test", version=1, payload={},
)
context = ProviderCallContext(conversation_state=state)
response = await provider.chat_with_retry(messages=messages, provider_context=context)
assert response is error
assert provider.calls == 1
assert messages == original
assert context.conversation_state is state
assert LLMProvider.public_error_kind(response) in {"authentication", "billing"}
# ---------------------------------------------------------------------------
_IMAGE_MSG = [
+53
View File
@@ -8,6 +8,7 @@ import pytest
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import RecoveryStateEvent, SessionUpdatedEvent
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import ProviderConversationState
from nanobot.session.manager import Session, SessionManager
from nanobot.session.recovery import (
PENDING_FOLLOWUPS_KEY,
@@ -735,6 +736,58 @@ async def test_dismiss_does_not_queue_work(tmp_path: Path) -> None:
assert bus.inbound.empty()
@pytest.mark.asyncio
async def test_model_failure_waits_across_restart_and_rejects_duplicate_continue(tmp_path: Path) -> None:
coordinator, bus, sessions = _coordinator(tmp_path)
session = sessions.get_or_create("websocket:chat")
session.messages = [{"role": "user", "content": "finish this"}]
_persist(sessions, session)
await coordinator.turn_completed("websocket:chat", failure_kind="model", failure_error_kind="connection")
assert bus.inbound.empty()
coordinator, bus, sessions = _coordinator(tmp_path)
await coordinator.scan()
assert bus.inbound.empty()
state = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]
assert state["failure_error_kind"] == "connection"
assert state["status"] == "awaiting_user"
payload = {"chat_id": "chat", "recovery_id": state["recovery_id"]}
await coordinator.handle_action("continue", payload)
with pytest.raises(RecoveryActionError):
await coordinator.handle_action("continue", payload)
continuation = bus.inbound.get_nowait()
assert continuation.metadata["_skip_user_persist"] is True
assert bus.inbound.empty()
await coordinator.turn_completed("websocket:chat", failure_kind="model", failure_error_kind="authentication")
failed_again = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]
assert failed_again["status"] == "awaiting_user"
assert failed_again["failure_error_kind"] == "authentication"
with pytest.raises(RecoveryActionError, match="stale"):
await coordinator.handle_action("continue", payload)
@pytest.mark.asyncio
async def test_new_input_after_model_failure_does_not_change_saved_context(tmp_path: Path) -> None:
coordinator, _, sessions = _coordinator(tmp_path)
session = sessions.get_or_create("websocket:chat")
session.messages = [{"role": "user", "content": "finish this"}]
session.provider_state = ProviderConversationState(
kind="openai_responses", provider="openai_codex", model="test-model", version=1,
payload={"response_id": "saved-response"},
)
_persist(sessions, session)
await coordinator.turn_completed("websocket:chat", failure_kind="model")
before = sessions.get_or_create("websocket:chat")
assert before.provider_state is not None
await coordinator.admit(InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="new request",
))
after = sessions.get_or_create("websocket:chat")
assert after.messages == before.messages
assert after.provider_state == before.provider_state
assert after.metadata[RECOVERY_METADATA_KEY]["reason"] == "superseded"
@pytest.mark.asyncio
async def test_scan_failure_is_visible_instead_of_aborting_other_sessions(
tmp_path: Path,
+47
View File
@@ -0,0 +1,47 @@
import { useState } from "react";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { useReadingTypography } from "@/hooks/useReadingTypography";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import type { UIMessage } from "@/lib/types";
const messages: UIMessage[] = [{
id: "failed-question",
role: "user" as const,
content: formatQuotedUserMessage("Please explain this failure. 请解释这个错误。", "Earlier context / 之前的上下文"),
images: [{ url: "data:image/svg+xml," + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="120"><rect width="160" height="120" fill="#ddd"/></svg>'), name: "Failure screenshot" }],
createdAt: 1_700_000_000_000,
}];
// Real components with controlled state. No model calls or saved user data.
export function ChatFailureFixture({ parameters }: { parameters: URLSearchParams }) {
useReadingTypography();
const [visible, setVisible] = useState(true);
const [action, setAction] = useState("");
const variant = parameters.get("variant") === "hero" ? "hero" : "thread";
const dismiss = () => { setVisible(false); setAction("dismissed"); };
const settings = () => setAction("settings");
return <main className="min-h-screen bg-background p-4 text-foreground">
<section className="mx-auto max-w-3xl py-8">
<ThreadMessages messages={messages} isStreaming={false} />
</section>
<div className={variant === "hero" ? "thread-composer-stack is-hero" : "thread-composer-stack"}>
{visible && (parameters.get("notice") === "stream"
? <StreamErrorNotice error={{ kind: "model_request_failed", chatId: "fixture", errorKind: "authentication" }} onDismiss={dismiss} onOpenSettings={settings} />
: parameters.get("notice") === "fallback"
? <ModelFallbackNotice model="Fallback model" onDismiss={dismiss} onOpenSettings={settings} />
: <RecoveryNotice
state={{ recovery_id: "fixture-recovery", status: "awaiting_user", reason: "model_request_failed", failure_error_kind: "authentication" }}
onContinue={async () => { setVisible(false); setAction("continued"); }}
onDismiss={async () => dismiss()}
onOpenSettings={settings}
/>)}
<ThreadComposer variant={variant} onSend={() => {}} workspaceControlsHidden />
</div>
<output aria-label="Fixture action">{action}</output>
</main>;
}
+95
View File
@@ -0,0 +1,95 @@
import { expect, test } from "@playwright/test";
for (const width of [1440, 390]) {
for (const variant of ["thread", "hero"]) {
for (const notice of ["recovery", "stream", "fallback"]) {
test(`${notice} aligns with ${variant} composer at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 1000 });
await page.emulateMedia({ reducedMotion: "reduce" });
await page.addInitScript(({ dark, locale }) => {
localStorage.setItem("nanobot.locale", locale);
localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({ schemaVersion: 1, readingTextSize: "large" }));
document.addEventListener("DOMContentLoaded", () => {
document.documentElement.classList.toggle("dark", dark);
});
}, { dark: variant === "hero", locale: width === 390 ? "zh-CN" : "en" });
await page.goto(`/browser/fixture.html?case=chat-failure&notice=${notice}&variant=${variant}`);
const alert = page.locator(".thread-composer-notice");
const composer = page.locator(".thread-composer-surface");
await expect(alert).toBeVisible();
await expect(composer).toBeVisible();
const noticeBox = (await alert.boundingBox())!;
const composerBox = (await composer.boundingBox())!;
expect(Math.abs(noticeBox.x - composerBox.x)).toBeLessThan(1);
expect(Math.abs(noticeBox.width - composerBox.width)).toBeLessThan(1);
for (const button of await alert.getByRole("button").all()) {
await expect(button).toBeInViewport({ ratio: 1 });
const box = (await button.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(noticeBox.x);
expect(box.x + box.width).toBeLessThanOrEqual(noticeBox.x + noticeBox.width);
}
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width);
if (notice === "recovery") {
await expect(alert).toContainText(width === 390 ? "模型提供商验证失败" : "Model provider authorization failed");
await alert.getByRole("button").first().click();
await expect(page.getByLabel("Fixture action")).toHaveText("settings");
await alert.getByRole("button").last().click();
await expect(alert).toBeHidden();
await expect(page.getByLabel("Fixture action")).toHaveText("continued");
} else {
await alert.getByRole("button").last().click();
await expect(alert).toBeHidden();
await expect(page.getByLabel("Fixture action")).toHaveText("dismissed");
}
});
}
}
}
for (const width of [1440, 390]) {
for (const size of ["small", "standard", "large"] as const) {
test(`image and quote retain the responsive message actions: ${size}, ${width}px`, async ({ page }, info) => {
await page.setViewportSize({ width, height: 1000 });
await page.addInitScript(({ size, locale }) => {
localStorage.setItem("nanobot.locale", locale);
localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({ schemaVersion: 1, readingTextSize: size }));
}, { size, locale: width === 390 ? "zh-CN" : "en" });
await page.goto("/browser/fixture.html?case=chat-failure");
const image = page.getByAltText("Failure screenshot");
await expect(image).toBeVisible();
await expect(page.getByText("Earlier context / 之前的上下文")).toBeVisible();
const bubble = page.locator("[data-user-text-bubble]");
const text = bubble.locator("p");
const trigger = page.locator("[data-message-block-menu-trigger]");
const fontSize = width === 390
? { small: 15, standard: 16, large: 18 }[size]
: { small: 16, standard: 18, large: 20 }[size];
await expect(text).toHaveCSS("font-size", `${fontSize}px`);
await bubble.hover();
await expect(trigger).toBeVisible();
const bubbleBox = (await bubble.boundingBox())!;
const triggerBox = (await trigger.boundingBox())!;
const imageBox = (await image.boundingBox())!;
expect(imageBox.y + imageBox.height).toBeLessThan(bubbleBox.y);
if (width === 390) {
// Narrow screens use a touch action row below the message, not a hover rail.
await expect(page.locator("[data-message-mobile-actions]")).toBeVisible();
expect(triggerBox.y).toBeGreaterThanOrEqual(bubbleBox.y + bubbleBox.height);
expect(triggerBox.height).toBeGreaterThanOrEqual(44);
await expect(trigger).toBeInViewport({ ratio: 1 });
} else {
const firstLineCenter = await text.evaluate(node => {
const style = getComputedStyle(node);
return node.getBoundingClientRect().y + parseFloat(style.paddingTop) + parseFloat(style.lineHeight) / 2;
});
expect(Math.abs(triggerBox.y + triggerBox.height / 2 - firstLineCenter)).toBeLessThan(1);
}
await trigger.click();
await expect(page.locator("[data-message-block-menu]")).toBeVisible();
if (width === 390) {
await expect(page.locator("[data-message-mobile-sheet]")).toBeInViewport({ ratio: 1 });
}
await page.screenshot({ path: info.outputPath("message-menu.png") });
});
}
}
+4 -1
View File
@@ -24,6 +24,7 @@ import "../src/globals.css";
import { DiagramFixture } from "./diagram-fixture";
import { TypographyFixture } from "./typography-fixture";
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
import { ChatFailureFixture } from "./chat-failure-fixture";
import { ThreadLoadingFixture } from "./thread-loading-fixture";
const history: UIMessage[] = [
@@ -146,7 +147,9 @@ function AppsFixture() {
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "typography"
{parameters.get("case") === "chat-failure"
? <ChatFailureFixture parameters={parameters} />
: parameters.get("case") === "typography"
? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>
: parameters.get("case") === "history-boundary"
? <ClientProvider client={railClient} token="fixture" webuiCapabilities={["webui.prompt-navigation.v1"]}><HistoryBoundaryFixture local={parameters.has("local")} navigate={parameters.has("navigate")} /></ClientProvider>
+16 -14
View File
@@ -483,10 +483,9 @@ export function MessageBubble({
);
return (
<div
data-user-text-bubble={hasText && !hasImages && !hasMedia && !quotedContext || undefined}
className="group relative ml-auto flex w-fit max-w-[min(85%,36rem)] flex-col items-end gap-1.5"
>
{contextMenu}
{!hasText ? contextMenu : null}
{hasImages ? <ImageGallery images={images} align="right" size="compact" /> : null}
{!hasImages && hasMedia ? (
<MessageMedia media={media} align="right" />
@@ -498,18 +497,21 @@ export function MessageBubble({
/>
) : null}
{hasText ? (
<p
data-temporary-message={temporary ? "true" : undefined}
className={cn(
"ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2",
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary
? "border border-dashed border-muted-foreground/40 bg-transparent"
: "bg-secondary/70",
)}
>
{messageText}
</p>
<div data-user-text-bubble className="relative ml-auto w-fit max-w-full min-w-0">
{contextMenu}
<p
data-temporary-message={temporary ? "true" : undefined}
className={cn(
"ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2",
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary
? "border border-dashed border-muted-foreground/40 bg-transparent"
: "bg-secondary/70",
)}
>
{messageText}
</p>
</div>
) : null}
{showDeliveryStatus ? (
<div className="flex min-h-8 items-center justify-end gap-1.5 text-muted-foreground">
@@ -16,7 +16,7 @@ export function ModelFallbackNotice({ model, reauthProvider, reauthProviderLabel
return (
<div
role="status"
className="mx-auto mb-2 flex w-full max-w-[49.5rem] items-center gap-2 rounded-control border border-border/60 bg-muted/40 px-3 py-2 text-xs text-foreground/80 animate-in fade-in-0 slide-in-from-bottom-1 motion-reduce:animate-none"
className="thread-composer-notice mb-2 flex items-center gap-2 rounded-control border border-border/60 bg-muted/40 px-3 py-2 text-xs text-foreground/80 animate-in fade-in-0 slide-in-from-bottom-1 motion-reduce:animate-none"
>
<PresetProviderIcon
provider={reauthProvider}
+18 -8
View File
@@ -8,14 +8,16 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { RecoveryState } from "@/lib/types";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
interface RecoveryNoticeProps {
state: RecoveryState;
onContinue: () => Promise<void>;
onDismiss: () => Promise<void>;
onOpenSettings?: () => void;
}
export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeProps) {
export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }: RecoveryNoticeProps) {
const { t } = useTranslation();
const [pending, setPending] = useState<"continue" | "dismiss" | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -33,14 +35,17 @@ export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeP
if (!waiting || hiddenRecoveryId === state.recovery_id) return null;
const contextUnavailable = state.can_continue === false;
const title = state.status === "failed"
const modelFailure = state.reason === "model_request_failed"
? resolveModelRequestFailureCopy({ errorKind: state.failure_error_kind }, t)
: null;
const title = modelFailure?.title ?? (state.status === "failed"
? t("recovery.failed", { defaultValue: "Task recovery failed" })
: t("recovery.interrupted", { defaultValue: "Task interrupted" });
const detail = state.status === "failed" || contextUnavailable
: t("recovery.interrupted", { defaultValue: "Task interrupted" }));
const detail = contextUnavailable || state.status === "failed"
? t("recovery.failedHelp", {
defaultValue: "The saved task could not be restored safely. Review it before continuing.",
})
: t("recovery.review", { defaultValue: "Review the task before continuing. Tools will not be replayed automatically." });
: modelFailure?.body ?? t("recovery.review", { defaultValue: "Review the task before continuing. Tools will not be replayed automatically." });
const run = (action: "continue" | "dismiss") => {
setPending(action);
setError(null);
@@ -60,13 +65,18 @@ export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeP
role="alert"
aria-live="assertive"
data-recovery-status={state.status}
className="mx-auto mb-2 flex w-full max-w-[49.5rem] items-center gap-3 rounded-control border border-border/70 bg-muted/35 px-3 py-2 text-sm transition-[background-color,border-color,opacity,transform] duration-200 ease-out motion-reduce:transition-none animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none"
className="thread-composer-notice mb-2 flex flex-wrap items-center gap-3 rounded-control border border-border/70 bg-muted/35 px-3 py-2 text-sm transition-[background-color,border-color,opacity,transform] duration-200 ease-out motion-reduce:transition-none animate-in fade-in-0 slide-in-from-bottom-1 duration-200 motion-reduce:animate-none"
>
<AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" aria-hidden />
<div className="min-w-0 flex-1">
<div className="min-w-0 flex-1 basis-48">
<p className="font-medium">
{title}
</p>
{modelFailure && onOpenSettings ? (
<Button variant="link" size="sm" className="h-auto px-0 py-1" onClick={onOpenSettings}>
{t("thread.composer.reauthSettings")}
</Button>
) : null}
<p className={cn(
"mt-0.5 text-xs",
error ? "text-destructive" : "text-muted-foreground",
@@ -74,7 +84,7 @@ export function RecoveryNotice({ state, onContinue, onDismiss }: RecoveryNoticeP
{error ?? detail}
</p>
</div>
<div className="flex shrink-0 items-center gap-1.5">
<div className="ms-auto flex shrink-0 items-center gap-1.5">
<Button
type="button"
size="sm"
@@ -10,6 +10,7 @@ import type { StreamError } from "@/lib/nanobot-client";
interface StreamErrorNoticeProps {
error: StreamError;
onDismiss: () => void;
onOpenSettings?: () => void;
}
/**
@@ -17,7 +18,7 @@ interface StreamErrorNoticeProps {
* visible failed message. ``role="alert"`` + ``aria-live="assertive"``
* ensures screen readers announce the failure.
*/
export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps) {
export function StreamErrorNotice({ error, onDismiss, onOpenSettings }: StreamErrorNoticeProps) {
const { t } = useTranslation();
const { title, body } = resolveCopy(error, t);
@@ -27,7 +28,7 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
role="alert"
aria-live="assertive"
className={cn(
"mb-2 flex items-start gap-2 rounded-lg border border-destructive/30",
"thread-composer-notice mb-2 flex items-start gap-2 rounded-control border border-destructive/30",
"bg-destructive/10 px-3 py-2 text-[12px] leading-5 text-destructive",
"animate-in fade-in-0 slide-in-from-bottom-1",
)}
@@ -36,9 +37,14 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
className="mt-0.5 h-4 w-4 shrink-0"
aria-hidden
/>
<div className="flex-1">
<div className="min-w-0 flex-1">
<p className="font-medium">{title}</p>
<p className="mt-0.5 text-destructive">{body}</p>
{error.kind === "model_request_failed" && onOpenSettings ? (
<Button variant="link" size="sm" className="h-auto px-0 py-1" onClick={onOpenSettings}>
{t("thread.composer.reauthSettings")}
</Button>
) : null}
</div>
<Button
variant="ghost"
@@ -2565,8 +2565,8 @@ export function ThreadComposer({
"thread-composer-surface group/composer relative mx-auto flex w-full flex-col overflow-visible transition-all duration-200",
paletteBeside && "col-start-1 row-start-1",
isHero
? "max-w-[58rem] rounded-prominent bg-muted/80 focus-within:bg-muted dark:bg-card dark:focus-within:bg-white/[0.06]"
: "max-w-[49.5rem] rounded-panel bg-muted/80 focus-within:bg-muted dark:bg-card dark:focus-within:bg-white/[0.06]",
? "max-w-[var(--composer-content-width,58rem)] rounded-prominent bg-muted/80 focus-within:bg-muted dark:bg-card dark:focus-within:bg-white/[0.06]"
: "max-w-[var(--composer-content-width,49.5rem)] rounded-panel bg-muted/80 focus-within:bg-muted dark:bg-card dark:focus-within:bg-white/[0.06]",
compactWhenIdle && "thread-composer-collapsible transition-colors motion-reduce:transition-none",
interactionDisabled && "opacity-60",
sessionDragPreview && "ring-1 ring-primary/25",
+4 -2
View File
@@ -1862,7 +1862,7 @@ export function ThreadShell({
);
const composer = (
<>
<div className={composerVariant === "hero" ? "thread-composer-stack is-hero" : "thread-composer-stack"}>
{modelFallback?.chatId === chatId && !modelFallback.dismissed ? (
<ModelFallbackNotice
model={modelFallback.model}
@@ -1879,12 +1879,14 @@ export function ThreadShell({
state={recoveryState}
onContinue={continueRecovery}
onDismiss={dismissRecovery}
onOpenSettings={onOpenModelSettings}
/>
) : null}
{streamError && !hasInlineDeliveryError(messages, streamError) ? (
<StreamErrorNotice
error={streamError}
onDismiss={dismissStreamError}
onOpenSettings={onOpenModelSettings}
/>
) : null}
{session ? (
@@ -2001,7 +2003,7 @@ export function ThreadShell({
onQuotedContextChange={setQuotedContext}
/>
)}
</>
</div>
);
const emptyState = initialHistoryLoading ? (
+21
View File
@@ -2,6 +2,27 @@
@tailwind components;
@tailwind utilities;
/* Notices and the input share one width, including the compact screen inset. */
.thread-composer-stack {
--composer-content-width: 49.5rem;
}
.thread-composer-stack.is-hero {
--composer-content-width: 58rem;
}
.thread-composer-notice {
width: calc(100% - 0.5rem);
max-width: var(--composer-content-width, 49.5rem);
margin-inline: auto;
}
.thread-composer-stack.is-hero .thread-composer-notice {
width: 100%;
}
@media (min-width: 640px) {
.thread-composer-notice {
width: 100%;
}
}
@supports (content-visibility: auto) {
.apps-catalog-row {
content-visibility: auto;
+12
View File
@@ -818,8 +818,14 @@ export function useNanobotStream(
...(typeof ev.can_continue === "boolean"
? { can_continue: ev.can_continue }
: {}),
...(typeof ev.failure_error_kind === "string"
? { failure_error_kind: ev.failure_error_kind }
: {}),
};
setRecoveryState(next);
if (ev.reason === "model_request_failed" || ev.status === "resuming") {
setStreamError(null);
}
if (ev.status === "resuming") {
setRunStartedAt((current) => current ?? Date.now() / 1000);
setIsStreaming(true);
@@ -846,6 +852,12 @@ export function useNanobotStream(
if (ev.event === "attached") {
setRecoveryState(ev.recovery_state ?? null);
if (
ev.recovery_state?.reason === "model_request_failed"
|| ev.recovery_state?.status === "resuming"
) {
setStreamError(null);
}
if (ev.recovery_state?.status === "resuming") {
setRunStartedAt((current) => current ?? Date.now() / 1000);
setIsStreaming(true);
+4 -2
View File
@@ -2564,6 +2564,8 @@
"body": "The gateway rejected this message. Review its text or attachments, then try again."
},
"modelRequestFailed": {
"authenticationTitle": "Model provider authorization failed",
"authenticationBody": "Sign in again or check the provider’s API key in model settings.",
"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",
@@ -2571,8 +2573,8 @@
"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."
"bodyWithAttempt": "Stopped after {{attempts}} attempts. Try again later or choose another model.",
"body": "Try again later or choose another model."
}
},
"workspace": {
+4 -2
View File
@@ -2365,6 +2365,8 @@
"body": "El gateway rechazó este mensaje. Revisa el texto o los archivos adjuntos e inténtalo de nuevo."
},
"modelRequestFailed": {
"authenticationTitle": "Falló la autorización del proveedor del modelo",
"authenticationBody": "Vuelve a iniciar sesión o revisa la clave API en los ajustes del modelo.",
"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",
@@ -2372,8 +2374,8 @@
"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."
"bodyWithAttempt": "Se detuvo tras {{attempts}} intentos. Inténtalo más tarde o elige otro modelo.",
"body": "Inténtalo más tarde o elige otro modelo."
}
},
"workspace": {
+4 -2
View File
@@ -2364,6 +2364,8 @@
"body": "La passerelle a refusé ce message. Vérifiez le texte ou les pièces jointes, puis réessayez."
},
"modelRequestFailed": {
"authenticationTitle": "Échec de l’autorisation du fournisseur du modèle",
"authenticationBody": "Reconnectez-vous ou vérifiez la clé API dans les paramètres du modèle.",
"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",
@@ -2371,8 +2373,8 @@
"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."
"bodyWithAttempt": "Arrêt après {{attempts}} tentatives. Réessayez plus tard ou choisissez un autre modèle.",
"body": "Réessayez plus tard ou choisissez un autre modèle."
}
},
"workspace": {
+4 -2
View File
@@ -2364,6 +2364,8 @@
"body": "Gateway menolak pesan ini. Periksa teks atau lampiran, lalu coba lagi."
},
"modelRequestFailed": {
"authenticationTitle": "Otorisasi penyedia model gagal",
"authenticationBody": "Masuk kembali atau periksa kunci API di pengaturan model.",
"billingTitle": "Kuota penyedia model tidak tersedia",
"billingBody": "Tambahkan kredit atau periksa tagihan akun penyedia, lalu coba lagi.",
"connectionTitle": "Tidak dapat terhubung ke penyedia model",
@@ -2371,8 +2373,8 @@
"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."
"bodyWithAttempt": "Dihentikan setelah {{attempts}} percobaan. Coba lagi nanti atau pilih model lain.",
"body": "Coba lagi nanti atau pilih model lain."
}
},
"workspace": {
+4 -2
View File
@@ -2364,6 +2364,8 @@
"body": "ゲートウェイがこのメッセージを拒否しました。本文または添付ファイルを確認して、もう一度お試しください。"
},
"modelRequestFailed": {
"authenticationTitle": "モデルプロバイダーの認証に失敗しました",
"authenticationBody": "モデル設定で再度ログインするか、API キーを確認してください。",
"billingTitle": "モデルプロバイダーの利用枠を使用できません",
"billingBody": "プロバイダーアカウントにクレジットを追加するか、請求状況を確認してから、もう一度お試しください。",
"connectionTitle": "モデルプロバイダーに接続できません",
@@ -2371,8 +2373,8 @@
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
"bodyWithAttempt": "{{attempts}} 回目の試行でもリクエストに失敗したため、再試行を停止しました。プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。",
"body": "プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。"
"bodyWithAttempt": "{{attempts}} 回試行して停止しました。後でもう一度試すか、別のモデルを選んでください。",
"body": "後でもう一度試すか、別のモデルを選んでください。"
}
},
"workspace": {
+4 -2
View File
@@ -2364,6 +2364,8 @@
"body": "게이트웨이가 이 메시지를 거부했습니다. 텍스트나 첨부 파일을 확인한 후 다시 시도하세요."
},
"modelRequestFailed": {
"authenticationTitle": "모델 제공업체 인증 실패",
"authenticationBody": "모델 설정에서 다시 로그인하거나 API 키를 확인하세요.",
"billingTitle": "모델 제공업체 할당량을 사용할 수 없음",
"billingBody": "제공업체 계정에 크레딧을 추가하거나 결제 상태를 확인한 후 다시 시도하세요.",
"connectionTitle": "모델 제공업체에 연결할 수 없음",
@@ -2371,8 +2373,8 @@
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
"serverTitle": "모델 제공업체 서비스 오류",
"unknownTitle": "모델 제공업체 요청 실패",
"bodyWithAttempt": "{{attempts}}번째 시도에서도 요청이 실패하여 재시도를 중지했습니다. 제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요.",
"body": "제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요."
"bodyWithAttempt": "{{attempts}}회 시도 후 중지했습니다. 나중에 다시 시도하거나 다른 모델을 선택하세요.",
"body": "나중에 다시 시도하거나 다른 모델을 선택하세요."
}
},
"workspace": {
+4 -2
View File
@@ -2378,6 +2378,8 @@
"body": "O gateway rejeitou esta mensagem. Revise o texto ou os anexos e tente novamente."
},
"modelRequestFailed": {
"authenticationTitle": "Falha na autorização do provedor do modelo",
"authenticationBody": "Entre novamente ou verifique a chave API nas configurações do modelo.",
"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",
@@ -2385,8 +2387,8 @@
"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."
"bodyWithAttempt": "Interrompido após {{attempts}} tentativas. Tente mais tarde ou escolha outro modelo.",
"body": "Tente mais tarde ou escolha outro modelo."
}
},
"workspace": {
+4 -2
View File
@@ -2364,6 +2364,8 @@
"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": {
"authenticationTitle": "Xác thực nhà cung cấp mô hình thất bại",
"authenticationBody": "Đăng nhập lại hoặc kiểm tra khóa API trong cài đặt mô hình.",
"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",
@@ -2371,8 +2373,8 @@
"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."
"bodyWithAttempt": "Đã dừng sau {{attempts}} lần thử. Hãy thử lại sau hoặc chọn mô hình khác.",
"body": "Hãy thử lại sau hoặc chọn mô hình khác."
}
},
"workspace": {
+4 -2
View File
@@ -2564,6 +2564,8 @@
"body": "网关拒绝了这条消息。请检查消息内容或附件后重试。"
},
"modelRequestFailed": {
"authenticationTitle": "模型提供商验证失败",
"authenticationBody": "请在模型设置中重新登录或检查 API 密钥。",
"billingTitle": "模型提供商账户额度不足",
"billingBody": "请为提供商账户充值或检查账单状态后重试。",
"connectionTitle": "无法连接模型提供商",
@@ -2571,8 +2573,8 @@
"rateLimitTitle": "模型提供商请求受限",
"serverTitle": "模型提供商服务异常",
"unknownTitle": "模型提供商请求失败",
"bodyWithAttempt": "模型提供商请求在第 {{attempts}} 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
"body": "请检查提供商配置或服务状态后重试。"
"bodyWithAttempt": "已尝试 {{attempts}} 次,仍未成功。可稍后继续或切换模型。",
"body": "可稍后继续或切换模型。"
}
},
"workspace": {
+4 -2
View File
@@ -2364,6 +2364,8 @@
"body": "閘道拒絕了這則訊息。請檢查內容或附件後再試一次。"
},
"modelRequestFailed": {
"authenticationTitle": "模型供應商驗證失敗",
"authenticationBody": "請在模型設定中重新登入或檢查 API 金鑰。",
"billingTitle": "模型供應商額度無法使用",
"billingBody": "請為供應商帳戶儲值或檢查帳單狀態後再試。",
"connectionTitle": "無法連線至模型供應商",
@@ -2371,8 +2373,8 @@
"rateLimitTitle": "模型供應商請求受到限制",
"serverTitle": "模型供應商服務發生錯誤",
"unknownTitle": "模型供應商請求失敗",
"bodyWithAttempt": "模型供應商請求在第 {{attempts}} 次嘗試後仍然失敗,已停止重試。請檢查供應商設定或服務狀態後再試。",
"body": "請檢查供應商設定或服務狀態後再試。"
"bodyWithAttempt": "已嘗試 {{attempts}} 次,仍未成功。可稍後繼續或切換模型。",
"body": "可稍後繼續或切換模型。"
}
},
"workspace": {
+4
View File
@@ -12,6 +12,8 @@ export function resolveModelRequestFailureCopy(
let titleKey = "errors.modelRequestFailed.unknownTitle";
if (details.errorKind === "billing") {
titleKey = "errors.modelRequestFailed.billingTitle";
} else if (details.errorKind === "authentication") {
titleKey = "errors.modelRequestFailed.authenticationTitle";
} else if (details.errorKind === "connection") {
titleKey = "errors.modelRequestFailed.connectionTitle";
} else if (details.errorKind === "timeout") {
@@ -25,6 +27,8 @@ export function resolveModelRequestFailureCopy(
let bodyKey = "errors.modelRequestFailed.body";
if (details.errorKind === "billing") {
bodyKey = "errors.modelRequestFailed.billingBody";
} else if (details.errorKind === "authentication") {
bodyKey = "errors.modelRequestFailed.authenticationBody";
} else if (typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0) {
bodyKey = "errors.modelRequestFailed.bodyWithAttempt";
}
+9 -7
View File
@@ -209,12 +209,12 @@ describe("MessageBubble", () => {
const pill = screen.getByText("hello");
expect(row).toHaveClass("ml-auto", "flex");
expect(row).toHaveAttribute("data-user-text-bubble", "true");
expect(pill.parentElement).toHaveAttribute("data-user-text-bubble", "true");
expect(pill).toHaveClass("ml-auto", "w-fit", "rounded-floating");
expect(pill).toHaveTextContent("hello");
});
it("aligns the context trigger to the first text line only when text leads the user block", () => {
it("anchors the context trigger to the text even below an image or quote", () => {
const message: UIMessage = {
id: "u-alignment", role: "user", content: "first line\nsecond line", createdAt: 0,
};
@@ -222,15 +222,17 @@ describe("MessageBubble", () => {
const { container, rerender } = render(
<MessageBubble message={message} contextMenu={contextMenu} />,
);
const row = container.firstElementChild!;
expect(row).toHaveAttribute("data-user-text-bubble", "true");
expect(screen.getByRole("button", { name: "Message actions" }).parentElement).toBe(row);
const anchor = container.querySelector("[data-user-text-bubble]")!;
expect(anchor).toHaveClass("relative");
expect(screen.getByRole("button", { name: "Message actions" }).parentElement).toBe(anchor);
rerender(<MessageBubble message={{ ...message, images: [{ name: "image.png" }] }} contextMenu={contextMenu} />);
expect(row).not.toHaveAttribute("data-user-text-bubble");
expect(screen.getByRole("button", { name: "Message actions" }).parentElement)
.toBe(container.querySelector("[data-user-text-bubble]"));
rerender(<MessageBubble message={{ ...message, content: "> [!QUOTE]\n> excerpt\n\nreply" }} contextMenu={contextMenu} />);
expect(row).not.toHaveAttribute("data-user-text-bubble");
expect(screen.getByRole("button", { name: "Message actions" }).parentElement)
.toBe(screen.getByText("reply").parentElement);
});
it("renders cross-session input with its public handle", () => {
@@ -5,11 +5,12 @@ 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(
const titles = ["authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown"].map(
(errorKind) => resolveModelRequestFailureCopy({ errorKind }, i18n.t).title,
);
expect(titles).toEqual([
"Model provider authorization failed",
"Model provider quota is unavailable",
"Could not connect to the model provider",
"Model provider request timed out",
@@ -24,8 +25,7 @@ describe("model request failure copy", () => {
{ 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.",
"Stopped after 4 attempts. Try again later or choose another model.",
);
});
@@ -42,7 +42,7 @@ describe("model request failure copy", () => {
const body = resolveModelRequestFailureCopy({ errorKind: "unknown" }, i18n.t).body;
expect(body).toBe(
"Check the provider configuration or service status, then try again.",
"Try again later or choose another model.",
);
});
});
+18 -1
View File
@@ -62,7 +62,7 @@ describe("RecoveryNotice", () => {
expect(notice).toHaveAttribute("data-recovery-status", "awaiting_user");
expect(notice).toHaveAttribute("aria-live", "assertive");
expect(notice).toHaveClass(
"max-w-[49.5rem]",
"thread-composer-notice",
"rounded-control",
"animate-in",
"fade-in-0",
@@ -136,4 +136,21 @@ describe("RecoveryNotice", () => {
expect(screen.queryByRole("button", { name: "Continue" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Dismiss" })).toBeInTheDocument();
});
it("shows model authorization recovery after loading saved state", () => {
const onOpenSettings = vi.fn();
render(
<RecoveryNotice
state={{ ...INTERRUPTED, reason: "model_request_failed", failure_error_kind: "authentication" }}
onContinue={vi.fn().mockResolvedValue(undefined)}
onDismiss={vi.fn().mockResolvedValue(undefined)}
onOpenSettings={onOpenSettings}
/>,
);
expect(screen.getByRole("alert")).toHaveTextContent("Model provider authorization failed");
expect(screen.getByRole("alert")).not.toHaveTextContent("Task interrupted");
fireEvent.click(screen.getByRole("button", { name: "Open model settings" }));
expect(onOpenSettings).toHaveBeenCalledOnce();
expect(screen.getByRole("button", { name: "Continue" })).toBeEnabled();
});
});
+2 -2
View File
@@ -589,7 +589,7 @@ describe("ThreadComposer", () => {
expect(input.className).toContain("pt-[27px]");
fireEvent.change(input, { target: { value: "1" } });
expect(input.className).toContain("pt-[27px]");
expect(input.parentElement?.parentElement?.className).toContain("max-w-[58rem]");
expect(input.parentElement?.parentElement?.className).toContain("max-w-[var(--composer-content-width,58rem)]");
});
it("defers textarea autosizing until IME composition commits", () => {
@@ -821,7 +821,7 @@ describe("ThreadComposer", () => {
const input = screen.getByPlaceholderText("Type your message...");
expect(input.className).toContain("min-h-[50px]");
expect(input.className).toContain("text-composer");
expect(input.parentElement?.parentElement?.className).toContain("max-w-[49.5rem]");
expect(input.parentElement?.parentElement?.className).toContain("max-w-[var(--composer-content-width,49.5rem)]");
expect(input.parentElement?.parentElement?.className).toContain("rounded-panel");
expect(input.parentElement?.parentElement?.className).not.toContain("shadow-");
expect(screen.getByRole("button", { name: "Send message" }).className).toContain("bg-foreground");
+28 -2
View File
@@ -5030,7 +5030,7 @@ describe("ThreadShell", () => {
});
});
it("keeps a terminal model failure visible until the next user action", async () => {
it.each([false, true])("keeps one terminal model failure visible until the next user action (recovery: %s)", async (recoverable) => {
const client = makeClient();
await act(async () => {
await i18n.changeLanguage("zh-CN");
@@ -5066,14 +5066,40 @@ describe("ThreadShell", () => {
const banner = await screen.findByRole("alert");
expect(banner).toHaveTextContent("无法连接模型提供商");
expect(banner).toHaveTextContent(
"模型提供商请求在第 4 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
"已尝试 4 次,仍未成功。可稍后继续或切换模型。",
);
expect(banner).not.toHaveTextContent("Unlocalized server failure");
if (recoverable) {
act(() => {
client._emitChat("chat-model-failure", {
event: "recovery_state",
chat_id: "chat-model-failure",
recovery_id: "model-recovery",
status: "awaiting_user",
reason: "model_request_failed",
failure_error_kind: "connection",
});
});
expect(screen.getAllByRole("alert")).toHaveLength(1);
expect(screen.getByRole("alert")).toHaveTextContent("无法连接模型提供商");
expect(screen.getByRole("button", { name: "继续" })).toBeEnabled();
}
fireEvent.change(screen.getByLabelText("消息输入框"), {
target: { value: "try again" },
});
fireEvent.click(screen.getByRole("button", { name: "发送消息" }));
if (recoverable) {
act(() => {
client._emitChat("chat-model-failure", {
event: "recovery_state",
chat_id: "chat-model-failure",
recovery_id: "model-recovery",
status: "recovered",
reason: "superseded",
});
});
}
await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+30
View File
@@ -726,6 +726,36 @@ describe("useNanobotStream", () => {
expect(fake.client.finishRunLocally).toHaveBeenCalledWith("chat-recovery");
});
it.each(["awaiting_user", "resuming"] as const)(
"reconciles a missed model recovery event after reconnecting to %s",
(status) => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-recovery", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
fake.emit("chat-recovery", {
event: "turn_end", chat_id: "chat-recovery",
outcome: "failed", failure_kind: "model", failure_error_kind: "connection",
});
});
expect(result.current.streamError?.kind).toBe("model_request_failed");
act(() => {
fake.emit("chat-recovery", {
event: "attached", chat_id: "chat-recovery",
recovery_state: {
recovery_id: "recovery-1", status,
reason: status === "resuming" ? "user_confirmed" : "model_request_failed",
failure_error_kind: "connection",
},
});
});
expect(result.current.streamError).toBeNull();
expect(result.current.recoveryState?.status).toBe(status);
expect(result.current.isStreaming).toBe(status === "resuming");
},
);
it("does not let historical recovered state clear a later active turn", () => {
const fake = fakeClient();
const { result } = renderHook(