Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: restore MCP startup error dialog (#7038) (#7940)

Jordan3d9cecba7cb5
diff --git a/web-app/src/containers/__tests__/ErrorDialog.test.tsx b/web-app/src/containers/__tests__/ErrorDialog.test.tsx
new file mode 100644
index 000000000..2039982fb
--- /dev/null
+++ b/web-app/src/containers/__tests__/ErrorDialog.test.tsx
@@ -0,0 +1,147 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import ErrorDialog from '../dialogs/ErrorDialog'
+import { useAppState } from '@/hooks/useAppState'
+
+const successToast = vi.fn()
+const errorToast = vi.fn()
+
+vi.mock('sonner', () => ({
+ toast: {
+ success: (...args: unknown[]) => successToast(...args),
+ error: (...args: unknown[]) => errorToast(...args),
+ },
+}))
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}))
+
+describe('ErrorDialog', () => {
+ const writeText = vi.fn()
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ Object.assign(navigator, {
+ clipboard: {
+ writeText,
+ },
+ })
+ useAppState.setState({
+ errorMessage: undefined,
+ })
+ })
+
+ afterEach(() => {
+ useAppState.setState({
+ errorMessage: undefined,
+ })
+ })
+
+ it('renders the dialog when there is an error message', () => {
+ useAppState.setState({
+ errorMessage: {
+ title: 'MCP startup failed',
+ subtitle: 'mcp-servers:checkParams',
+ message: 'Failed to start MCP server NotesMCP',
+ },
+ })
+
+ render(<ErrorDialog />)
+
+ expect(screen.getByText('common:error')).toBeInTheDocument()
+ expect(screen.getByText('MCP startup failed')).toBeInTheDocument()
+ expect(screen.getByText('Failed to start MCP server NotesMCP')).toBeInTheDocument()
+ })
+
+ it('clears the global error state when dismissed', async () => {
+ useAppState.setState({
+ errorMessage: {
+ subtitle: 'mcp-servers:checkParams',
+ message: 'Failed to start MCP server NotesMCP',
+ },
+ })
+
+ render(<ErrorDialog />)
+
+ fireEvent.click(screen.getByText('common:cancel'))
+
+ await waitFor(() => {
+ expect(useAppState.getState().errorMessage).toBeUndefined()
+ })
+ })
+
+ it('copies the error details to the clipboard', async () => {
+ writeText.mockResolvedValue(undefined)
+ useAppState.setState({
+ errorMessage: {
+ subtitle: 'mcp-servers:checkParams',
+ message: 'stderr details',
+ },
+ })
+
+ render(<ErrorDialog />)
+
+ fireEvent.click(screen.getByText('common:copy'))
+
+ await waitFor(() => {
+ expect(writeText).toHaveBeenCalledWith('stderr details')
+ expect(successToast).toHaveBeenCalledWith('common:toast.errorCopied.title', {
+ id: 'copy-error',
+ description: 'common:toast.errorCopied.description',
+ })
+ })
+ })
+
+ it('shows a translated error toast when copying fails', async () => {
+ writeText.mockRejectedValueOnce(new Error('clipboard unavailable'))
+ useAppState.setState({
+ errorMessage: {
+ subtitle: 'mcp-servers:checkParams',
+ message: 'stderr details',
+ },
+ })
+
+ render(<ErrorDialog />)
+
+ fireEvent.click(screen.getByText('common:copy'))
+
+ await waitFor(() => {
+ expect(errorToast).toHaveBeenCalledWith('common:toast.errorCopyFailed.title', {
+ id: 'copy-error-failed',
+ description: 'common:toast.errorCopyFailed.description',
+ })
+ })
+ })
+
+ it('hides the details until expanded state is toggled', () => {
+ useAppState.setState({
+ errorMessage: {
+ subtitle: 'mcp-servers:checkParams',
+ message: 'long stderr details',
+ },
+ })
+
+ render(<ErrorDialog />)
+
+ expect(screen.getByText('long stderr details')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'common:errorDialog.details' }))
+ expect(screen.queryByText('long stderr details')).not.toBeInTheDocument()
+ })
+
+ it('renders the translated fallback title when no title is provided', () => {
+ useAppState.setState({
+ errorMessage: {
+ subtitle: 'mcp-servers:checkParams',
+ message: 'stderr details',
+ },
+ })
+
+ render(<ErrorDialog />)
+
+ expect(screen.getByText('common:errorDialog.titleFallback')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common:errorDialog.details' })).toBeInTheDocument()
+ })
+})
diff --git a/web-app/src/containers/dialogs/ErrorDialog.tsx b/web-app/src/containers/dialogs/ErrorDialog.tsx
new file mode 100644
index 000000000..af76cf232
--- /dev/null
+++ b/web-app/src/containers/dialogs/ErrorDialog.tsx
@@ -0,0 +1,125 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { AlertTriangle, ChevronDown, ChevronRight } from 'lucide-react'
+import { IconCopy, IconCopyCheck } from '@tabler/icons-react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { toast } from 'sonner'
+import { useState } from 'react'
+import { useAppState } from '@/hooks/useAppState'
+
+export default function ErrorDialog() {
+ const { t } = useTranslation()
+ const errorMessage = useAppState((state) => state.errorMessage)
+ const setErrorMessage = useAppState((state) => state.setErrorMessage)
+ const [isCopying, setIsCopying] = useState(false)
+ const [isDetailExpanded, setIsDetailExpanded] = useState(true)
+
+ const handleCopy = async () => {
+ setIsCopying(true)
+ try {
+ await navigator.clipboard.writeText(errorMessage?.message ?? '')
+ toast.success(t('common:toast.errorCopied.title'), {
+ id: 'copy-error',
+ description: t('common:toast.errorCopied.description'),
+ })
+ } catch {
+ toast.error(t('common:toast.errorCopyFailed.title'), {
+ id: 'copy-error-failed',
+ description: t('common:toast.errorCopyFailed.description'),
+ })
+ } finally {
+ setTimeout(() => setIsCopying(false), 2000)
+ }
+ }
+
+ const handleDialogOpen = (open: boolean) => {
+ setErrorMessage(open ? errorMessage : undefined)
+ }
+
+ return (
+ <Dialog open={!!errorMessage} onOpenChange={handleDialogOpen}>
+ <DialogContent showCloseButton={false}>
+ <DialogHeader>
+ <div className="flex items-start gap-3">
+ <div className="shrink-0">
+ <AlertTriangle className="size-4 text-destructive" />
+ </div>
+ <div>
+ <DialogTitle>{t('common:error')}</DialogTitle>
+ <DialogDescription className="mt-1 text-main-view-fg/70">
+ {errorMessage?.title ?? t('common:errorDialog.titleFallback')}
+ </DialogDescription>
+ </div>
+ </div>
+ </DialogHeader>
+
+ <div className="bg-main-view-fg/2 p-2 border border-main-view-fg/5 rounded-lg space-y-2">
+ <div>
+ <button
+ type="button"
+ onClick={() => setIsDetailExpanded((prev) => !prev)}
+ className="flex items-center gap-1 text-sm text-main-view-fg/60 hover:text-main-view-fg/80 transition-colors cursor-pointer"
+ >
+ {isDetailExpanded ? (
+ <ChevronDown className="size-3" />
+ ) : (
+ <ChevronRight className="size-3" />
+ )}
+ {t('common:errorDialog.details')}
+ </button>
+
+ {isDetailExpanded && (
+ <div
+ className="mt-2 text-sm text-main-view-fg/70 leading-relaxed max-h-[150px] overflow-y-auto break-all bg-main-view-fg/10 p-2 rounded border border-main-view-fg/5"
+ ref={(el) => {
+ if (el) {
+ el.scrollTop = el.scrollHeight
+ }
+ }}
+ >
+ {errorMessage?.message}
+ </div>
+ )}
+ </div>
+ <span className="text-sm text-main-view-fg/60">{errorMessage?.subtitle}</span>
+ </div>
+
+ <DialogFooter className="flex flex-col gap-2 sm:flex-row sm:justify-end">
+ <Button
+ variant="link"
+ onClick={() => handleDialogOpen(false)}
+ className="flex-1 text-right sm:flex-none"
+ >
+ {t('common:cancel')}
+ </Button>
+ <Button
+ variant="link"
+ onClick={() => void handleCopy()}
+ disabled={isCopying}
+ autoFocus
+ className="flex-1 text-right sm:flex-none border border-main-view-fg/20 !px-2"
+ >
+ {isCopying ? (
+ <>
+ <IconCopyCheck className="text-accent" />
+ {t('common:copied')}
+ </>
+ ) : (
+ <>
+ <IconCopy />
+ {t('common:copy')}
+ </>
+ )}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-app/src/locales/ca/common.json b/web-app/src/locales/ca/common.json
index 8392238b9..187e34eae 100644
--- a/web-app/src/locales/ca/common.json
+++ b/web-app/src/locales/ca/common.json
@@ -304,6 +304,10 @@
"attachmentEmbeddedIndicator": "Incrustat per a RAG",
"viewInjectedContent": "Mostra el contingut injectat",
"injectedContentTitle": "Contingut del fitxer injectat",
+ "errorDialog": {
+ "titleFallback": "Alguna cosa ha anat malament",
+ "details": "Detalls"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "S’han desmarcat tots els fils",
@@ -321,6 +325,14 @@
"title": "Fil suprimit",
"description": "Aquest fil s’ha suprimit definitivament."
},
+ "errorCopied": {
+ "title": "Còpia correcta",
+ "description": "La informació de l'error s'ha copiat al porta-retalls"
+ },
+ "errorCopyFailed": {
+ "title": "No s'ha pogut copiar",
+ "description": "No s'ha pogut copiar la informació de l'error al porta-retalls"
+ },
"editMessage": {
"title": "Missatge editat",
"description": "Missatge editat correctament. Espera la resposta del model."
diff --git a/web-app/src/locales/cs/common.json b/web-app/src/locales/cs/common.json
index c9d52216c..a0b0330e6 100644
--- a/web-app/src/locales/cs/common.json
+++ b/web-app/src/locales/cs/common.json
@@ -303,6 +303,10 @@
"tryDifferentSearch": "Zkuste jiný vyhledávací výraz",
"uploadingFiles": "Nahrávání souborů…"
},
+ "errorDialog": {
+ "titleFallback": "Něco se pokazilo",
+ "details": "Podrobnosti"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Všechna vlákna odebrána z oblíbených",
@@ -320,6 +324,14 @@
"title": "Smazat vlákno",
"description": "Toto vlákno bylo trvale smazáno."
},
+ "errorCopied": {
+ "title": "Zkopírování se podařilo",
+ "description": "Informace o chybě byly zkopírovány do schránky"
+ },
+ "errorCopyFailed": {
+ "title": "Nepodařilo se zkopírovat",
+ "description": "Nepodařilo se zkopírovat informace o chybě do schránky"
+ },
"editMessage": {
"title": "Upravit zprávu",
"description": "Zpráva byla úspěšně upravena. Počkejte prosím na odpověď modelu."
diff --git a/web-app/src/locales/de-DE/common.json b/web-app/src/locales/de-DE/common.json
index 6b7dc075e..48d7a62d5 100644
--- a/web-app/src/locales/de-DE/common.json
+++ b/web-app/src/locales/de-DE/common.json
@@ -303,6 +303,10 @@
"tryDifferentSearch": "Versuchen Sie einen anderen Suchbegriff",
"uploadingFiles": "Dateien werden hochgeladen…"
},
+ "errorDialog": {
+ "titleFallback": "Etwas ist schiefgelaufen",
+ "details": "Details"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Alle Threads De-Favorisieren ",
@@ -348,6 +352,14 @@
"title": "Thread löschen",
"description": "This thread has been permanently deleted."
},
+ "errorCopied": {
+ "title": "Erfolgreich kopiert",
+ "description": "Fehlerinformationen wurden in die Zwischenablage kopiert"
+ },
+ "errorCopyFailed": {
+ "title": "Kopieren fehlgeschlagen",
+ "description": "Fehlerinformationen konnten nicht in die Zwischenablage kopiert werden"
+ },
"editMessage": {
"title": "Nachricht bearbeiten",
"description": "Die Nachricht wurde erfolgreich bearbeitet. Bitte warte auf die Antwort des Models."
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 383ae697a..041975042 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -262,6 +262,10 @@
"title": "Message Metadata"
}
},
+ "errorDialog": {
+ "titleFallback": "Something went wrong",
+ "details": "Details"
+ },
"projects": {
"title": "Projects",
"new": "New Projects",
@@ -357,6 +361,14 @@
"title": "Delete Thread",
"description": "This thread has been permanently deleted."
},
+ "errorCopied": {
+ "title": "Copy successful",
+ "description": "Error information copied to clipboard"
+ },
+ "errorCopyFailed": {
+ "title": "Failed to copy",
+ "description": "Failed to copy error information to clipboard"
+ },
"editMessage": {
"title": "Edit Message",
"description": "Message edited successfully. Please wait for the model to respond."
diff --git a/web-app/src/locales/es/common.json b/web-app/src/locales/es/common.json
index 6510070ed..6f2a3c57f 100644
--- a/web-app/src/locales/es/common.json
+++ b/web-app/src/locales/es/common.json
@@ -342,6 +342,10 @@
"attachmentEmbeddedIndicator": "Embebido para RAG",
"viewInjectedContent": "Ver contenido inyectado",
"injectedContentTitle": "Contenido del archivo inyectado",
+ "errorDialog": {
+ "titleFallback": "Algo salió mal",
+ "details": "Detalles"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Todos los hilos sin estrella",
@@ -359,6 +363,14 @@
"title": "Eliminar hilo",
"description": "Este hilo ha sido eliminado permanentemente."
},
+ "errorCopied": {
+ "title": "Copia realizada con éxito",
+ "description": "La información del error se copió al portapapeles"
+ },
+ "errorCopyFailed": {
+ "title": "Error al copiar",
+ "description": "No se pudo copiar la información del error al portapapeles"
+ },
"editMessage": {
"title": "Editar mensaje",
"description": "Mensaje editado correctamente. Por favor espera la respuesta del modelo."
diff --git a/web-app/src/locales/fr/common.json b/web-app/src/locales/fr/common.json
index a3a0bfb8d..2c75f0705 100644
--- a/web-app/src/locales/fr/common.json
+++ b/web-app/src/locales/fr/common.json
@@ -302,6 +302,10 @@
"tryDifferentSearch": "Essayez un autre terme de recherche",
"uploadingFiles": "Téléversement des fichiers…"
},
+ "errorDialog": {
+ "titleFallback": "Une erreur s'est produite",
+ "details": "Détails"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Toutes les discussions retirées des favoris",
@@ -319,6 +323,14 @@
"title": "Supprimer la discussion",
"description": "Cette discussion a été supprimée définitivement."
},
+ "errorCopied": {
+ "title": "Copie réussie",
+ "description": "Les informations d'erreur ont été copiées dans le presse-papiers"
+ },
+ "errorCopyFailed": {
+ "title": "Échec de la copie",
+ "description": "Impossible de copier les informations d'erreur dans le presse-papiers"
+ },
"editMessage": {
"title": "Modifier le message",
"description": "Message modifié avec succès. Veuillez attendre la réponse du modèle."
diff --git a/web-app/src/locales/id/common.json b/web-app/src/locales/id/common.json
index a3492d77c..be50b104f 100644
--- a/web-app/src/locales/id/common.json
+++ b/web-app/src/locales/id/common.json
@@ -247,6 +247,10 @@
"title": "Metadata Pesan"
}
},
+ "errorDialog": {
+ "titleFallback": "Terjadi kesalahan",
+ "details": "Detail"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Semua Utas Batal Difavoritkan",
@@ -264,6 +268,14 @@
"title": "Hapus Utas",
"description": "Utas ini telah dihapus secara permanen."
},
+ "errorCopied": {
+ "title": "Berhasil disalin",
+ "description": "Informasi kesalahan disalin ke papan klip"
+ },
+ "errorCopyFailed": {
+ "title": "Gagal menyalin",
+ "description": "Gagal menyalin informasi kesalahan ke papan klip"
+ },
"editMessage": {
"title": "Edit Pesan",
"description": "Pesan berhasil diedit. Silakan tunggu model merespons."
diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.json
index ec036c420..f57257f2a 100644
--- a/web-app/src/locales/ja/common.json
+++ b/web-app/src/locales/ja/common.json
@@ -294,6 +294,10 @@
"update": "更新",
"uploadingFiles": "ファイルをアップロードしています…"
},
+ "errorDialog": {
+ "titleFallback": "問題が発生しました",
+ "details": "詳細"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "すべてのスレッドのお気に入りを解除しました",
@@ -311,6 +315,14 @@
"title": "スレッドを削除",
"description": "このスレッドは完全に削除されました。"
},
+ "errorCopied": {
+ "title": "コピーしました",
+ "description": "エラー情報をクリップボードにコピーしました"
+ },
+ "errorCopyFailed": {
+ "title": "コピーに失敗しました",
+ "description": "エラー情報をクリップボードにコピーできませんでした"
+ },
"editMessage": {
"title": "メッセージを編集",
"description": "メッセージは正常に編集されました。モデルの応答をお待ちください。"
diff --git a/web-app/src/locales/ko/common.json b/web-app/src/locales/ko/common.json
index 00c2b1b5e..42c373a52 100644
--- a/web-app/src/locales/ko/common.json
+++ b/web-app/src/locales/ko/common.json
@@ -340,6 +340,10 @@
"attachmentEmbeddedIndicator": "RAG용으로 임베딩됨",
"viewInjectedContent": "삽입된 콘텐츠 보기",
"injectedContentTitle": "삽입된 파일 콘텐츠",
+ "errorDialog": {
+ "titleFallback": "문제가 발생했습니다",
+ "details": "세부 정보"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "모든 스레드 즐겨찾기 해제됨",
@@ -357,6 +361,14 @@
"title": "스레드 삭제",
"description": "이 스레드는 영구적으로 삭제되었습니다."
},
+ "errorCopied": {
+ "title": "복사되었습니다",
+ "description": "오류 정보가 클립보드에 복사되었습니다"
+ },
+ "errorCopyFailed": {
+ "title": "복사에 실패했습니다",
+ "description": "오류 정보를 클립보드에 복사하지 못했습니다"
+ },
"editMessage": {
"title": "메시지 수정",
"description": "메시지가 성공적으로 수정되었습니다. 모델이 응답할 때까지 기다려 주세요."
diff --git a/web-app/src/locales/pl/common.json b/web-app/src/locales/pl/common.json
index 354e1e607..84d7fe427 100644
--- a/web-app/src/locales/pl/common.json
+++ b/web-app/src/locales/pl/common.json
@@ -297,6 +297,10 @@
"tryDifferentSearch": "Spróbuj innego wyszukiwania",
"uploadingFiles": "Przesyłanie plików…"
},
+ "errorDialog": {
+ "titleFallback": "Coś poszło nie tak",
+ "details": "Szczegóły"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Wszystkie Wątki Usunięte z Ulubionych",
@@ -314,6 +318,14 @@
"title": "Usuń Wątek",
"description": "Wątek został usunięty."
},
+ "errorCopied": {
+ "title": "Skopiowano pomyślnie",
+ "description": "Informacje o błędzie zostały skopiowane do schowka"
+ },
+ "errorCopyFailed": {
+ "title": "Nie udało się skopiować",
+ "description": "Nie udało się skopiować informacji o błędzie do schowka"
+ },
"editMessage": {
"title": "Edytuj Wiadomość",
"description": "Pomyślnie edytowano wiadomość. Proszę poczekać na odpowiedź modelu."
diff --git a/web-app/src/locales/pt-BR/common.json b/web-app/src/locales/pt-BR/common.json
index 392f31b2b..243d20acf 100644
--- a/web-app/src/locales/pt-BR/common.json
+++ b/web-app/src/locales/pt-BR/common.json
@@ -300,6 +300,10 @@
"tryDifferentSearch": "Tente um termo de busca diferente",
"uploadingFiles": "Enviando arquivos…"
},
+ "errorDialog": {
+ "titleFallback": "Algo deu errado",
+ "details": "Detalhes"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Todas as Conversas Removidas dos Favoritos",
@@ -317,6 +321,14 @@
"title": "Remover Conversa",
"description": "Esta conversa foi removida permanentemente."
},
+ "errorCopied": {
+ "title": "Cópia realizada com sucesso",
+ "description": "As informações do erro foram copiadas para a área de transferência"
+ },
+ "errorCopyFailed": {
+ "title": "Falha ao copiar",
+ "description": "Não foi possível copiar as informações do erro para a área de transferência"
+ },
"editMessage": {
"title": "Editar Mensagem",
"description": "Mensagem editada com sucesso. Aguarde a resposta do modelo."
diff --git a/web-app/src/locales/ru/common.json b/web-app/src/locales/ru/common.json
index 079622d18..330232c00 100644
--- a/web-app/src/locales/ru/common.json
+++ b/web-app/src/locales/ru/common.json
@@ -313,6 +313,10 @@
"attachmentEmbeddedIndicator": "Эмбеддинг для RAG",
"viewInjectedContent": "Просмотреть вставленный контент",
"injectedContentTitle": "Содержимое файла",
+ "errorDialog": {
+ "titleFallback": "Что-то пошло не так",
+ "details": "Подробности"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Все обсуждения удалены из избранного",
@@ -330,6 +334,14 @@
"title": "Удаление обсуждения",
"description": "Это обсуждение было удалено безвозвратно."
},
+ "errorCopied": {
+ "title": "Скопировано успешно",
+ "description": "Информация об ошибке скопирована в буфер обмена"
+ },
+ "errorCopyFailed": {
+ "title": "Не удалось скопировать",
+ "description": "Не удалось скопировать информацию об ошибке в буфер обмена"
+ },
"editMessage": {
"title": "Редактирование сообщения",
"description": "Сообщение успешно отредактировано. Пожалуйста, подождите ответа модели."
diff --git a/web-app/src/locales/vn/common.json b/web-app/src/locales/vn/common.json
index 42cf06438..ae0876cfd 100644
--- a/web-app/src/locales/vn/common.json
+++ b/web-app/src/locales/vn/common.json
@@ -303,6 +303,10 @@
"title": "Siêu dữ liệu tin nhắn"
}
},
+ "errorDialog": {
+ "titleFallback": "Đã xảy ra lỗi",
+ "details": "Chi tiết"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "Tất cả các chủ đề đã được bỏ yêu thích",
@@ -320,6 +324,14 @@
"title": "Xóa chủ đề",
"description": "Chủ đề này đã bị xóa vĩnh viễn."
},
+ "errorCopied": {
+ "title": "Sao chép thành công",
+ "description": "Thông tin lỗi đã được sao chép vào bộ nhớ tạm"
+ },
+ "errorCopyFailed": {
+ "title": "Không thể sao chép",
+ "description": "Không thể sao chép thông tin lỗi vào bộ nhớ tạm"
+ },
"editMessage": {
"title": "Chỉnh sửa tin nhắn",
"description": "Tin nhắn đã được chỉnh sửa thành công. Vui lòng đợi mô hình phản hồi."
diff --git a/web-app/src/locales/zh-CN/common.json b/web-app/src/locales/zh-CN/common.json
index 50bc235a1..5b7a8fcb6 100644
--- a/web-app/src/locales/zh-CN/common.json
+++ b/web-app/src/locales/zh-CN/common.json
@@ -303,6 +303,10 @@
"title": "消息元数据"
}
},
+ "errorDialog": {
+ "titleFallback": "出了点问题",
+ "details": "详细信息"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "所有会话已取消收藏",
@@ -320,6 +324,14 @@
"title": "删除会话",
"description": "此会话已被永久删除。"
},
+ "errorCopied": {
+ "title": "复制成功",
+ "description": "错误信息已复制到剪贴板"
+ },
+ "errorCopyFailed": {
+ "title": "复制失败",
+ "description": "无法将错误信息复制到剪贴板"
+ },
"editMessage": {
"title": "编辑消息",
"description": "消息编辑成功。请等待模型响应。"
diff --git a/web-app/src/locales/zh-TW/common.json b/web-app/src/locales/zh-TW/common.json
index 6118a58e8..be361e2f7 100644
--- a/web-app/src/locales/zh-TW/common.json
+++ b/web-app/src/locales/zh-TW/common.json
@@ -303,6 +303,10 @@
"title": "訊息元資料"
}
},
+ "errorDialog": {
+ "titleFallback": "發生了一些問題",
+ "details": "詳細資訊"
+ },
"toast": {
"allThreadsUnfavorited": {
"title": "所有對話已取消收藏",
@@ -320,6 +324,14 @@
"title": "刪除對話",
"description": "此對話已永久刪除。"
},
+ "errorCopied": {
+ "title": "複製成功",
+ "description": "錯誤資訊已複製到剪貼簿"
+ },
+ "errorCopyFailed": {
+ "title": "複製失敗",
+ "description": "無法將錯誤資訊複製到剪貼簿"
+ },
"editMessage": {
"title": "編輯訊息",
"description": "訊息編輯成功。請等待模型回應。"
diff --git a/web-app/src/routes/__root.tsx b/web-app/src/routes/__root.tsx
index 572374a6a..620dc531c 100644
--- a/web-app/src/routes/__root.tsx
+++ b/web-app/src/routes/__root.tsx
@@ -29,6 +29,7 @@ import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
import { LeftSidebar } from '@/components/left-sidebar'
import { WindowControls } from '@/components/WindowControls'
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'
+import ErrorDialog from '@/containers/dialogs/ErrorDialog'
export const Route = createRootRoute({
component: RootLayout,
@@ -155,6 +156,7 @@ function RootLayout() {
{/* <TanStackRouterDevtools position="bottom-right" /> */}
<ToolApproval />
<AttachmentIngestionDialog />
+ <ErrorDialog />
<OutOfContextPromiseModal />
</TranslationProvider>
</ServiceHubProvider>
diff --git a/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx b/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx
new file mode 100644
index 000000000..d7c4c8b45
--- /dev/null
+++ b/web-app/src/routes/settings/__tests__/mcp-servers.error.test.tsx
@@ -0,0 +1,239 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { Route as McpServersRoute } from '../mcp-servers'
+import { useAppState } from '@/hooks/useAppState'
+
+const activateMCPServer = vi.fn()
+const deactivateMCPServer = vi.fn()
+const getConnectedServers = vi.fn().mockResolvedValue([])
+
+vi.mock('@/containers/SettingsMenu', () => ({
+ default: () => <div data-testid="settings-menu">Settings Menu</div>,
+}))
+
+vi.mock('@/containers/HeaderPage', () => ({
+ default: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="header-page">{children}</div>
+ ),
+}))
+
+vi.mock('@/containers/Card', () => ({
+ Card: ({ header, children }: { header?: React.ReactNode; children: React.ReactNode }) => (
+ <div data-testid="card">
+ {header}
+ {children}
+ </div>
+ ),
+ CardItem: ({
+ title,
+ description,
+ actions,
+ }: {
+ title?: React.ReactNode
+ description?: React.ReactNode
+ actions?: React.ReactNode
+ }) => (
+ <div data-testid="card-item">
+ <div>{title}</div>
+ <div>{description}</div>
+ <div>{actions}</div>
+ </div>
+ ),
+}))
+
+vi.mock('@/containers/dialogs/AddEditMCPServer', () => ({
+ default: () => null,
+}))
+
+vi.mock('@/containers/dialogs/DeleteMCPServerConfirm', () => ({
+ default: () => null,
+}))
+
+vi.mock('@/containers/dialogs/EditJsonMCPserver', () => ({
+ default: () => null,
+}))
+
+vi.mock('@/containers/McpRouterModelPicker', () => ({
+ McpRouterModelPicker: () => null,
+}))
+
+vi.mock('@/components/ui/button', () => ({
+ Button: ({
+ children,
+ onClick,
+ }: {
+ children: React.ReactNode
+ onClick?: () => void
+ }) => <button onClick={onClick}>{children}</button>,
+}))
+
+vi.mock('@/components/ui/switch', () => ({
+ Switch: ({
+ checked,
+ onCheckedChange,
+ disabled,
+ }: {
+ checked?: boolean
+ onCheckedChange?: (value: boolean) => void
+ disabled?: boolean
+ }) => (
+ <button
+ type="button"
+ disabled={disabled}
+ aria-pressed={checked}
+ onClick={() => onCheckedChange?.(!checked)}
+ >
+ toggle
+ </button>
+ ),
+}))
+
+vi.mock('@/components/ui/input', () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}))
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ useServiceHub: () => ({
+ mcp: () => ({
+ activateMCPServer,
+ deactivateMCPServer,
+ getConnectedServers,
+ }),
+ }),
+}))
+
+vi.mock('@/hooks/useToolApproval', () => ({
+ useToolApproval: () => ({
+ allowAllMCPPermissions: true,
+ setAllowAllMCPPermissions: vi.fn(),
+ }),
+}))
+
+vi.mock('@/hooks/useModelProvider', () => ({
+ useModelProvider: (selector: (state: { providers: never[] }) => unknown) =>
+ selector({ providers: [] }),
+}))
+
+vi.mock('@/hooks/useMCPServers', () => ({
+ DEFAULT_MCP_SETTINGS: {
+ toolCallTimeoutSeconds: 60,
+ enableSmartToolRouting: false,
+ useLightweightRouterModel: false,
+ routerModelProvider: '',
+ routerModelId: '',
+ },
+ useMCPServers: () => ({
+ mcpServers: {
+ NotesMCP: {
+ command: 'npx',
+ args: ['notes'],
+ env: {},
+ type: 'stdio',
+ active: false,
+ },
+ },
+ settings: {
+ toolCallTimeoutSeconds: 60,
+ enableSmartToolRouting: false,
+ useLightweightRouterModel: false,
+ routerModelProvider: '',
+ routerModelId: '',
+ },
+ addServer: vi.fn(),
+ editServer: vi.fn(),
+ renameServer: vi.fn(),
+ deleteServer: vi.fn(),
+ syncServers: vi.fn(),
+ syncServersAndRestart: vi.fn(),
+ getServerConfig: () => ({
+ command: 'npx',
+ args: ['notes'],
+ env: {},
+ type: 'stdio',
+ active: false,
+ }),
+ setSettings: vi.fn(),
+ updateSettings: vi.fn(),
+ }),
+}))
+
+vi.mock('@/i18n/react-i18next-compat', () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record<string, string>) =>
+ params?.serverKey ? `${key}:${params.serverKey}` : key,
+ }),
+}))
+
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn().mockResolvedValue(() => {}),
+}))
+
+vi.mock('@/types/events', () => ({
+ SystemEvent: {
+ MCP_UPDATE: 'mcp-update',
+ },
+}))
+
+vi.mock('@tanstack/react-router', () => ({
+ createFileRoute: (_path: string) => (config: { component: React.ComponentType }) => config,
+}))
+
+vi.mock('@/constants/routes', () => ({
+ route: {
+ settings: {
+ mcp_servers: '/settings/mcp-servers',
+ },
+ },
+}))
+
+vi.mock('sonner', () => ({
+ toast: {
+ success: vi.fn(),
+ error: vi.fn(),
+ },
+}))
+
+describe('MCP servers route error handling', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ useAppState.setState({
+ errorMessage: undefined,
+ })
+ getConnectedServers.mockResolvedValue([])
+ })
+
+ it('stores a normalized activation error when activation rejects with an Error', async () => {
+ activateMCPServer.mockRejectedValueOnce(new Error('stdio startup failed'))
+
+ const Component = McpServersRoute.component as React.ComponentType
+ render(<Component />)
+
+ const toggles = screen.getAllByRole('button', { name: 'toggle' })
+ await act(async () => {
+ fireEvent.click(toggles[toggles.length - 1])
+ })
+
+ await waitFor(() => {
+ expect(useAppState.getState().errorMessage).toEqual({
+ message: 'stdio startup failed',
+ subtitle: 'mcp-servers:checkParams',
+ })
+ })
+ })
+
+ it('stores a normalized activation error when activation rejects with an object payload', async () => {
+ activateMCPServer.mockRejectedValueOnce({ message: 'wrapped startup failed' })
+
+ const Component = McpServersRoute.component as React.ComponentType
+ render(<Component />)
+
+ const toggles = screen.getAllByRole('button', { name: 'toggle' })
+ await act(async () => {
+ fireEvent.click(toggles[toggles.length - 1])
+ })
+
+ await waitFor(() => {
+ expect(useAppState.getState().errorMessage?.message).toBe('wrapped startup failed')
+ })
+ })
+})
diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsx
index bb08fcadc..a3b3c91a3 100644
--- a/web-app/src/routes/settings/mcp-servers.tsx
+++ b/web-app/src/routes/settings/mcp-servers.tsx
@@ -34,6 +34,7 @@ import { cn } from '@/lib/utils'
import { useModelProvider } from '@/hooks/useModelProvider'
import { McpRouterModelPicker } from '@/containers/McpRouterModelPicker'
import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'
+import { normalizeAppError } from '@/utils/appError'
// Function to mask sensitive URL parameters
@@ -358,7 +359,7 @@ function MCPServersDesktop() {
active: false,
})
setErrorMessage({
- message: error,
+ message: normalizeAppError(error),
subtitle: t('mcp-servers:checkParams'),
})
})
diff --git a/web-app/src/utils/__tests__/appError.test.ts b/web-app/src/utils/__tests__/appError.test.ts
new file mode 100644
index 000000000..b05ade640
--- /dev/null
+++ b/web-app/src/utils/__tests__/appError.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest'
+import { normalizeAppError } from '../appError'
+
+describe('normalizeAppError', () => {
+ it('returns plain string errors as-is', () => {
+ expect(normalizeAppError('startup failed')).toBe('startup failed')
+ })
+
+ it('returns error messages from Error instances', () => {
+ expect(normalizeAppError(new Error('boom'))).toBe('boom')
+ })
+
+ it('returns message fields from plain objects', () => {
+ expect(normalizeAppError({ message: 'from object' })).toBe('from object')
+ })
+
+ it('stringifies unexpected objects', () => {
+ expect(normalizeAppError({ code: 42 })).toBe('{"code":42}')
+ })
+
+ it('falls back for empty values', () => {
+ expect(normalizeAppError(' ')).toBe('Unknown error')
+ expect(normalizeAppError(null)).toBe('Unknown error')
+ })
+})
diff --git a/web-app/src/utils/appError.ts b/web-app/src/utils/appError.ts
new file mode 100644
index 000000000..9ec11027d
--- /dev/null
+++ b/web-app/src/utils/appError.ts
@@ -0,0 +1,30 @@
+export function normalizeAppError(error: unknown): string {
+ if (typeof error === 'string') {
+ return normalizeWhitespace(error)
+ }
+
+ if (error instanceof Error) {
+ return normalizeWhitespace(error.message)
+ }
+
+ if (typeof error === 'object' && error !== null) {
+ const record = error as { message?: unknown }
+
+ if (typeof record.message === 'string') {
+ return normalizeWhitespace(record.message)
+ }
+
+ try {
+ return normalizeWhitespace(JSON.stringify(error))
+ } catch {
+ return 'Unknown error'
+ }
+ }
+
+ return 'Unknown error'
+}
+
+function normalizeWhitespace(value: string): string {
+ const trimmed = value.trim()
+ return trimmed.length > 0 ? trimmed : 'Unknown error'
+}