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

@@ -57,7 +57,14 @@ import type { FileEditDisplayMode } from "@/lib/local-preferences";
import { logoFallbackUrls } from "@/lib/provider-brand";
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, ToolProgressEvent, UIFileEdit, UIMessage } from "@/lib/types";
import type {
CliAppInfo,
McpPresetInfo,
RetryStatus,
ToolProgressEvent,
UIFileEdit,
UIMessage,
} from "@/lib/types";
const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;
@@ -143,6 +150,7 @@ interface AgentActivityClusterProps {
turnLatencyMs?: number;
/** User turn start timestamp for live activity before the first trace/reasoning row. */
startedAtMs?: number;
retryStatus?: RetryStatus | null;
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
onOpenFilePreview?: (path: string) => void;
@@ -158,6 +166,7 @@ export function AgentActivityCluster({
hasBodyBelow,
turnLatencyMs,
startedAtMs,
retryStatus = null,
cliApps = [],
mcpPresets = [],
onOpenFilePreview,
@@ -219,7 +228,34 @@ export function AgentActivityCluster({
startedAtMs,
);
const activityDuration = formatActivityDuration(durationMs);
const activityLabel = isTurnStreaming
const retryError = retryStatus?.error_kind === "connection"
? t("message.retryConnection", { defaultValue: "Connection failed" })
: retryStatus?.error_kind === "timeout"
? t("message.retryTimeout", { defaultValue: "Model timed out" })
: retryStatus?.error_kind === "rate_limit"
? t("message.retryRateLimit", { defaultValue: "Rate limited" })
: retryStatus?.error_kind === "server"
? t("message.retryServer", { defaultValue: "Model unavailable" })
: t("message.retryUnknown", { defaultValue: "Model request failed" });
const retryAttempt = retryStatus?.max_attempts
? `${retryStatus.attempt}/${retryStatus.max_attempts}`
: String(retryStatus?.attempt ?? "");
const retrySeconds = retryStatus?.next_retry_at === undefined
? 0
: Math.max(0, Math.ceil(retryStatus.next_retry_at - now / 1000));
const activityLabel = retryStatus?.state === "exhausted"
? t("message.retryExhausted", {
error: retryError,
defaultValue: "{{error}} · ending turn",
})
: retryStatus?.state === "waiting"
? t("message.retryWaiting", {
error: retryError,
seconds: retrySeconds,
attempt: retryAttempt,
defaultValue: "{{error}} · retrying in {{seconds}}s · attempt {{attempt}}",
})
: isTurnStreaming
? t("message.activityWorkingFor", {
duration: activityDuration,
defaultValue: "Working for {{duration}}",
@@ -1,7 +1,9 @@
import { AlertTriangle, X } from "lucide-react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
import { cn } from "@/lib/utils";
import type { StreamError } from "@/lib/nanobot-client";
@@ -53,7 +55,7 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
function resolveCopy(
error: StreamError,
t: (key: string) => string,
t: TFunction,
): { title: string; body: string } {
switch (error.kind) {
case "message_too_big":
@@ -71,6 +73,8 @@ function resolveCopy(
title: t("errors.turnRejected.title"),
body: t("errors.turnRejected.body"),
};
case "model_request_failed":
return resolveModelRequestFailureCopy(error, t);
default: {
// Exhaustiveness guard: if a new StreamError kind is added, TS will
// complain here until we add a corresponding i18n branch.
+14 -2
View File
@@ -4,7 +4,7 @@ import { MessageBubble } from "@/components/MessageBubble";
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
import type { CliAppInfo, McpPresetInfo, SlashCommand, UIMessage } from "@/lib/types";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
interface ThreadMessagesProps {
messages: UIMessage[];
@@ -14,6 +14,7 @@ interface ThreadMessagesProps {
activeTurnId?: string | null;
/** Optimistic or canonical active-turn start, in unix seconds. */
runStartedAt?: number | null;
retryStatus?: RetryStatus | null;
hiddenUserMessageCount?: number;
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
@@ -63,6 +64,7 @@ export function ThreadMessages({
isStreaming = false,
activeTurnId = null,
runStartedAt = null,
retryStatus = null,
hiddenUserMessageCount = 0,
cliApps = [],
mcpPresets = [],
@@ -97,7 +99,7 @@ export function ThreadMessages({
isStreaming
&& liveActivityClusterIndices.size === 0
&& pendingTurn !== null
&& !pendingTurn.hasVisibleOutput
&& (retryStatus !== null || !pendingTurn.hasVisibleOutput)
) ? pendingTurn : null;
const currentTurnStartIndex = isStreaming
? activeTurnStartIndex(units, activeTurnId)
@@ -161,6 +163,11 @@ export function ThreadMessages({
: index > currentTurnStartIndex
)
}
retryStatus={
unit.type === "activity" && liveActivityClusterIndices.has(index)
? retryStatus
: null
}
forkIndex={forkIndex}
showForkBoundary={index === forkBoundaryAfterUnitIndex}
forkBoundaryLabel={t("thread.forkedFromHistory")}
@@ -179,6 +186,7 @@ export function ThreadMessages({
messages={[]}
isTurnStreaming
hasBodyBelow={false}
retryStatus={retryStatus}
startedAtMs={
runStartedAt != null
? runStartedAt * 1000
@@ -243,6 +251,7 @@ interface ThreadDisplayUnitProps {
hasBodyBelow: boolean;
deferOffscreenRender: boolean;
isTurnStreaming: boolean;
retryStatus: RetryStatus | null;
forkIndex?: number;
showForkBoundary: boolean;
forkBoundaryLabel: string;
@@ -262,6 +271,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
hasBodyBelow,
deferOffscreenRender,
isTurnStreaming,
retryStatus,
forkIndex,
showForkBoundary,
forkBoundaryLabel,
@@ -293,6 +303,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
<AgentActivityCluster
messages={unit.messages}
isTurnStreaming={isTurnStreaming}
retryStatus={retryStatus}
hasBodyBelow={hasBodyBelow}
turnLatencyMs={unit.turnLatencyMs}
startedAtMs={unit.startedAtMs}
@@ -329,6 +340,7 @@ function threadDisplayUnitPropsEqual(
&& previous.hasBodyBelow === next.hasBodyBelow
&& previous.deferOffscreenRender === next.deferOffscreenRender
&& previous.isTurnStreaming === next.isTurnStreaming
&& previous.retryStatus === next.retryStatus
&& previous.forkIndex === next.forkIndex
&& previous.showForkBoundary === next.showForkBoundary
&& previous.forkBoundaryLabel === next.forkBoundaryLabel
@@ -820,6 +820,7 @@ export function ThreadShell({
messagesReady,
isStreaming,
runStartedAt,
retryStatus,
goalState,
recoveryState,
continueRecovery,
@@ -1726,6 +1727,7 @@ export function ThreadShell({
temporary={temporary}
isStreaming={turnActive}
runStartedAt={currentRunStartedAt}
retryStatus={retryStatus}
emptyState={emptyState}
composer={composerPortalTarget === undefined ? composer : null}
activeTurnId={viewportTurnId}
@@ -26,7 +26,7 @@ import {
promptTop,
} from "@/components/thread/promptNavigation";
import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, SlashCommand, UIMessage } from "@/lib/types";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
export interface ThreadViewportHandle {
jumpToUserPrompt: (promptId: string) => void;
@@ -39,6 +39,7 @@ interface ThreadViewportProps {
isStreaming: boolean;
/** Optimistic or canonical start time for the active turn, in unix seconds. */
runStartedAt?: number | null;
retryStatus?: RetryStatus | null;
composer?: ReactNode;
emptyState?: ReactNode;
scrollToBottomSignal?: number;
@@ -221,6 +222,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
temporary = false,
isStreaming,
runStartedAt = null,
retryStatus = null,
composer,
emptyState,
scrollToBottomSignal = 0,
@@ -878,6 +880,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
isStreaming={isStreaming}
activeTurnId={activeTurnId}
runStartedAt={runStartedAt}
retryStatus={retryStatus}
hiddenUserMessageCount={hiddenUserMessageCount}
cliApps={cliApps}
mcpPresets={mcpPresets}
+78 -1
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { useClient } from "@/providers/ClientProvider";
import { toMediaAttachment } from "@/lib/media";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
import {
mergeToolProgressEvents,
mergeToolProgressTraceLines,
@@ -39,6 +40,7 @@ import type {
GoalStateWsPayload,
MessageDeliveryStatus,
RecoveryState,
RetryStatus,
UIMediaAttachment,
UIMessage,
WorkspaceScopePayload,
@@ -247,6 +249,8 @@ export function useNanobotStream(
isStreaming: boolean;
/** Unix epoch seconds when the current user turn started (WebSocket ``goal_status``). */
runStartedAt: number | null;
/** Transient model retry state for the active turn. */
retryStatus: RetryStatus | null;
/** Latest sustained goal for this ``chatId`` (``goal_state`` WS events). */
goalState: GoalStateWsPayload | undefined;
recoveryState: RecoveryState | null;
@@ -281,6 +285,7 @@ export function useNanobotStream(
);
/** Unix epoch seconds when the current user turn started; cleared on ``idle``. */
const [runStartedAt, setRunStartedAt] = useState<number | null>(initialRunStartedAt);
const [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
const [streamError, setStreamError] = useState<StreamError | null>(null);
@@ -366,6 +371,7 @@ export function useNanobotStream(
// still be shown in the mounted thread, but cannot roll back any turn.
if (!chatId || (err.chatId && err.chatId !== chatId)) return;
setStreamError(err);
if (err.kind === "model_request_failed") return;
if (!err.turnId) return;
const rejectedTurnId = err.turnId;
@@ -680,6 +686,7 @@ export function useNanobotStream(
);
setStreamError(null);
setRunStartedAt(restoredRunStartedAt);
setRetryStatus(null);
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null);
buffer.current = null;
@@ -802,6 +809,13 @@ export function useNanobotStream(
});
return;
}
if (
ev.event === "delta"
|| ev.event === "message"
|| ev.event === "file_edit"
|| ev.event === "reasoning_delta"
|| ev.event === "stream_end"
) setRetryStatus(null);
if (ev.event === "delta") {
if (suppressStreamUntilTurnEndRef.current) return;
const chunk = typeof ev.text === "string" ? ev.text : "";
@@ -875,11 +889,42 @@ export function useNanobotStream(
if (ev.event === "goal_status") {
if (ev.status === "running" && typeof ev.started_at === "number") {
setStreamError(null);
setRunStartedAt(ev.started_at);
setIsStreaming(true);
} else {
setRunStartedAt(null);
setIsStreaming(false);
setRetryStatus(null);
}
return;
}
if (ev.event === "retry_status") {
const activeTurnId = client.getRunTurnId(chatId);
if (ev.turn_id && activeTurnId && ev.turn_id !== activeTurnId) return;
if (ev.state === "recovered" || ev.state === "cleared") {
setRetryStatus(null);
} else {
const retryAfterSeconds =
typeof ev.retry_after_s === "number" &&
Number.isFinite(ev.retry_after_s) &&
ev.retry_after_s >= 0
? ev.retry_after_s
: undefined;
setRetryStatus({
state: ev.state,
attempt: ev.attempt,
error_kind: ev.error_kind,
...(typeof ev.max_attempts === "number"
? { max_attempts: ev.max_attempts }
: {}),
...(retryAfterSeconds !== undefined
? { next_retry_at: Date.now() / 1000 + retryAfterSeconds }
: {}),
...(ev.turn_id ? { turn_id: ev.turn_id } : {}),
});
setIsStreaming(true);
}
return;
}
@@ -890,9 +935,29 @@ export function useNanobotStream(
setGoalState(ev.goal_state);
}
setRunStartedAt(null);
setRetryStatus(null);
// Definitive signal that the turn is fully complete, so stop the
// loading indicator immediately.
setIsStreaming(false);
const modelRequestFailed = ev.outcome === "failed" && ev.failure_kind === "model";
const failureAttempts =
typeof ev.failure_attempts === "number"
&& Number.isInteger(ev.failure_attempts)
&& ev.failure_attempts > 0
? ev.failure_attempts
: undefined;
const modelFailure = modelRequestFailed
? {
kind: "model_request_failed" as const,
chatId,
...(ev.turn_id ? { turnId: ev.turn_id } : {}),
...(typeof ev.failure_error_kind === "string"
? { errorKind: ev.failure_error_kind }
: {}),
...(failureAttempts !== undefined ? { attempts: failureAttempts } : {}),
}
: null;
if (modelFailure) setStreamError(modelFailure);
const completedAt = Date.now();
setMessages((prev) => {
let finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
@@ -920,7 +985,13 @@ export function useNanobotStream(
return finalized;
});
suppressStreamUntilTurnEndRef.current = false;
notifyInBackground(t("recovery.completed", { defaultValue: "Task completed" }));
notifyInBackground(
modelFailure
? resolveModelRequestFailureCopy(modelFailure, t).body
: ev.outcome === "failed"
? ev.failure_message || "This turn failed and has ended."
: t("recovery.completed", { defaultValue: "Task completed" }),
);
onTurnEnd?.();
return;
}
@@ -945,6 +1016,7 @@ export function useNanobotStream(
|| ev.status === "recovered"
|| ev.status === "failed"
) {
setRetryStatus(null);
// Recovery is an explicit boundary. The interrupted turn is no
// longer running, so do not let the stale start time keep the
// activity clock (or composer stop state) alive underneath the
@@ -1211,6 +1283,7 @@ export function useNanobotStream(
// them via ``media`` paths.
if (!hasAttachments && !content.trim()) return null;
setStreamError(null);
const sideChannel = options?.sideChannel === true;
const finalizeActiveTurn = options?.finalizeActiveTurn === true;
const continueActiveTurn = options?.continueActiveTurn === true;
@@ -1220,6 +1293,7 @@ export function useNanobotStream(
flushPendingStreamEvents();
if (finalizeActiveTurn) {
setIsStreaming(false);
setRetryStatus(null);
}
const turnId = crypto.randomUUID();
const userMessageId = crypto.randomUUID();
@@ -1280,6 +1354,7 @@ export function useNanobotStream(
if (!chatId) return;
flushPendingStreamEvents();
setIsStreaming(false);
setRetryStatus(null);
setMessages((prev) => {
buffer.current = null;
activeAssistantRef.current = null;
@@ -1301,6 +1376,7 @@ export function useNanobotStream(
clearActivitySegment();
suppressStreamUntilTurnEndRef.current = false;
setRunStartedAt(null);
setRetryStatus(null);
setIsStreaming(false);
}, [clearActivitySegment, clearPendingStreamWork]);
@@ -1332,6 +1408,7 @@ export function useNanobotStream(
messagesReady: messageOwnerChatId === chatId,
isStreaming,
runStartedAt,
retryStatus,
goalState,
recoveryState,
continueRecovery,
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "Working for {{duration}}",
"activityWorked": "Worked",
"activityWorkedFor": "Worked for {{duration}}",
"retryConnection": "Connection failed",
"retryTimeout": "Model timed out",
"retryRateLimit": "Rate limited",
"retryServer": "Model unavailable",
"retryUnknown": "Model request failed",
"retryWaiting": "{{error}} · retrying in {{seconds}}s · attempt {{attempt}}",
"retryExhausted": "{{error}} · ending turn",
"cliActivityRunningOne": "Using {{name}}",
"cliActivityRanOne": "Used {{name}}",
"cliActivityFailedOne": "{{name}} failed",
@@ -1546,6 +1553,17 @@
"turnRejected": {
"title": "Message was not sent",
"body": "The gateway rejected this message. Review its text or attachments, then try again."
},
"modelRequestFailed": {
"billingTitle": "Model provider quota is unavailable",
"billingBody": "Add credit or check billing for the provider account, then try again.",
"connectionTitle": "Could not connect to the model provider",
"timeoutTitle": "Model provider request timed out",
"rateLimitTitle": "Model provider rate limit reached",
"serverTitle": "Model provider service error",
"unknownTitle": "Model provider request failed",
"bodyWithAttempt": "The request still failed on attempt {{attempts}}, so retries stopped. Check the provider configuration or service status, then try again.",
"body": "Check the provider configuration or service status, then try again."
}
},
"workspace": {
+18
View File
@@ -1435,6 +1435,13 @@
"activityWorkingFor": "Trabajando durante {{duration}}",
"activityWorked": "Trabajo completado",
"activityWorkedFor": "Trabajó durante {{duration}}",
"retryConnection": "Error de conexión",
"retryTimeout": "Se agotó el tiempo de espera del modelo",
"retryRateLimit": "Límite de solicitudes alcanzado",
"retryServer": "Modelo no disponible",
"retryUnknown": "La solicitud al modelo falló",
"retryWaiting": "{{error}} · reintentando en {{seconds}} s · intento {{attempt}}",
"retryExhausted": "{{error}} · finalizando el turno",
"cliActivityRunningOne": "Usando {{name}}",
"cliActivityRanOne": "Usó {{name}}",
"cliActivityFailedOne": "Falló {{name}}",
@@ -1533,6 +1540,17 @@
"turnRejected": {
"title": "El mensaje no se envió",
"body": "El gateway rechazó este mensaje. Revisa el texto o los archivos adjuntos e inténtalo de nuevo."
},
"modelRequestFailed": {
"billingTitle": "La cuota del proveedor del modelo no está disponible",
"billingBody": "Añade crédito o revisa la facturación de la cuenta del proveedor y vuelve a intentarlo.",
"connectionTitle": "No se pudo conectar con el proveedor del modelo",
"timeoutTitle": "La solicitud al proveedor del modelo agotó el tiempo de espera",
"rateLimitTitle": "Se alcanzó el límite de solicitudes del proveedor del modelo",
"serverTitle": "Error del servicio del proveedor del modelo",
"unknownTitle": "La solicitud al proveedor del modelo falló",
"bodyWithAttempt": "La solicitud siguió fallando en el intento {{attempts}}, por lo que se detuvieron los reintentos. Revisa la configuración o el estado del proveedor y vuelve a intentarlo.",
"body": "Revisa la configuración o el estado del proveedor y vuelve a intentarlo."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Travail en cours depuis {{duration}}",
"activityWorked": "Travail terminé",
"activityWorkedFor": "Travail terminé en {{duration}}",
"retryConnection": "Échec de la connexion",
"retryTimeout": "Délai d’attente du modèle dépassé",
"retryRateLimit": "Limite de requêtes atteinte",
"retryServer": "Modèle indisponible",
"retryUnknown": "Échec de la requête au modèle",
"retryWaiting": "{{error}} · nouvelle tentative dans {{seconds}} s · tentative {{attempt}}",
"retryExhausted": "{{error}} · fin du tour",
"cliActivityRunningOne": "Utilisation de {{name}}",
"cliActivityRanOne": "{{name}} utilisé",
"cliActivityFailedOne": "Échec de {{name}}",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "Le message n’a pas été envoyé",
"body": "La passerelle a refusé ce message. Vérifiez le texte ou les pièces jointes, puis réessayez."
},
"modelRequestFailed": {
"billingTitle": "Quota du fournisseur du modèle indisponible",
"billingBody": "Ajoutez du crédit ou vérifiez la facturation du compte fournisseur, puis réessayez.",
"connectionTitle": "Impossible de se connecter au fournisseur du modèle",
"timeoutTitle": "La requête au fournisseur du modèle a expiré",
"rateLimitTitle": "Limite de requêtes du fournisseur du modèle atteinte",
"serverTitle": "Erreur du service du fournisseur du modèle",
"unknownTitle": "Échec de la requête au fournisseur du modèle",
"bodyWithAttempt": "La requête a encore échoué à la tentative {{attempts}} ; les nouvelles tentatives ont donc été arrêtées. Vérifiez la configuration ou l’état du fournisseur, puis réessayez.",
"body": "Vérifiez la configuration ou l’état du fournisseur, puis réessayez."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Memproses selama {{duration}}",
"activityWorked": "Selesai memproses",
"activityWorkedFor": "Diproses selama {{duration}}",
"retryConnection": "Koneksi gagal",
"retryTimeout": "Waktu respons model habis",
"retryRateLimit": "Batas permintaan tercapai",
"retryServer": "Model tidak tersedia",
"retryUnknown": "Permintaan model gagal",
"retryWaiting": "{{error}} · mencoba lagi dalam {{seconds}} dtk · percobaan {{attempt}}",
"retryExhausted": "{{error}} · mengakhiri giliran",
"cliActivityRunningOne": "Menggunakan {{name}}",
"cliActivityRanOne": "Menggunakan {{name}} selesai",
"cliActivityFailedOne": "{{name}} gagal",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "Pesan tidak terkirim",
"body": "Gateway menolak pesan ini. Periksa teks atau lampiran, lalu coba lagi."
},
"modelRequestFailed": {
"billingTitle": "Kuota penyedia model tidak tersedia",
"billingBody": "Tambahkan kredit atau periksa tagihan akun penyedia, lalu coba lagi.",
"connectionTitle": "Tidak dapat terhubung ke penyedia model",
"timeoutTitle": "Permintaan ke penyedia model kehabisan waktu",
"rateLimitTitle": "Batas permintaan penyedia model tercapai",
"serverTitle": "Kesalahan layanan penyedia model",
"unknownTitle": "Permintaan ke penyedia model gagal",
"bodyWithAttempt": "Permintaan masih gagal pada percobaan ke-{{attempts}}, sehingga percobaan ulang dihentikan. Periksa konfigurasi atau status layanan penyedia, lalu coba lagi.",
"body": "Periksa konfigurasi atau status layanan penyedia, lalu coba lagi."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "{{duration}}作業中",
"activityWorked": "作業しました",
"activityWorkedFor": "{{duration}}作業しました",
"retryConnection": "接続に失敗しました",
"retryTimeout": "モデルがタイムアウトしました",
"retryRateLimit": "リクエスト制限に達しました",
"retryServer": "モデルを利用できません",
"retryUnknown": "モデルリクエストに失敗しました",
"retryWaiting": "{{error}} · {{seconds}}秒後に再試行 · 試行 {{attempt}}",
"retryExhausted": "{{error}} · ターンを終了します",
"cliActivityRunningOne": "{{name}} を使用中",
"cliActivityRanOne": "{{name}} を使用しました",
"cliActivityFailedOne": "{{name}} が失敗しました",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "メッセージは送信されませんでした",
"body": "ゲートウェイがこのメッセージを拒否しました。本文または添付ファイルを確認して、もう一度お試しください。"
},
"modelRequestFailed": {
"billingTitle": "モデルプロバイダーの利用枠を使用できません",
"billingBody": "プロバイダーアカウントにクレジットを追加するか、請求状況を確認してから、もう一度お試しください。",
"connectionTitle": "モデルプロバイダーに接続できません",
"timeoutTitle": "モデルプロバイダーへのリクエストがタイムアウトしました",
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
"bodyWithAttempt": "{{attempts}} 回目の試行でもリクエストに失敗したため、再試行を停止しました。プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。",
"body": "プロバイダーの設定またはサービス状況を確認して、もう一度お試しください。"
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "{{duration}} 동안 작업 중",
"activityWorked": "작업함",
"activityWorkedFor": "{{duration}} 동안 작업함",
"retryConnection": "연결 실패",
"retryTimeout": "모델 응답 시간 초과",
"retryRateLimit": "요청 한도 초과",
"retryServer": "모델을 사용할 수 없음",
"retryUnknown": "모델 요청 실패",
"retryWaiting": "{{error}} · {{seconds}}초 후 재시도 · 시도 {{attempt}}",
"retryExhausted": "{{error}} · 턴 종료 중",
"cliActivityRunningOne": "{{name}} 사용 중",
"cliActivityRanOne": "{{name}} 사용함",
"cliActivityFailedOne": "{{name}} 실패",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "메시지가 전송되지 않았습니다",
"body": "게이트웨이가 이 메시지를 거부했습니다. 텍스트나 첨부 파일을 확인한 후 다시 시도하세요."
},
"modelRequestFailed": {
"billingTitle": "모델 제공업체 할당량을 사용할 수 없음",
"billingBody": "제공업체 계정에 크레딧을 추가하거나 결제 상태를 확인한 후 다시 시도하세요.",
"connectionTitle": "모델 제공업체에 연결할 수 없음",
"timeoutTitle": "모델 제공업체 요청 시간 초과",
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
"serverTitle": "모델 제공업체 서비스 오류",
"unknownTitle": "모델 제공업체 요청 실패",
"bodyWithAttempt": "{{attempts}}번째 시도에서도 요청이 실패하여 재시도를 중지했습니다. 제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요.",
"body": "제공업체 설정 또는 서비스 상태를 확인한 후 다시 시도하세요."
}
},
"workspace": {
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "Trabalhando por {{duration}}",
"activityWorked": "Trabalhou",
"activityWorkedFor": "Trabalhou por {{duration}}",
"retryConnection": "Falha na conexão",
"retryTimeout": "O modelo excedeu o tempo limite",
"retryRateLimit": "Limite de solicitações atingido",
"retryServer": "Modelo indisponível",
"retryUnknown": "Falha na solicitação ao modelo",
"retryWaiting": "{{error}} · tentando novamente em {{seconds}} s · tentativa {{attempt}}",
"retryExhausted": "{{error}} · encerrando o turno",
"cliActivityRunningOne": "Usando {{name}}",
"cliActivityRanOne": "Usou {{name}}",
"cliActivityFailedOne": "Falhou em {{name}}",
@@ -1546,6 +1553,17 @@
"turnRejected": {
"title": "A mensagem não foi enviada",
"body": "O gateway rejeitou esta mensagem. Revise o texto ou os anexos e tente novamente."
},
"modelRequestFailed": {
"billingTitle": "A cota do provedor do modelo está indisponível",
"billingBody": "Adicione créditos ou verifique o faturamento da conta do provedor e tente novamente.",
"connectionTitle": "Não foi possível conectar ao provedor do modelo",
"timeoutTitle": "A solicitação ao provedor do modelo expirou",
"rateLimitTitle": "Limite de solicitações do provedor do modelo atingido",
"serverTitle": "Erro no serviço do provedor do modelo",
"unknownTitle": "Falha na solicitação ao provedor do modelo",
"bodyWithAttempt": "A solicitação ainda falhou na tentativa {{attempts}}, então as novas tentativas foram interrompidas. Verifique a configuração ou o status do provedor e tente novamente.",
"body": "Verifique a configuração ou o status do provedor e tente novamente."
}
},
"workspace": {
+18
View File
@@ -1434,6 +1434,13 @@
"activityWorkingFor": "Đang xử lý trong {{duration}}",
"activityWorked": "Đã xử lý",
"activityWorkedFor": "Đã xử lý trong {{duration}}",
"retryConnection": "Kết nối thất bại",
"retryTimeout": "Mô hình đã hết thời gian chờ",
"retryRateLimit": "Đã đạt giới hạn yêu cầu",
"retryServer": "Mô hình không khả dụng",
"retryUnknown": "Yêu cầu mô hình thất bại",
"retryWaiting": "{{error}} · thử lại sau {{seconds}} giây · lần thử {{attempt}}",
"retryExhausted": "{{error}} · đang kết thúc lượt",
"cliActivityRunningOne": "Đang dùng {{name}}",
"cliActivityRanOne": "Đã dùng {{name}}",
"cliActivityFailedOne": "{{name}} thất bại",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "Tin nhắn chưa được gửi",
"body": "Gateway đã từ chối tin nhắn này. Hãy kiểm tra nội dung hoặc tệp đính kèm rồi thử lại."
},
"modelRequestFailed": {
"billingTitle": "Hạn mức của nhà cung cấp mô hình không khả dụng",
"billingBody": "Hãy nạp thêm tín dụng hoặc kiểm tra thanh toán của tài khoản nhà cung cấp rồi thử lại.",
"connectionTitle": "Không thể kết nối với nhà cung cấp mô hình",
"timeoutTitle": "Yêu cầu tới nhà cung cấp mô hình đã hết thời gian chờ",
"rateLimitTitle": "Đã đạt giới hạn yêu cầu của nhà cung cấp mô hình",
"serverTitle": "Lỗi dịch vụ nhà cung cấp mô hình",
"unknownTitle": "Yêu cầu tới nhà cung cấp mô hình không thành công",
"bodyWithAttempt": "Yêu cầu vẫn thất bại ở lần thử {{attempts}}, nên hệ thống đã dừng thử lại. Hãy kiểm tra cấu hình hoặc trạng thái dịch vụ của nhà cung cấp rồi thử lại.",
"body": "Hãy kiểm tra cấu hình hoặc trạng thái dịch vụ của nhà cung cấp rồi thử lại."
}
},
"workspace": {
+18
View File
@@ -1421,6 +1421,13 @@
"activityWorkingFor": "处理中 {{duration}}",
"activityWorked": "已处理",
"activityWorkedFor": "处理了 {{duration}}",
"retryConnection": "连接失败",
"retryTimeout": "模型响应超时",
"retryRateLimit": "请求频率受限",
"retryServer": "模型服务不可用",
"retryUnknown": "模型请求失败",
"retryWaiting": "{{error}} · {{seconds}} 秒后重试 · 第 {{attempt}} 次",
"retryExhausted": "{{error}} · 正在结束本次任务",
"cliActivityRunningOne": "正在使用 {{name}}",
"cliActivityRanOne": "已使用 {{name}}",
"cliActivityFailedOne": "使用 {{name}} 失败",
@@ -1546,6 +1553,17 @@
"turnRejected": {
"title": "消息未发送",
"body": "网关拒绝了这条消息。请检查消息内容或附件后重试。"
},
"modelRequestFailed": {
"billingTitle": "模型提供商账户额度不足",
"billingBody": "请为提供商账户充值或检查账单状态后重试。",
"connectionTitle": "无法连接模型提供商",
"timeoutTitle": "模型提供商请求超时",
"rateLimitTitle": "模型提供商请求受限",
"serverTitle": "模型提供商服务异常",
"unknownTitle": "模型提供商请求失败",
"bodyWithAttempt": "模型提供商请求在第 {{attempts}} 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
"body": "请检查提供商配置或服务状态后重试。"
}
},
"workspace": {
+18
View File
@@ -1433,6 +1433,13 @@
"activityWorkingFor": "處理中,已 {{duration}}",
"activityWorked": "已處理",
"activityWorkedFor": "已處理 {{duration}}",
"retryConnection": "連線失敗",
"retryTimeout": "模型回應逾時",
"retryRateLimit": "請求頻率受限",
"retryServer": "模型服務無法使用",
"retryUnknown": "模型請求失敗",
"retryWaiting": "{{error}} · {{seconds}} 秒後重試 · 第 {{attempt}} 次",
"retryExhausted": "{{error}} · 正在結束本輪",
"cliActivityRunningOne": "正在使用 @{{name}}",
"cliActivityRanOne": "已使用 @{{name}}",
"cliActivityFailedOne": "使用 @{{name}} 失敗",
@@ -1532,6 +1539,17 @@
"turnRejected": {
"title": "訊息未傳送",
"body": "閘道拒絕了這則訊息。請檢查內容或附件後再試一次。"
},
"modelRequestFailed": {
"billingTitle": "模型供應商帳戶額度不足",
"billingBody": "請為供應商帳戶儲值或檢查帳單狀態後再試。",
"connectionTitle": "無法連線至模型供應商",
"timeoutTitle": "模型供應商請求逾時",
"rateLimitTitle": "模型供應商請求受到限制",
"serverTitle": "模型供應商服務發生錯誤",
"unknownTitle": "模型供應商請求失敗",
"bodyWithAttempt": "模型供應商請求在第 {{attempts}} 次嘗試後仍然失敗,已停止重試。請檢查供應商設定或服務狀態後再試。",
"body": "請檢查供應商設定或服務狀態後再試。"
}
},
"workspace": {
+36
View File
@@ -0,0 +1,36 @@
import type { TFunction } from "i18next";
export interface ModelRequestFailureDetails {
errorKind?: string;
attempts?: number;
}
export function resolveModelRequestFailureCopy(
details: ModelRequestFailureDetails,
t: TFunction,
): { title: string; body: string } {
let titleKey = "errors.modelRequestFailed.unknownTitle";
if (details.errorKind === "billing") {
titleKey = "errors.modelRequestFailed.billingTitle";
} else if (details.errorKind === "connection") {
titleKey = "errors.modelRequestFailed.connectionTitle";
} else if (details.errorKind === "timeout") {
titleKey = "errors.modelRequestFailed.timeoutTitle";
} else if (details.errorKind === "rate_limit") {
titleKey = "errors.modelRequestFailed.rateLimitTitle";
} else if (details.errorKind === "server") {
titleKey = "errors.modelRequestFailed.serverTitle";
}
const attempts = details.attempts;
let bodyKey = "errors.modelRequestFailed.body";
if (details.errorKind === "billing") {
bodyKey = "errors.modelRequestFailed.billingBody";
} else if (typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0) {
bodyKey = "errors.modelRequestFailed.bodyWithAttempt";
}
return {
title: t(titleKey),
body: t(bodyKey, { attempts }),
};
}
+10 -3
View File
@@ -79,9 +79,9 @@ type RunStatusHandler = (chatId: string, startedAt: number | null) => void;
/** Structured errors surfaced to the UI.
*
* Most entries are transport-level or protocol-level faults. Workspace scope
* rejections are server application errors promoted here because they affect
* controls outside the message stream and must be visible immediately.
* Most entries are transport-level or protocol-level faults. Runtime and
* workspace failures are promoted here when they must remain visible outside
* the message stream.
*/
export type StreamError =
/** Server rejected the inbound frame as too large (WS close code 1009).
@@ -100,6 +100,13 @@ export type StreamError =
reason?: string;
chatId: string;
turnId: string;
}
| {
kind: "model_request_failed";
chatId: string;
turnId?: string;
errorKind?: string;
attempts?: number;
};
type ErrorHandler = (error: StreamError) => void;
+10 -1
View File
@@ -1,4 +1,4 @@
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../../packages/client-events/notifications";
import type { ContextCompaction, NotificationEvent, RecoveryState, RetryStatus as WireRetryStatus } from "../../../packages/client-events/notifications";
export type { RecoveryState, RecoveryStatus } from "../../../packages/client-events/notifications";
type Role = "user" | "assistant" | "tool" | "system";
@@ -64,6 +64,10 @@ export interface TurnUsage {
export type RoundUsage = TurnUsage;
export interface RetryStatus extends WireRetryStatus {
next_retry_at?: number;
turn_id?: string;
}
export interface UIMessage {
id: string;
role: Role;
@@ -1422,6 +1426,11 @@ export type InboundEvent =
context_window_tokens?: number;
/** Authoritative sustained-goal snapshot for this chat (same shape as ``goal_state`` events). */
goal_state?: GoalStateWsPayload;
outcome?: "completed" | "failed" | "cancelled" | "interrupted";
failure_kind?: string;
failure_error_kind?: string;
failure_attempts?: number;
failure_message?: string;
} & InboundTurnMetadata)
| ({
event: "goal_status";
@@ -140,6 +140,27 @@ function installReducedMotion() {
}
describe("AgentActivityCluster", () => {
it("shows model retries in the existing live activity header", () => {
render(
<AgentActivityCluster
messages={[]}
isTurnStreaming
hasBodyBelow={false}
retryStatus={{
state: "waiting",
attempt: 1,
max_attempts: 4,
error_kind: "connection",
next_retry_at: Date.now() / 1000 + 5,
}}
/>,
);
expect(
screen.getByText("Connection failed · retrying in 5s · attempt 1/4"),
).toBeInTheDocument();
});
it("keeps intermediate assistant output as normal Markdown inside live activity", async () => {
await act(async () => {
await preloadMarkdownText();
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import i18n from "@/i18n";
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
describe("model request failure copy", () => {
it("maps every sanitized provider error category to a specific cause", () => {
const titles = ["billing", "connection", "timeout", "rate_limit", "server", "unknown"].map(
(errorKind) => resolveModelRequestFailureCopy({ errorKind }, i18n.t).title,
);
expect(titles).toEqual([
"Model provider quota is unavailable",
"Could not connect to the model provider",
"Model provider request timed out",
"Model provider rate limit reached",
"Model provider service error",
"Model provider request failed",
]);
});
it("reports the final attempt and a concrete recovery action", () => {
expect(resolveModelRequestFailureCopy(
{ errorKind: "connection", attempts: 4 },
i18n.t,
).body).toBe(
"The request still failed on attempt 4, so retries stopped. "
+ "Check the provider configuration or service status, then try again.",
);
});
it("provides billing recovery without claiming a retry occurred", () => {
expect(resolveModelRequestFailureCopy(
{ errorKind: "billing" },
i18n.t,
).body).toBe(
"Add credit or check billing for the provider account, then try again.",
);
});
it("does not claim retries stopped without an attempt count", () => {
const body = resolveModelRequestFailureCopy({ errorKind: "unknown" }, i18n.t).body;
expect(body).toBe(
"Check the provider configuration or service status, then try again.",
);
});
});
+8
View File
@@ -3,6 +3,14 @@ import fixtures from "../../../packages/client-events/fixtures.json";
import { acceptsCompactionPhase, decodeNotification } from "../../../packages/client-events/notifications";
describe("shared notification contract", () => {
it("rejects malformed retry counters and relative delays", () => {
const retry = { event: "retry_status", chat_id: "chat", state: "waiting",
attempt: 1, max_attempts: 4, error_kind: "connection", retry_after_s: 2 };
for (const invalid of [
{ attempt: 0 }, { attempt: 1.5 }, { max_attempts: 0 }, { max_attempts: NaN },
{ retry_after_s: -1 }, { retry_after_s: Infinity }, { state: "unknown" },
]) expect(decodeNotification({ ...retry, ...invalid })).toBeNull();
});
it.each(fixtures)("accepts the Python wire fixture %#", (event) => {
expect(decodeNotification(event)).toEqual(event);
expect(decodeNotification({ ...event, turn_id: "turn" })).toMatchObject(event);
+51
View File
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { ThreadCameraController } from "@/components/thread/thread-camera";
import { ThreadShell } from "@/components/thread/ThreadShell";
import i18n from "@/i18n";
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
@@ -3793,6 +3794,56 @@ describe("ThreadShell", () => {
});
});
it("keeps a terminal model failure visible until the next user action", async () => {
const client = makeClient();
await act(async () => {
await i18n.changeLanguage("zh-CN");
});
render(
wrap(
client,
<ThreadShell
session={session("chat-model-failure")}
title="Chat model failure"
onToggleSidebar={() => {}}
onGoHome={() => {}}
onNewChat={() => {}}
/>,
),
);
await act(async () => {});
act(() => {
client._emitChat("chat-model-failure", {
event: "turn_end",
chat_id: "chat-model-failure",
turn_id: "turn-model-failure",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Unlocalized server failure",
});
});
const banner = await screen.findByRole("alert");
expect(banner).toHaveTextContent("无法连接模型提供商");
expect(banner).toHaveTextContent(
"模型提供商请求在第 4 次尝试后仍然失败,已停止重试。请检查提供商配置或服务状态后重试。",
);
expect(banner).not.toHaveTextContent("Unlocalized server failure");
fireEvent.change(screen.getByLabelText("消息输入框"), {
target: { value: "try again" },
});
fireEvent.click(screen.getByRole("button", { name: "发送消息" }));
await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
it("moves a correlated delivery error from the banner into the failed message tooltip", async () => {
const client = makeClient();
+69
View File
@@ -125,6 +125,9 @@ function fakeClient() {
const v = runStartedAtByChatId.get(chatId);
return v === undefined ? null : v;
},
getRunTurnId() {
return null;
},
getGoalState(chatId: string) {
return goalStateByChatId.get(chatId);
},
@@ -3227,6 +3230,72 @@ describe("useNanobotStream", () => {
expect(result.current.isStreaming).toBe(false);
});
it("clears retry status and exposes a terminal model failure at turn end", () => {
const dateNow = vi.spyOn(Date, "now").mockReturnValue(120_000);
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-retry", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => {
fake.emit("chat-retry", {
event: "retry_status",
chat_id: "chat-retry",
turn_id: "turn-1",
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
retry_after_s: 3.5,
});
});
expect(result.current.retryStatus).toEqual({
state: "waiting",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
next_retry_at: 123.5,
turn_id: "turn-1",
});
expect(result.current.isStreaming).toBe(true);
act(() => {
fake.emit("chat-retry", {
event: "retry_status",
chat_id: "chat-retry",
turn_id: "turn-1",
state: "cleared",
attempt: 2,
max_attempts: 4,
error_kind: "connection",
});
});
expect(result.current.retryStatus).toBeNull();
act(() => {
fake.emit("chat-retry", {
event: "turn_end",
chat_id: "chat-retry",
turn_id: "turn-1",
outcome: "failed",
failure_kind: "model",
failure_error_kind: "connection",
failure_attempts: 4,
failure_message: "Unlocalized server failure",
});
});
expect(result.current.retryStatus).toBeNull();
expect(result.current.isStreaming).toBe(false);
expect(result.current.streamError).toEqual({
kind: "model_request_failed",
chatId: "chat-retry",
turnId: "turn-1",
errorKind: "connection",
attempts: 4,
});
dateNow.mockRestore();
});
it("clears runStartedAt on turn_end even without idle", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-g", EMPTY_MESSAGES), {