🙌 OpenHands: AI-Driven Development
[codex] Improve backend disconnect guidance (#1223)
Graham Neubigd0af9615ea7c
diff --git a/__tests__/components/backends/add-backend-modal.test.tsx b/__tests__/components/backends/add-backend-modal.test.tsxindex a835cabdb9..803fa4985b 100644--- a/__tests__/components/backends/add-backend-modal.test.tsx+++ b/__tests__/components/backends/add-backend-modal.test.tsx@@ -198,7 +198,7 @@ describe("AddBackendModal – two-column layout", () => {"BACKEND$CONNECTION_TEST_FAILED",);expect(screen.getByTestId("add-backend-error")).toHaveTextContent(- "Failed to fetch",+ "Disconnected",);expect(onClose).not.toHaveBeenCalled();});diff --git a/__tests__/components/backends/manage-backends-modal.test.tsx b/__tests__/components/backends/manage-backends-modal.test.tsxindex 56d90315a6..4457c0ed02 100644--- a/__tests__/components/backends/manage-backends-modal.test.tsx+++ b/__tests__/components/backends/manage-backends-modal.test.tsx@@ -141,7 +141,7 @@ describe("ManageBackendsModal", () => {await waitFor(() =>expect(screen.getByTestId("manage-backends-status-Local"),- ).toHaveTextContent("AUTH$INVALID_KEY"),+ ).toHaveTextContent("BACKEND$STATUS_DISCONNECTED_CHECK_API_KEY"),);expect(row.querySelector('[data-testid="backend-status-dot"]'),diff --git a/__tests__/components/onboarding/onboarding-modal.test.tsx b/__tests__/components/onboarding/onboarding-modal.test.tsxindex 1d0b404903..136d51c3ca 100644--- a/__tests__/components/onboarding/onboarding-modal.test.tsx+++ b/__tests__/components/onboarding/onboarding-modal.test.tsx@@ -230,7 +230,7 @@ describe("OnboardingModal", () => {await screen.findByTestId("onboarding-backend-error"),).toHaveTextContent("BACKEND$CONNECTION_TEST_FAILED");expect(screen.getByTestId("onboarding-backend-error")).toHaveTextContent(- "Failed to fetch",+ "Disconnected",);});diff --git a/src/api/backend-registry/health-storage.ts b/src/api/backend-registry/health-storage.tsindex 85ca85dc6b..f7ee5b97cc 100644--- a/src/api/backend-registry/health-storage.ts+++ b/src/api/backend-registry/health-storage.ts@@ -1,3 +1,5 @@+import { getUserFacingConnectionErrorMessage } from "#/utils/user-facing-error";+export const BACKEND_HEALTH_STORAGE_KEY = "openhands-backend-health";/**@@ -73,14 +75,7 @@ export function writeStoredHealth(map: BackendHealthMap): void {}export function truncateErrorMessage(error: unknown): string {- let message: string;- if (error instanceof Error) {- message = error.message || error.name || "Unknown error";- } else if (typeof error === "string") {- message = error;- } else {- message = "Unknown error";- }+ const message = getUserFacingConnectionErrorMessage(error) ?? "Unknown error";return message.length > MAX_ERROR_MESSAGE_LENGTH? `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}…`: message;diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsxindex 6fd2266f1f..86c20e15aa 100644--- a/src/components/features/backends/backend-form-modal.tsx+++ b/src/components/features/backends/backend-form-modal.tsx@@ -22,11 +22,13 @@ import {import ChevronDownSmallIcon from "#/icons/chevron-down-small.svg?react";import { I18nKey } from "#/i18n/declaration";import type { Backend, BackendKind } from "#/api/backend-registry/types";+import { getUserFacingConnectionErrorMessage } from "#/utils/user-facing-error";import { cn } from "#/utils/utils";import {modalTitleLgClassName,modalTitleLgMediumClassName,} from "#/utils/modal-classes";+import { getBackendStatusLabel } from "./backend-status-label";import { BackendStatusDot } from "./backend-status-dot";import { DeviceFlowAuth } from "./device-flow-auth";@@ -133,9 +135,7 @@ function getConnectionTestFailedTitle(}function getConnectionErrorDetail(error: unknown): string | null {- if (error instanceof Error) return error.message;- if (typeof error === "string") return error;- return null;+ return getUserFacingConnectionErrorMessage(error);}function getConnectionTestFailedMessage(title: string, error: unknown): string {@@ -197,14 +197,7 @@ function BackendStatusBadge({enabled: backend.kind === "local" && !disabled,});- let statusLabel: string;- if (isConnected === true) {- statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_CONNECTED);- } else if (isConnected === false) {- statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_DISCONNECTED);- } else {- statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING);- }+ const statusLabel = getBackendStatusLabel(t, backend, health);const kindLabel =backend.kind === "cloud"diff --git a/src/components/features/backends/backend-row.tsx b/src/components/features/backends/backend-row.tsxindex 3fea356daf..ba8fb3df33 100644--- a/src/components/features/backends/backend-row.tsx+++ b/src/components/features/backends/backend-row.tsx@@ -12,6 +12,7 @@ import { cn } from "#/utils/utils";import { BackendStatusDot } from "./backend-status-dot";import { BackendVersion } from "./backend-version";import { DeviceFlowAuth } from "./device-flow-auth";+import { getBackendStatusLabel } from "./backend-status-label";const ROW_ACTION_BUTTON_CLASS ="inline-flex cursor-pointer items-center justify-center rounded-md p-1 text-muted transition-colors hover:bg-interactive-hover hover:text-white";@@ -45,24 +46,15 @@ export function BackendRow({health.lastError? health.lastError: null;- let statusLabel: string;- let statusClassName = "text-[var(--oh-muted)]";-- if (isCloudLoggedOut) {- statusLabel = t(I18nKey.BACKEND$LOGGED_OUT);- statusClassName = "text-red-300";- } else if (isInvalidApiKey) {- statusLabel = t(I18nKey.AUTH$INVALID_KEY);- statusClassName = "text-red-300";- } else if (health?.isConnected === true) {- statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_CONNECTED);- statusClassName = "text-green-300";- } else if (health?.isConnected === false) {- statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_DISCONNECTED);- statusClassName = "text-red-300";- } else {- statusLabel = t(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING);- }+ const statusLabel = isCloudLoggedOut+ ? t(I18nKey.BACKEND$LOGGED_OUT)+ : getBackendStatusLabel(t, backend, health);+ const statusClassName =+ health?.isConnected === true+ ? "text-green-300"+ : health?.isConnected === false+ ? "text-red-300"+ : "text-[var(--oh-muted)]";const dotStatus = isInvalidApiKey ? false : (health?.isConnected ?? null);const canSelect = health?.isConnected === true && !isInvalidApiKey;diff --git a/src/components/features/backends/backend-status-label.test.ts b/src/components/features/backends/backend-status-label.test.tsnew file mode 100644index 0000000000..f5820706e7--- /dev/null+++ b/src/components/features/backends/backend-status-label.test.ts@@ -0,0 +1,101 @@+import type { TFunction } from "i18next";+import { describe, expect, it } from "vitest";+import {+ INVALID_BACKEND_API_KEY_ERROR,+ MISSING_BACKEND_API_KEY_ERROR,+} from "#/hooks/query/use-backends-health";+import { I18nKey } from "#/i18n/declaration";+import { CORS_OR_NETWORK_ERROR_MESSAGE } from "#/utils/user-facing-error";+import { getBackendStatusLabel } from "./backend-status-label";++const t = ((key: string) => key) as TFunction<"openhands">;++describe("getBackendStatusLabel", () => {+ it("prefers add API key for Cloud backends with a blank API key", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "cloud", apiKey: "" },+ { isConnected: false, lastError: CORS_OR_NETWORK_ERROR_MESSAGE },+ ),+ ).toBe(I18nKey.BACKEND$STATUS_DISCONNECTED_ADD_API_KEY);+ });++ it("maps Cloud browser-network failures to API key or network guidance", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "cloud", apiKey: "oh-cloud-key" },+ { isConnected: false, lastError: CORS_OR_NETWORK_ERROR_MESSAGE },+ ),+ ).toBe(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_CLOUD_ACCESS);+ });++ it("keeps local browser-network failures generic", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "local", apiKey: "" },+ { isConnected: false, lastError: CORS_OR_NETWORK_ERROR_MESSAGE },+ ),+ ).toBe(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_URL_OR_NETWORK);+ });++ it("returns connected when the health probe is connected", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "local", apiKey: "" },+ { isConnected: true, lastError: null },+ ),+ ).toBe(I18nKey.ONBOARDING$BACKEND_STATUS_CONNECTED);+ });++ it("returns disconnected for failed probes without a more specific reason", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "local", apiKey: "" },+ { isConnected: false, lastError: "Unexpected failure" },+ ),+ ).toBe(I18nKey.ONBOARDING$BACKEND_STATUS_DISCONNECTED);+ });++ it("returns checking while the health probe is unresolved", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "local", apiKey: "" },+ { isConnected: null, lastError: null },+ ),+ ).toBe(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING);+ });++ it("maps request timeouts to tunnel guidance", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "local", apiKey: "" },+ { isConnected: false, lastError: "Backend request timed out" },+ ),+ ).toBe(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_TUNNEL);+ });++ it("maps missing and invalid API key health errors to credential guidance", () => {+ expect(+ getBackendStatusLabel(+ t,+ { kind: "cloud", apiKey: "oh-cloud-key" },+ { isConnected: false, lastError: MISSING_BACKEND_API_KEY_ERROR },+ ),+ ).toBe(I18nKey.BACKEND$STATUS_DISCONNECTED_ADD_API_KEY);++ expect(+ getBackendStatusLabel(+ t,+ { kind: "cloud", apiKey: "oh-cloud-key" },+ { isConnected: false, lastError: INVALID_BACKEND_API_KEY_ERROR },+ ),+ ).toBe(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_API_KEY);+ });+});diff --git a/src/components/features/backends/backend-status-label.ts b/src/components/features/backends/backend-status-label.tsnew file mode 100644index 0000000000..709f8d389b--- /dev/null+++ b/src/components/features/backends/backend-status-label.ts@@ -0,0 +1,77 @@+import type { TFunction } from "i18next";+import {+ isCloudBackendApiKeyOrNetworkHealthError,+ isCloudBackendLoggedOutHealthError,+ isInvalidBackendApiKeyHealthError,+ isMissingBackendApiKeyHealthError,+} from "#/hooks/query/use-backends-health";+import { I18nKey } from "#/i18n/declaration";+import {+ isBackendRequestTimeoutMessage,+ isCorsOrNetworkErrorMessage,+} from "#/utils/user-facing-error";++interface BackendStatusLabelHealth {+ isConnected?: boolean | null;+ lastError?: string | null;+}++export function getBackendStatusLabel(+ t: TFunction<"openhands">,+ backend:+ | {+ kind?: "local" | "cloud";+ apiKey?: string | null;+ }+ | undefined,+ health: BackendStatusLabelHealth | undefined,+): string {+ const lastError = health?.lastError ?? null;+ const isCloud = backend?.kind === "cloud";++ if (isCloud && !backend?.apiKey?.trim()) {+ return t(I18nKey.BACKEND$STATUS_DISCONNECTED_ADD_API_KEY);+ }++ if (isMissingBackendApiKeyHealthError(lastError)) {+ return t(I18nKey.BACKEND$STATUS_DISCONNECTED_ADD_API_KEY);+ }++ if (isInvalidBackendApiKeyHealthError(lastError)) {+ return t(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_API_KEY);+ }++ if (isCloudBackendLoggedOutHealthError(lastError)) {+ return t(I18nKey.BACKEND$LOGGED_OUT);+ }++ if (health?.isConnected === true) {+ return t(I18nKey.ONBOARDING$BACKEND_STATUS_CONNECTED);+ }++ if (+ isCloud &&+ health?.isConnected === false &&+ (isCloudBackendApiKeyOrNetworkHealthError(lastError) ||+ isCorsOrNetworkErrorMessage(lastError))+ ) {+ return t(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_CLOUD_ACCESS);+ }++ if (+ health?.isConnected === false &&+ isBackendRequestTimeoutMessage(lastError)+ ) {+ return t(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_TUNNEL);+ }++ if (health?.isConnected === false && isCorsOrNetworkErrorMessage(lastError)) {+ return t(I18nKey.BACKEND$STATUS_DISCONNECTED_CHECK_URL_OR_NETWORK);+ }++ if (health?.isConnected === false) {+ return t(I18nKey.ONBOARDING$BACKEND_STATUS_DISCONNECTED);+ }++ return t(I18nKey.ONBOARDING$BACKEND_STATUS_CHECKING);+}diff --git a/src/components/features/onboarding/steps/check-backend-step.tsx b/src/components/features/onboarding/steps/check-backend-step.tsxindex f1d186b482..94ad54d800 100644--- a/src/components/features/onboarding/steps/check-backend-step.tsx+++ b/src/components/features/onboarding/steps/check-backend-step.tsx@@ -2,6 +2,7 @@ import React from "react";import { useTranslation } from "react-i18next";import { CheckCircle2, Loader2, AlertCircle } from "lucide-react";import { isNoBackend } from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";import {getAgentServerFormDefaults,isAuthRequired,@@ -14,13 +15,22 @@ import { useBackendsHealth } from "#/hooks/query/use-backends-health";import { I18nKey } from "#/i18n/declaration";import ChevronDownSmallIcon from "#/icons/chevron-down-small.svg?react";import { cn } from "#/utils/utils";+import { getBackendStatusLabel } from "#/components/features/backends/backend-status-label";interface CheckBackendStepProps {onBack?: () => void;onNext: () => void;}-function ConnectionBanner({ isConnected }: { isConnected: boolean | null }) {+function ConnectionBanner({+ backend,+ isConnected,+ lastError,+}: {+ backend: Backend;+ isConnected: boolean | null;+ lastError: string | null;+}) {const { t } = useTranslation("openhands");if (isConnected === true) {@@ -46,6 +56,10 @@ function ConnectionBanner({ isConnected }: { isConnected: boolean | null }) {}if (isConnected === false) {+ const statusLabel = getBackendStatusLabel(t, backend, {+ isConnected,+ lastError,+ });return (<divrole="alert"@@ -55,7 +69,7 @@ function ConnectionBanner({ isConnected }: { isConnected: boolean | null }) {<AlertCircle className="mt-0.5 size-5 shrink-0 text-red-400" /><div className="flex flex-col gap-1"><span className="text-sm font-medium text-red-200">- {t(I18nKey.ONBOARDING$BACKEND_DISCONNECTED_TITLE)}+ {statusLabel}</span><span className="text-xs text-red-200/80">{t(I18nKey.ONBOARDING$BACKEND_DISCONNECTED_BODY)}@@ -105,6 +119,9 @@ export function CheckBackendStep({ onBack, onNext }: CheckBackendStepProps) {const isConnected = noBackendSelected? false: (healthByBackendId[backend.id]?.isConnected ?? null);+ const lastError = noBackendSelected+ ? null+ : (healthByBackendId[backend.id]?.lastError ?? null);const [configurationOpen, setConfigurationOpen] = React.useState(false);React.useEffect(() => {@@ -129,7 +146,11 @@ export function CheckBackendStep({ onBack, onNext }: CheckBackendStepProps) {</p></header>- <ConnectionBanner isConnected={isConnected} />+ <ConnectionBanner+ backend={backendForForm}+ isConnected={isConnected}+ lastError={lastError}+ />{isConnected === true ? (<buttondiff --git a/src/hooks/query/use-backends-health.ts b/src/hooks/query/use-backends-health.tsindex 69cfb32e23..6919bf031a 100644--- a/src/hooks/query/use-backends-health.ts+++ b/src/hooks/query/use-backends-health.ts@@ -12,6 +12,10 @@ import {} from "#/api/agent-server-compatibility";import type { Backend } from "#/api/backend-registry/types";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";+import {+ isCorsOrNetworkError,+ isCorsOrNetworkErrorMessage,+} from "#/utils/user-facing-error";import {getHealthSnapshot,recordBackendFailure,@@ -23,6 +27,9 @@ import { MAX_CONSECUTIVE_FAILURES } from "#/api/backend-registry/health-storage"const REFRESH_INTERVAL_MS = 10000;const PROBE_TIMEOUT_MS = 4000;export const INVALID_BACKEND_API_KEY_ERROR = "Invalid API key";+export const MISSING_BACKEND_API_KEY_ERROR = "API key required";+export const CLOUD_BACKEND_API_KEY_OR_NETWORK_ERROR =+ "Cloud API key or network issue";export const CLOUD_BACKEND_LOGGED_OUT_ERROR = "Logged out";export function isInvalidBackendApiKeyHealthError(@@ -31,6 +38,22 @@ export function isInvalidBackendApiKeyHealthError(return error === INVALID_BACKEND_API_KEY_ERROR;}+export function isMissingBackendApiKeyHealthError(+ error: string | null | undefined,+): boolean {+ return error === MISSING_BACKEND_API_KEY_ERROR;+}++export function isCloudBackendApiKeyOrNetworkHealthError(+ error: string | null | undefined,+): boolean {+ return error === CLOUD_BACKEND_API_KEY_OR_NETWORK_ERROR;+}++function hasMissingBackendApiKey(backend: Backend): boolean {+ return backend.kind === "cloud" && !backend.apiKey.trim();+}+export function isCloudBackendLoggedOutHealthError(error: string | null | undefined,): boolean {@@ -44,24 +67,30 @@ export function isCloudBackendLoggedOutHealthError(* - Local agent-server: GET `/api/settings`, then `/server_info` via the* typescript-client. The settings call validates the configured session* API key; the server info call validates the version compatibility floor.- * - Cloud: GET `/api/keys/current` via the bundled local- * agent-server's `/api/cloud-proxy`. That endpoint is lightweight,- * requires auth, and `getCurrentCloudApiKey` already absorbs the- * legacy-key 400 fallback so we treat that as "connected" too.- * Any other failure (network, 401, 5xx, …) means the backend is- * not reachable / not usable from the GUI.+ * - Cloud: GET `/api/keys/current` directly against the cloud host. That+ * endpoint is lightweight, requires auth, and `getCurrentCloudApiKey`+ * already absorbs the legacy-key 400 fallback so we treat that as+ * "connected" too. Missing / rejected keys are reported explicitly instead+ * of falling through to the browser's opaque CORS/network error shape.** Throws on failure so React Query marks the query as errored — the* dropdown reads `isSuccess` to flip the indicator green.*/async function probeBackend(backend: Backend): Promise<true> {if (backend.kind === "cloud") {+ if (!backend.apiKey?.trim()) {+ throw new Error(MISSING_BACKEND_API_KEY_ERROR);+ }+try {await getCurrentCloudApiKey(backend);} catch (error) {if (axios.isAxiosError(error) && error.response?.status === 401) {throw new Error(CLOUD_BACKEND_LOGGED_OUT_ERROR);}+ if (isCorsOrNetworkError(error)) {+ throw new Error(CLOUD_BACKEND_API_KEY_OR_NETWORK_ERROR);+ }throw error;}return true;@@ -139,8 +168,18 @@ export function useBackendsHealth(const results = useQueries({queries: backends.map((b) => {- const isDisabled = healthMap[b.id]?.disabled === true;- const shouldProbe = !isDisabled || probeDisabledOnce;+ const entry = healthMap[b.id];+ const hasMissingCloudApiKey = hasMissingBackendApiKey(b);+ const isDisabled = entry?.disabled === true;+ const shouldReprobeStaleCloudNetworkError =+ isDisabled &&+ b.kind === "cloud" &&+ isCorsOrNetworkErrorMessage(entry?.lastError);+ const shouldProbe =+ !hasMissingCloudApiKey &&+ (!isDisabled ||+ probeDisabledOnce ||+ shouldReprobeStaleCloudNetworkError);return {queryKey: ["backend-health",@@ -160,11 +199,14 @@ export function useBackendsHealth(}},enabled: shouldProbe,- refetchInterval: isDisabled ? (false as const) : REFRESH_INTERVAL_MS,+ refetchInterval:+ isDisabled || hasMissingCloudApiKey+ ? (false as const)+ : REFRESH_INTERVAL_MS,refetchIntervalInBackground: false,refetchOnMount: isDisabled && probeDisabledOnce ? "always" : true,- refetchOnReconnect: !isDisabled,- refetchOnWindowFocus: !isDisabled,+ refetchOnReconnect: !isDisabled && !hasMissingCloudApiKey,+ refetchOnWindowFocus: !isDisabled && !hasMissingCloudApiKey,retry: false,// Keep the previous verdict visible while the next probe is in// flight so the indicator doesn't flicker on routine polling.@@ -178,12 +220,19 @@ export function useBackendsHealth(backends.forEach((b, i) => {const r = results[i];const entry = healthMap[b.id];- const disabled = entry?.disabled === true;- const consecutiveFailures = entry?.consecutiveFailures ?? 0;- const lastError = entry?.lastError ?? null;+ const hasMissingCloudApiKey = hasMissingBackendApiKey(b);+ const disabled = hasMissingCloudApiKey ? false : entry?.disabled === true;+ const consecutiveFailures = hasMissingCloudApiKey+ ? 0+ : (entry?.consecutiveFailures ?? 0);+ const lastError = hasMissingCloudApiKey+ ? MISSING_BACKEND_API_KEY_ERROR+ : (entry?.lastError ?? null);let isConnected: boolean | null;- if (disabled) {+ if (hasMissingCloudApiKey) {+ isConnected = false;+ } else if (disabled) {// Polling stopped after hitting the cap — treat as disconnected// so existing consumers (dot, badge) render red without needing// to know about the new fields.diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 4984760497..0b93e560a9 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -7020,6 +7020,40 @@"uk": "Сталася помилка","ca": "S'ha produït un error"},+ "ERROR$CORS_OR_NETWORK": {+ "en": "Disconnected (check URL or network). Check that the backend URL is correct and the backend server is reachable. If the backend is on another origin, check that it allows this frontend origin.",+ "ja": "切断されています(URL またはネットワークを確認)。バックエンド URL が正しく、バックエンドサーバーに到達できることを確認してください。バックエンドが別のオリジンにある場合は、このフロントエンドのオリジンを許可していることも確認してください。",+ "zh-CN": "已断开连接(检查 URL 或网络)。请确认后端 URL 正确且后端服务器可访问。如果后端位于其他源,请确认它允许此前端源。",+ "zh-TW": "已中斷連線(檢查 URL 或網路)。請確認後端 URL 正確且後端伺服器可連線。如果後端位於其他來源,請確認它允許此前端來源。",+ "ko-KR": "연결이 끊어졌습니다(URL 또는 네트워크 확인). 백엔드 URL이 올바르고 백엔드 서버에 연결할 수 있는지 확인하세요. 백엔드가 다른 출처에 있는 경우 이 프런트엔드 출처를 허용하는지도 확인하세요.",+ "de": "Getrennt (URL oder Netzwerk prüfen). Prüfen Sie, ob die Backend-URL korrekt und der Backend-Server erreichbar ist. Wenn das Backend auf einem anderen Origin liegt, prüfen Sie außerdem, ob es diesen Frontend-Origin zulässt.",+ "no": "Frakoblet (sjekk URL eller nettverk). Kontroller at backend-URL-en er riktig og at backend-serveren er tilgjengelig. Hvis backend-en er på en annen origin, må du også kontrollere at den tillater denne frontend-originen.",+ "it": "Disconnesso (controlla URL o rete). Verifica che l'URL del backend sia corretto e che il server backend sia raggiungibile. Se il backend si trova su un'altra origine, verifica anche che consenta questa origine del frontend.",+ "pt": "Desconectado (verifique URL ou rede). Verifique se a URL do backend está correta e se o servidor backend está acessível. Se o backend estiver em outra origem, verifique também se ele permite esta origem do frontend.",+ "es": "Desconectado (comprueba la URL o la red). Comprueba que la URL del backend sea correcta y que el servidor backend sea accesible. Si el backend está en otro origen, comprueba también que permita este origen del frontend.",+ "ar": "تم قطع الاتصال (تحقق من عنوان URL أو الشبكة). تأكد من صحة عنوان URL للواجهة الخلفية وأن خادم الواجهة الخلفية يمكن الوصول إليه. إذا كانت الواجهة الخلفية على أصل مختلف، فتأكد أيضًا من أنها تسمح بأصل هذه الواجهة الأمامية.",+ "fr": "Déconnecté (vérifiez l'URL ou le réseau). Vérifiez que l'URL du backend est correcte et que le serveur backend est joignable. Si le backend se trouve sur une autre origine, vérifiez aussi qu'il autorise cette origine du frontend.",+ "tr": "Bağlantı kesildi (URL'yi veya ağı kontrol edin). Backend URL'sinin doğru olduğundan ve backend sunucusuna erişilebildiğinden emin olun. Backend farklı bir origin üzerindeyse bu frontend origin'ine izin verdiğini de kontrol edin.",+ "uk": "Від’єднано (перевірте URL або мережу). Переконайтеся, що URL бекенду правильний і сервер бекенду доступний. Якщо бекенд розміщено на іншому origin, також перевірте, чи він дозволяє цей origin фронтенду.",+ "ca": "Desconnectat (comproveu l'URL o la xarxa). Comproveu que l'URL del backend sigui correcta i que el servidor backend sigui accessible. Si el backend és en un altre origen, comproveu també que permeti aquest origen del frontend."+ },+ "ERROR$BACKEND_REQUEST_TIMEOUT": {+ "en": "Disconnected (request timed out). Check that the backend URL is correct and reachable.",+ "ja": "切断されています(リクエストがタイムアウトしました)。バックエンド URL が正しく、到達可能であることを確認してください。",+ "zh-CN": "已断开连接(请求超时)。请确认后端 URL 正确且可访问。",+ "zh-TW": "已中斷連線(請求逾時)。請確認後端 URL 正確且可連線。",+ "ko-KR": "연결이 끊어졌습니다(요청 시간 초과). 백엔드 URL이 올바르고 연결할 수 있는지 확인하세요.",+ "de": "Getrennt (Anfragezeit überschritten). Prüfen Sie, ob die Backend-URL korrekt und erreichbar ist.",+ "no": "Frakoblet (forespørselen tidsavbrøt). Kontroller at backend-URL-en er riktig og tilgjengelig.",+ "it": "Disconnesso (richiesta scaduta). Verifica che l'URL del backend sia corretto e raggiungibile.",+ "pt": "Desconectado (a solicitação expirou). Verifique se a URL do backend está correta e acessível.",+ "es": "Desconectado (la solicitud agotó el tiempo). Comprueba que la URL del backend sea correcta y accesible.",+ "ar": "تم قطع الاتصال (انتهت مهلة الطلب). تأكد من صحة عنوان URL للواجهة الخلفية وإمكانية الوصول إليه.",+ "fr": "Déconnecté (délai de requête dépassé). Vérifiez que l'URL du backend est correcte et joignable.",+ "tr": "Bağlantı kesildi (istek zaman aşımına uğradı). Backend URL'sinin doğru ve erişilebilir olduğundan emin olun.",+ "uk": "Від’єднано (час очікування запиту минув). Переконайтеся, що URL бекенду правильний і доступний.",+ "ca": "Desconnectat (la sol·licitud ha esgotat el temps). Comproveu que l'URL del backend sigui correcta i accessible."+ },"GITHUB$AUTH_SCOPE": {"en": "openid email profile","ja": "openid email profile",@@ -27148,6 +27182,91 @@"tr": "{{count}} denemeden sonra yeniden deneme durduruldu. Yeniden denemek için sunucuyu veya API anahtarını güncelleyin.","uk": "Зупинено повторні спроби після {{count}} спроб. Оновіть хост або API-ключ, щоб повторити."},+ "BACKEND$STATUS_DISCONNECTED_ADD_API_KEY": {+ "en": "Disconnected (add API key)",+ "ja": "切断されています(API キーを追加)",+ "zh-CN": "已断开连接(添加 API 密钥)",+ "zh-TW": "已中斷連線(新增 API 金鑰)",+ "ko-KR": "연결 끊김(API 키 추가)",+ "no": "Frakoblet (legg til API-nøkkel)",+ "ar": "تم قطع الاتصال (أضف مفتاح API)",+ "de": "Getrennt (API-Schlüssel hinzufügen)",+ "fr": "Déconnecté (ajoutez une clé API)",+ "it": "Disconnesso (aggiungi chiave API)",+ "pt": "Desconectado (adicione chave de API)",+ "es": "Desconectado (añade clave de API)",+ "ca": "Desconnectat (afegiu clau d'API)",+ "tr": "Bağlantı kesildi (API anahtarı ekleyin)",+ "uk": "Від’єднано (додайте API-ключ)"+ },+ "BACKEND$STATUS_DISCONNECTED_CHECK_API_KEY": {+ "en": "Disconnected (check API key)",+ "ja": "切断されています(API キーを確認)",+ "zh-CN": "已断开连接(检查 API 密钥)",+ "zh-TW": "已中斷連線(檢查 API 金鑰)",+ "ko-KR": "연결 끊김(API 키 확인)",+ "no": "Frakoblet (sjekk API-nøkkel)",+ "ar": "تم قطع الاتصال (تحقق من مفتاح API)",+ "de": "Getrennt (API-Schlüssel prüfen)",+ "fr": "Déconnecté (vérifiez la clé API)",+ "it": "Disconnesso (controlla chiave API)",+ "pt": "Desconectado (verifique chave de API)",+ "es": "Desconectado (comprueba clave de API)",+ "ca": "Desconnectat (comproveu clau d'API)",+ "tr": "Bağlantı kesildi (API anahtarını kontrol edin)",+ "uk": "Від’єднано (перевірте API-ключ)"+ },+ "BACKEND$STATUS_DISCONNECTED_CHECK_CLOUD_ACCESS": {+ "en": "Disconnected (check API key or network)",+ "ja": "切断されています(API キーまたはネットワークを確認)",+ "zh-CN": "已断开连接(检查 API 密钥或网络)",+ "zh-TW": "已中斷連線(檢查 API 金鑰或網路)",+ "ko-KR": "연결 끊김(API 키 또는 네트워크 확인)",+ "no": "Frakoblet (sjekk API-nøkkel eller nettverk)",+ "ar": "تم قطع الاتصال (تحقق من مفتاح API أو الشبكة)",+ "de": "Getrennt (API-Schlüssel oder Netzwerk prüfen)",+ "fr": "Déconnecté (vérifiez la clé API ou le réseau)",+ "it": "Disconnesso (controlla chiave API o rete)",+ "pt": "Desconectado (verifique chave de API ou rede)",+ "es": "Desconectado (comprueba clave de API o red)",+ "ca": "Desconnectat (comproveu clau d'API o xarxa)",+ "tr": "Bağlantı kesildi (API anahtarını veya ağı kontrol edin)",+ "uk": "Від’єднано (перевірте API-ключ або мережу)"+ },+ "BACKEND$STATUS_DISCONNECTED_CHECK_TUNNEL": {+ "en": "Disconnected (request timed out)",+ "ja": "切断されています(リクエストがタイムアウト)",+ "zh-CN": "已断开连接(请求超时)",+ "zh-TW": "已中斷連線(請求逾時)",+ "ko-KR": "연결 끊김(요청 시간 초과)",+ "no": "Frakoblet (forespørselen tidsavbrøt)",+ "ar": "تم قطع الاتصال (انتهت مهلة الطلب)",+ "de": "Getrennt (Anfragezeit überschritten)",+ "fr": "Déconnecté (délai de requête dépassé)",+ "it": "Disconnesso (richiesta scaduta)",+ "pt": "Desconectado (solicitação expirou)",+ "es": "Desconectado (solicitud agotada)",+ "ca": "Desconnectat (sol·licitud esgotada)",+ "tr": "Bağlantı kesildi (istek zaman aşımına uğradı)",+ "uk": "Від’єднано (час очікування запиту минув)"+ },+ "BACKEND$STATUS_DISCONNECTED_CHECK_URL_OR_NETWORK": {+ "en": "Disconnected (check URL or network)",+ "ja": "切断されています(URL またはネットワークを確認)",+ "zh-CN": "已断开连接(检查 URL 或网络)",+ "zh-TW": "已中斷連線(檢查 URL 或網路)",+ "ko-KR": "연결 끊김(URL 또는 네트워크 확인)",+ "no": "Frakoblet (sjekk URL eller nettverk)",+ "ar": "تم قطع الاتصال (تحقق من عنوان URL أو الشبكة)",+ "de": "Getrennt (URL oder Netzwerk prüfen)",+ "fr": "Déconnecté (vérifiez l'URL ou le réseau)",+ "it": "Disconnesso (controlla URL o rete)",+ "pt": "Desconectado (verifique URL ou rede)",+ "es": "Desconectado (comprueba URL o red)",+ "ca": "Desconnectat (comproveu URL o xarxa)",+ "tr": "Bağlantı kesildi (URL'yi veya ağı kontrol edin)",+ "uk": "Від’єднано (перевірте URL або мережу)"+ },"SETTINGS$BACKEND_SYNCED_BADGE": {"en": "These settings are synced from {{name}} backend ({{host}})","ja": "これらの設定は {{name}} バックエンド ({{host}}) と同期されています",diff --git a/src/utils/custom-toast-handlers.tsx b/src/utils/custom-toast-handlers.tsxindex e776b92f77..25e401bb32 100644--- a/src/utils/custom-toast-handlers.tsx+++ b/src/utils/custom-toast-handlers.tsx@@ -6,6 +6,10 @@ import { calculateToastDuration } from "./toast-duration";import { cn } from "#/utils/utils";import i18n from "#/i18n";import { I18nKey } from "#/i18n/declaration";+import {+ isBackendRequestTimeoutMessage,+ isCorsOrNetworkErrorMessage,+} from "./user-facing-error";// react-hot-toast accepts only CSSProperties via the style option — cannot use classNameconst TOAST_STYLE: CSSProperties = {@@ -90,7 +94,12 @@ export const ERROR_TOAST_OPTIONS: ToastOptions = {};export const displayErrorToast = (error: string | null | undefined) => {- const errorMessage = error || i18n.t(I18nKey.STATUS$ERROR);+ let errorMessage = error || i18n.t(I18nKey.STATUS$ERROR);+ if (isCorsOrNetworkErrorMessage(errorMessage)) {+ errorMessage = i18n.t(I18nKey.ERROR$CORS_OR_NETWORK);+ } else if (isBackendRequestTimeoutMessage(errorMessage)) {+ errorMessage = i18n.t(I18nKey.ERROR$BACKEND_REQUEST_TIMEOUT);+ }const duration = calculateToastDuration(errorMessage, 4000);toast(<ErrorToastContent message={errorMessage} />, {...ERROR_TOAST_OPTIONS,diff --git a/src/utils/retrieve-axios-error-message.ts b/src/utils/retrieve-axios-error-message.tsindex 49493f349a..34227ffe82 100644--- a/src/utils/retrieve-axios-error-message.ts+++ b/src/utils/retrieve-axios-error-message.ts@@ -3,24 +3,47 @@ import {isAxiosErrorWithErrorField,isAxiosErrorWithMessageField,} from "./type-guards";+import { getUserFacingConnectionErrorMessage } from "./user-facing-error";++function isAxiosError(error: unknown): error is AxiosError {+ return (+ typeof error === "object" &&+ error !== null &&+ "isAxiosError" in error &&+ (error as { isAxiosError?: unknown }).isAxiosError === true+ );+}/*** Retrieve the error message from an Axios error* @param error The error to render a toast for*/-export const retrieveAxiosErrorMessage = (error: AxiosError) => {+export const retrieveAxiosErrorMessage = (error: unknown): string => {let errorMessage: string | null = null;+ let shouldPreferExtractedMessage = false;- if (isAxiosErrorWithErrorField(error) && error.response?.data.error) {- errorMessage = error.response?.data.error;- } else if (- isAxiosErrorWithMessageField(error) &&- error.response?.data.message- ) {- errorMessage = error.response?.data.message;- } else {+ if (isAxiosError(error)) {+ shouldPreferExtractedMessage = true;+ if (isAxiosErrorWithErrorField(error) && error.response?.data.error) {+ errorMessage = error.response?.data.error;+ } else if (+ isAxiosErrorWithMessageField(error) &&+ error.response?.data.message+ ) {+ errorMessage = error.response?.data.message;+ } else {+ errorMessage = error.message;+ }+ } else if (error instanceof Error) {errorMessage = error.message;+ } else if (typeof error === "string") {+ errorMessage = error;+ } else {+ errorMessage = null;}- return errorMessage;+ const userFacingMessage = getUserFacingConnectionErrorMessage(+ shouldPreferExtractedMessage ? (errorMessage ?? error) : error,+ );+ return userFacingMessage ?? errorMessage ?? "";};diff --git a/src/utils/user-facing-error.test.ts b/src/utils/user-facing-error.test.tsnew file mode 100644index 0000000000..defcb8ca3f--- /dev/null+++ b/src/utils/user-facing-error.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";+import {+ BACKEND_REQUEST_TIMEOUT_MESSAGE,+ CORS_OR_NETWORK_ERROR_MESSAGE,+ getUserFacingConnectionErrorMessage,+ isCorsOrNetworkErrorMessage,+} from "./user-facing-error";++describe("user-facing connection errors", () => {+ it("maps browser fetch failures to the CORS or network message", () => {+ expect(+ getUserFacingConnectionErrorMessage(+ new Error("Request failed: Failed to fetch"),+ ),+ ).toBe(CORS_OR_NETWORK_ERROR_MESSAGE);+ });++ it("looks through wrapped causes from fetch-based clients", () => {+ expect(+ getUserFacingConnectionErrorMessage(+ new Error("Request failed", {+ cause: new TypeError("Failed to fetch"),+ }),+ ),+ ).toBe(CORS_OR_NETWORK_ERROR_MESSAGE);+ });++ it("detects existing CORS or network labels", () => {+ expect(isCorsOrNetworkErrorMessage(CORS_OR_NETWORK_ERROR_MESSAGE)).toBe(+ true,+ );+ });++ it("maps request timeouts to a backend timeout message", () => {+ expect(+ getUserFacingConnectionErrorMessage(+ new Error("Request timeout after 5000ms"),+ ),+ ).toBe(BACKEND_REQUEST_TIMEOUT_MESSAGE);+ });++ it("leaves ordinary server errors intact", () => {+ expect(+ getUserFacingConnectionErrorMessage(new Error("Invalid API key")),+ ).toBe("Invalid API key");+ });+});diff --git a/src/utils/user-facing-error.ts b/src/utils/user-facing-error.tsnew file mode 100644index 0000000000..50615d8620--- /dev/null+++ b/src/utils/user-facing-error.ts@@ -0,0 +1,92 @@+export const CORS_OR_NETWORK_ERROR_MESSAGE =+ "Disconnected (check URL or network). Check that the backend URL is correct and the backend server is reachable. If the backend is on another origin, check that it allows this frontend origin.";++export const BACKEND_REQUEST_TIMEOUT_MESSAGE =+ "Disconnected (request timed out). Check that the backend URL is correct and reachable.";++const MAX_CAUSE_DEPTH = 4;++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null;+}++function collectErrorMessages(error: unknown): string[] {+ const messages: string[] = [];+ const seen = new Set<unknown>();+ let current: unknown = error;+ let depth = 0;++ while (current !== undefined && current !== null && depth < MAX_CAUSE_DEPTH) {+ if (seen.has(current)) break;+ seen.add(current);++ if (current instanceof Error) {+ if (current.message) messages.push(current.message);+ current = current.cause;+ } else if (typeof current === "string") {+ if (current) messages.push(current);+ break;+ } else if (isRecord(current)) {+ const message = current.message;+ if (typeof message === "string" && message) messages.push(message);+ current = current.cause;+ } else {+ break;+ }++ depth += 1;+ }++ return messages;+}++export function getRawErrorMessage(error: unknown): string | null {+ return collectErrorMessages(error)[0] ?? null;+}++export function isCorsOrNetworkErrorMessage(+ message: string | null | undefined,+): boolean {+ if (!message) return false;+ const normalized = message.toLowerCase();++ return (+ normalized.includes("disconnected (check cors or network)") ||+ normalized.includes("disconnected (check url or network)") ||+ normalized.includes("blocked by cors") ||+ normalized.includes("failed to fetch") ||+ normalized.includes("network error") ||+ normalized.includes("load failed") ||+ normalized.includes("networkerror when attempting to fetch resource") ||+ (normalized.includes("cors") && normalized.includes("blocked"))+ );+}++export function isCorsOrNetworkError(error: unknown): boolean {+ return collectErrorMessages(error).some(isCorsOrNetworkErrorMessage);+}++export function isBackendRequestTimeoutMessage(+ message: string | null | undefined,+): boolean {+ if (!message) return false;+ const normalized = message.toLowerCase();+ return (+ normalized.includes("request timeout") ||+ normalized.includes("timeout after") ||+ normalized.includes("backend request timed out")+ );+}++export function getUserFacingConnectionErrorMessage(+ error: unknown,+): string | null {+ const messages = collectErrorMessages(error);+ if (messages.some(isCorsOrNetworkErrorMessage)) {+ return CORS_OR_NETWORK_ERROR_MESSAGE;+ }+ if (messages.some(isBackendRequestTimeoutMessage)) {+ return BACKEND_REQUEST_TIMEOUT_MESSAGE;+ }+ return messages[0] ?? null;+}