Email for professionals and teams
Make the undo-send window an account setting
Kevin Kyburz1160e0a0b43b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1136d6d..e9de67b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -123,7 +123,7 @@ Native push goes straight to APNs when the server has `APNS_KEY_ID`/`APNS_TEAM_I### Read receipts are an opt-in pixel-The composer's eye toggle (`use-track-opens.ts`, remembered per browser) sends `trackOpens`. `deliverEmail` creates the `message_tracking` token at actual delivery, so a cancelled undo-send or reschedule leaves none, and injects the pixel only into the HTML handed to the provider: the stored Sent copy never contains it. The pixel is `GET /api/i/<token>.gif` (public, always the same GIF); `classifyOpen` (`src/lib/tracking/open-tracking-utils.ts`) names the client and device, drops device and location for proxies (Gmail, Yahoo, Apple), and flags Apple Mail Privacy Protection (Apple ASNs) and fetches within 10 s of delivery as `automated`, which `open_count` excludes. Pixel origin is the sender domain's own host from `domain_tracking_hosts` (set on the Domains page, must be the domain or a subdomain and attached to the Worker as a custom domain, kept out of `domains` so sending never depends on migration 0069), else `APP_URL`, else the composer request's origin; with neither, or before migration 0068, mail goes out untracked rather than failing. One pixel per message, so opens are not attributed to a recipient.+The composer's eye toggle (`use-track-opens.ts`) starts from the account default in `user_compose_preferences` (Settings → Inbox → Compose, `/api/settings/compose`, migration 0072, off before it) and sends `trackOpens`; toggling it changes only that message. The same table holds `undo_send_seconds` (migration 0073, 0/5/10/15/30, default 15), which `sendEmail` reads for `undoSend` requests; 0 delivers at once. `deliverEmail` creates the `message_tracking` token at actual delivery, so a cancelled undo-send or reschedule leaves none, and injects the pixel only into the HTML handed to the provider: the stored Sent copy never contains it. The pixel is `GET /api/i/<token>.gif` (public, always the same GIF); `classifyOpen` (`src/lib/tracking/open-tracking-utils.ts`) names the client and device, drops device and location for proxies (Gmail, Yahoo, Apple), and flags Apple Mail Privacy Protection (Apple ASNs) and fetches within 10 s of delivery as `automated`, which `open_count` excludes. Pixel origin is the sender domain's own host from `domain_tracking_hosts` (set on the Domains page, must be the domain or a subdomain and attached to the Worker as a custom domain, kept out of `domains` so sending never depends on migration 0069), else `APP_URL`, else the composer request's origin; with neither, or before migration 0068, mail goes out untracked rather than failing. One pixel per message, so opens are not attributed to a recipient.### Spam scoring adds up signalsdiff --git a/drizzle/migrations/0073_add_undo_send_seconds.sql b/drizzle/migrations/0073_add_undo_send_seconds.sqlnew file mode 100644index 0000000..df2fc3f--- /dev/null+++ b/drizzle/migrations/0073_add_undo_send_seconds.sql@@ -0,0 +1 @@+ALTER TABLE `user_compose_preferences` ADD `undo_send_seconds` integer DEFAULT 15 NOT NULL;diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.jsonindex e525c94..9181edb 100644--- a/drizzle/migrations/meta/_journal.json+++ b/drizzle/migrations/meta/_journal.json@@ -449,6 +449,13 @@"when": 1792840800000,"tag": "0072_add_user_compose_preferences","breakpoints": true+ },+ {+ "idx": 65,+ "version": "6",+ "when": 1792844400000,+ "tag": "0073_add_undo_send_seconds",+ "breakpoints": true}]}diff --git a/public/locales/ar.json b/public/locales/ar.jsonindex 4e59ebd..17317f0 100644--- a/public/locales/ar.json+++ b/public/locales/ar.json@@ -762,6 +762,10 @@"settings.compose.trackOpensDescription": "تبدأ الرسائل الجديدة والعين مفعّلة. قد تحظر تطبيقات المستلمين الصورة مع ذلك.","settings.compose.failed": "تعذّر حفظ إعدادات الكتابة.","settings.compose.migrationRequired": "شغّل أولًا «تحديث قاعدة البيانات» في الإدارة.",+ "settings.compose.undoTitle": "التراجع عن الإرسال",+ "settings.compose.undoDescription": "مدة انتظار الرسالة المرسلة حتى تتمكن من إلغائها.",+ "settings.compose.undoOff": "متوقف، إرسال فوري",+ "settings.compose.undoSeconds": "{seconds} ثانية","settingsPage.inbox.shortcuts": "الاختصارات","settingsPage.inbox.shortcutsDescription": "اختر ما إذا كانت اختصارات لوحة المفاتيح مفعّلة.","settingsPage.inbox.notifications": "الإشعارات",diff --git a/public/locales/bn.json b/public/locales/bn.jsonindex a8138de..77f1e5a 100644--- a/public/locales/bn.json+++ b/public/locales/bn.json@@ -736,6 +736,10 @@"settings.compose.trackOpensDescription": "নতুন বার্তা চোখ চালু অবস্থায় শুরু হয়। প্রাপকদের অ্যাপ তবুও ছবি আটকাতে পারে।","settings.compose.failed": "লেখার সেটিংস সংরক্ষণ করা যায়নি।","settings.compose.migrationRequired": "প্রথমে অ্যাডমিনে “ডেটাবেস আপডেট করুন” চালান।",+ "settings.compose.undoTitle": "পাঠানো বাতিল",+ "settings.compose.undoDescription": "পাঠানো বার্তা কতক্ষণ অপেক্ষা করবে যাতে আপনি এখনও বাতিল করতে পারেন।",+ "settings.compose.undoOff": "বন্ধ, এখনই পাঠান",+ "settings.compose.undoSeconds": "{seconds} সেকেন্ড","settingsPage.inbox.shortcuts": "শর্টকাট","settingsPage.inbox.shortcutsDescription": "কীবোর্ড শর্টকাট সক্রিয় থাকবে কি না তা বেছে নিন।","settingsPage.inbox.notifications": "বিজ্ঞপ্তি",diff --git a/public/locales/de.json b/public/locales/de.jsonindex 0d09309..5ca13c8 100644--- a/public/locales/de.json+++ b/public/locales/de.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "Neue Nachrichten starten mit eingeschaltetem Auge. Mail-Apps der Empfänger können das Bild trotzdem blockieren.","settings.compose.failed": "Die Einstellungen zum Verfassen konnten nicht gespeichert werden.","settings.compose.migrationRequired": "Führen Sie zuerst im Admin „Datenbank aktualisieren“ aus.",+ "settings.compose.undoTitle": "Senden rückgängig machen",+ "settings.compose.undoDescription": "Wie lange eine gesendete Nachricht wartet, damit Sie sie noch abbrechen können.",+ "settings.compose.undoOff": "Aus, sofort senden",+ "settings.compose.undoSeconds": "{seconds} Sekunden","settingsPage.inbox.shortcuts": "Tastenkürzel","settingsPage.inbox.shortcutsDescription": "Wählen Sie, ob Tastaturkürzel aktiv sind.","settingsPage.inbox.notifications": "Benachrichtigungen",diff --git a/public/locales/es.json b/public/locales/es.jsonindex 930f0c5..22e781e 100644--- a/public/locales/es.json+++ b/public/locales/es.json@@ -744,6 +744,10 @@"settings.compose.trackOpensDescription": "Los mensajes nuevos empiezan con el ojo activado. Las apps de los destinatarios pueden bloquear la imagen igualmente.","settings.compose.failed": "No se pudieron guardar los ajustes de redacción.","settings.compose.migrationRequired": "Ejecuta primero «Actualizar base de datos» en Administración.",+ "settings.compose.undoTitle": "Deshacer envío",+ "settings.compose.undoDescription": "Cuánto espera un mensaje enviado para que aún puedas cancelarlo.",+ "settings.compose.undoOff": "Desactivado, enviar al instante",+ "settings.compose.undoSeconds": "{seconds} segundos","settingsPage.inbox.shortcuts": "Atajos","settingsPage.inbox.shortcutsDescription": "Elige si los atajos de teclado están activos.","settingsPage.inbox.notifications": "Notificaciones",diff --git a/public/locales/fa.json b/public/locales/fa.jsonindex cb5dfdf..d0deafd 100644--- a/public/locales/fa.json+++ b/public/locales/fa.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "پیامهای جدید با چشم روشن شروع میشوند. برنامههای گیرندگان ممکن است همچنان تصویر را مسدود کنند.","settings.compose.failed": "تنظیمات نوشتن ذخیره نشد.","settings.compose.migrationRequired": "ابتدا در مدیریت «بهروزرسانی پایگاه داده» را اجرا کنید.",+ "settings.compose.undoTitle": "لغو ارسال",+ "settings.compose.undoDescription": "مدت انتظار پیام ارسالشده تا هنوز بتوانید آن را لغو کنید.",+ "settings.compose.undoOff": "خاموش، ارسال فوری",+ "settings.compose.undoSeconds": "{seconds} ثانیه","settingsPage.inbox.shortcuts": "میانبرها","settingsPage.inbox.shortcutsDescription": "انتخاب کنید میانبرهای صفحهکلید فعال باشند یا نه.","settingsPage.inbox.notifications": "اعلانها",diff --git a/public/locales/fr.json b/public/locales/fr.jsonindex d48fd75..4286857 100644--- a/public/locales/fr.json+++ b/public/locales/fr.json@@ -744,6 +744,10 @@"settings.compose.trackOpensDescription": "Les nouveaux messages démarrent avec l'œil activé. Les applications des destinataires peuvent quand même bloquer l'image.","settings.compose.failed": "Impossible d'enregistrer les réglages de rédaction.","settings.compose.migrationRequired": "Lancez d'abord « Mettre à jour la base de données » dans l'administration.",+ "settings.compose.undoTitle": "Annuler l'envoi",+ "settings.compose.undoDescription": "Durée pendant laquelle un message envoyé attend pour pouvoir encore être annulé.",+ "settings.compose.undoOff": "Désactivé, envoyer immédiatement",+ "settings.compose.undoSeconds": "{seconds} secondes","settingsPage.inbox.shortcuts": "Raccourcis","settingsPage.inbox.shortcutsDescription": "Choisissez si les raccourcis clavier sont actifs.","settingsPage.inbox.notifications": "Notifications",diff --git a/public/locales/gu.json b/public/locales/gu.jsonindex b870751..e2bb934 100644--- a/public/locales/gu.json+++ b/public/locales/gu.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "નવા સંદેશા આંખ ચાલુ સાથે શરૂ થાય છે. પ્રાપ્તકર્તાઓની એપ્સ છતાં છબી અવરોધી શકે છે.","settings.compose.failed": "લખવાની સેટિંગ્સ સાચવી શકાઈ નહીં.","settings.compose.migrationRequired": "પહેલાં એડમિનમાં “ડેટાબેઝ અપડેટ કરો” ચલાવો.",+ "settings.compose.undoTitle": "મોકલવાનું રદ કરો",+ "settings.compose.undoDescription": "મોકલેલો સંદેશ કેટલો સમય રાહ જુએ જેથી તમે તેને રદ કરી શકો.",+ "settings.compose.undoOff": "બંધ, તરત મોકલો",+ "settings.compose.undoSeconds": "{seconds} સેકન્ડ","settingsPage.inbox.shortcuts": "શૉર્ટકટ","settingsPage.inbox.shortcutsDescription": "કીબોર્ડ શૉર્ટકટ સક્રિય છે કે નહીં તે પસંદ કરો.","settingsPage.inbox.notifications": "સૂચનાઓ",diff --git a/public/locales/ha.json b/public/locales/ha.jsonindex b691e41..7edb2be 100644--- a/public/locales/ha.json+++ b/public/locales/ha.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "Sabbin saƙonni suna farawa da ido a kunne. Manhajojin masu karɓa na iya toshe hoton duk da haka.","settings.compose.failed": "Ba a iya ajiye saitunan rubutu ba.","settings.compose.migrationRequired": "Da farko gudanar da “Sabunta bayanan bayanai” a Gudanarwa.",+ "settings.compose.undoTitle": "Soke aikawa",+ "settings.compose.undoDescription": "Tsawon lokacin da saƙon da aka aika zai jira don ka iya soke shi.",+ "settings.compose.undoOff": "A kashe, aika nan take",+ "settings.compose.undoSeconds": "Daƙiƙa {seconds}","settingsPage.inbox.shortcuts": "Gajerun hanyoyi","settingsPage.inbox.shortcutsDescription": "Zaɓi ko gajerun hanyoyin madannai suna aiki.","settingsPage.inbox.notifications": "Sanarwa",diff --git a/public/locales/hi.json b/public/locales/hi.jsonindex 043b492..f4364fd 100644--- a/public/locales/hi.json+++ b/public/locales/hi.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "नए संदेश आँख चालू के साथ शुरू होते हैं। प्राप्तकर्ताओं के ऐप फिर भी छवि रोक सकते हैं।","settings.compose.failed": "लिखने की सेटिंग सहेजी नहीं जा सकी।","settings.compose.migrationRequired": "पहले एडमिन में “डेटाबेस अपडेट करें” चलाएँ।",+ "settings.compose.undoTitle": "भेजना पूर्ववत करें",+ "settings.compose.undoDescription": "भेजा गया संदेश कितनी देर रुके ताकि आप उसे रद्द कर सकें।",+ "settings.compose.undoOff": "बंद, तुरंत भेजें",+ "settings.compose.undoSeconds": "{seconds} सेकंड","settingsPage.inbox.shortcuts": "शॉर्टकट","settingsPage.inbox.shortcutsDescription": "चुनें कि कीबोर्ड शॉर्टकट सक्रिय हों या नहीं।","settingsPage.inbox.notifications": "सूचनाएँ",diff --git a/public/locales/id.json b/public/locales/id.jsonindex d975cf7..df61a10 100644--- a/public/locales/id.json+++ b/public/locales/id.json@@ -732,6 +732,10 @@"settings.compose.trackOpensDescription": "Pesan baru dimulai dengan mata aktif. Aplikasi penerima tetap bisa memblokir gambar.","settings.compose.failed": "Pengaturan menulis tidak dapat disimpan.","settings.compose.migrationRequired": "Jalankan dulu “Perbarui database” di Admin.",+ "settings.compose.undoTitle": "Urungkan kirim",+ "settings.compose.undoDescription": "Berapa lama pesan terkirim menunggu agar masih bisa dibatalkan.",+ "settings.compose.undoOff": "Mati, kirim langsung",+ "settings.compose.undoSeconds": "{seconds} detik","settingsPage.inbox.shortcuts": "Pintasan","settingsPage.inbox.shortcutsDescription": "Pilih apakah pintasan keyboard aktif.","settingsPage.inbox.notifications": "Notifikasi",diff --git a/public/locales/it.json b/public/locales/it.jsonindex 271fd22..1d9fcb5 100644--- a/public/locales/it.json+++ b/public/locales/it.json@@ -744,6 +744,10 @@"settings.compose.trackOpensDescription": "I nuovi messaggi partono con l'occhio attivo. Le app dei destinatari possono comunque bloccare l'immagine.","settings.compose.failed": "Impossibile salvare le impostazioni di scrittura.","settings.compose.migrationRequired": "Esegui prima «Aggiorna database» in Amministrazione.",+ "settings.compose.undoTitle": "Annulla invio",+ "settings.compose.undoDescription": "Quanto attende un messaggio inviato per poterlo ancora annullare.",+ "settings.compose.undoOff": "Disattivato, invia subito",+ "settings.compose.undoSeconds": "{seconds} secondi","settingsPage.inbox.shortcuts": "Scorciatoie","settingsPage.inbox.shortcutsDescription": "Scegli se attivare le scorciatoie da tastiera.","settingsPage.inbox.notifications": "Notifiche",diff --git a/public/locales/ja.json b/public/locales/ja.jsonindex 3997c81..afb491a 100644--- a/public/locales/ja.json+++ b/public/locales/ja.json@@ -732,6 +732,10 @@"settings.compose.trackOpensDescription": "新しいメッセージは目のアイコンがオンの状態で始まります。受信者のメールアプリが画像をブロックすることはあります。","settings.compose.failed": "作成の設定を保存できませんでした。","settings.compose.migrationRequired": "先に管理画面で「データベースを更新」を実行してください。",+ "settings.compose.undoTitle": "送信取り消し",+ "settings.compose.undoDescription": "送信したメッセージを取り消せるよう待機する時間です。",+ "settings.compose.undoOff": "オフ(すぐに送信)",+ "settings.compose.undoSeconds": "{seconds} 秒","settingsPage.inbox.shortcuts": "ショートカット","settingsPage.inbox.shortcutsDescription": "キーボードショートカットを有効にするかどうかを選択します。","settingsPage.inbox.notifications": "通知",diff --git a/public/locales/kn.json b/public/locales/kn.jsonindex 1fa2c7d..ebacc1f 100644--- a/public/locales/kn.json+++ b/public/locales/kn.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "ಹೊಸ ಸಂದೇಶಗಳು ಕಣ್ಣು ಆನ್ ಆಗಿ ಪ್ರಾರಂಭವಾಗುತ್ತವೆ. ಸ್ವೀಕರಿಸುವವರ ಆ್ಯಪ್ಗಳು ಆದರೂ ಚಿತ್ರವನ್ನು ತಡೆಯಬಹುದು.","settings.compose.failed": "ಬರೆಯುವ ಸೆಟ್ಟಿಂಗ್ಗಳನ್ನು ಉಳಿಸಲಾಗಲಿಲ್ಲ.","settings.compose.migrationRequired": "ಮೊದಲು ಆಡ್ಮಿನ್ನಲ್ಲಿ “ಡೇಟಾಬೇಸ್ ನವೀಕರಿಸಿ” ಚಲಾಯಿಸಿ.",+ "settings.compose.undoTitle": "ಕಳುಹಿಸುವಿಕೆ ರದ್ದುಮಾಡಿ",+ "settings.compose.undoDescription": "ಕಳುಹಿಸಿದ ಸಂದೇಶವನ್ನು ರದ್ದುಮಾಡಲು ಅದು ಎಷ್ಟು ಹೊತ್ತು ಕಾಯುತ್ತದೆ.",+ "settings.compose.undoOff": "ಆಫ್, ತಕ್ಷಣ ಕಳುಹಿಸಿ",+ "settings.compose.undoSeconds": "{seconds} ಸೆಕೆಂಡುಗಳು","settingsPage.inbox.shortcuts": "ಶಾರ್ಟ್ಕಟ್ಗಳು","settingsPage.inbox.shortcutsDescription": "ಕೀಬೋರ್ಡ್ ಶಾರ್ಟ್ಕಟ್ಗಳು ಸಕ್ರಿಯವಾಗಿರಬೇಕೇ ಎಂಬುದನ್ನು ಆರಿಸಿ.","settingsPage.inbox.notifications": "ಅಧಿಸೂಚನೆಗಳು",diff --git a/public/locales/ko.json b/public/locales/ko.jsonindex f5b49c0..832952d 100644--- a/public/locales/ko.json+++ b/public/locales/ko.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "새 메시지는 눈 아이콘이 켜진 상태로 시작합니다. 받는 사람의 메일 앱이 이미지를 차단할 수는 있습니다.","settings.compose.failed": "작성 설정을 저장하지 못했습니다.","settings.compose.migrationRequired": "먼저 관리자에서 “데이터베이스 업데이트”를 실행하세요.",+ "settings.compose.undoTitle": "보내기 취소",+ "settings.compose.undoDescription": "보낸 메시지를 취소할 수 있도록 기다리는 시간입니다.",+ "settings.compose.undoOff": "끄기, 바로 보내기",+ "settings.compose.undoSeconds": "{seconds}초","settingsPage.inbox.shortcuts": "단축키","settingsPage.inbox.shortcutsDescription": "키보드 단축키를 사용할지 선택하세요.","settingsPage.inbox.notifications": "알림",diff --git a/public/locales/ml.json b/public/locales/ml.jsonindex 6c58bd7..5a0df70 100644--- a/public/locales/ml.json+++ b/public/locales/ml.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "പുതിയ സന്ദേശങ്ങൾ കണ്ണ് ഓണാക്കി തുടങ്ങുന്നു. സ്വീകർത്താക്കളുടെ ആപ്പുകൾ എന്നിട്ടും ചിത്രം തടഞ്ഞേക്കാം.","settings.compose.failed": "എഴുത്ത് ക്രമീകരണങ്ങൾ സംരക്ഷിക്കാനായില്ല.","settings.compose.migrationRequired": "ആദ്യം അഡ്മിനിൽ “ഡാറ്റാബേസ് അപ്ഡേറ്റ് ചെയ്യുക” പ്രവർത്തിപ്പിക്കുക.",+ "settings.compose.undoTitle": "അയയ്ക്കൽ പഴയപടിയാക്കുക",+ "settings.compose.undoDescription": "അയച്ച സന്ദേശം റദ്ദാക്കാൻ എത്ര സമയം കാത്തിരിക്കും.",+ "settings.compose.undoOff": "ഓഫ്, ഉടൻ അയയ്ക്കുക",+ "settings.compose.undoSeconds": "{seconds} സെക്കൻഡ്","settingsPage.inbox.shortcuts": "കുറുക്കുവഴികൾ","settingsPage.inbox.shortcutsDescription": "കീബോർഡ് കുറുക്കുവഴികൾ സജീവമാകണോ എന്ന് തിരഞ്ഞെടുക്കുക.","settingsPage.inbox.notifications": "അറിയിപ്പുകൾ",diff --git a/public/locales/mr.json b/public/locales/mr.jsonindex 023f216..dbf05f4 100644--- a/public/locales/mr.json+++ b/public/locales/mr.json@@ -736,6 +736,10 @@"settings.compose.trackOpensDescription": "नवीन संदेश डोळा चालू ठेवून सुरू होतात. प्राप्तकर्त्यांची ॲप्स तरीही प्रतिमा रोखू शकतात.","settings.compose.failed": "लिहिण्याच्या सेटिंग्ज जतन करता आल्या नाहीत.","settings.compose.migrationRequired": "आधी ॲडमिनमध्ये “डेटाबेस अपडेट करा” चालवा.",+ "settings.compose.undoTitle": "पाठवणे पूर्ववत करा",+ "settings.compose.undoDescription": "पाठवलेला संदेश रद्द करता यावा म्हणून तो किती वेळ थांबतो.",+ "settings.compose.undoOff": "बंद, लगेच पाठवा",+ "settings.compose.undoSeconds": "{seconds} सेकंद","settingsPage.inbox.shortcuts": "शॉर्टकट","settingsPage.inbox.shortcutsDescription": "कीबोर्ड शॉर्टकट सक्रिय असावेत का ते निवडा.","settingsPage.inbox.notifications": "सूचना",diff --git a/public/locales/ms.json b/public/locales/ms.jsonindex 16dbef6..f07ba7c 100644--- a/public/locales/ms.json+++ b/public/locales/ms.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "Mesej baharu bermula dengan mata aktif. Aplikasi penerima masih boleh menyekat imej.","settings.compose.failed": "Tetapan menulis tidak dapat disimpan.","settings.compose.migrationRequired": "Jalankan dahulu “Kemas kini pangkalan data” dalam Pentadbir.",+ "settings.compose.undoTitle": "Buat asal hantar",+ "settings.compose.undoDescription": "Berapa lama mesej yang dihantar menunggu supaya anda masih boleh membatalkannya.",+ "settings.compose.undoOff": "Mati, hantar serta-merta",+ "settings.compose.undoSeconds": "{seconds} saat","settingsPage.inbox.shortcuts": "Pintasan","settingsPage.inbox.shortcutsDescription": "Pilih sama ada pintasan papan kekunci aktif.","settingsPage.inbox.notifications": "Pemberitahuan",diff --git a/public/locales/nl.json b/public/locales/nl.jsonindex aeba516..fd50b8e 100644--- a/public/locales/nl.json+++ b/public/locales/nl.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "Nieuwe berichten starten met het oog aan. Mailapps van ontvangers kunnen de afbeelding toch blokkeren.","settings.compose.failed": "De instellingen voor opstellen konden niet worden opgeslagen.","settings.compose.migrationRequired": "Voer eerst ‘Database bijwerken’ uit in Beheer.",+ "settings.compose.undoTitle": "Verzenden ongedaan maken",+ "settings.compose.undoDescription": "Hoe lang een verzonden bericht wacht zodat je het nog kunt annuleren.",+ "settings.compose.undoOff": "Uit, direct verzenden",+ "settings.compose.undoSeconds": "{seconds} seconden","settingsPage.inbox.shortcuts": "Sneltoetsen","settingsPage.inbox.shortcutsDescription": "Kies of toetsenbordsneltoetsen actief zijn.","settingsPage.inbox.notifications": "Meldingen",diff --git a/public/locales/pa.json b/public/locales/pa.jsonindex 3eb5940..f1cafe7 100644--- a/public/locales/pa.json+++ b/public/locales/pa.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "ਨਵੇਂ ਸੁਨੇਹੇ ਅੱਖ ਚਾਲੂ ਨਾਲ ਸ਼ੁਰੂ ਹੁੰਦੇ ਹਨ। ਪ੍ਰਾਪਤਕਰਤਾਵਾਂ ਦੀਆਂ ਐਪਾਂ ਫਿਰ ਵੀ ਤਸਵੀਰ ਰੋਕ ਸਕਦੀਆਂ ਹਨ।","settings.compose.failed": "ਲਿਖਣ ਦੀਆਂ ਸੈਟਿੰਗਾਂ ਸੰਭਾਲੀਆਂ ਨਹੀਂ ਜਾ ਸਕੀਆਂ।","settings.compose.migrationRequired": "ਪਹਿਲਾਂ ਐਡਮਿਨ ਵਿੱਚ “ਡਾਟਾਬੇਸ ਅੱਪਡੇਟ ਕਰੋ” ਚਲਾਓ।",+ "settings.compose.undoTitle": "ਭੇਜਣਾ ਰੱਦ ਕਰੋ",+ "settings.compose.undoDescription": "ਭੇਜਿਆ ਸੁਨੇਹਾ ਕਿੰਨੀ ਦੇਰ ਉਡੀਕੇ ਤਾਂ ਜੋ ਤੁਸੀਂ ਉਸਨੂੰ ਰੱਦ ਕਰ ਸਕੋ।",+ "settings.compose.undoOff": "ਬੰਦ, ਤੁਰੰਤ ਭੇਜੋ",+ "settings.compose.undoSeconds": "{seconds} ਸਕਿੰਟ","settingsPage.inbox.shortcuts": "ਸ਼ਾਰਟਕੱਟ","settingsPage.inbox.shortcutsDescription": "ਚੁਣੋ ਕਿ ਕੀਬੋਰਡ ਸ਼ਾਰਟਕੱਟ ਸਰਗਰਮ ਹਨ ਜਾਂ ਨਹੀਂ।","settingsPage.inbox.notifications": "ਸੂਚਨਾਵਾਂ",diff --git a/public/locales/pl.json b/public/locales/pl.jsonindex f752889..1988f31 100644--- a/public/locales/pl.json+++ b/public/locales/pl.json@@ -750,6 +750,10 @@"settings.compose.trackOpensDescription": "Nowe wiadomości zaczynają z włączonym okiem. Aplikacje odbiorców mogą mimo to zablokować obraz.","settings.compose.failed": "Nie udało się zapisać ustawień pisania.","settings.compose.migrationRequired": "Najpierw uruchom „Aktualizuj bazę danych” w panelu administratora.",+ "settings.compose.undoTitle": "Cofnij wysłanie",+ "settings.compose.undoDescription": "Jak długo wysłana wiadomość czeka, aby można ją było jeszcze anulować.",+ "settings.compose.undoOff": "Wyłączone, wyślij od razu",+ "settings.compose.undoSeconds": "{seconds} s","settingsPage.inbox.shortcuts": "Skróty","settingsPage.inbox.shortcutsDescription": "Wybierz, czy skróty klawiszowe są aktywne.","settingsPage.inbox.notifications": "Powiadomienia",diff --git a/public/locales/pt-BR.json b/public/locales/pt-BR.jsonindex 4baab77..e061d5c 100644--- a/public/locales/pt-BR.json+++ b/public/locales/pt-BR.json@@ -744,6 +744,10 @@"settings.compose.trackOpensDescription": "Novas mensagens começam com o olho ativado. Os apps dos destinatários ainda podem bloquear a imagem.","settings.compose.failed": "Não foi possível salvar as configurações de escrita.","settings.compose.migrationRequired": "Execute primeiro “Atualizar banco de dados” no Admin.",+ "settings.compose.undoTitle": "Desfazer envio",+ "settings.compose.undoDescription": "Quanto tempo uma mensagem enviada espera para que você ainda possa cancelá-la.",+ "settings.compose.undoOff": "Desativado, enviar imediatamente",+ "settings.compose.undoSeconds": "{seconds} segundos","settingsPage.inbox.shortcuts": "Atalhos","settingsPage.inbox.shortcutsDescription": "Escolha se os atalhos de teclado ficam ativos.","settingsPage.inbox.notifications": "Notificações",diff --git a/public/locales/pt-PT.json b/public/locales/pt-PT.jsonindex 0cee981..df4405a 100644--- a/public/locales/pt-PT.json+++ b/public/locales/pt-PT.json@@ -744,6 +744,10 @@"settings.compose.trackOpensDescription": "As novas mensagens começam com o olho ativado. As aplicações dos destinatários podem bloquear a imagem.","settings.compose.failed": "Não foi possível guardar as definições de escrita.","settings.compose.migrationRequired": "Execute primeiro “Atualizar base de dados” na Administração.",+ "settings.compose.undoTitle": "Anular envio",+ "settings.compose.undoDescription": "Quanto tempo uma mensagem enviada espera para que ainda a possa cancelar.",+ "settings.compose.undoOff": "Desativado, enviar imediatamente",+ "settings.compose.undoSeconds": "{seconds} segundos","settingsPage.inbox.shortcuts": "Atalhos","settingsPage.inbox.shortcutsDescription": "Escolha se os atalhos de teclado ficam ativos.","settingsPage.inbox.notifications": "Notificações",diff --git a/public/locales/ru.json b/public/locales/ru.jsonindex 993a137..2861d5f 100644--- a/public/locales/ru.json+++ b/public/locales/ru.json@@ -750,6 +750,10 @@"settings.compose.trackOpensDescription": "Новые письма начинаются с включённым глазом. Почтовые приложения получателей всё равно могут блокировать изображение.","settings.compose.failed": "Не удалось сохранить настройки написания.","settings.compose.migrationRequired": "Сначала выполните «Обновить базу данных» в админке.",+ "settings.compose.undoTitle": "Отмена отправки",+ "settings.compose.undoDescription": "Сколько отправленное письмо ждёт, чтобы его ещё можно было отменить.",+ "settings.compose.undoOff": "Выкл., отправлять сразу",+ "settings.compose.undoSeconds": "{seconds} с","settingsPage.inbox.shortcuts": "Горячие клавиши","settingsPage.inbox.shortcutsDescription": "Выберите, включены ли сочетания клавиш.","settingsPage.inbox.notifications": "Уведомления",diff --git a/public/locales/si.json b/public/locales/si.jsonindex 4c7caa3..887fd71 100644--- a/public/locales/si.json+++ b/public/locales/si.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "නව පණිවිඩ ඇස සක්රිය කර ආරම්භ වේ. ලබන්නන්ගේ යෙදුම් තවමත් රූපය අවහිර කළ හැක.","settings.compose.failed": "ලිවීමේ සැකසුම් සුරැකිය නොහැකි විය.","settings.compose.migrationRequired": "පළමුව පරිපාලනයේ “දත්ත සමුදාය යාවත්කාලීන කරන්න” ධාවනය කරන්න.",+ "settings.compose.undoTitle": "යැවීම අහෝසි කරන්න",+ "settings.compose.undoDescription": "යැවූ පණිවිඩය අවලංගු කිරීමට එය කොපමණ කාලයක් රැඳේද.",+ "settings.compose.undoOff": "අක්රිය, වහාම යවන්න",+ "settings.compose.undoSeconds": "තත්පර {seconds}","settingsPage.inbox.shortcuts": "කෙටිමං","settingsPage.inbox.shortcutsDescription": "යතුරුපුවරු කෙටිමං සක්රීය විය යුතුද යන්න තෝරන්න.","settingsPage.inbox.notifications": "දැනුම්දීම්",diff --git a/public/locales/sw.json b/public/locales/sw.jsonindex c66fa8c..a1dcac5 100644--- a/public/locales/sw.json+++ b/public/locales/sw.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "Ujumbe mpya huanza jicho likiwa limewashwa. Programu za wapokeaji bado zinaweza kuzuia picha.","settings.compose.failed": "Imeshindikana kuhifadhi mipangilio ya kuandika.","settings.compose.migrationRequired": "Kwanza endesha “Sasisha hifadhidata” kwenye Usimamizi.",+ "settings.compose.undoTitle": "Tendua kutuma",+ "settings.compose.undoDescription": "Muda ujumbe uliotumwa unasubiri ili bado uweze kuughairi.",+ "settings.compose.undoOff": "Imezimwa, tuma mara moja",+ "settings.compose.undoSeconds": "Sekunde {seconds}","settingsPage.inbox.shortcuts": "Njia za mkato","settingsPage.inbox.shortcutsDescription": "Chagua kama njia za mkato za kibodi zinatumika.","settingsPage.inbox.notifications": "Arifa",diff --git a/public/locales/ta.json b/public/locales/ta.jsonindex b136fac..3270879 100644--- a/public/locales/ta.json+++ b/public/locales/ta.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "புதிய செய்திகள் கண் இயக்கத்துடன் தொடங்கும். பெறுநர்களின் பயன்பாடுகள் படத்தைத் தடுக்கலாம்.","settings.compose.failed": "எழுதும் அமைப்புகளைச் சேமிக்க முடியவில்லை.","settings.compose.migrationRequired": "முதலில் நிர்வாகத்தில் “தரவுத்தளத்தைப் புதுப்பி” இயக்கவும்.",+ "settings.compose.undoTitle": "அனுப்புதலைச் செயல்தவிர்",+ "settings.compose.undoDescription": "அனுப்பிய செய்தியை ரத்துசெய்ய அது எவ்வளவு நேரம் காத்திருக்கும்.",+ "settings.compose.undoOff": "முடக்கு, உடனே அனுப்பு",+ "settings.compose.undoSeconds": "{seconds} விநாடிகள்","settingsPage.inbox.shortcuts": "குறுக்குவழிகள்","settingsPage.inbox.shortcutsDescription": "விசைப்பலகை குறுக்குவழிகள் செயலில் இருக்க வேண்டுமா என்பதைத் தேர்வுசெய்யவும்.","settingsPage.inbox.notifications": "அறிவிப்புகள்",diff --git a/public/locales/te.json b/public/locales/te.jsonindex 1bd8563..652e15a 100644--- a/public/locales/te.json+++ b/public/locales/te.json@@ -736,6 +736,10 @@"settings.compose.trackOpensDescription": "కొత్త సందేశాలు కన్ను ఆన్తో మొదలవుతాయి. గ్రహీతల యాప్లు అయినా చిత్రాన్ని నిరోధించవచ్చు.","settings.compose.failed": "వ్రాసే సెట్టింగ్లను సేవ్ చేయలేకపోయాం.","settings.compose.migrationRequired": "ముందుగా అడ్మిన్లో “డేటాబేస్ అప్డేట్ చేయి” నడపండి.",+ "settings.compose.undoTitle": "పంపడం రద్దు చేయి",+ "settings.compose.undoDescription": "పంపిన సందేశాన్ని రద్దు చేయడానికి అది ఎంతసేపు వేచి ఉంటుంది.",+ "settings.compose.undoOff": "ఆఫ్, వెంటనే పంపు",+ "settings.compose.undoSeconds": "{seconds} సెకన్లు","settingsPage.inbox.shortcuts": "షార్ట్కట్లు","settingsPage.inbox.shortcutsDescription": "కీబోర్డ్ షార్ట్కట్లు సక్రియంగా ఉండాలో లేదో ఎంచుకోండి.","settingsPage.inbox.notifications": "నోటిఫికేషన్లు",diff --git a/public/locales/th.json b/public/locales/th.jsonindex 6f53ab1..2893a67 100644--- a/public/locales/th.json+++ b/public/locales/th.json@@ -738,6 +738,10 @@"settings.compose.trackOpensDescription": "ข้อความใหม่จะเริ่มด้วยไอคอนตาที่เปิดอยู่ แอปของผู้รับยังอาจบล็อกรูปภาพได้","settings.compose.failed": "ไม่สามารถบันทึกการตั้งค่าการเขียนได้","settings.compose.migrationRequired": "เรียกใช้ “อัปเดตฐานข้อมูล” ในผู้ดูแลก่อน",+ "settings.compose.undoTitle": "เลิกทำการส่ง",+ "settings.compose.undoDescription": "ระยะเวลาที่ข้อความที่ส่งจะรอเพื่อให้คุณยังยกเลิกได้",+ "settings.compose.undoOff": "ปิด ส่งทันที",+ "settings.compose.undoSeconds": "{seconds} วินาที","settingsPage.inbox.shortcuts": "ทางลัด","settingsPage.inbox.shortcutsDescription": "เลือกว่าจะเปิดใช้ทางลัดแป้นพิมพ์หรือไม่","settingsPage.inbox.notifications": "การแจ้งเตือน",diff --git a/public/locales/tr.json b/public/locales/tr.jsonindex bc1b722..b5402e9 100644--- a/public/locales/tr.json+++ b/public/locales/tr.json@@ -731,6 +731,10 @@"settings.compose.trackOpensDescription": "Yeni iletiler göz açık olarak başlar. Alıcıların e-posta uygulamaları görseli yine de engelleyebilir.","settings.compose.failed": "Yazma ayarları kaydedilemedi.","settings.compose.migrationRequired": "Önce Yönetim'de “Veritabanını güncelle”yi çalıştırın.",+ "settings.compose.undoTitle": "Göndermeyi geri al",+ "settings.compose.undoDescription": "Gönderilen iletinin iptal edilebilmesi için ne kadar bekleyeceği.",+ "settings.compose.undoOff": "Kapalı, hemen gönder",+ "settings.compose.undoSeconds": "{seconds} saniye","settingsPage.inbox.shortcuts": "Kısayollar","settingsPage.inbox.shortcutsDescription": "Klavye kısayollarının etkin olup olmayacağını seçin.","settingsPage.inbox.notifications": "Bildirimler",diff --git a/public/locales/uk.json b/public/locales/uk.jsonindex 663043d..92711d7 100644--- a/public/locales/uk.json+++ b/public/locales/uk.json@@ -750,6 +750,10 @@"settings.compose.trackOpensDescription": "Нові листи починаються з увімкненим оком. Поштові застосунки отримувачів усе одно можуть блокувати зображення.","settings.compose.failed": "Не вдалося зберегти налаштування написання.","settings.compose.migrationRequired": "Спершу виконайте «Оновити базу даних» в адмінці.",+ "settings.compose.undoTitle": "Скасування надсилання",+ "settings.compose.undoDescription": "Скільки надісланий лист чекає, щоб його ще можна було скасувати.",+ "settings.compose.undoOff": "Вимк., надсилати одразу",+ "settings.compose.undoSeconds": "{seconds} с","settingsPage.inbox.shortcuts": "Скорочення","settingsPage.inbox.shortcutsDescription": "Виберіть, чи активні скорочення клавіатури.","settingsPage.inbox.notifications": "Сповіщення",diff --git a/public/locales/ur.json b/public/locales/ur.jsonindex b409d8a..337fe37 100644--- a/public/locales/ur.json+++ b/public/locales/ur.json@@ -736,6 +736,10 @@"settings.compose.trackOpensDescription": "نئے پیغامات آنکھ آن کے ساتھ شروع ہوتے ہیں۔ وصول کنندگان کی ایپس پھر بھی تصویر روک سکتی ہیں۔","settings.compose.failed": "لکھنے کی ترتیبات محفوظ نہیں ہو سکیں۔","settings.compose.migrationRequired": "پہلے ایڈمن میں “ڈیٹا بیس اپ ڈیٹ کریں” چلائیں۔",+ "settings.compose.undoTitle": "بھیجنا منسوخ کریں",+ "settings.compose.undoDescription": "بھیجا گیا پیغام کتنی دیر انتظار کرے تاکہ آپ اسے منسوخ کر سکیں۔",+ "settings.compose.undoOff": "بند، فوراً بھیجیں",+ "settings.compose.undoSeconds": "{seconds} سیکنڈ","settingsPage.inbox.shortcuts": "شارٹ کٹس","settingsPage.inbox.shortcutsDescription": "منتخب کریں کہ کی بورڈ شارٹ کٹس فعال ہوں یا نہیں۔","settingsPage.inbox.notifications": "اطلاعات",diff --git a/public/locales/vi.json b/public/locales/vi.jsonindex 121f8eb..3328785 100644--- a/public/locales/vi.json+++ b/public/locales/vi.json@@ -732,6 +732,10 @@"settings.compose.trackOpensDescription": "Thư mới bắt đầu với biểu tượng mắt bật. Ứng dụng của người nhận vẫn có thể chặn hình ảnh.","settings.compose.failed": "Không thể lưu cài đặt soạn thư.","settings.compose.migrationRequired": "Trước tiên hãy chạy “Cập nhật cơ sở dữ liệu” trong Quản trị.",+ "settings.compose.undoTitle": "Hoàn tác gửi",+ "settings.compose.undoDescription": "Thư đã gửi chờ bao lâu để bạn vẫn có thể hủy.",+ "settings.compose.undoOff": "Tắt, gửi ngay",+ "settings.compose.undoSeconds": "{seconds} giây","settingsPage.inbox.shortcuts": "Phím tắt","settingsPage.inbox.shortcutsDescription": "Chọn xem phím tắt bàn phím có hoạt động hay không.","settingsPage.inbox.notifications": "Thông báo",diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.jsonindex fb40126..9bbd71b 100644--- a/public/locales/zh-CN.json+++ b/public/locales/zh-CN.json@@ -732,6 +732,10 @@"settings.compose.trackOpensDescription": "新邮件开始时眼睛图标为开启状态。收件人的邮件应用仍可能阻止图片。","settings.compose.failed": "无法保存撰写设置。","settings.compose.migrationRequired": "请先在管理后台运行“更新数据库”。",+ "settings.compose.undoTitle": "撤销发送",+ "settings.compose.undoDescription": "已发送邮件等待多久,以便您仍可取消。",+ "settings.compose.undoOff": "关闭,立即发送",+ "settings.compose.undoSeconds": "{seconds} 秒","settingsPage.inbox.shortcuts": "快捷键","settingsPage.inbox.shortcutsDescription": "选择是否启用键盘快捷键。","settingsPage.inbox.notifications": "通知",diff --git a/src/app/api/settings/compose/route.ts b/src/app/api/settings/compose/route.tsindex 8add1eb..9173b60 100644--- a/src/app/api/settings/compose/route.ts+++ b/src/app/api/settings/compose/route.ts@@ -1,7 +1,9 @@import { NextResponse } from "next/server";import { requireSessionUser } from "@/lib/api/auth";import { getEnv } from "@/lib/cloudflare";-import { ComposePreferencesUnavailableError, getComposePreferences, setComposePreferences } from "@/lib/compose/preferences";+import { parseUndoSendSeconds } from "@/lib/compose/compose-utils";+import { ComposePreferencesUnavailableError, getComposePreferences, updateComposePreferences } from "@/lib/compose/preferences";+import type { ComposePreferences } from "@/lib/compose/types";export async function GET(request: Request) {const env = getEnv();@@ -14,12 +16,20 @@ export async function PATCH(request: Request) {const env = getEnv();const auth = await requireSessionUser(env, request);if (auth.error) return auth.error;- const body = (await request.json().catch(() => null)) as { trackOpensDefault?: unknown } | null;- if (typeof body?.trackOpensDefault !== "boolean") {- return NextResponse.json({ error: "trackOpensDefault must be a boolean" }, { status: 400 });+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;+ const patch: Partial<ComposePreferences> = {};+ if (body && "trackOpensDefault" in body) {+ if (typeof body.trackOpensDefault !== "boolean") return NextResponse.json({ error: "trackOpensDefault must be a boolean" }, { status: 400 });+ patch.trackOpensDefault = body.trackOpensDefault;}+ if (body && "undoSendSeconds" in body) {+ const seconds = parseUndoSendSeconds(body.undoSendSeconds);+ if (seconds === null) return NextResponse.json({ error: "undoSendSeconds must be 0, 5, 10, 15 or 30" }, { status: 400 });+ patch.undoSendSeconds = seconds;+ }+ if (Object.keys(patch).length === 0) return NextResponse.json({ error: "Nothing to update" }, { status: 400 });try {- return NextResponse.json(await setComposePreferences(env, auth.user.id, { trackOpensDefault: body.trackOpensDefault }));+ return NextResponse.json(await updateComposePreferences(env, auth.user.id, patch));} catch (error) {if (error instanceof ComposePreferencesUnavailableError) {return NextResponse.json({ error: error.message, code: "MIGRATION_REQUIRED" }, { status: 409 });diff --git a/src/components/compose/compose-preferences-utils.ts b/src/components/compose/compose-preferences-utils.tsindex 5701ea3..24821ea 100644--- a/src/components/compose/compose-preferences-utils.ts+++ b/src/components/compose/compose-preferences-utils.ts@@ -23,7 +23,7 @@ export function getCachedComposePreferences(): ComposePreferences | null {return cached;}-export async function updateComposePreferences(next: ComposePreferences): Promise<ComposePreferences> {+export async function updateComposePreferences(next: Partial<ComposePreferences>): Promise<ComposePreferences> {const response = await authFetch("/api/settings/compose", {method: "PATCH",headers: { "Content-Type": "application/json" },@@ -31,6 +31,6 @@ export async function updateComposePreferences(next: ComposePreferences): Promis});const data = (await response.json().catch(() => null)) as (ComposePreferences & { error?: string; code?: string }) | null;if (!response.ok || !data) throw new Error(data?.code === "MIGRATION_REQUIRED" ? "MIGRATION_REQUIRED" : data?.error ?? "Failed to save composer settings");- cached = { trackOpensDefault: data.trackOpensDefault };+ cached = { trackOpensDefault: data.trackOpensDefault, undoSendSeconds: data.undoSendSeconds };return cached;}diff --git a/src/components/settings/compose-defaults-settings.tsx b/src/components/settings/compose-defaults-settings.tsxindex 69a88e3..4f317fa 100644--- a/src/components/settings/compose-defaults-settings.tsx+++ b/src/components/settings/compose-defaults-settings.tsx@@ -3,12 +3,15 @@import { useEffect, useState } from "react";import { loadComposePreferences, updateComposePreferences } from "@/components/compose/compose-preferences-utils";import { useLanguage } from "@/components/language-provider";+import { Select } from "@/components/ui/select";import { Switch } from "@/components/ui/switch";+import { DEFAULT_UNDO_SEND_SECONDS, UNDO_SEND_OPTIONS, parseUndoSendSeconds } from "@/lib/compose/compose-utils";+import type { ComposePreferences } from "@/lib/compose/types";-/** Account-wide composer defaults; each message can still change them in the composer. */+/** Account-wide composer defaults; each message can still change the read receipt in the composer. */export function ComposeDefaultsSettings() {const { t } = useLanguage();- const [trackOpens, setTrackOpens] = useState(false);+ const [preferences, setPreferences] = useState<ComposePreferences>({ trackOpensDefault: false, undoSendSeconds: DEFAULT_UNDO_SEND_SECONDS });const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);@@ -16,8 +19,8 @@ export function ComposeDefaultsSettings() {useEffect(() => {let active = true;void loadComposePreferences()- .then((preferences) => {- if (active) setTrackOpens(preferences.trackOpensDefault);+ .then((loaded) => {+ if (active) setPreferences(loaded);}).catch(() => {if (active) setError(t("settings.compose.failed"));@@ -30,34 +33,57 @@ export function ComposeDefaultsSettings() {};}, [t]);- function change(next: boolean) {- const previous = trackOpens;- setTrackOpens(next);+ function change(patch: Partial<ComposePreferences>) {+ const previous = preferences;+ setPreferences({ ...preferences, ...patch });setSaving(true);setError(null);- void updateComposePreferences({ trackOpensDefault: next })+ void updateComposePreferences(patch)+ .then(setPreferences).catch((saveError) => {- setTrackOpens(previous);+ setPreferences(previous);setError(saveError instanceof Error && saveError.message === "MIGRATION_REQUIRED" ? t("settings.compose.migrationRequired") : t("settings.compose.failed"));}).finally(() => setSaving(false));}return (- <div>+ <div className="space-y-3"><label className="flex items-start gap-3 rounded-xl bg-neutral-50 p-4"><span className="flex-1"><span className="block text-sm font-medium text-neutral-900">{t("settings.compose.trackOpensTitle")}</span><span className="mt-1 block text-sm text-neutral-500">{t("settings.compose.trackOpensDescription")}</span></span><Switch- checked={trackOpens}+ checked={preferences.trackOpensDefault}disabled={loading || saving}- onCheckedChange={change}+ onCheckedChange={(trackOpensDefault) => change({ trackOpensDefault })}aria-label={t("settings.compose.trackOpensTitle")}/></label>- {error && <p role="alert" className="mt-2 px-4 text-sm text-red-600">{error}</p>}+ <div className="flex items-start gap-3 rounded-xl bg-neutral-50 p-4">+ <span className="flex-1">+ <label htmlFor="compose-undo-send" className="block text-sm font-medium text-neutral-900">{t("settings.compose.undoTitle")}</label>+ <span className="mt-1 block text-sm text-neutral-500">{t("settings.compose.undoDescription")}</span>+ </span>+ <Select+ id="compose-undo-send"+ value={String(preferences.undoSendSeconds)}+ disabled={loading || saving}+ className="py-1.5 text-sm text-neutral-900"+ onChange={(event) => {+ const undoSendSeconds = parseUndoSendSeconds(event.target.value);+ if (undoSendSeconds !== null) change({ undoSendSeconds });+ }}+ >+ {UNDO_SEND_OPTIONS.map((seconds) => (+ <option key={seconds} value={seconds}>+ {seconds === 0 ? t("settings.compose.undoOff") : t("settings.compose.undoSeconds", { seconds })}+ </option>+ ))}+ </Select>+ </div>+ {error && <p role="alert" className="px-4 text-sm text-red-600">{error}</p>}</div>);}diff --git a/src/db/schema/index.ts b/src/db/schema/index.tsindex 48b74c1..39bf658 100644--- a/src/db/schema/index.ts+++ b/src/db/schema/index.ts@@ -477,6 +477,7 @@ export const messageOpens = sqliteTable(export const userComposePreferences = sqliteTable("user_compose_preferences", {userId: text("user_id").primaryKey().references(() => users.id, { onDelete: "cascade" }),trackOpensDefault: integer("track_opens_default", { mode: "boolean" }).notNull().default(false),+ undoSendSeconds: integer("undo_send_seconds").notNull().default(15),updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),});diff --git a/src/lib/compose/compose-utils.ts b/src/lib/compose/compose-utils.tsnew file mode 100644index 0000000..70c77aa--- /dev/null+++ b/src/lib/compose/compose-utils.ts@@ -0,0 +1,8 @@+/** Seconds a send waits so it can still be cancelled; 0 sends at once. */+export const UNDO_SEND_OPTIONS = [0, 5, 10, 15, 30] as const;+export const DEFAULT_UNDO_SEND_SECONDS = 15;++export function parseUndoSendSeconds(value: unknown): number | null {+ const seconds = typeof value === "string" && value.trim() !== "" ? Number(value) : value;+ return typeof seconds === "number" && (UNDO_SEND_OPTIONS as readonly number[]).includes(seconds) ? seconds : null;+}diff --git a/src/lib/compose/preferences.ts b/src/lib/compose/preferences.tsindex 6716458..35c9f2a 100644--- a/src/lib/compose/preferences.ts+++ b/src/lib/compose/preferences.ts@@ -1,10 +1,11 @@-import { eq } from "drizzle-orm";+import { eq, sql } from "drizzle-orm";import { getDb } from "@/db";import { userComposePreferences } from "@/db/schema";-import { isMissingTableError } from "@/lib/database-errors";+import { isMissingColumnError, isMissingTableError } from "@/lib/database-errors";+import { DEFAULT_UNDO_SEND_SECONDS, parseUndoSendSeconds } from "./compose-utils";import type { ComposePreferences } from "./types";-const DEFAULTS: ComposePreferences = { trackOpensDefault: false };+const DEFAULTS: ComposePreferences = { trackOpensDefault: false, undoSendSeconds: DEFAULT_UNDO_SEND_SECONDS };export class ComposePreferencesUnavailableError extends Error {constructor() {@@ -12,31 +13,49 @@ export class ComposePreferencesUnavailableError extends Error {}}-/** The user's composer defaults; before migration 0072 everyone gets the defaults. */+/** The user's composer defaults; missing migrations (0072, 0073) fall back to the defaults. */export async function getComposePreferences(env: CloudflareEnv, userId: string): Promise<ComposePreferences> {+ const db = getDb(env);try {- const [row] = await getDb(env)- .select({ trackOpensDefault: userComposePreferences.trackOpensDefault })+ const [row] = await db+ .select({ trackOpensDefault: userComposePreferences.trackOpensDefault, undoSendSeconds: userComposePreferences.undoSendSeconds }).from(userComposePreferences).where(eq(userComposePreferences.userId, userId)).limit(1);- return row ?? DEFAULTS;+ if (!row) return DEFAULTS;+ return { trackOpensDefault: row.trackOpensDefault, undoSendSeconds: parseUndoSendSeconds(row.undoSendSeconds) ?? DEFAULT_UNDO_SEND_SECONDS };} catch (error) {if (isMissingTableError(error)) return DEFAULTS;- throw error;+ if (!isMissingColumnError(error)) throw error;}+ const [row] = await db+ .select({ trackOpensDefault: userComposePreferences.trackOpensDefault })+ .from(userComposePreferences)+ .where(eq(userComposePreferences.userId, userId))+ .limit(1);+ return { ...DEFAULTS, trackOpensDefault: row?.trackOpensDefault ?? false };}-export async function setComposePreferences(env: CloudflareEnv, userId: string, preferences: ComposePreferences): Promise<ComposePreferences> {- const values = { trackOpensDefault: preferences.trackOpensDefault, updatedAt: new Date() };+export async function updateComposePreferences(env: CloudflareEnv, userId: string, patch: Partial<ComposePreferences>): Promise<ComposePreferences> {+ const next = { ...(await getComposePreferences(env, userId)), ...patch };+ const db = getDb(env);+ const updatedAt = new Date();try {- await getDb(env)+ await db.insert(userComposePreferences)- .values({ userId, ...values })- .onConflictDoUpdate({ target: userComposePreferences.userId, set: values });+ .values({ userId, ...next, updatedAt })+ .onConflictDoUpdate({ target: userComposePreferences.userId, set: { ...next, updatedAt } });+ return next;} catch (error) {if (isMissingTableError(error)) throw new ComposePreferencesUnavailableError();- throw error;+ if (!isMissingColumnError(error)) throw error;}- return { trackOpensDefault: preferences.trackOpensDefault };+ // Before migration 0073 only the read-receipt default can be stored.+ if (next.undoSendSeconds !== DEFAULT_UNDO_SEND_SECONDS) throw new ComposePreferencesUnavailableError();+ await db.run(sql`+ INSERT INTO user_compose_preferences (user_id, track_opens_default, updated_at)+ VALUES (${userId}, ${next.trackOpensDefault ? 1 : 0}, ${Math.floor(updatedAt.getTime() / 1000)})+ ON CONFLICT (user_id) DO UPDATE SET track_opens_default = excluded.track_opens_default, updated_at = excluded.updated_at+ `);+ return next;}diff --git a/src/lib/compose/types.d.ts b/src/lib/compose/types.d.tsindex cd2eb13..79b1b72 100644--- a/src/lib/compose/types.d.ts+++ b/src/lib/compose/types.d.ts@@ -1,4 +1,6 @@export type ComposePreferences = {/** New messages start with the read-receipt pixel on. */trackOpensDefault: boolean;+ /** One of UNDO_SEND_OPTIONS; 0 sends without an undo window. */+ undoSendSeconds: number;};diff --git a/src/lib/database-errors.ts b/src/lib/database-errors.tsindex dd9cab2..0e08da9 100644--- a/src/lib/database-errors.ts+++ b/src/lib/database-errors.ts@@ -20,6 +20,11 @@ export function isMissingTableError(error: unknown): boolean {return errorChainMatches(error, /no such table/i);}+/** A column added by a migration that may not be applied yet. */+export function isMissingColumnError(error: unknown): boolean {+ return errorChainMatches(error, /no such column|has no column named/i);+}+export function isUniqueConstraintError(error: unknown): boolean {return errorChainMatches(error, /UNIQUE constraint failed/i);}diff --git a/src/lib/email/send.ts b/src/lib/email/send.tsindex 90e52c7..32ea870 100644--- a/src/lib/email/send.ts+++ b/src/lib/email/send.ts@@ -17,6 +17,7 @@ import { prepareCloudflareAttachments } from "@/lib/email/cloud-attachment-utilsimport { ensureTrackingToken, getTrackingHostForSender } from "@/lib/tracking/open-tracking";import { setFollowUp } from "@/lib/follow-ups/service";import { buildTrackingPixelUrl, injectTrackingPixel, resolveTrackingOrigin } from "@/lib/tracking/open-tracking-utils";+import { getComposePreferences } from "@/lib/compose/preferences";export type SendEmailInput = {userId: string;@@ -39,7 +40,7 @@ export type SendEmailInput = {attachments?: AttachmentContent[];/** Future delivery time. Values at or before the current time send immediately. */scheduledAt?: string | Date;- /** Hold the send for UNDO_SEND_SECONDS (via the scheduled queue) so the user can cancel it. */+ /** Hold the send for the user's undo window (via the scheduled queue) so they can cancel it. */undoSend?: boolean;/** Add a read-receipt pixel to the HTML part (the stored Sent copy stays without it). */trackOpens?: boolean;@@ -49,7 +50,6 @@ export type SendEmailInput = {};/** How long a send started from the composer waits before it is delivered. */-export const UNDO_SEND_SECONDS = 15;const MAX_RECIPIENTS = 50;const MAX_QUEUE_DELAY_SECONDS = 24 * 60 * 60;@@ -122,8 +122,9 @@ export async function sendEmail(const userScheduledAt = requestedSchedule && requestedSchedule.getTime() > Date.now()? requestedSchedule: null;- // An explicit schedule wins; otherwise an undoable send waits out the undo window.- const scheduledAt = userScheduledAt ?? (input.undoSend ? new Date(Date.now() + UNDO_SEND_SECONDS * 1000) : null);+ // An explicit schedule wins; otherwise an undoable send waits out the user's undo window.+ const undoSeconds = !userScheduledAt && input.undoSend ? (await getComposePreferences(env, input.userId)).undoSendSeconds : 0;+ const scheduledAt = userScheduledAt ?? (undoSeconds > 0 ? new Date(Date.now() + undoSeconds * 1000) : null);const snippet = buildSnippet(input.text ?? null, input.html ?? null);const toAddr = joinEmailAddressList(to);@@ -186,7 +187,7 @@ export async function sendEmail(};if (scheduledAt) {await enqueueScheduledDelivery(env, delivery, scheduledAt);- return userScheduledAt ? { messageId, scheduled: true } : { messageId, scheduled: true, undoSeconds: UNDO_SEND_SECONDS };+ return userScheduledAt ? { messageId, scheduled: true } : { messageId, scheduled: true, undoSeconds };}await deliverEmail(env, delivery);diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex c18a366..bb02e26 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -744,6 +744,10 @@"settings.compose.trackOpensDescription": "New messages start with the eye switched on. Recipients' mail apps may still block the image.","settings.compose.failed": "Composer settings could not be saved.","settings.compose.migrationRequired": "Run “Update database” in Admin first.",+ "settings.compose.undoTitle": "Undo send",+ "settings.compose.undoDescription": "How long a sent message waits so you can still cancel it.",+ "settings.compose.undoOff": "Off, send immediately",+ "settings.compose.undoSeconds": "{seconds} seconds","settingsPage.inbox.shortcuts": "Shortcuts","settingsPage.inbox.shortcutsDescription": "Choose whether keyboard shortcuts are active.","settingsPage.inbox.notifications": "Notifications",diff --git a/tests/compose-preferences.test.mjs b/tests/compose-preferences.test.mjsindex 511d61d..dd5ed4b 100644--- a/tests/compose-preferences.test.mjs+++ b/tests/compose-preferences.test.mjs@@ -31,34 +31,47 @@ const service = await load("service");const { SqliteDatabase } = await load("database");const { applyMigrations } = await load("migrate");-async function createFixture(t, { dropTable = false } = {}) {+async function createFixture(t, { dropTable = false, dropUndoColumn = false } = {}) {const database = new SqliteDatabase(join(outDir, `${crypto.randomUUID()}.sqlite`));t.after(() => database.db.close());await applyMigrations(database, join(root, "drizzle/migrations"));if (dropTable) database.db.exec("DROP TABLE user_compose_preferences");+ if (dropUndoColumn) database.db.exec("ALTER TABLE user_compose_preferences DROP COLUMN undo_send_seconds");database.db.prepare("INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', '[email protected]', 'Kevin', 'x', 0)").run();return { env: { DB: database }, database };}-test("read receipts default to off and the saved choice persists per user", async (t) => {+test("defaults are no read receipt and a 15 second undo window", async (t) => {const { env } = await createFixture(t);- assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: false });- await service.setComposePreferences(env, "u1", { trackOpensDefault: true });- assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: true });- await service.setComposePreferences(env, "u1", { trackOpensDefault: false });- assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: false });+ assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: false, undoSendSeconds: 15 });+});++test("each setting is saved on its own without resetting the other", async (t) => {+ const { env } = await createFixture(t);+ await service.updateComposePreferences(env, "u1", { trackOpensDefault: true });+ await service.updateComposePreferences(env, "u1", { undoSendSeconds: 0 });+ assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: true, undoSendSeconds: 0 });+ await service.updateComposePreferences(env, "u1", { trackOpensDefault: false });+ assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: false, undoSendSeconds: 0 });});test("preferences are removed with the user", async (t) => {const { env, database } = await createFixture(t);database.db.exec("PRAGMA foreign_keys = ON");- await service.setComposePreferences(env, "u1", { trackOpensDefault: true });+ await service.updateComposePreferences(env, "u1", { trackOpensDefault: true });database.db.exec("DELETE FROM users WHERE id = 'u1'");assert.equal(database.db.prepare("SELECT count(*) AS n FROM user_compose_preferences").get().n, 0);});-test("before migration 0072 reads fall back to off and saving asks for the migration", async (t) => {+test("before migration 0072 reads fall back to the defaults and saving asks for the migration", async (t) => {const { env } = await createFixture(t, { dropTable: true });- assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: false });- await assert.rejects(service.setComposePreferences(env, "u1", { trackOpensDefault: true }), service.ComposePreferencesUnavailableError);+ assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: false, undoSendSeconds: 15 });+ await assert.rejects(service.updateComposePreferences(env, "u1", { trackOpensDefault: true }), service.ComposePreferencesUnavailableError);+});++test("before migration 0073 the read receipt still saves and only the undo window needs the migration", async (t) => {+ const { env } = await createFixture(t, { dropUndoColumn: true });+ assert.deepEqual(await service.updateComposePreferences(env, "u1", { trackOpensDefault: true }), { trackOpensDefault: true, undoSendSeconds: 15 });+ assert.deepEqual(await service.getComposePreferences(env, "u1"), { trackOpensDefault: true, undoSendSeconds: 15 });+ await assert.rejects(service.updateComposePreferences(env, "u1", { undoSendSeconds: 5 }), service.ComposePreferencesUnavailableError);});