fix: explain failed sends in plain words and keep toasts off the Send button

This commit is contained in:
Linus Rath
2026-10-11 19:54:02 +02:00
parent 2ae8c89990
commit 935a410c8f
4 changed files with 265 additions and 8 deletions
@@ -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<typeof state>) => 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<typeof state>) => 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<typeof state>) => 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<typeof state>) => 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<typeof state>) => 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<typeof state>) => 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<typeof state>) => 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: '<p>Hello there</p>',
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(<EmailComposer initialData={DRAFT} onSend={onSend} />);
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(<EmailComposer initialData={DRAFT} onSend={onSend} />);
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(<EmailComposer initialData={DRAFT} />);
expect(document.documentElement.dataset.composerOpen).toBe('1');
unmount();
expect(document.documentElement.dataset.composerOpen).toBeUndefined();
});
});
+25 -7
View File
@@ -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);
+1 -1
View File
@@ -234,7 +234,7 @@ export function ToastContainer({ toasts, onClose }: { toasts: Toast[]; onClose:
return createPortal(
<div
className="fixed bottom-5 right-5 z-[99999] flex flex-col-reverse gap-2.5"
className="fixed bottom-5 right-5 z-[99999] flex flex-col-reverse gap-2.5 [html[data-composer-open]_&]:bottom-20"
role="status"
aria-live="polite"
style={{ pointerEvents: "none" }}
+1
View File
@@ -710,6 +710,7 @@
"drop_files": "Drop files to attach",
"show_less": "Show less",
"send_failed": "Failed to send email",
"send_offline": "You seem to be offline. The message is still here, send it again once you are back online.",
"send_timeout": "The server stopped responding. Check your Sent folder before sending again — the message may have gone out.",
"send_recipients_rejected": "Not sent - the server rejected every recipient.",
"send_plugin_failed": "Not sent - a plugin that handles sending failed or took too long. Check your Sent folder before sending again.",