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

+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(