From 935a410c8f9b2c14f8b4cec3571d23b8bb8a4be3 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:54:02 +0200 Subject: [PATCH] fix: explain failed sends in plain words and keep toasts off the Send button --- .../__tests__/composer-send-errors.test.tsx | 238 ++++++++++++++++++ components/email/email-composer.tsx | 32 ++- components/ui/toast.tsx | 2 +- locales/en/common.json | 1 + 4 files changed, 265 insertions(+), 8 deletions(-) create mode 100644 components/email/__tests__/composer-send-errors.test.tsx diff --git a/components/email/__tests__/composer-send-errors.test.tsx b/components/email/__tests__/composer-send-errors.test.tsx new file mode 100644 index 000000000..1f2a4fba0 --- /dev/null +++ b/components/email/__tests__/composer-send-errors.test.tsx @@ -0,0 +1,238 @@ +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import React from 'react'; +import { EmailComposer } from '../email-composer'; + +// ─── Heavy component mocks (mirrors reply-addressing.test.tsx) ──────────────── + +const editorKeyDown = vi.hoisted(() => vi.fn()); +const toastError = vi.hoisted(() => vi.fn()); + +vi.mock('@/components/email/rich-text-editor', () => ({ + RichTextEditor: () => React.createElement('div', { + 'data-testid': 'rich-text-editor', + onKeyDown: (event: React.KeyboardEvent) => { + if (!event.defaultPrevented) editorKeyDown(); + }, + }), +})); + +vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null })); +vi.mock('@/components/ui/avatar', () => ({ Avatar: () => null })); +vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null })); +vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null })); +vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null })); +vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null })); +vi.mock('@/hooks/use-focus-trap', () => ({ + useFocusTrap: () => ({ current: null }), +})); +vi.mock('@/hooks/use-pro-multi-account-identities', () => ({ + useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }), + stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }), +})); + +// ─── Store mocks ────────────────────────────────────────────────────────────── + +vi.mock('@/stores/auth-store', () => { + const state = { + client: null, + identities: [], + primaryIdentity: null, + isAuthenticated: false, + isDemoMode: false, + activeAccountId: null, + connectionLost: false, + getClientForAccount: () => undefined, + getAllConnectedClients: () => new Map(), + syncIdentities: () => {}, + refreshIdentities: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAuthStore: hook }; +}); + +vi.mock('@/stores/identity-store', () => { + const state = { + identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }], + defaultIdentityId: 'id-me', + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useIdentityStore: hook }; +}); + +vi.mock('@/stores/account-store', () => { + const state = { accounts: [], getAccountById: () => undefined }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useAccountStore: hook }; +}); + +vi.mock('@/stores/email-store', () => { + const state = { + draftSaveEnabled: false, + sendRawEmail: async () => ({ sent: true }), + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useEmailStore: hook }; +}); + +const updateSetting = vi.fn(); + +vi.mock('@/stores/settings-store', () => { + const state = { + timeFormat: '24h', + plainTextMode: false, + subAddressDelimiter: '+', + autoSelectReplyIdentity: true, + attachmentReminderEnabled: false, + attachmentReminderKeywords: [], + emptySubjectWarningEnabled: true, + sendDelaySeconds: 0, + signaturePosition: 'above_quote', + signatureSeparatorEnabled: false, + requestReadReceiptDefault: false, + addTrustedSender: () => {}, + trustedSendersAddressBook: null, + updateSetting: (...args: unknown[]) => updateSetting(...args), + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useSettingsStore: hook }; +}); + +vi.mock('@/stores/contact-store', () => { + const state = { + contacts: [], + getAutocomplete: async () => [], + addToTrustedSendersBook: async () => {}, + }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useContactStore: hook }; +}); + +vi.mock('@/stores/template-store', () => { + const state = { templates: [], addTemplate: async () => {} }; + const hook = (sel?: (s: typeof state) => unknown) => + typeof sel === 'function' ? sel(state) : state; + hook.getState = () => state; + hook.setState = (p: Partial) => Object.assign(state, p); + return { useTemplateStore: hook }; +}); + +// ─── Misc dependency mocks ──────────────────────────────────────────────────── + +vi.mock('@/stores/toast-store', () => ({ + toast: { info: () => {}, error: toastError, success: () => {} }, +})); + +vi.mock('@/lib/plugin-hooks', () => ({ + emailHooks: { + onComposerOpen: { call: async () => [] }, + onRecipientChange: { call: async () => [] }, + getRecipientSuggestions: { call: async () => [] }, + onRecipientChipsChange: { transform: async (chips: unknown) => chips }, + onDraftChange: { emit: () => {} }, + onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft }, + onBeforeEmailSend: { intercept: async () => true }, + onComposeSend: { takeOver: async () => 'default' }, + onTransformOutgoingEmail: { transform: async (email: unknown) => email }, + }, + contactHooks: { + search: { call: async () => [] }, + onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial }, + }, +})); + +vi.mock('@/lib/email-sanitization', () => ({ + sanitizeSignatureHtml: (v: string) => v, + sanitizeEmailHtml: (v: string) => v, + parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'), +})); + +vi.mock('@/lib/email-threading', () => ({ + computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }), +})); +vi.mock('@/lib/signature-utils', () => ({ + appendPlainTextSignature: (body: string) => body, + getPlainTextSignature: () => '', +})); +vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' })); +vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } })); +vi.mock('@/components/email/quoted-html', () => ({ + buildQuotedHtmlBlock: () => '', + serializeEditorContent: () => '', +})); +vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s })); + +// ─── Tests ──────────────────────────────────────────────────────────────────── + +const DRAFT = { + to: 'bob@example.com', + cc: '', + bcc: '', + subject: 'Lunch', + body: '

Hello there

', + showCc: false, + showBcc: false, + selectedIdentityId: 'id-me', + subAddressTag: '', + mode: 'compose' as const, + draftId: null, +}; + +const sendButton = () => screen.getAllByTestId('composer-send')[0] as HTMLButtonElement; + +describe('composer send errors', () => { + beforeEach(() => { + toastError.mockClear(); + updateSetting.mockClear(); + editorKeyDown.mockClear(); + }); + + it('says the user is offline instead of "Failed to fetch"', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const onSend = vi.fn().mockRejectedValue(new TypeError('Failed to fetch')); + render(); + + fireEvent.click(sendButton()); + + await waitFor(() => expect(toastError).toHaveBeenCalled()); + expect(toastError).toHaveBeenCalledWith('send_failed', { message: 'send_offline' }); + }); + + it('puts the server\'s message under a plain title', async () => { + const onSend = vi.fn().mockRejectedValue(new Error('No recipients found in email. [noRecipients]')); + render(); + + fireEvent.click(sendButton()); + + await waitFor(() => expect(toastError).toHaveBeenCalled()); + expect(toastError).toHaveBeenCalledWith('send_failed', { message: 'No recipients found in email. [noRecipients]' }); + }); +}); + +describe('composer and the toast stack', () => { + it('marks the page while open so toasts move clear of the Send button', () => { + const { unmount } = render(); + expect(document.documentElement.dataset.composerOpen).toBe('1'); + + unmount(); + expect(document.documentElement.dataset.composerOpen).toBeUndefined(); + }); +}); diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx index b6ce64bc8..c3ffc2518 100644 --- a/components/email/email-composer.tsx +++ b/components/email/email-composer.tsx @@ -2351,6 +2351,19 @@ export function EmailComposer({ // The user confirmed sending without a subject for this message. const emptySubjectConfirmedRef = useRef(false); + // Toasts sit in the bottom corner, right over the composer's Send button. + // The attribute lifts them clear while a composer is open (see toast.tsx). + useEffect(() => { + const root = document.documentElement; + const open = Number(root.dataset.composerOpen ?? 0) + 1; + root.dataset.composerOpen = String(open); + return () => { + const left = Number(root.dataset.composerOpen ?? 1) - 1; + if (left > 0) root.dataset.composerOpen = String(left); + else delete root.dataset.composerOpen; + }; + }, []); + const handleSend = async ({ skipAttachmentCheck = false, skipSubjectCheck = false, delayedUntil }: { skipAttachmentCheck?: boolean; skipSubjectCheck?: boolean; @@ -2728,13 +2741,18 @@ export function EmailComposer({ // server and gone out, with only the answer lost. Saying "send failed" // would invite a re-send and a duplicate, so point at Sent instead (#702). // The same goes for a send the server answered without confirming it. - toast.error( - err instanceof RequestTimeoutError || err instanceof SendUnconfirmedError - ? t('send_timeout') - : err instanceof ScheduleTooLateError - ? t('schedule_send_too_late') - : err instanceof Error ? err.message : t('send_failed') - ); + if (err instanceof RequestTimeoutError || err instanceof SendUnconfirmedError) { + toast.error(t('send_timeout')); + } else if (err instanceof ScheduleTooLateError) { + toast.error(t('schedule_send_too_late')); + } else if (err instanceof TypeError || (typeof navigator !== 'undefined' && navigator.onLine === false)) { + // fetch() rejects with a TypeError when the network is gone; its + // "Failed to fetch" told the user nothing. + toast.error(t('send_failed'), { message: t('send_offline') }); + } else { + // The server's own words go under a plain title instead of on their own. + toast.error(t('send_failed'), { message: err instanceof Error ? err.message : undefined }); + } } finally { isSendingRef.current = false; setIsSending(false); diff --git a/components/ui/toast.tsx b/components/ui/toast.tsx index 6d11aabf5..28c7dbd91 100644 --- a/components/ui/toast.tsx +++ b/components/ui/toast.tsx @@ -234,7 +234,7 @@ export function ToastContainer({ toasts, onClose }: { toasts: Toast[]; onClose: return createPortal(