From 14c6d14b556eeaaaac399a08e7cd09c75d0e9662 Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 21:20:53 +0100 Subject: [PATCH 01/15] feat(messages): add shared reversible actions with undo toasts --- public/locales/ar.json | 19 +- public/locales/bn.json | 19 +- public/locales/de.json | 19 +- public/locales/es.json | 19 +- public/locales/fa.json | 19 +- public/locales/fr.json | 19 +- public/locales/gu.json | 19 +- public/locales/ha.json | 19 +- public/locales/hi.json | 19 +- public/locales/id.json | 19 +- public/locales/it.json | 19 +- public/locales/ja.json | 19 +- public/locales/kn.json | 19 +- public/locales/ko.json | 19 +- public/locales/ml.json | 19 +- public/locales/mr.json | 19 +- public/locales/ms.json | 19 +- public/locales/nl.json | 19 +- public/locales/pa.json | 19 +- public/locales/pl.json | 19 +- public/locales/pt-BR.json | 19 +- public/locales/pt-PT.json | 19 +- public/locales/ru.json | 19 +- public/locales/si.json | 19 +- public/locales/sw.json | 19 +- public/locales/ta.json | 19 +- public/locales/te.json | 19 +- public/locales/th.json | 19 +- public/locales/tr.json | 19 +- public/locales/uk.json | 19 +- public/locales/ur.json | 19 +- public/locales/vi.json | 19 +- public/locales/zh-CN.json | 19 +- src/app/(dashboard)/layout.tsx | 2 + .../api/messages/[messageId]/star/route.ts | 8 +- src/app/api/messages/actions/route.ts | 44 +++ src/components/dashboard-nav-utils.ts | 14 +- .../message-actions/message-actions.tsx | 8 +- src/components/message-actions/utils.ts | 18 +- .../messages/conversation-thread.tsx | 2 +- .../messages/message-folder-page.tsx | 25 +- .../message-list-row-actions-utils.ts | 38 +- .../messages/message-thread-cache.ts | 15 +- .../messages/thread-message-actions.tsx | 4 +- src/components/messages/undo-toasts.tsx | 100 +++++ src/components/messages/use-message-thread.ts | 13 +- src/components/messages/utils.ts | 30 +- src/hooks/use-messages.ts | 6 +- src/hooks/utils.ts | 41 +- src/lib/i18n/en.json | 19 +- src/lib/messages/actions/client.ts | 110 ++++++ src/lib/messages/actions/definitions.ts | 222 +++++++++++ src/lib/messages/actions/executor.ts | 160 ++++++++ src/lib/messages/actions/service.ts | 351 +++++++++++++++++ src/lib/messages/actions/token.ts | 85 +++++ src/lib/messages/actions/types.d.ts | 92 +++++ src/lib/messages/actions/undo-store.ts | 104 +++++ src/lib/messages/detail-cache.ts | 6 + tests/message-action-undo.test.mjs | 361 ++++++++++++++++++ 59 files changed, 2400 insertions(+), 105 deletions(-) create mode 100644 src/app/api/messages/actions/route.ts create mode 100644 src/components/messages/undo-toasts.tsx create mode 100644 src/lib/messages/actions/client.ts create mode 100644 src/lib/messages/actions/definitions.ts create mode 100644 src/lib/messages/actions/executor.ts create mode 100644 src/lib/messages/actions/service.ts create mode 100644 src/lib/messages/actions/token.ts create mode 100644 src/lib/messages/actions/types.d.ts create mode 100644 src/lib/messages/actions/undo-store.ts create mode 100644 tests/message-action-undo.test.mjs diff --git a/public/locales/ar.json b/public/locales/ar.json index 528602c28..b897b0b81 100644 --- a/public/locales/ar.json +++ b/public/locales/ar.json @@ -2511,5 +2511,22 @@ "actions.unsubscribeDeleteAll": "إلغاء الاشتراك وحذف الكل", "actions.unsubscribeDeleteConfirm": "نقل {count} من الرسائل القديمة لهذا المرسل إلى سلة المهملات؟", "actions.unsubscribeTrashDone": "تم إلغاء الاشتراك ونُقل {count} رسالة إلى سلة المهملات", - "attachment.downloadAllFlagged": "بعض المرفقات معلَّمة بأنها قد تكون خطيرة. هل تريد تنزيل الأرشيف على أي حال؟" + "attachment.downloadAllFlagged": "بعض المرفقات معلَّمة بأنها قد تكون خطيرة. هل تريد تنزيل الأرشيف على أي حال؟", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/bn.json b/public/locales/bn.json index 983d5579e..44013978d 100644 --- a/public/locales/bn.json +++ b/public/locales/bn.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "সাবস্ক্রিপশন বাতিল ও সব মুছুন", "actions.unsubscribeDeleteConfirm": "এই প্রেরকের {count}টি পুরনো ইমেইল ট্র্যাশে নেবেন?", "actions.unsubscribeTrashDone": "সাবস্ক্রিপশন বাতিল; {count}টি ইমেইল ট্র্যাশে গেছে", - "attachment.downloadAllFlagged": "কিছু সংযুক্তি সম্ভাব্য বিপজ্জনক হিসেবে চিহ্নিত। তবুও আর্কাইভ ডাউনলোড করবেন?" + "attachment.downloadAllFlagged": "কিছু সংযুক্তি সম্ভাব্য বিপজ্জনক হিসেবে চিহ্নিত। তবুও আর্কাইভ ডাউনলোড করবেন?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/de.json b/public/locales/de.json index c287d9ff5..1dec30811 100644 --- a/public/locales/de.json +++ b/public/locales/de.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "Abbestellen & alle löschen", "actions.unsubscribeDeleteConfirm": "{count} ältere E-Mails dieses Absenders in den Papierkorb verschieben?", "actions.unsubscribeTrashDone": "Abbestellt und {count} E-Mails in den Papierkorb verschoben", - "attachment.downloadAllFlagged": "Einige Anhänge sind als potenziell gefährlich markiert. Archiv trotzdem herunterladen?" + "attachment.downloadAllFlagged": "Einige Anhänge sind als potenziell gefährlich markiert. Archiv trotzdem herunterladen?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/es.json b/public/locales/es.json index 03bb73336..bd74c91d6 100644 --- a/public/locales/es.json +++ b/public/locales/es.json @@ -2466,5 +2466,22 @@ "actions.unsubscribeDeleteAll": "Darse de baja y borrar todo", "actions.unsubscribeDeleteConfirm": "¿Mover {count} correos anteriores de este remitente a la Papelera?", "actions.unsubscribeTrashDone": "Dado de baja; {count} correos movidos a la Papelera", - "attachment.downloadAllFlagged": "Algunos archivos adjuntos están marcados como potencialmente peligrosos. ¿Descargar el archivo de todos modos?" + "attachment.downloadAllFlagged": "Algunos archivos adjuntos están marcados como potencialmente peligrosos. ¿Descargar el archivo de todos modos?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/fa.json b/public/locales/fa.json index df07be546..ad576c6fc 100644 --- a/public/locales/fa.json +++ b/public/locales/fa.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "لغو اشتراک و حذف همه", "actions.unsubscribeDeleteConfirm": "آیا {count} ایمیل قدیمی این فرستنده به سطل زباله منتقل شود؟", "actions.unsubscribeTrashDone": "اشتراک لغو شد؛ {count} ایمیل به سطل زباله منتقل شد", - "attachment.downloadAllFlagged": "برخی پیوست‌ها به‌عنوان بالقوه خطرناک پرچم‌گذاری شده‌اند. با این حال آرشیو دانلود شود؟" + "attachment.downloadAllFlagged": "برخی پیوست‌ها به‌عنوان بالقوه خطرناک پرچم‌گذاری شده‌اند. با این حال آرشیو دانلود شود؟", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/fr.json b/public/locales/fr.json index 0e453ff91..84965258b 100644 --- a/public/locales/fr.json +++ b/public/locales/fr.json @@ -2466,5 +2466,22 @@ "actions.unsubscribeDeleteAll": "Se désabonner et tout supprimer", "actions.unsubscribeDeleteConfirm": "Déplacer {count} anciens e-mails de cet expéditeur dans la corbeille ?", "actions.unsubscribeTrashDone": "Désabonné, {count} e-mails placés dans la corbeille", - "attachment.downloadAllFlagged": "Certaines pièces jointes sont signalées comme potentiellement dangereuses. Télécharger l'archive quand même ?" + "attachment.downloadAllFlagged": "Certaines pièces jointes sont signalées comme potentiellement dangereuses. Télécharger l'archive quand même ?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/gu.json b/public/locales/gu.json index 74682ee6c..a5188be26 100644 --- a/public/locales/gu.json +++ b/public/locales/gu.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "સભ્યતા રદ કરો અને બધું કાઢી નાખો", "actions.unsubscribeDeleteConfirm": "આ મોકલનારના {count} જૂના ઇમેઇલ ટ્રેશમાં ખસેડવા?", "actions.unsubscribeTrashDone": "સભ્યતા રદ; {count} ઇમેઇલ ટ્રેશમાં ગયા", - "attachment.downloadAllFlagged": "કેટલીક જોડાણો સંભવિત જોખમી તરીકે ચિહ્નિત છે. તેમ છતાં આર્કાઇવ ડાઉનલોડ કરવું?" + "attachment.downloadAllFlagged": "કેટલીક જોડાણો સંભવિત જોખમી તરીકે ચિહ્નિત છે. તેમ છતાં આર્કાઇવ ડાઉનલોડ કરવું?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ha.json b/public/locales/ha.json index fdc25ab41..396f5ddc9 100644 --- a/public/locales/ha.json +++ b/public/locales/ha.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "Soke rajin & goge duk", "actions.unsubscribeDeleteConfirm": "Aka mika saƙonni {count} na tsoho daga wannan mai aikawa zuwa Trash?", "actions.unsubscribeTrashDone": "An soke rajin; aka mika saƙonni {count} zuwa Trash", - "attachment.downloadAllFlagged": "Wasu abubuwan da ake da su an yi su tambarin yiwuwa hadari. Duk da haka a sauke ajiya?" + "attachment.downloadAllFlagged": "Wasu abubuwan da ake da su an yi su tambarin yiwuwa hadari. Duk da haka a sauke ajiya?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/hi.json b/public/locales/hi.json index f0996e3d8..01b9cc91a 100644 --- a/public/locales/hi.json +++ b/public/locales/hi.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "सदस्यता रद्द करें और सब हटाएँ", "actions.unsubscribeDeleteConfirm": "इस प्रेषक के {count} पुराने ईमेल ट्रैश में ले जाएँ?", "actions.unsubscribeTrashDone": "सदस्यता रद्द; {count} ईमेल ट्रैश में ले जाए गए", - "attachment.downloadAllFlagged": "कुछ अटैचमेंट संभावित रूप से खतरनाक चिह्नित हैं। फिर भी संग्रह डाउनलोड करें?" + "attachment.downloadAllFlagged": "कुछ अटैचमेंट संभावित रूप से खतरनाक चिह्नित हैं। फिर भी संग्रह डाउनलोड करें?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/id.json b/public/locales/id.json index 0d6039fca..51b757762 100644 --- a/public/locales/id.json +++ b/public/locales/id.json @@ -2433,5 +2433,22 @@ "actions.unsubscribeDeleteAll": "Berhenti berlangganan & hapus semua", "actions.unsubscribeDeleteConfirm": "Pindahkan {count} email lama dari pengirim ini ke Sampah?", "actions.unsubscribeTrashDone": "Berhenti berlangganan; {count} email dipindahkan ke Sampah", - "attachment.downloadAllFlagged": "Beberapa lampiran ditandai berpotensi berbahaya. Tetap unduh arsip?" + "attachment.downloadAllFlagged": "Beberapa lampiran ditandai berpotensi berbahaya. Tetap unduh arsip?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/it.json b/public/locales/it.json index f6d320733..124a9d3a8 100644 --- a/public/locales/it.json +++ b/public/locales/it.json @@ -2466,5 +2466,22 @@ "actions.unsubscribeDeleteAll": "Annulla iscrizione ed elimina tutto", "actions.unsubscribeDeleteConfirm": "Spostare {count} email precedenti di questo mittente nel Cestino?", "actions.unsubscribeTrashDone": "Iscrizione annullata; {count} email spostate nel Cestino", - "attachment.downloadAllFlagged": "Alcuni allegati sono segnalati come potenzialmente pericolosi. Scaricare comunque l'archivio?" + "attachment.downloadAllFlagged": "Alcuni allegati sono segnalati come potenzialmente pericolosi. Scaricare comunque l'archivio?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ja.json b/public/locales/ja.json index d68cfb878..624892bd6 100644 --- a/public/locales/ja.json +++ b/public/locales/ja.json @@ -2433,5 +2433,22 @@ "actions.unsubscribeDeleteAll": "登録解除してすべて削除", "actions.unsubscribeDeleteConfirm": "この差出人の過去のメール {count} 件をゴミ箱に移動しますか?", "actions.unsubscribeTrashDone": "登録解除し、{count} 件をゴミ箱に移動しました", - "attachment.downloadAllFlagged": "一部の添付ファイルに危険の可能性のフラグがあります。それでもアーカイブをダウンロードしますか?" + "attachment.downloadAllFlagged": "一部の添付ファイルに危険の可能性のフラグがあります。それでもアーカイブをダウンロードしますか?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/kn.json b/public/locales/kn.json index e156a2542..3eb801e71 100644 --- a/public/locales/kn.json +++ b/public/locales/kn.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "ಚಂದಾದಾರಿಕೆ ರದ್ದು ಮತ್ತು ಎಲ್ಲಾ ಅಳಿಸಿ", "actions.unsubscribeDeleteConfirm": "ಈ ಕಳುಹಿಸುವವರ {count} ಹಳೆಯ ಇಮెයిల್‌ಗಳನ್ನು ಟ್ರ್ಯಾಶ್‌ಗೆ ಸರಿಸಬೇಕೆ?", "actions.unsubscribeTrashDone": "ಚಂದಾದಾರಿಕೆ ರದ್ದಾಯಿತು; {count} ಇಮೆಯಿಲ್‌ಗಳು ಟ್ರ್ಯಾಶ್‌ಗೆ ಹೋದವು", - "attachment.downloadAllFlagged": "ಕೆಲವು ಲಗತ್ತುಗಳು ಸಂಭಾವ್ಯ ಅಪಾಯಕಾರಿ ಎಂದು ಗುರುತಿಸಲಾಗಿವೆ. ಹೇಗೂ ಆರ್ಕೈವ್ ಡೌನ್‌ಲೋಡ್ ಮಾಡಬೇಕೆ?" + "attachment.downloadAllFlagged": "ಕೆಲವು ಲಗತ್ತುಗಳು ಸಂಭಾವ್ಯ ಅಪಾಯಕಾರಿ ಎಂದು ಗುರುತಿಸಲಾಗಿವೆ. ಹೇಗೂ ಆರ್ಕೈವ್ ಡೌನ್‌ಲೋಡ್ ಮಾಡಬೇಕೆ?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ko.json b/public/locales/ko.json index cc861a007..f45e88d4d 100644 --- a/public/locales/ko.json +++ b/public/locales/ko.json @@ -2447,5 +2447,22 @@ "actions.unsubscribeDeleteAll": "구독 해지 및 모두 삭제", "actions.unsubscribeDeleteConfirm": "이 발신자의 이전 이메일 {count}개를 휴지통으로 옮길까요?", "actions.unsubscribeTrashDone": "구독을 해지하고 이메일 {count}개를 휴지통으로 옮겼습니다", - "attachment.downloadAllFlagged": "일부 첨부 파일이 잠재적으로 위험하다고 표시되었습니다. 그래도 아카이브를 다운로드할까요?" + "attachment.downloadAllFlagged": "일부 첨부 파일이 잠재적으로 위험하다고 표시되었습니다. 그래도 아카이브를 다운로드할까요?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ml.json b/public/locales/ml.json index e42bbbfd9..db0c24ca8 100644 --- a/public/locales/ml.json +++ b/public/locales/ml.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "സബ്‌സ്‌ക്രിപ്‌ഷൻ റദ്ദാക്കി എല്ലാം നീക്കുക", "actions.unsubscribeDeleteConfirm": "ഈ അയച്ചയാളുടെ {count} പഴയ ഇമെയിലുകൾ ട്രാഷിലേക്ക് മാറ്റണോ?", "actions.unsubscribeTrashDone": "സബ്‌സ്‌ക്രിപ്‌ഷൻ റദ്ദായി; {count} ഇമെയിലുകൾ ട്രാഷിലേക്ക് മാറ്റി", - "attachment.downloadAllFlagged": "ചില അറ്റാച്ച്‌മെന്റുകൾ അപകടകരമെന്ന് അടയാളപ്പെടുത്തിയിരിക്കുന്നു. എങ്കിലും ആർക്കൈവ് ഡൗൺലോഡ് ചെയ്യണോ?" + "attachment.downloadAllFlagged": "ചില അറ്റാച്ച്‌മെന്റുകൾ അപകടകരമെന്ന് അടയാളപ്പെടുത്തിയിരിക്കുന്നു. എങ്കിലും ആർക്കൈവ് ഡൗൺലോഡ് ചെയ്യണോ?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/mr.json b/public/locales/mr.json index 657f6615a..8f0ffa166 100644 --- a/public/locales/mr.json +++ b/public/locales/mr.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "सदस्यता रद्द करा आणि सर्व हटवा", "actions.unsubscribeDeleteConfirm": "या प्रेषकाचे {count} जुने ईमेल ट्रॅशमध्ये हलवायचे?", "actions.unsubscribeTrashDone": "सदस्यता रद्द; {count} ईमेल ट्रॅशमध्ये गेले", - "attachment.downloadAllFlagged": "काही अटॅचमेंट संभावित धोकादायक म्हणून चिन्हांकित आहेत. तरीही संग्रह डाउनलोड करायचा?" + "attachment.downloadAllFlagged": "काही अटॅचमेंट संभावित धोकादायक म्हणून चिन्हांकित आहेत. तरीही संग्रह डाउनलोड करायचा?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ms.json b/public/locales/ms.json index f163a83a9..f2c966d88 100644 --- a/public/locales/ms.json +++ b/public/locales/ms.json @@ -2447,5 +2447,22 @@ "actions.unsubscribeDeleteAll": "Berhenti melanggan & padam semua", "actions.unsubscribeDeleteConfirm": "Alihkan {count} e-mel lama daripada penghantar ini ke Sampah?", "actions.unsubscribeTrashDone": "Berhenti melanggan; {count} e-mel dialihkan ke Sampah", - "attachment.downloadAllFlagged": "Some attachments are flagged as potentially dangerous. Download the archive anyway?" + "attachment.downloadAllFlagged": "Some attachments are flagged as potentially dangerous. Download the archive anyway?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/nl.json b/public/locales/nl.json index be14820af..06b615e17 100644 --- a/public/locales/nl.json +++ b/public/locales/nl.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "Afmelden & alles verwijderen", "actions.unsubscribeDeleteConfirm": "{count} eerdere e-mails van deze afzender naar de prullenbak verplaatsen?", "actions.unsubscribeTrashDone": "Afgemeld en {count} e-mails naar de prullenbak verplaatst", - "attachment.downloadAllFlagged": "Sommige bijlagen zijn gemarkeerd als mogelijk gevaarlijk. Het archief toch downloaden?" + "attachment.downloadAllFlagged": "Sommige bijlagen zijn gemarkeerd als mogelijk gevaarlijk. Het archief toch downloaden?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/pa.json b/public/locales/pa.json index 0071aaa76..f87d5ff69 100644 --- a/public/locales/pa.json +++ b/public/locales/pa.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "ਸਬਸਕ੍ਰਿਪਸ਼ਨ ਰੱਦ ਕਰੋ ਅਤੇ ਸਭ ਮਿਟਾਓ", "actions.unsubscribeDeleteConfirm": "ਇਸ ਭੇਜਣ ਵਾਲੇ ਦੇ {count} ਪੁਰਾਣੇ ਈਮੇਲ ਟ੍ਰੈਸ਼ ਵਿੱਚ ਭੇਜੀਏ?", "actions.unsubscribeTrashDone": "ਸਬਸਕ੍ਰਿਪਸ਼ਨ ਰੱਦ; {count} ਈਮੇਲ ਟ੍ਰੈਸ਼ ਵਿੱਚ ਭੇਜੇ ਗਏ", - "attachment.downloadAllFlagged": "ਕੁਝ ਅਟੈਚਮੈਂਟ ਸੰਭਾਵੀ ਖ਼ਤਰਨਾਕ ਵਜੋਂ ਨਿਸ਼ਾਨਾਬੱਧ ਹਨ। ਫਿਰ ਵੀ ਆਰਕਾਈਵ ਡਾਊਨਲੋਡ ਕਰੀਏ?" + "attachment.downloadAllFlagged": "ਕੁਝ ਅਟੈਚਮੈਂਟ ਸੰਭਾਵੀ ਖ਼ਤਰਨਾਕ ਵਜੋਂ ਨਿਸ਼ਾਨਾਬੱਧ ਹਨ। ਫਿਰ ਵੀ ਆਰਕਾਈਵ ਡਾਊਨਲੋਡ ਕਰੀਏ?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/pl.json b/public/locales/pl.json index c6e4146e1..e4bd9e78e 100644 --- a/public/locales/pl.json +++ b/public/locales/pl.json @@ -2481,5 +2481,22 @@ "actions.unsubscribeDeleteAll": "Wypisz się i usuń wszystko", "actions.unsubscribeDeleteConfirm": "Przenieść {count} wcześniejszych wiadomości tego nadawcy do Kosza?", "actions.unsubscribeTrashDone": "Wypisano; {count} wiadomości przeniesiono do Kosza", - "attachment.downloadAllFlagged": "Niektóre załączniki są oznaczone jako potencjalnie niebezpieczne. Pobrać archiwum mimo to?" + "attachment.downloadAllFlagged": "Niektóre załączniki są oznaczone jako potencjalnie niebezpieczne. Pobrać archiwum mimo to?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/pt-BR.json b/public/locales/pt-BR.json index 7ab32412c..cf4c3af46 100644 --- a/public/locales/pt-BR.json +++ b/public/locales/pt-BR.json @@ -2466,5 +2466,22 @@ "actions.unsubscribeDeleteAll": "Cancelar inscrição e apagar tudo", "actions.unsubscribeDeleteConfirm": "Mover {count} e-mails antigos deste remetente para a Lixeira?", "actions.unsubscribeTrashDone": "Inscrição cancelada; {count} e-mails movidos para a Lixeira", - "attachment.downloadAllFlagged": "Alguns anexos estão marcados como potencialmente perigosos. Baixar o arquivo mesmo assim?" + "attachment.downloadAllFlagged": "Alguns anexos estão marcados como potencialmente perigosos. Baixar o arquivo mesmo assim?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/pt-PT.json b/public/locales/pt-PT.json index c188cd5d9..58b948ec3 100644 --- a/public/locales/pt-PT.json +++ b/public/locales/pt-PT.json @@ -2466,5 +2466,22 @@ "actions.unsubscribeDeleteAll": "Anular subscrição e eliminar tudo", "actions.unsubscribeDeleteConfirm": "Mover {count} e-mails anteriores deste remetente para o Lixo?", "actions.unsubscribeTrashDone": "Subscrição anulada; {count} e-mails movidos para o Lixo", - "attachment.downloadAllFlagged": "Alguns anexos estão marcados como potencialmente perigosos. Transferir o ficheiro mesmo assim?" + "attachment.downloadAllFlagged": "Alguns anexos estão marcados como potencialmente perigosos. Transferir o ficheiro mesmo assim?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ru.json b/public/locales/ru.json index 7d846ace2..0547ab0ce 100644 --- a/public/locales/ru.json +++ b/public/locales/ru.json @@ -2481,5 +2481,22 @@ "actions.unsubscribeDeleteAll": "Отписаться и удалить всё", "actions.unsubscribeDeleteConfirm": "Переместить {count} писем от этого отправителя в корзину?", "actions.unsubscribeTrashDone": "Отписано; {count} писем перемещено в корзину", - "attachment.downloadAllFlagged": "Некоторые вложения помечены как потенциально опасные. Всё равно скачать архив?" + "attachment.downloadAllFlagged": "Некоторые вложения помечены как потенциально опасные. Всё равно скачать архив?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/si.json b/public/locales/si.json index 64740cf2e..f0e3b7a6a 100644 --- a/public/locales/si.json +++ b/public/locales/si.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "දායකත්වය අවලංගු කර සියල්ල මකන්න", "actions.unsubscribeDeleteConfirm": "මෙම යවන්නාගේ පැරණි විද්‍යුත් තැපෑල {count} කුණු කූඩයට ගෙනයාමටද?", "actions.unsubscribeTrashDone": "දායකත්වය අවලංගුයි; විද්‍යුත් තැපෑල {count} කුණු කූඩයට ගියේය", - "attachment.downloadAllFlagged": "සමහර ඇමුණුම් අන්තරායන්හි ලෙස සලකුණු කර ඇත. තවදුරටත් සංරක්ෂණාගාරය බාගන්නවාද?" + "attachment.downloadAllFlagged": "සමහර ඇමුණුම් අන්තරායන්හි ලෙස සලකුණු කර ඇත. තවදුරටත් සංරක්ෂණාගාරය බාගන්නවාද?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/sw.json b/public/locales/sw.json index b396df8a9..692415eba 100644 --- a/public/locales/sw.json +++ b/public/locales/sw.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "Ondoa usajili & futa zote", "actions.unsubscribeDeleteConfirm": "Uhamishe barua pepe {count} za zamu za mtumaji huyu kwenda Taka?", "actions.unsubscribeTrashDone": "Usajili umeondolewa; barua pepe {count} zimehamishiwa Taka", - "attachment.downloadAllFlagged": "Baadhi ya viambatisho vimepigwa bendera kuwa hatari. Bila shaka upakue kumbukumbu?" + "attachment.downloadAllFlagged": "Baadhi ya viambatisho vimepigwa bendera kuwa hatari. Bila shaka upakue kumbukumbu?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ta.json b/public/locales/ta.json index 9031c8b82..6b2ea58c2 100644 --- a/public/locales/ta.json +++ b/public/locales/ta.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "சந்தாவை நிறுத்தி அனைத்தையும் நீக்கு", "actions.unsubscribeDeleteConfirm": "இந்த அனுப்புநரின் {count} பழைய மின்னஞ்சல்களை குப்பைக்கு நகர்த்தவா?", "actions.unsubscribeTrashDone": "சந்தா நிறுத்தப்பட்டது; {count} மின்னஞ்சல்கள் குப்பைக்கு நகர்ந்தன", - "attachment.downloadAllFlagged": "சில இணைப்புகள் ஆபத்தானதாகக் குறிக்கப்பட்டுள்ளன. இருந்தும் காப்பகத்தைப் பதிவிறக்கவா?" + "attachment.downloadAllFlagged": "சில இணைப்புகள் ஆபத்தானதாகக் குறிக்கப்பட்டுள்ளன. இருந்தும் காப்பகத்தைப் பதிவிறக்கவா?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/te.json b/public/locales/te.json index 94bff3a32..ffaffee1b 100644 --- a/public/locales/te.json +++ b/public/locales/te.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "చందా రద్దు & అన్నీ తొలగించు", "actions.unsubscribeDeleteConfirm": "ఈ పంపిణీదారి {count} పాత ఇమెయిల్‌లను ట్రాష్‌కు తరలించాలా?", "actions.unsubscribeTrashDone": "చందా రద్దైంది; {count} ఇమెయిల్‌లు ట్రాష్‌కు వెళ్లాయి", - "attachment.downloadAllFlagged": "కొన్ని అటాచ్‌మెంట్‌లు ప్రమాదకరంగా గుర్తు పెట్టబడ్డాయి. అయినా ఆర్కైవ్ డౌన్‌లోడ్ చేయాలా?" + "attachment.downloadAllFlagged": "కొన్ని అటాచ్‌మెంట్‌లు ప్రమాదకరంగా గుర్తు పెట్టబడ్డాయి. అయినా ఆర్కైవ్ డౌన్‌లోడ్ చేయాలా?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/th.json b/public/locales/th.json index e90915765..8709517ae 100644 --- a/public/locales/th.json +++ b/public/locales/th.json @@ -2447,5 +2447,22 @@ "actions.unsubscribeDeleteAll": "ยกเลิกการสมัครรับและลบทั้งหมด", "actions.unsubscribeDeleteConfirm": "ย้ายอีเมลเดิม {count} ฉบับจากผู้ส่งรายนี้ไปถังขยะ?", "actions.unsubscribeTrashDone": "ยกเลิกการสมัครรับแล้ว ย้าย {count} ฉบับไปถังขยะ", - "attachment.downloadAllFlagged": "ไฟล์แนบบางไฟล์ถูกตั้งค่าสถานะว่าอาจเป็นอันตราย ดาวน์โหลดไฟล์เก็บถาวรต่อไหม" + "attachment.downloadAllFlagged": "ไฟล์แนบบางไฟล์ถูกตั้งค่าสถานะว่าอาจเป็นอันตราย ดาวน์โหลดไฟล์เก็บถาวรต่อไหม", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/tr.json b/public/locales/tr.json index 636a76e36..138e515cf 100644 --- a/public/locales/tr.json +++ b/public/locales/tr.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "Abonelikten çık ve tümünü sil", "actions.unsubscribeDeleteConfirm": "Bu gönderenin {count} eski e-postası Çöp Kutusuna taşınsın mı?", "actions.unsubscribeTrashDone": "Abonelikten çıkıldı; {count} e-posta Çöp Kutusuna taşındı", - "attachment.downloadAllFlagged": "Bazı ekler potansiyel olarak tehlikeli olarak işaretlendi. Yine de arşiv indirilsin mi?" + "attachment.downloadAllFlagged": "Bazı ekler potansiyel olarak tehlikeli olarak işaretlendi. Yine de arşiv indirilsin mi?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/uk.json b/public/locales/uk.json index a3fc318ab..3fde0edac 100644 --- a/public/locales/uk.json +++ b/public/locales/uk.json @@ -2481,5 +2481,22 @@ "actions.unsubscribeDeleteAll": "Відписатися й видалити все", "actions.unsubscribeDeleteConfirm": "Перемістити {count} листів від цього відправника до кошика?", "actions.unsubscribeTrashDone": "Відписано; {count} листів переміщено до кошика", - "attachment.downloadAllFlagged": "Деякі вкладення позначено як потенційно небезпечні. Завантажити архів усе одно?" + "attachment.downloadAllFlagged": "Деякі вкладення позначено як потенційно небезпечні. Завантажити архів усе одно?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/ur.json b/public/locales/ur.json index 4be35d1bc..6245aab05 100644 --- a/public/locales/ur.json +++ b/public/locales/ur.json @@ -2451,5 +2451,22 @@ "actions.unsubscribeDeleteAll": "سبسکرپشن ختم کریں اور سب حذف کریں", "actions.unsubscribeDeleteConfirm": "اس مرسل کے {count} پرانے ای میلز کو ٹریش میں منتقل کریں؟", "actions.unsubscribeTrashDone": "سبسکرپشن ختم؛ {count} ای میلز ٹریش میں منتقل کر دی گئیں", - "attachment.downloadAllFlagged": "بعض منسلکات کو ممکنہ طور پر خطرناک قرار دیا گیا ہے۔ پھر بھی آرکائیو ڈاؤن لوڈ کریں؟" + "attachment.downloadAllFlagged": "بعض منسلکات کو ممکنہ طور پر خطرناک قرار دیا گیا ہے۔ پھر بھی آرکائیو ڈاؤن لوڈ کریں؟", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/vi.json b/public/locales/vi.json index 70ef6a312..8e67b84a6 100644 --- a/public/locales/vi.json +++ b/public/locales/vi.json @@ -2433,5 +2433,22 @@ "actions.unsubscribeDeleteAll": "Hủy đăng ký & xóa tất cả", "actions.unsubscribeDeleteConfirm": "Chuyển {count} email cũ của người gửi này vào Thùng rác?", "actions.unsubscribeTrashDone": "Đã hủy đăng ký; {count} email đã chuyển vào Thùng rác", - "attachment.downloadAllFlagged": "Một số tệp đính kèm bị gắn cờ là có khả năng nguy hiểm. Vẫn tải xuống tệp nén?" + "attachment.downloadAllFlagged": "Một số tệp đính kèm bị gắn cờ là có khả năng nguy hiểm. Vẫn tải xuống tệp nén?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.json index 7bbb71060..b75be4340 100644 --- a/public/locales/zh-CN.json +++ b/public/locales/zh-CN.json @@ -2433,5 +2433,22 @@ "actions.unsubscribeDeleteAll": "退订并全部删除", "actions.unsubscribeDeleteConfirm": "将此发件人的 {count} 封旧邮件移至垃圾箱?", "actions.unsubscribeTrashDone": "已退订,并将 {count} 封邮件移至垃圾箱", - "attachment.downloadAllFlagged": "部分附件被标记为可能存在危险。仍要下载该压缩包吗?" + "attachment.downloadAllFlagged": "部分附件被标记为可能存在危险。仍要下载该压缩包吗?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/src/app/(dashboard)/layout.tsx b/src/app/(dashboard)/layout.tsx index a8fd3fede..245a8beb2 100644 --- a/src/app/(dashboard)/layout.tsx +++ b/src/app/(dashboard)/layout.tsx @@ -27,6 +27,7 @@ import { useDashboardState } from "./dashboard-state"; import { useAssistantAvailability } from "./use-assistant-availability"; import { RouteTitle } from "@/components/route-title"; import { useAppBadge } from "@/hooks/use-app-badge"; +import { UndoToasts } from "@/components/messages/undo-toasts"; export default function DashboardLayout({ children, @@ -93,6 +94,7 @@ export default function DashboardLayout({ + diff --git a/src/app/api/messages/[messageId]/star/route.ts b/src/app/api/messages/[messageId]/star/route.ts index b62c4124c..b0042f364 100644 --- a/src/app/api/messages/[messageId]/star/route.ts +++ b/src/app/api/messages/[messageId]/star/route.ts @@ -26,7 +26,13 @@ export async function POST( const access = await getMailboxAccessLevel(db, user, message.mailboxId); if (!access?.canRead) return NextResponse.json({ error: "Message not found" }, { status: 404 }); - const starred = !message.starred; + const body = (await _request.json().catch(() => null)) as { starred?: unknown } | null; + const payload = body && typeof body === "object" ? body : {}; + if (payload.starred !== undefined && typeof payload.starred !== "boolean") { + return NextResponse.json({ error: "Invalid star state" }, { status: 400 }); + } + + const starred = payload.starred ?? !message.starred; await db.update(messages).set({ starred }).where(eq(messages.id, message.id)); return NextResponse.json({ starred }); } diff --git a/src/app/api/messages/actions/route.ts b/src/app/api/messages/actions/route.ts new file mode 100644 index 000000000..915591a7f --- /dev/null +++ b/src/app/api/messages/actions/route.ts @@ -0,0 +1,44 @@ +import { NextResponse } from "next/server"; +import { getCurrentUser } from "@/lib/auth/cookies"; +import { getEnv } from "@/lib/cloudflare"; +import { + MessageActionError, + applyMessageActionForUser, + undoMessageActionForUser, +} from "@/lib/messages/actions/service"; +import type { MessageActionInput } from "@/lib/messages/actions/types"; + +type ActionRequest = (Partial & { op?: "apply" | "undo"; token?: string }) | null; + +export async function POST(request: Request) { + const env = getEnv(); + const user = await getCurrentUser(env, request); + if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + + const payload = (await request.json().catch(() => null)) as ActionRequest; + if (!payload) return NextResponse.json({ error: "Invalid request" }, { status: 400 }); + + try { + if (payload.op === "undo") { + if (typeof payload.token !== "string" || !payload.token) { + return NextResponse.json({ error: "Undo token is required" }, { status: 400 }); + } + return NextResponse.json(await undoMessageActionForUser(env, user, payload.token)); + } + + if (!payload.action || !Array.isArray(payload.messageIds)) { + return NextResponse.json({ error: "Invalid message action" }, { status: 400 }); + } + return NextResponse.json(await applyMessageActionForUser(env, user, { + action: payload.action, + messageIds: payload.messageIds, + folderId: payload.folderId, + snoozedUntil: payload.snoozedUntil, + })); + } catch (error) { + if (error instanceof MessageActionError) { + return NextResponse.json({ error: error.message }, { status: error.status }); + } + throw error; + } +} diff --git a/src/components/dashboard-nav-utils.ts b/src/components/dashboard-nav-utils.ts index aef03b802..7f7b13d7b 100644 --- a/src/components/dashboard-nav-utils.ts +++ b/src/components/dashboard-nav-utils.ts @@ -1,20 +1,12 @@ -import type { BulkMessageAction } from "@/app/api/messages/bulk/types"; import type { MessageCounts, MessageFolder } from "@/hooks/types"; -import { authFetch } from "@/lib/auth/client"; +import { performMessageAction } from "@/lib/messages/actions/client"; export function getFolderNavCount(folder: MessageFolder, counts: MessageCounts["folders"]): number | undefined { return counts[folder].unread; } -async function moveMessages(payload: { messageIds: string[]; action: BulkMessageAction; folderId?: string }) { - const response = await authFetch("/api/messages/bulk", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - }); - - if (!response.ok) throw new Error("Unable to move messages"); - window.dispatchEvent(new Event("mailflare:messages-changed")); +async function moveMessages(payload: { messageIds: string[]; action: "archive" | "spam" | "trash" | "folder"; folderId?: string }) { + await performMessageAction(payload); } export function moveMessagesToSystemFolder(messageIds: string[], action: "archive" | "spam" | "trash") { diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsx index 26a5fc19d..3f1ab602c 100644 --- a/src/components/message-actions/message-actions.tsx +++ b/src/components/message-actions/message-actions.tsx @@ -70,11 +70,11 @@ export function MessageActions({ const [sourceOpen, setSourceOpen] = useState(false); const [snoozeOpen, setSnoozeOpen] = useState(false); - const runAction = useCallback(async (action: BulkMessageAction) => { + const runAction = useCallback(async (action: BulkMessageAction, options: { undo?: boolean } = {}) => { setPendingAction(action); setError(null); try { - await runSingleMessageAction(messageId, action); + await runSingleMessageAction(messageId, action, options); const redirect = getMessageActionRedirect(action, listHref); if (redirect) router.push(autoAdvance() ?? redirect); router.refresh(); @@ -224,7 +224,7 @@ export function MessageActions({ try { await createTrashSenderRule({ mailboxId, senderAddress }); - await runAction("trash"); + await runAction("trash", { undo: false }); } catch { setError(t("actions.error.trashRule")); setPendingAction(null); @@ -260,7 +260,7 @@ export function MessageActions({ setPendingAction("block"); try { await blockMessageContact({ mailboxId, senderAddress }); - await runSingleMessageAction(messageId, "trash"); + await runSingleMessageAction(messageId, "trash", { undo: false }); router.push(autoAdvance() ?? listHref); router.refresh(); } catch (blockError) { diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts index e4d72beb8..dc9726e07 100644 --- a/src/components/message-actions/utils.ts +++ b/src/components/message-actions/utils.ts @@ -3,7 +3,8 @@ import { confirmDestructive } from "@/components/ui/confirm-dialog"; import { authFetch } from "@/lib/auth/client"; import { throwIfDeleteSkipped } from "@/lib/messages/permanent-delete-utils"; import { dispatchMessagesChanged } from "@/lib/messages/change-events"; -import { markMessagesReadInCaches } from "@/hooks/utils"; +import { performMessageAction } from "@/lib/messages/actions/client"; +import { isReversibleMessageAction } from "@/lib/messages/actions/definitions"; import { getEmailAddress, normalizeEmailAddress, splitEmailAddressList } from "@/lib/email/address"; import { getLatestEmailContent } from "@/lib/email/reply-content-utils"; import { formatUserDate } from "@/lib/time/utils"; @@ -43,7 +44,17 @@ export function getMessageBackHref( export async function runSingleMessageAction( messageId: string, action: BulkMessageAction, + options: { undo?: boolean; notify?: boolean } = {}, ) { + if (isReversibleMessageAction(action)) { + await performMessageAction( + { action, messageIds: [messageId] }, + { undo: options.undo !== false, notify: options.notify !== false }, + ); + return; + } + if (action !== "delete") throw new Error("Unable to update message"); + const response = await authFetch("/api/messages/bulk", { method: "POST", headers: { "Content-Type": "application/json" }, @@ -55,10 +66,7 @@ export async function runSingleMessageAction( } await throwIfDeleteSkipped(response, action); - const readChanged = action === "read" || action === "unread"; - if (readChanged) markMessagesReadInCaches([messageId], action === "read"); - if (readChanged) dispatchMessagesChanged({ kind: "read", messageIds: [messageId], read: action === "read" }); - else dispatchMessagesChanged(); + dispatchMessagesChanged(); } export function openUnsubscribeUrl(url: string) { diff --git a/src/components/messages/conversation-thread.tsx b/src/components/messages/conversation-thread.tsx index 466107076..666c2971d 100644 --- a/src/components/messages/conversation-thread.tsx +++ b/src/components/messages/conversation-thread.tsx @@ -201,7 +201,7 @@ export function ConversationMessageCard({ setLocallyExpanded(shouldExpand); if (!shouldExpand || locallyRead) return; setLocallyRead(true); - void runSingleMessageAction(message.id, "read").catch(() => setLocallyRead(false)); + void runSingleMessageAction(message.id, "read", { undo: false }).catch(() => setLocallyRead(false)); }} aria-expanded={expanded} className="flex min-w-0 flex-1 basis-40 items-center gap-3 text-left cursor-pointer" diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx index fe45e380a..b299ed15d 100644 --- a/src/components/messages/message-folder-page.tsx +++ b/src/components/messages/message-folder-page.tsx @@ -153,7 +153,7 @@ function MessageListRowComponent({ setRead(true); if (previousThreadUnread !== undefined) setThreadUnread(Math.max(0, previousThreadUnread - 1)); if (affectsInboxCount && message.direction === "inbound") dispatchMessageCountsDelta({ inboxUnreadDelta: -1 }); - void runBulkMessageAction([message.id], "read", false).catch(() => { + void runBulkMessageAction([message.id], "read", false, undefined, { undo: false }).catch(() => { setRead(false); setThreadUnread(previousThreadUnread); if (affectsInboxCount && message.direction === "inbound") dispatchMessageCountsDelta({ inboxUnreadDelta: 1 }); @@ -257,7 +257,7 @@ function MessageListRowComponent({ size="sm" className="relative z-10" onClick={() => { - void toggleMessageStar(message.id).then((result) => setStarred(result.starred)); + void toggleMessageStar(message.id, !starred).then((result) => setStarred(result.starred)); }} aria-label={t("message.star")} aria-pressed={starred} @@ -549,7 +549,10 @@ export function MessageFolderPage({ } setPendingBulkAction(true); - const previousMessages = messages; + const previousReadStates = new Map(messages + .filter((message) => selectedIdSet.has(message.id)) + .map((message) => [message.id, { read: message.read, threadUnread: message.threadUnread }])); + const previousSelectedRead = new Map(selectedMessages.map((message) => [message.id, message.read])); const readValue = action === "read" ? true : action === "unread" ? false : null; const inboxUnreadDelta = readValue === null || config.folder !== "inbox" || config.folderId ? 0 @@ -570,7 +573,21 @@ export function MessageFolderPage({ setSelectedMessages([]); } catch (error) { if (readValue !== null) { - updateMessages(previousMessages); + // Roll back only the fields this action optimistically changed, and only + // on the rows it touched; another action must not be clobbered. + updateMessages((current) => current.map((message) => { + const previous = previousReadStates.get(message.id); + if (!previous) return message; + return { + ...message, + read: previous.read, + ...(message.threadMessageIds ? { threadUnread: previous.threadUnread } : {}), + }; + })); + setSelectedMessages((current) => current.map((message) => { + const previous = previousSelectedRead.get(message.id); + return previous === undefined ? message : { ...message, read: previous }; + })); if (inboxUnreadDelta) dispatchMessageCountsDelta({ inboxUnreadDelta: -inboxUnreadDelta }); } throw error; diff --git a/src/components/messages/message-list-row-actions-utils.ts b/src/components/messages/message-list-row-actions-utils.ts index 99fafa7fe..2197b9c29 100644 --- a/src/components/messages/message-list-row-actions-utils.ts +++ b/src/components/messages/message-list-row-actions-utils.ts @@ -1,5 +1,6 @@ import type { TranslationKey } from "@/lib/i18n/types"; import { authFetch } from "@/lib/auth/client"; +import { performMessageAction } from "@/lib/messages/actions/client"; import type { MessageCountsDelta } from "@/hooks/types"; import { dateFromZonedFields, formatUserDateTimeLocal, getUserTimeZone, parseUserDateTimeLocal, zonedDateFields } from "@/lib/time/utils"; @@ -31,13 +32,7 @@ export function getSnoozePresets(now = new Date()): SnoozePreset[] { export async function snoozeMessage(messageId: string, snoozedUntil: string) { const parsed = parseUserDateTimeLocal(snoozedUntil); if (!parsed) throw new Error("Choose a valid snooze time"); - const response = await authFetch(`/api/messages/${messageId}/snooze`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ snoozedUntil: parsed.toISOString() }), - }); - if (!response.ok) throw new Error("Unable to snooze message"); - window.dispatchEvent(new Event("mailflare:messages-changed")); + await performMessageAction({ action: "snooze", messageIds: [messageId], snoozedUntil: parsed.toISOString() }); } export function isMessageSnoozed(snoozedUntil?: string | null): boolean { @@ -45,17 +40,28 @@ export function isMessageSnoozed(snoozedUntil?: string | null): boolean { } export async function unsnoozeMessage(messageId: string) { - const response = await authFetch(`/api/messages/${messageId}/snooze`, { method: "DELETE" }); - if (!response.ok) throw new Error("Unable to unsnooze message"); - window.dispatchEvent(new Event("mailflare:messages-changed")); + await performMessageAction({ action: "unsnooze", messageIds: [messageId] }); } -export async function toggleMessageStar(messageId: string) { - const response = await authFetch(`/api/messages/${messageId}/star`, { method: "POST" }); - if (!response.ok) throw new Error("Unable to update message star"); - const result = (await response.json()) as { starred: boolean }; - window.dispatchEvent(new Event("mailflare:message-counts-changed")); - return result; +/** + * Star through the desired-state action so rapid clicks and undo cannot turn + * into a non-idempotent toggle. The legacy toggle endpoint is kept for callers + * that do not know the current state. + */ +export async function toggleMessageStar(messageId: string, starred?: boolean) { + if (starred === undefined) { + const response = await authFetch(`/api/messages/${messageId}/star`, { method: "POST" }); + if (!response.ok) throw new Error("Unable to update message star"); + const result = (await response.json()) as { starred: boolean }; + window.dispatchEvent(new Event("mailflare:message-counts-changed")); + return result; + } + const response = await performMessageAction({ + action: starred ? "star" : "unstar", + messageIds: [messageId], + }); + const record = response.applied.find((item) => item.id === messageId); + return { starred: record?.applied.starred ?? starred }; } export function dispatchMessageCountsDelta(detail: MessageCountsDelta) { diff --git a/src/components/messages/message-thread-cache.ts b/src/components/messages/message-thread-cache.ts index c01da6505..18097ad3f 100644 --- a/src/components/messages/message-thread-cache.ts +++ b/src/components/messages/message-thread-cache.ts @@ -73,18 +73,29 @@ export function fetchMessageThread(messageId: string): Promise return request; } -export function markMessageThreadReadInCaches(messageIds: string[], read: boolean): void { +export function patchMessageThreadFieldsInCaches( + messageIds: string[], + patch: { read?: boolean; starred?: boolean }, +): void { if (messageIds.length === 0) return; const ids = new Set(messageIds); + // Any request already in flight may predate this patch; dropping it avoids + // caching a stale read/star value after the optimistic change. + generation += 1; + threadRequests.clear(); for (const [messageId, cached] of threadCache) { if (!cached.messages.some((message) => ids.has(message.id))) continue; threadCache.set(messageId, { ...cached, - messages: cached.messages.map((message) => (ids.has(message.id) ? { ...message, read } : message)), + messages: cached.messages.map((message) => (ids.has(message.id) ? { ...message, ...patch } : message)), }); } } +export function markMessageThreadReadInCaches(messageIds: string[], read: boolean): void { + patchMessageThreadFieldsInCaches(messageIds, { read }); +} + export function clearMessageThreadCache(): void { generation += 1; threadCache.clear(); diff --git a/src/components/messages/thread-message-actions.tsx b/src/components/messages/thread-message-actions.tsx index 455fdcc18..a33205309 100644 --- a/src/components/messages/thread-message-actions.tsx +++ b/src/components/messages/thread-message-actions.tsx @@ -58,7 +58,7 @@ export function ThreadMessageActions({ setPending(true); setError(null); try { - setStarred((await toggleMessageStar(message.id)).starred); + setStarred((await toggleMessageStar(message.id, !starred)).starred); } catch (nextError) { setError(nextError instanceof Error ? nextError.message : t("message.error.star")); } finally { @@ -126,7 +126,7 @@ export function ThreadMessageActions({ setError(null); try { await blockMessageContact({ mailboxId, senderAddress: message.fromAddr }); - await runSingleMessageAction(message.id, "trash"); + await runSingleMessageAction(message.id, "trash", { undo: false }); } catch (nextError) { setError(nextError instanceof Error ? nextError.message : t("message.error.block")); } finally { diff --git a/src/components/messages/undo-toasts.tsx b/src/components/messages/undo-toasts.tsx new file mode 100644 index 000000000..39c1cfed5 --- /dev/null +++ b/src/components/messages/undo-toasts.tsx @@ -0,0 +1,100 @@ +"use client"; + +import { useSyncExternalStore } from "react"; +import { useLanguage } from "@/components/language-provider"; +import { undoMessageAction } from "@/lib/messages/actions/client"; +import type { ReversibleMessageAction } from "@/lib/messages/actions/types"; +import { + beginUndoToast, + dismissUndoToast, + failUndoToast, + getUndoToasts, + subscribeUndoToasts, +} from "@/lib/messages/actions/undo-store"; +import type { UndoToastEntry } from "@/lib/messages/actions/undo-store"; +import type { TranslationKey } from "@/lib/i18n/types"; +import { cn } from "@/lib/utils"; + +const ACTION_LABELS: Record = { + archive: "undo.label.archive", + trash: "undo.label.trash", + spam: "undo.label.spam", + inbox: "undo.label.inbox", + folder: "undo.label.folder", + read: "undo.label.read", + unread: "undo.label.unread", + star: "undo.label.star", + unstar: "undo.label.unstar", + snooze: "undo.label.snooze", + unsnooze: "undo.label.unsnooze", +}; + +const EMPTY: UndoToastEntry[] = []; + +/** Independent stack for message-action undo; compose's single send notice is untouched. */ +export function UndoToasts() { + const { t } = useLanguage(); + const toasts = useSyncExternalStore(subscribeUndoToasts, getUndoToasts, () => EMPTY); + if (toasts.length === 0) return null; + + async function undo(entry: UndoToastEntry) { + if (entry.status !== "idle") return; + beginUndoToast(entry.id); + try { + const result = await undoMessageAction(entry); + if (result.restored.length === 0) failUndoToast(entry.id); + else dismissUndoToast(entry.id); + } catch { + failUndoToast(entry.id); + } + } + + return ( +
+ {toasts.map((entry) => { + const label = t(ACTION_LABELS[entry.action]); + const text = entry.records.length > 1 + ? t("undo.bulk", { action: label, count: entry.records.length }) + : label; + return ( +
+
+

{entry.status === "failed" ? t("undo.failed") : text}

+ {entry.skipped > 0 && entry.status !== "failed" && ( +

+ {t("undo.partial", { applied: entry.records.length, total: entry.records.length + entry.skipped })} +

+ )} +
+ {entry.status !== "failed" && ( + + )} + +
+ ); + })} +
+ ); +} diff --git a/src/components/messages/use-message-thread.ts b/src/components/messages/use-message-thread.ts index 506d0b85b..0b765ff61 100644 --- a/src/components/messages/use-message-thread.ts +++ b/src/components/messages/use-message-thread.ts @@ -21,7 +21,9 @@ export function useMessageThread(messageId: string, threadId: string | null | un if (!threadId) return; let cancelled = false; let refreshTimer: number | null = null; + let loadVersion = 0; async function load() { + const version = ++loadVersion; const cached = getCachedMessageThread(messageId); if (cached) { if (!cancelled) { @@ -33,25 +35,26 @@ export function useMessageThread(messageId: string, threadId: string | null | un setLoading(true); try { const next = await fetchMessageThread(messageId); - if (!cancelled) setMessages(next); + if (!cancelled && version === loadVersion) setMessages(next); } catch (error) { // A newer load is queued; keep the conversation on screen. - if (!cancelled && !isMessageThreadInvalidated(error)) setMessages([]); + if (!cancelled && version === loadVersion && !isMessageThreadInvalidated(error)) setMessages([]); } finally { - if (!cancelled) setLoading(false); + if (!cancelled && version === loadVersion) setLoading(false); } } void load(); function patchReadState(event: Event) { const detail = (event as CustomEvent<{ kind?: string; messageIds?: string[]; read?: boolean }>).detail; if (detail?.kind !== "read" || !detail.messageIds?.length) return; + // A response started before the read flip must not overwrite it. + loadVersion += 1; const ids = new Set(detail.messageIds); const read = detail.read !== false; markMessageThreadReadInCaches(detail.messageIds, read); setMessages((current) => current.map((message) => (ids.has(message.id) ? { ...message, read } : message))); } - function scheduleLoad(event?: Event) { - if ((event as CustomEvent<{ kind?: string }> | undefined)?.detail?.kind === "read") return; + function scheduleLoad() { if (document.visibilityState !== "visible") return; if (refreshTimer) window.clearTimeout(refreshTimer); refreshTimer = window.setTimeout(() => { diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts index a88b32462..102ba4f48 100644 --- a/src/components/messages/utils.ts +++ b/src/components/messages/utils.ts @@ -1,7 +1,8 @@ import type { Message } from "@/hooks/types"; import { authFetch } from "@/lib/auth/client"; import { dispatchMessagesChanged } from "@/lib/messages/change-events"; -import { markMessagesReadInCaches } from "@/hooks/utils"; +import { performMessageAction } from "@/lib/messages/actions/client"; +import { isReversibleMessageAction } from "@/lib/messages/actions/definitions"; import { getEmailDisplayName, splitEmailAddressList } from "@/lib/email/address"; import { formatUserDate, getUserTimeZone, zonedDateFields } from "@/lib/time/utils"; import type { MailboxOption } from "@/components/mailbox-provider"; @@ -95,21 +96,30 @@ export function formatEmailPageTitle({ location, total, unread, emailAddress, in return `${location} (${count})${suffix}`; } -export async function runBulkMessageAction(messageIds: string[], action: string, notify = true, folderId?: string) { +export async function runBulkMessageAction( + messageIds: string[], + action: string, + notify = true, + folderId?: string, + options: { undo?: boolean } = {}, +) { + if (isReversibleMessageAction(action)) { + await performMessageAction( + { action, messageIds, folderId }, + { notify, undo: options.undo !== false }, + ); + return; + } + if (action !== "delete") throw new Error(defaultTranslator("error.updateSelected")); + const response = await authFetch("/api/messages/bulk", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ messageIds, action, folderId }), + body: JSON.stringify({ messageIds, action }), }); - if (!response.ok) throw new Error(defaultTranslator("error.updateSelected")); await throwIfDeleteSkipped(response, action); - const readChanged = action === "read" || action === "unread"; - if (readChanged) markMessagesReadInCaches(messageIds, action === "read"); - if (notify) { - if (readChanged) dispatchMessagesChanged({ kind: "read", messageIds, read: action === "read" }); - else dispatchMessagesChanged(); - } + dispatchMessagesChanged(); } /** diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts index 484137341..e8b21e69e 100644 --- a/src/hooks/use-messages.ts +++ b/src/hooks/use-messages.ts @@ -71,8 +71,10 @@ export function useMessages( } function onMessagesChanged(event: Event) { const readOnly = (event as CustomEvent<{ kind?: string }>).detail?.kind === "read"; - // Read flips patch in place; "unread only" still needs a server refetch. - if (readOnly && filters?.read !== "unread") return; + // A read patch can overtake a list request that started before it. Bump + // the request number so that response can never repaint the old state; + // a quiet refetch then reconciles the page with the server. + requestNumber += 1; if (!readOnly) { clearMessageListCache(); clearMessageCountsCache(); diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts index a5af295b4..72ff66c3c 100644 --- a/src/hooks/utils.ts +++ b/src/hooks/utils.ts @@ -1,7 +1,7 @@ import { authFetch } from "@/lib/auth/client"; import { parseSearchQuery } from "@/lib/search/query-utils"; import { getUserTimeZone } from "@/lib/time/utils"; -import { setCachedMessageRead } from "@/lib/messages/detail-cache"; +import { patchCachedMessage } from "@/lib/messages/detail-cache"; import { isReadOnlyChange } from "@/lib/messages/change-events"; import type { MessageFilterOptions, MessageFolder } from "./types"; import type { MessageCounts, MessageListResponse } from "./types"; @@ -90,12 +90,26 @@ export function clearMessageListCache() { messageListRequests.clear(); } +/** Drops in-flight list requests without throwing away already-patched cached pages. */ +export function invalidateMessageListRequests() { + messageCacheGeneration += 1; + messageListRequests.clear(); +} + +export type CachedMessagePatch = { + read?: boolean; + starred?: boolean; +}; + /** - * Mirror a read/unread change into the cached lists and details, so a list - * remounted later (or a detail reopened) never shows the old state. + * Mirror a field-scoped change into every cached list page and detail. Used by + * optimistic reads, star toggles and undo, so a remount never repaints the + * state the action just replaced. */ -export function markMessagesReadInCaches(messageIds: string[], read: boolean) { +export function patchMessagesInCaches(messageIds: string[], patch: CachedMessagePatch) { + if (messageIds.length === 0) return; const ids = new Set(messageIds); + invalidateMessageListRequests(); for (const [key, response] of messageListCache) { if (!response.messages?.some((message) => ids.has(message.id) || message.threadMessageIds?.some((id) => ids.has(id)))) continue; @@ -106,14 +120,25 @@ export function markMessagesReadInCaches(messageIds: string[], read: boolean) { const threadSize = message.threadMessageIds.length; const flipped = message.threadMessageIds.reduce((total, id) => total + (ids.has(id) ? 1 : 0), 0); if (!flipped) return message; - const threadUnread = Math.min(threadSize, Math.max(0, (message.threadUnread ?? 0) + (read ? -flipped : flipped))); - return { ...message, read: threadUnread === 0, threadUnread }; + if (patch.read !== undefined) { + const threadUnread = Math.min(threadSize, Math.max(0, (message.threadUnread ?? 0) + (patch.read ? -flipped : flipped))); + return { ...message, read: threadUnread === 0, threadUnread, ...(patch.starred !== undefined ? { starred: patch.starred } : {}) }; + } + return patch.starred !== undefined ? { ...message, starred: patch.starred } : message; } - return ids.has(message.id) ? { ...message, read } : message; + return ids.has(message.id) ? { ...message, ...patch } : message; }), }); } - for (const id of ids) setCachedMessageRead(id, read); + for (const id of ids) patchCachedMessage(id, patch); +} + +/** + * Mirror a read/unread change into the cached lists and details, so a list + * remounted later (or a detail reopened) never shows the old state. + */ +export function markMessagesReadInCaches(messageIds: string[], read: boolean) { + patchMessagesInCaches(messageIds, { read }); } // Caches must drop on every change, including ones made while no list is mounted diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json index 7fece483e..af1c34449 100644 --- a/src/lib/i18n/en.json +++ b/src/lib/i18n/en.json @@ -2456,5 +2456,22 @@ "actions.unsubscribeDeleteAll": "Unsubscribe & delete all", "actions.unsubscribeDeleteConfirm": "Move {count} past emails from this sender to Trash?", "actions.unsubscribeTrashDone": "Unsubscribed and moved {count} emails to Trash", - "attachment.downloadAllFlagged": "Some attachments are flagged as potentially dangerous. Download the archive anyway?" + "attachment.downloadAllFlagged": "Some attachments are flagged as potentially dangerous. Download the archive anyway?", + "undo.button": "Undo", + "undo.dismiss": "Dismiss", + "undo.failed": "Could not undo that change", + "undo.partial": "{applied} of {total} messages updated", + "undo.bulk.one": "{action} · {count} message", + "undo.bulk.other": "{action} · {count} messages", + "undo.label.archive": "Archived", + "undo.label.trash": "Moved to Trash", + "undo.label.spam": "Moved to Spam", + "undo.label.inbox": "Moved to Inbox", + "undo.label.folder": "Moved to folder", + "undo.label.read": "Marked as read", + "undo.label.unread": "Marked as unread", + "undo.label.star": "Starred", + "undo.label.unstar": "Unstarred", + "undo.label.snooze": "Snoozed", + "undo.label.unsnooze": "Unsnoozed" } diff --git a/src/lib/messages/actions/client.ts b/src/lib/messages/actions/client.ts new file mode 100644 index 000000000..1eb4e281f --- /dev/null +++ b/src/lib/messages/actions/client.ts @@ -0,0 +1,110 @@ +"use client"; + +import { authFetch } from "@/lib/auth/client"; +import { dispatchMessagesChanged } from "@/lib/messages/change-events"; +import { patchMessagesInCaches } from "@/hooks/utils"; +import { + MessageActionExecutor, + MessageActionRequestError, + getChangedRecords, + hasMembershipChange, + readPatchGroups, + starPatchGroups, + type MessageActionExecutorHooks, + type MessageActionHookOptions, + type MessageActionTransport, +} from "./executor"; +import { showUndoToast } from "./undo-store"; +import type { + MessageActionInput, + MessageActionRequestOptions, + MessageActionResponse, + MessageActionTransportBody, + UndoMessageActionResponse, +} from "./types"; +import type { UndoToastEntry } from "./undo-store"; + +async function sendMessageAction( + body: MessageActionTransportBody, +): Promise { + const response = await authFetch("/api/messages/actions", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + const data = (await response.json().catch(() => ({}))) as { error?: string }; + if (!response.ok) { + throw new MessageActionRequestError(data.error ?? "Unable to update message", response.status); + } + return data as MessageActionResponse | UndoMessageActionResponse; +} + +function dispatchRead(ids: string[], read: boolean) { + if (ids.length === 0) return; + patchMessagesInCaches(ids, { read }); + dispatchMessagesChanged({ kind: "read", messageIds: ids, read }); +} + +const defaultHooks: MessageActionExecutorHooks = { + onApplied(response: MessageActionResponse, options: MessageActionHookOptions) { + const changed = getChangedRecords(response.applied); + if (changed.length === 0) return; + for (const [read, ids] of readPatchGroups(changed, "applied")) { + patchMessagesInCaches(ids, { read }); + if (options.notify) dispatchMessagesChanged({ kind: "read", messageIds: ids, read }); + } + const starred = starPatchGroups(changed, "applied"); + for (const [value, ids] of starred) patchMessagesInCaches(ids, { starred: value }); + if (options.notify && (starred.size > 0 || changed.some(hasMembershipChange))) dispatchMessagesChanged(); + }, + onUndoOptimistic(records) { + // Read/unread undo must feel immediate; other fields stay server-first. + for (const [read, ids] of readPatchGroups(records, "previous")) dispatchRead(ids, read); + }, + onUndoCompleted(records, response) { + const restoredSet = new Set(response.restored); + const restored = records.filter((record) => restoredSet.has(record.id)); + for (const [read, ids] of readPatchGroups(restored, "previous")) dispatchRead(ids, read); + const starred = starPatchGroups(restored, "previous"); + for (const [value, ids] of starred) patchMessagesInCaches(ids, { starred: value }); + if (starred.size > 0 || restored.some(hasMembershipChange) || response.skipped.length > 0) { + dispatchMessagesChanged(); + } + }, + onUndoFailed(records) { + // Roll the optimistic read patch back to what the failed action wrote. + for (const [read, ids] of readPatchGroups(records, "applied")) dispatchRead(ids, read); + for (const [value, ids] of starPatchGroups(records, "applied")) patchMessagesInCaches(ids, { starred: value }); + dispatchMessagesChanged(); + }, + onResync() { + dispatchMessagesChanged(); + }, +}; + +export const messageActionExecutor = new MessageActionExecutor(sendMessageAction as MessageActionTransport, defaultHooks); + +/** Applies an explicit action and, unless suppressed, shows its independent undo toast. */ +export async function performMessageAction( + input: MessageActionInput, + options: MessageActionRequestOptions = {}, +): Promise { + const response = await messageActionExecutor.run(input, { notify: options.notify }); + if (options.undo !== false) { + const records = getChangedRecords(response.applied); + showUndoToast({ + action: response.action, + records, + undoToken: response.undoToken, + skipped: response.skipped.length, + }); + } + return response; +} + +/** Undo runs through the same per-message queue as the action it reverts. */ +export function undoMessageAction(entry: Pick) { + return messageActionExecutor.undo(entry.records, entry.undoToken); +} + +export { MessageActionRequestError }; diff --git a/src/lib/messages/actions/definitions.ts b/src/lib/messages/actions/definitions.ts new file mode 100644 index 000000000..b5835ca99 --- /dev/null +++ b/src/lib/messages/actions/definitions.ts @@ -0,0 +1,222 @@ +import type { + MessageActionSkipReason, + MessageActionSkipped, + MessageStateField, + MessageStateSnapshot, + ReversibleMessageAction, +} from "./types"; + +/** Statuses a message may have before or after a reversible action. */ +export const REVERSIBLE_MESSAGE_STATUSES = ["received", "sent", "draft", "queued", "failed", "trash", "spam", "archived"] as const; + +const reversibleActions = new Set([ + "archive", + "trash", + "spam", + "inbox", + "folder", + "read", + "unread", + "star", + "unstar", + "snooze", + "unsnooze", +]); + +export function isReversibleMessageAction(value: unknown): value is ReversibleMessageAction { + return typeof value === "string" && reversibleActions.has(value as ReversibleMessageAction); +} + +/** Status and folder changes need manage access; read and star need read access, as before. */ +export function actionNeedsManage(action: ReversibleMessageAction): boolean { + return action !== "read" && action !== "unread" && action !== "star" && action !== "unstar"; +} + +export function isStatusAction(action: ReversibleMessageAction): boolean { + return action === "archive" || action === "trash" || action === "spam" || action === "inbox" || action === "folder"; +} + +/** Types the server reads for an action target; no bodies or internal keys. */ +export type MessageActionTarget = { + id: string; + mailboxId: string | null; + direction: "inbound" | "outbound" | string; + status: string; + read: boolean; + starred: boolean; + folderId: string | null; + snoozedUntil: Date | string | null; +}; + +export function toIsoOrNull(value: Date | string | null | undefined): string | null { + if (!value) return null; + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) return null; + // Timestamps are stored as whole seconds in every dialect. + return new Date(Math.floor(date.getTime() / 1000) * 1000).toISOString(); +} + +export function snapshotMessageState(message: MessageActionTarget): MessageStateSnapshot { + return { + status: message.status, + read: message.read, + starred: message.starred, + folderId: message.folderId, + snoozedUntil: toIsoOrNull(message.snoozedUntil), + }; +} + +export function applySnapshotPatch( + state: MessageStateSnapshot, + patch: Partial, +): MessageStateSnapshot { + return { ...state, ...patch }; +} + +export function getChangedStateFields(previous: MessageStateSnapshot, applied: MessageStateSnapshot): MessageStateField[] { + const fields: MessageStateField[] = []; + if (previous.status !== applied.status) fields.push("status"); + if (previous.read !== applied.read) fields.push("read"); + if (previous.starred !== applied.starred) fields.push("starred"); + if (previous.folderId !== applied.folderId) fields.push("folderId"); + if (previous.snoozedUntil !== applied.snoozedUntil) fields.push("snoozedUntil"); + return fields; +} + +export function recordHasChanges(record: { previous: MessageStateSnapshot; applied: MessageStateSnapshot }): boolean { + return getChangedStateFields(record.previous, record.applied).length > 0; +} + +export type MessageActionPatchResult = + | { patch: Partial; reason?: never } + | { patch?: never; reason: MessageActionSkipReason }; + +/** + * The fields an action writes for one message. It deliberately models only + * reversible fields: mailbox, ownership, bodies and attachments are never + * touched by the shared executor. + */ +export function getMessageActionPatch( + action: ReversibleMessageAction, + input: { folderId?: string | null; snoozedUntil?: string | null }, + message: MessageActionTarget, +): MessageActionPatchResult { + switch (action) { + case "archive": + return { patch: { status: "archived", folderId: null } }; + case "trash": + return { patch: { status: "trash", folderId: null } }; + case "spam": + return message.direction === "inbound" + ? { patch: { status: "spam", folderId: null } } + : { reason: "not_applicable" }; + case "inbox": + return { patch: { status: "received", folderId: null, snoozedUntil: null } }; + case "folder": + return input.folderId + ? { patch: { status: "received", folderId: input.folderId } } + : { reason: "invalid_target" }; + case "read": + return { patch: { read: true } }; + case "unread": + return { patch: { read: false } }; + case "star": + return { patch: { starred: true } }; + case "unstar": + return { patch: { starred: false } }; + case "snooze": { + const snoozedUntil = parseFutureDate(input.snoozedUntil); + if (!snoozedUntil || message.direction !== "inbound") return { reason: "invalid_target" }; + return { patch: { snoozedUntil } }; + } + case "unsnooze": + return message.direction === "inbound" + ? { patch: { snoozedUntil: null } } + : { reason: "not_applicable" }; + } +} + +function parseFutureDate(value: string | null | undefined): string | null { + if (typeof value !== "string") return null; + const date = new Date(value); + if (Number.isNaN(date.getTime()) || date <= new Date()) return null; + return new Date(Math.floor(date.getTime() / 1000) * 1000).toISOString(); +} + +export function isValidReversibleStatus(status: unknown): status is string { + return typeof status === "string" && (REVERSIBLE_MESSAGE_STATUSES as readonly string[]).includes(status); +} + +function isStateSnapshot(value: unknown): value is MessageStateSnapshot { + if (!value || typeof value !== "object") return false; + const state = value as Partial; + return typeof state.status === "string" + && typeof state.read === "boolean" + && typeof state.starred === "boolean" + && (typeof state.folderId === "string" || state.folderId === null) + && (typeof state.snoozedUntil === "string" || state.snoozedUntil === null); +} + +function fieldsMatch( + left: MessageStateSnapshot, + right: MessageStateSnapshot, + fields: MessageStateField[], +): boolean { + return fields.every((field) => left[field] === right[field]); +} + +export type UndoAccess = { canRead: boolean; canManage: boolean }; + +export type UndoRecordPlan = + | { id: string; patch: Partial; fields: MessageStateField[] } + | { id: string; reason: MessageActionSkipReason }; + +/** + * Validates one signed snapshot against the message as it is now. Restores + * only fields the action changed and only when the current value is still the + * one the action wrote, so a later action is never clobbered. Folder ownership + * and access are checked server-side before any write. + */ +export function planUndoRecord( + record: { id: string; mailboxId: string | null; previous: MessageStateSnapshot; applied: MessageStateSnapshot }, + current: MessageActionTarget, + access: UndoAccess, + folderMailboxId: string | null | undefined, +): UndoRecordPlan { + if (record.id !== current.id) return { id: record.id, reason: "not_found" }; + if (!record.mailboxId || record.mailboxId !== current.mailboxId) return { id: record.id, reason: "forbidden" }; + if (!isStateSnapshot(record.previous) || !isStateSnapshot(record.applied)) { + return { id: record.id, reason: "invalid_target" }; + } + + const fields = getChangedStateFields(record.previous, record.applied); + if (fields.length === 0) return { id: record.id, reason: "not_applicable" }; + + const needsManage = fields.some((field) => field === "status" || field === "folderId" || field === "snoozedUntil"); + if (!access.canRead || (needsManage && !access.canManage)) return { id: record.id, reason: "forbidden" }; + + if (!isValidReversibleStatus(record.previous.status)) return { id: record.id, reason: "invalid_target" }; + if (record.previous.folderId !== null) { + if (!folderMailboxId || folderMailboxId !== current.mailboxId) return { id: record.id, reason: "invalid_target" }; + } + if (record.previous.snoozedUntil !== null) { + if (current.direction !== "inbound" || Number.isNaN(new Date(record.previous.snoozedUntil).getTime())) { + return { id: record.id, reason: "invalid_target" }; + } + } + + const currentState = snapshotMessageState(current); + if (!fieldsMatch(currentState, record.applied, fields)) return { id: record.id, reason: "stale" }; + + const patch: Partial = {}; + for (const field of fields) { + patch[field] = record.previous[field] as never; + } + return { id: record.id, patch, fields }; +} + +export function summarizeActionSkips(skipped: MessageActionSkipped[]) { + const byReason = new Map(); + for (const item of skipped) byReason.set(item.reason, (byReason.get(item.reason) ?? 0) + 1); + return byReason; +} diff --git a/src/lib/messages/actions/executor.ts b/src/lib/messages/actions/executor.ts new file mode 100644 index 000000000..66e81dfe4 --- /dev/null +++ b/src/lib/messages/actions/executor.ts @@ -0,0 +1,160 @@ +import { getChangedStateFields, recordHasChanges } from "./definitions"; +import type { + MessageActionInput, + MessageActionRecord, + MessageActionResponse, + MessageActionTransportBody, + MessageStateSnapshot, + UndoMessageActionResponse, +} from "./types"; + +export class MessageActionRequestError extends Error { + constructor( + message: string, + readonly status = 400, + readonly skipped = 0, + ) { + super(message); + this.name = "MessageActionRequestError"; + } +} + +export type MessageActionTransport = ( + body: MessageActionTransportBody, +) => Promise; + +export type MessageActionHookOptions = { notify: boolean }; + +export type MessageActionExecutorHooks = { + onApplyOptimistic?: (input: MessageActionInput, options: MessageActionHookOptions) => void; + onApplyFailed?: (input: MessageActionInput, options: MessageActionHookOptions) => void; + onApplied?: (response: MessageActionResponse, options: MessageActionHookOptions) => void; + onUndoOptimistic?: (records: MessageActionRecord[]) => void; + onUndoCompleted?: (records: MessageActionRecord[], response: UndoMessageActionResponse) => void; + onUndoFailed?: (records: MessageActionRecord[]) => void; + onResync?: () => void; +}; + +/** + * Serializes actions per message id while letting unrelated messages proceed + * in parallel. A second action on the same message (including an undo) waits + * for the first response, so snapshots and UI patches cannot interleave. + */ +export class MessageActionExecutor { + private readonly tails = new Map>(); + + constructor( + private readonly transport: MessageActionTransport, + private readonly hooks: MessageActionExecutorHooks = {}, + ) {} + + async run(input: MessageActionInput, options: { notify?: boolean } = {}): Promise { + return this.withLocks(input.messageIds, async () => { + const hookOptions = { notify: options.notify !== false }; + this.hooks.onApplyOptimistic?.(input, hookOptions); + let response: MessageActionResponse | UndoMessageActionResponse; + try { + response = await this.transport({ op: "apply", ...input }); + } catch (error) { + this.hooks.onApplyFailed?.(input, hookOptions); + throw error; + } + if (!response || response.ok !== true || !("applied" in response) || !Array.isArray(response.applied) || !Array.isArray(response.skipped)) { + this.hooks.onApplyFailed?.(input, hookOptions); + throw new MessageActionRequestError("Unable to update message", 502); + } + const result = response as MessageActionResponse; + this.hooks.onApplied?.(result, hookOptions); + if (result.applied.length === 0 && result.skipped.length > 0) { + throw new MessageActionRequestError("No accessible messages", 404, result.skipped.length); + } + return result; + }); + } + + async undo(records: MessageActionRecord[], token: string | undefined): Promise { + if (!token) throw new MessageActionRequestError("This undo has expired", 410); + return this.withLocks(records.map((record) => record.id), async () => { + this.hooks.onUndoOptimistic?.(records); + try { + const response = await this.transport({ op: "undo", token }); + if (!response || response.ok !== true || !Array.isArray((response as UndoMessageActionResponse).restored)) { + throw new MessageActionRequestError("Could not undo that change", 502); + } + const result = response as UndoMessageActionResponse; + this.hooks.onUndoCompleted?.(records, result); + if (result.skipped.length > 0) this.hooks.onResync?.(); + return result; + } catch (error) { + this.hooks.onUndoFailed?.(records); + this.hooks.onResync?.(); + throw error; + } + }); + } + + private withLocks(ids: string[], task: () => Promise): Promise { + const keys = [...new Set(ids)]; + const previous = keys + .map((key) => this.tails.get(key)) + .filter((tail): tail is Promise => !!tail); + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const tail = Promise.allSettled(previous).then(() => gate); + for (const key of keys) this.tails.set(key, tail); + + return (async () => { + await Promise.allSettled(previous); + try { + return await task(); + } finally { + release(); + for (const key of keys) { + if (this.tails.get(key) === tail) this.tails.delete(key); + } + } + })(); + } +} + +export function getChangedRecords(records: MessageActionRecord[]): MessageActionRecord[] { + return records.filter(recordHasChanges); +} + +export function readPatchGroups(records: MessageActionRecord[], direction: "previous" | "applied") { + const groups = new Map(); + for (const record of records) { + if (record.previous.read === record.applied.read) continue; + const read = record[direction].read; + const ids = groups.get(read) ?? []; + ids.push(record.id); + groups.set(read, ids); + } + return groups; +} + +export function starPatchGroups(records: MessageActionRecord[], direction: "previous" | "applied") { + const groups = new Map(); + for (const record of records) { + if (record.previous.starred === record.applied.starred) continue; + const starred = record[direction].starred; + const ids = groups.get(starred) ?? []; + ids.push(record.id); + groups.set(starred, ids); + } + return groups; +} + +export function hasMembershipChange(record: MessageActionRecord): boolean { + return getChangedStateFields(record.previous, record.applied) + .some((field) => field === "status" || field === "folderId" || field === "snoozedUntil"); +} + +export function restoreSnapshots( + records: MessageActionRecord[], + state: (record: MessageActionRecord) => MessageStateSnapshot, +) { + return records.map((record) => ({ ...record, applied: state(record) })); +} diff --git a/src/lib/messages/actions/service.ts b/src/lib/messages/actions/service.ts new file mode 100644 index 000000000..7a6ee5534 --- /dev/null +++ b/src/lib/messages/actions/service.ts @@ -0,0 +1,351 @@ +import { and, eq, inArray, isNull } from "drizzle-orm"; +import type { AppDatabase } from "@/db"; +import { getDb } from "@/db"; +import { folders, messages } from "@/db/schema"; +import type { SessionUser } from "@/lib/auth/types"; +import { createAuditLogs } from "@/lib/mailboxes/audit"; +import { getMailboxAccessLevel } from "@/lib/mailboxes/access"; +import type { MailboxAccessLevel } from "@/lib/mailboxes/types"; +import { applySpamFeedback } from "@/lib/spam/feedback"; +import { + actionNeedsManage, + applySnapshotPatch, + getChangedStateFields, + getMessageActionPatch, + isReversibleMessageAction, + recordHasChanges, + snapshotMessageState, + planUndoRecord, + type MessageActionTarget, +} from "./definitions"; +import { signUndoTokenForEnv, verifyUndoTokenForEnv } from "./token"; +import type { + MessageActionInput, + MessageActionRecord, + MessageActionResponse, + MessageActionSkipped, + MessageStateSnapshot, + UndoMessageActionResponse, +} from "./types"; + +const MAX_ACTION_MESSAGES = 5000; +const MESSAGE_ID_CHUNK = 90; +const MESSAGE_QUERY_CONCURRENCY = 5; + +export class MessageActionError extends Error { + constructor( + message: string, + readonly status = 400, + ) { + super(message); + this.name = "MessageActionError"; + } +} + +type LoadedTarget = MessageActionTarget & { mailboxId: string | null }; + +function selectTargetChunk(db: AppDatabase, chunk: string[]) { + return db.select({ + id: messages.id, + mailboxId: messages.mailboxId, + direction: messages.direction, + status: messages.status, + read: messages.read, + starred: messages.starred, + folderId: messages.folderId, + snoozedUntil: messages.snoozedUntil, + }).from(messages).where(inArray(messages.id, chunk)); +} + +async function loadTargets(db: AppDatabase, ids: string[]): Promise { + const chunks: string[][] = []; + for (let index = 0; index < ids.length; index += MESSAGE_ID_CHUNK) chunks.push(ids.slice(index, index + MESSAGE_ID_CHUNK)); + const rows: LoadedTarget[] = []; + for (let index = 0; index < chunks.length; index += MESSAGE_QUERY_CONCURRENCY) { + const batch = await Promise.all(chunks.slice(index, index + MESSAGE_QUERY_CONCURRENCY).map((chunk) => selectTargetChunk(db, chunk))); + rows.push(...batch.flat()); + } + return rows; +} + +async function loadAccessMap( + db: AppDatabase, + user: SessionUser, + rows: Array<{ mailboxId: string | null }>, +): Promise> { + const ids = [...new Set(rows.map((row) => row.mailboxId).filter((id): id is string => !!id))]; + return new Map(await Promise.all(ids.map(async (id) => [id, await getMailboxAccessLevel(db, user, id)] as const))); +} + +function normalizeMessageIds(input: MessageActionInput): string[] { + if (!Array.isArray(input.messageIds)) throw new MessageActionError("Message IDs are required"); + const ids = [...new Set(input.messageIds.filter((id): id is string => typeof id === "string" && id.length > 0))]; + if (ids.length === 0) throw new MessageActionError("Message IDs are required"); + if (ids.length > MAX_ACTION_MESSAGES) throw new MessageActionError(`Select up to ${MAX_ACTION_MESSAGES} messages at a time`); + return ids; +} + +function toDatabasePatch(patch: Partial) { + const { snoozedUntil, ...fields } = patch; + return { + ...fields, + ...(snoozedUntil !== undefined + ? { snoozedUntil: snoozedUntil ? new Date(snoozedUntil) : null } + : {}), + }; +} + +function validateSnoozeTime(value: string | null | undefined): string { + if (typeof value !== "string") throw new MessageActionError("Choose a future snooze time"); + const date = new Date(value); + if (Number.isNaN(date.getTime()) || date <= new Date()) throw new MessageActionError("Choose a future snooze time"); + return date.toISOString(); +} + +async function loadActionFolder( + db: AppDatabase, + user: SessionUser, + folderId: string | null | undefined, +) { + if (!folderId) throw new MessageActionError("Folder is required"); + const [folder] = await db.select({ id: folders.id, mailboxId: folders.mailboxId }).from(folders).where(eq(folders.id, folderId)).limit(1); + if (!folder) throw new MessageActionError("Folder not found", 404); + const access = await getMailboxAccessLevel(db, user, folder.mailboxId); + if (!access?.canManage) throw new MessageActionError("Folder not found", 404); + return folder; +} + +/** Applies one explicit action and returns the exact before/after state of every message it changed. */ +export async function applyMessageActionForUser( + env: CloudflareEnv, + user: SessionUser, + input: MessageActionInput, +): Promise { + if (!isReversibleMessageAction(input.action)) throw new MessageActionError("Invalid message action"); + const action = input.action; + const ids = normalizeMessageIds(input); + const snoozedUntil = action === "snooze" ? validateSnoozeTime(input.snoozedUntil) : undefined; + const db = getDb(env); + const folder = action === "folder" ? await loadActionFolder(db, user, input.folderId) : null; + const rows = await loadTargets(db, ids); + if (rows.length === 0) throw new MessageActionError("No accessible messages", 404); + + const accessByMailbox = await loadAccessMap(db, user, rows); + const applied: MessageActionRecord[] = []; + const skipped: MessageActionSkipped[] = []; + const confirmed = new Set(); + const updates = new Map; ids: string[] }>(); + const seen = new Set(); + + for (const row of rows) { + seen.add(row.id); + if (!row.mailboxId) { + skipped.push({ id: row.id, reason: "not_found" }); + continue; + } + const access = accessByMailbox.get(row.mailboxId); + const required = actionNeedsManage(action) ? access?.canManage : access?.canRead; + if (!required) { + skipped.push({ id: row.id, reason: "forbidden" }); + continue; + } + if (action === "folder" && folder && row.mailboxId !== folder.mailboxId) { + skipped.push({ id: row.id, reason: "not_applicable" }); + continue; + } + + const result = getMessageActionPatch(action, { folderId: input.folderId, snoozedUntil }, row); + if (!result.patch) { + skipped.push({ id: row.id, reason: result.reason }); + continue; + } + const previous = snapshotMessageState(row); + const next = applySnapshotPatch(previous, result.patch); + + try { + if (action === "spam") { + const changed = await applySpamFeedback(env, user, row.id, "spam", access); + if (!changed) { + skipped.push({ id: row.id, reason: "not_applicable" }); + continue; + } + confirmed.add(row.id); + } + if (action === "inbox" && row.status === "spam") { + await applySpamFeedback(env, user, row.id, "ham", access); + } + } catch { + skipped.push({ id: row.id, reason: "failed" }); + continue; + } + + applied.push({ id: row.id, mailboxId: row.mailboxId, previous, applied: next }); + + // Spam feedback already wrote status/folder; every other path writes the full + // patch so the stored row is exactly the applied state the token promises. + if (action !== "spam") { + const patch = getChangedStateFields(previous, next).length > 0 ? result.patch : null; + if (patch) { + const key = JSON.stringify(patch); + const group = updates.get(key) ?? { patch, ids: [] }; + group.ids.push(row.id); + updates.set(key, group); + } else { + confirmed.add(row.id); + } + } + } + + for (const missing of ids.filter((id) => !seen.has(id))) { + skipped.push({ id: missing, reason: "not_found" }); + } + + for (const group of updates.values()) { + for (let index = 0; index < group.ids.length; index += MESSAGE_ID_CHUNK) { + const chunk = group.ids.slice(index, index + MESSAGE_ID_CHUNK); + try { + await db.update(messages).set(toDatabasePatch(group.patch)).where(inArray(messages.id, chunk)); + for (const id of chunk) confirmed.add(id); + } catch { + for (const id of chunk) skipped.push({ id, reason: "failed" }); + } + } + } + + const confirmedApplied = applied.filter((record) => confirmed.has(record.id)); + if (confirmedApplied.length === 0 && skipped.some((item) => item.reason === "failed")) { + throw new MessageActionError("Could not update messages", 500); + } + + const changedRecords = confirmedApplied.filter(recordHasChanges); + const auditRecords = action === "spam" + ? [] + : action === "inbox" + ? changedRecords.filter((record) => record.previous.status !== "spam") + : changedRecords; + if (auditRecords.length > 0) { + await createAuditLogs(env, auditRecords.map((record) => ({ + actorUserId: user.id, + messageId: record.id, + action: action === "read" || action === "unread" ? "email.read" : "email.delete", + metadata: { messageAction: action }, + }))); + } + + const undoToken = changedRecords.length > 0 + ? await signUndoTokenForEnv(env, { + v: 1, + issuedAt: Date.now(), + action, + records: changedRecords, + }) + : undefined; + + return { ok: true, action, applied: confirmedApplied, skipped, undoToken }; +} + +/** Restores only the fields the signed action changed, and only while they still hold its result. */ +export async function undoMessageActionForUser( + env: CloudflareEnv, + user: SessionUser, + token: string, +): Promise { + const payload = await verifyUndoTokenForEnv(env, token); + if (!payload || !isReversibleMessageAction(payload.action)) { + throw new MessageActionError("This undo has expired", 410); + } + if (payload.records.length === 0) throw new MessageActionError("Nothing to undo"); + if (payload.records.length > MAX_ACTION_MESSAGES) throw new MessageActionError("Too many messages to undo"); + + const records = [...new Map(payload.records.map((record) => [record.id, record])).values()]; + const db = getDb(env); + const ids = records.map((record) => record.id); + const rows = await loadTargets(db, ids); + const byId = new Map(rows.map((row) => [row.id, row])); + const accessByMailbox = await loadAccessMap(db, user, rows); + const folderIds = [...new Set(records.map((record) => record.previous.folderId).filter((id): id is string => !!id))]; + const folderMailboxes = new Map(); + for (let index = 0; index < folderIds.length; index += MESSAGE_ID_CHUNK) { + const chunk = folderIds.slice(index, index + MESSAGE_ID_CHUNK); + const folderRows = await db.select({ id: folders.id, mailboxId: folders.mailboxId }).from(folders).where(inArray(folders.id, chunk)); + for (const folder of folderRows) folderMailboxes.set(folder.id, folder.mailboxId); + } + + const restored: string[] = []; + const skipped: MessageActionSkipped[] = []; + const updates = new Map; + fields: (keyof MessageStateSnapshot)[]; + applied: MessageStateSnapshot; + ids: string[]; + }>(); + + for (const record of records) { + const current = byId.get(record.id); + if (!current) { + skipped.push({ id: record.id, reason: "not_found" }); + continue; + } + const access = current.mailboxId ? accessByMailbox.get(current.mailboxId) : null; + const plan = planUndoRecord( + record, + current, + { canRead: !!access?.canRead, canManage: !!access?.canManage }, + record.previous.folderId ? folderMailboxes.get(record.previous.folderId) : null, + ); + if (!("patch" in plan)) { + skipped.push({ id: plan.id, reason: plan.reason }); + continue; + } + const key = JSON.stringify({ patch: plan.patch, applied: plan.fields.map((field) => record.applied[field]) }); + const group = updates.get(key) ?? { patch: plan.patch, fields: plan.fields, applied: record.applied, ids: [] }; + group.ids.push(record.id); + updates.set(key, group); + } + + for (const group of updates.values()) { + for (let index = 0; index < group.ids.length; index += MESSAGE_ID_CHUNK) { + const chunk = group.ids.slice(index, index + MESSAGE_ID_CHUNK); + const conditions = [inArray(messages.id, chunk)]; + for (const field of group.fields) { + const expected = group.applied[field]; + if (field === "status") conditions.push(eq(messages.status, expected as string)); + else if (field === "read") conditions.push(eq(messages.read, expected as boolean)); + else if (field === "starred") conditions.push(eq(messages.starred, expected as boolean)); + else if (field === "folderId") conditions.push(expected === null ? isNull(messages.folderId) : eq(messages.folderId, expected as string)); + else if (field === "snoozedUntil") conditions.push(expected === null ? isNull(messages.snoozedUntil) : eq(messages.snoozedUntil, new Date(expected as string))); + } + try { + // Compare-and-swap on the exact fields the action wrote, so a later + // change in another tab or request wins instead of being clobbered. + const updated = await db.update(messages) + .set(toDatabasePatch(group.patch)) + .where(and(...conditions)) + .returning({ id: messages.id }); + const updatedIds = new Set(updated.map((row) => row.id)); + for (const id of chunk) { + if (updatedIds.has(id)) restored.push(id); + else skipped.push({ id, reason: "stale" }); + } + } catch { + for (const id of chunk) skipped.push({ id, reason: "failed" }); + } + } + } + + if (restored.length > 0) { + const restoredSet = new Set(restored); + await createAuditLogs(env, records + .filter((record) => restoredSet.has(record.id)) + .map((record) => ({ + actorUserId: user.id, + messageId: record.id, + action: getChangedStateFields(record.previous, record.applied).every((field) => field === "read" || field === "starred") + ? "email.read" + : "email.delete", + metadata: { undoOf: payload.action }, + }))); + } + + return { ok: true, action: payload.action, restored, skipped }; +} diff --git a/src/lib/messages/actions/token.ts b/src/lib/messages/actions/token.ts new file mode 100644 index 000000000..e4e9f646a --- /dev/null +++ b/src/lib/messages/actions/token.ts @@ -0,0 +1,85 @@ +import { getServerSecret } from "@/lib/security/server-secret"; +import type { MessageUndoTokenPayload } from "./types"; + +const TOKEN_VERSION = 1; +const MAX_UNDO_AGE_MS = 10 * 60_000; +const CLOCK_SKEW_MS = 60_000; + +function bytesToBase64Url(bytes: Uint8Array): string { + let binary = ""; + for (let index = 0; index < bytes.length; index += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000)); + } + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); +} + +function base64UrlToBytes(value: string): Uint8Array | null { + try { + const padded = value.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - value.length % 4) % 4); + const binary = atob(padded); + return Uint8Array.from(binary, (character) => character.charCodeAt(0)); + } catch { + return null; + } +} + +async function importTokenKey(secret: string): Promise { + return crypto.subtle.importKey( + "raw", + new TextEncoder().encode(`message-action-undo\n${secret}`), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign", "verify"], + ); +} + +/** Signs the exact server-confirmed before/after states, so a client cannot invent an undo. */ +export async function signUndoToken(secret: string, payload: MessageUndoTokenPayload): Promise { + const body = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload))); + const signature = await crypto.subtle.sign("HMAC", await importTokenKey(secret), new TextEncoder().encode(body)); + return `${body}.${bytesToBase64Url(new Uint8Array(signature))}`; +} + +/** Returns null for tampered, malformed or expired tokens. */ +export async function verifyUndoToken( + secret: string, + token: string, + now = Date.now(), +): Promise { + const [body, signature] = token.split("."); + if (!body || !signature) return null; + const signatureBytes = base64UrlToBytes(signature); + if (!signatureBytes) return null; + const signatureBuffer = new ArrayBuffer(signatureBytes.length); + new Uint8Array(signatureBuffer).set(signatureBytes); + const valid = await crypto.subtle.verify( + "HMAC", + await importTokenKey(secret), + signatureBuffer, + new TextEncoder().encode(body), + ); + if (!valid) return null; + const bodyBytes = base64UrlToBytes(body); + if (!bodyBytes) return null; + let payload: MessageUndoTokenPayload; + try { + payload = JSON.parse(new TextDecoder().decode(bodyBytes)) as MessageUndoTokenPayload; + } catch { + return null; + } + if (payload?.v !== TOKEN_VERSION || typeof payload.issuedAt !== "number" || !Array.isArray(payload.records)) return null; + if (payload.issuedAt > now + CLOCK_SKEW_MS || payload.issuedAt < now - MAX_UNDO_AGE_MS) return null; + return payload; +} + +export async function signUndoTokenForEnv(env: CloudflareEnv, payload: MessageUndoTokenPayload): Promise { + return signUndoToken(await getServerSecret(env), payload); +} + +export async function verifyUndoTokenForEnv( + env: CloudflareEnv, + token: string, + now = Date.now(), +): Promise { + return verifyUndoToken(await getServerSecret(env), token, now); +} diff --git a/src/lib/messages/actions/types.d.ts b/src/lib/messages/actions/types.d.ts new file mode 100644 index 000000000..dc9b00c35 --- /dev/null +++ b/src/lib/messages/actions/types.d.ts @@ -0,0 +1,92 @@ +/** Explicit message actions whose effect can be reverted from the undo toast. */ +export type ReversibleMessageAction = + | "archive" + | "trash" + | "spam" + | "inbox" + | "folder" + | "read" + | "unread" + | "star" + | "unstar" + | "snooze" + | "unsnooze"; + +/** The message fields an action may change. Undo restores only the fields it changed. */ +export type MessageStateSnapshot = { + status: string; + read: boolean; + starred: boolean; + folderId: string | null; + snoozedUntil: string | null; +}; + +export type MessageStateField = keyof MessageStateSnapshot; + +/** One successfully applied message, with the server-confirmed before and after states. */ +export type MessageActionRecord = { + id: string; + mailboxId: string | null; + previous: MessageStateSnapshot; + applied: MessageStateSnapshot; +}; + +export type MessageActionSkipReason = + | "not_found" + | "forbidden" + | "not_applicable" + | "invalid_target" + | "stale" + | "failed"; + +export type MessageActionSkipped = { + id: string; + reason: MessageActionSkipReason; +}; + +export type MessageActionInput = { + action: ReversibleMessageAction; + messageIds: string[]; + folderId?: string | null; + snoozedUntil?: string | null; +}; + +export type MessageActionResponse = { + ok: true; + action: ReversibleMessageAction; + applied: MessageActionRecord[]; + skipped: MessageActionSkipped[]; + /** Signed, short-lived proof of the server-confirmed previous states. */ + undoToken?: string; +}; + +export type UndoMessageActionResponse = { + ok: true; + action: ReversibleMessageAction; + restored: string[]; + skipped: MessageActionSkipped[]; +}; + +/** Payload carried by the signed undo token; never trusted from the request body directly. */ +export type MessageUndoTokenPayload = { + v: 1; + issuedAt: number; + action: ReversibleMessageAction; + records: MessageActionRecord[]; +}; + +export type MessageActionRequestOptions = { + /** Show the independent undo toast. Defaults to true for explicit actions. */ + undo?: boolean; + /** Suppress the global cache/change event; the caller owns optimistic state. */ + notify?: boolean; +}; + +export type MessageActionTransportBody = + | ({ + op: "apply"; + } & MessageActionInput) + | { + op: "undo"; + token: string; + }; diff --git a/src/lib/messages/actions/undo-store.ts b/src/lib/messages/actions/undo-store.ts new file mode 100644 index 000000000..ab63ae85c --- /dev/null +++ b/src/lib/messages/actions/undo-store.ts @@ -0,0 +1,104 @@ +"use client"; + +import type { MessageActionRecord, ReversibleMessageAction } from "./types"; + +export type UndoToastStatus = "idle" | "undoing" | "failed"; + +export type UndoToastEntry = { + id: number; + action: ReversibleMessageAction; + records: MessageActionRecord[]; + undoToken: string; + skipped: number; + status: UndoToastStatus; +}; + +const UNDO_WINDOW_MS = 9000; +const FAILED_WINDOW_MS = 5000; +const MAX_TOASTS = 4; + +let entries: UndoToastEntry[] = []; +let nextId = 0; +const timers = new Map(); +const listeners = new Set<() => void>(); + +function emit() { + for (const listener of listeners) listener(); +} + +function setTimer(id: number, delay: number) { + if (typeof window === "undefined") return; + const existing = timers.get(id); + if (existing) window.clearTimeout(existing); + timers.set(id, window.setTimeout(() => { + timers.delete(id); + dismissUndoToast(id); + }, delay)); +} + +function clearTimer(id: number) { + if (typeof window === "undefined") return; + const timer = timers.get(id); + if (timer) window.clearTimeout(timer); + timers.delete(id); +} + +export function subscribeUndoToasts(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +export function getUndoToasts(): UndoToastEntry[] { + return entries; +} + +/** Adds an independent toast; compose's single send notice is never touched. */ +export function showUndoToast(input: { + action: ReversibleMessageAction; + records: MessageActionRecord[]; + undoToken?: string; + skipped?: number; +}): number | null { + if (!input.undoToken || input.records.length === 0 || typeof window === "undefined") return null; + const id = ++nextId; + entries = [ + ...entries.slice(-(MAX_TOASTS - 1)), + { + id, + action: input.action, + records: input.records, + undoToken: input.undoToken, + skipped: input.skipped ?? 0, + status: "idle", + }, + ]; + setTimer(id, UNDO_WINDOW_MS); + emit(); + return id; +} + +export function beginUndoToast(id: number) { + clearTimer(id); + entries = entries.map((entry) => (entry.id === id ? { ...entry, status: "undoing" } : entry)); + emit(); +} + +export function failUndoToast(id: number) { + entries = entries.map((entry) => (entry.id === id ? { ...entry, status: "failed" } : entry)); + setTimer(id, FAILED_WINDOW_MS); + emit(); +} + +export function dismissUndoToast(id: number) { + clearTimer(id); + entries = entries.filter((entry) => entry.id !== id); + emit(); +} + +/** Test-only reset; the provider never calls this. */ +export function resetUndoToastsForTests() { + for (const id of timers.keys()) clearTimer(id); + entries = []; + nextId = 0; + emit(); +} diff --git a/src/lib/messages/detail-cache.ts b/src/lib/messages/detail-cache.ts index 8d6f24455..d56527214 100644 --- a/src/lib/messages/detail-cache.ts +++ b/src/lib/messages/detail-cache.ts @@ -40,6 +40,12 @@ export function setCachedMessageRead(messageId: string, read: boolean): void { if (cached?.message) cacheDetail(messageId, { ...cached, message: { ...cached.message, read } }); } +/** Field-scoped detail patch for star toggles and undo; read still goes through setCachedMessageRead. */ +export function patchCachedMessage(messageId: string, patch: { read?: boolean; starred?: boolean }): void { + const cached = getCachedMessageDetail(messageId); + if (cached?.message) cacheDetail(messageId, { ...cached, message: { ...cached.message, ...patch } }); +} + /** Merge the row header into the cache; a missing body is fetched separately. */ export function primeMessageDetail(message: Message): void { const cached = getCachedMessageDetail(message.id); diff --git a/tests/message-action-undo.test.mjs b/tests/message-action-undo.test.mjs new file mode 100644 index 000000000..0b7e97502 --- /dev/null +++ b/tests/message-action-undo.test.mjs @@ -0,0 +1,361 @@ +import assert from "node:assert/strict"; +import { readFileSync, readdirSync, mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-undo-actions-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +await build({ + stdin: { + contents: ` + export { + getMessageActionPatch, getChangedStateFields, recordHasChanges, planUndoRecord, snapshotMessageState, + } from "./src/lib/messages/actions/definitions.ts"; + export { + MessageActionExecutor, MessageActionRequestError, getChangedRecords, readPatchGroups, hasMembershipChange, + } from "./src/lib/messages/actions/executor.ts"; + export { signUndoToken, verifyUndoToken } from "./src/lib/messages/actions/token.ts"; + `, + resolveDir: root, + sourcefile: "message-action-undo-entry.ts", + }, + outfile: join(directory, "entry.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" }, + logLevel: "silent", +}); +const m = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +await build({ + entryPoints: [join(root, "src/hooks/utils.ts")], + outfile: join(directory, "cache.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + logLevel: "silent", +}); +const cache = await import(pathToFileURL(join(directory, "cache.mjs")).href); + +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); + +const record = (previous, applied, overrides = {}) => ({ + id: "m1", + mailboxId: "mb1", + previous, + applied, + ...overrides, +}); + +const target = (overrides = {}) => ({ + id: "m1", + mailboxId: "mb1", + direction: "inbound", + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); + +test("actions write only their reversible fields", () => { + assert.deepEqual(m.getMessageActionPatch("archive", {}, target()).patch, { status: "archived", folderId: null }); + assert.deepEqual(m.getMessageActionPatch("trash", {}, target()).patch, { status: "trash", folderId: null }); + assert.deepEqual(m.getMessageActionPatch("inbox", {}, target()).patch, { status: "received", folderId: null, snoozedUntil: null }); + assert.deepEqual(m.getMessageActionPatch("folder", { folderId: "f1" }, target()).patch, { status: "received", folderId: "f1" }); + assert.deepEqual(m.getMessageActionPatch("read", {}, target()).patch, { read: true }); + assert.deepEqual(m.getMessageActionPatch("star", {}, target()).patch, { starred: true }); + assert.equal(m.getMessageActionPatch("spam", {}, target({ direction: "outbound" })).reason, "not_applicable"); + assert.equal(m.getMessageActionPatch("snooze", { snoozedUntil: "2000-01-01T00:00:00.000Z" }, target()).reason, "invalid_target"); + assert.equal(m.getMessageActionPatch("folder", {}, target()).reason, "invalid_target"); +}); + +test("only fields the action changed are marked for undo", () => { + const previous = state({ read: true }); + const applied = state({ read: true, status: "archived", folderId: "f1" }); + assert.deepEqual(m.getChangedStateFields(previous, applied), ["status", "folderId"]); + assert.equal(m.recordHasChanges({ previous, applied }), true); + assert.equal(m.recordHasChanges({ previous, applied: previous }), false); +}); + +test("undo restores read with read access and status with manage access", () => { + const previous = state(); + const applied = state({ read: true }); + const readPlan = m.planUndoRecord(record(previous, applied), target({ read: true }), { canRead: true, canManage: false }, null); + assert.deepEqual(readPlan.patch, { read: false }); + assert.deepEqual(readPlan.fields, ["read"]); + + const archivePrevious = state({ status: "received", folderId: "f1" }); + const archiveApplied = state({ status: "archived", folderId: null }); + const archiveCurrent = target({ status: "archived", folderId: null }); + const forbidden = m.planUndoRecord(record(archivePrevious, archiveApplied), archiveCurrent, { canRead: true, canManage: false }, "mb1"); + assert.equal(forbidden.reason, "forbidden"); + const allowed = m.planUndoRecord(record(archivePrevious, archiveApplied), archiveCurrent, { canRead: true, canManage: true }, "mb1"); + assert.deepEqual(allowed.patch, { status: "received", folderId: "f1" }); +}); + +test("undo rejects a foreign folder, a foreign mailbox and malformed snapshots", () => { + const previous = state({ status: "archived", folderId: "foreign" }); + const applied = state(); + assert.equal(m.planUndoRecord(record(previous, applied), target(), { canRead: true, canManage: true }, "other-mailbox").reason, "invalid_target"); + assert.equal(m.planUndoRecord(record(previous, applied, { mailboxId: "other" }), target(), { canRead: true, canManage: true }, "mb1").reason, "forbidden"); + assert.equal(m.planUndoRecord(record(state({ status: "hacked" }), applied), target(), { canRead: true, canManage: true }, null).reason, "invalid_target"); +}); + +test("undo is skipped when a later action changed the same field", () => { + const previous = state(); + const applied = state({ status: "archived" }); + assert.equal(m.planUndoRecord(record(previous, applied), target({ status: "trash" }), { canRead: true, canManage: true }, null).reason, "stale"); + // A different field changed later does not block restoring the action's field. + const starredLater = target({ status: "archived", starred: true }); + assert.deepEqual(m.planUndoRecord(record(previous, applied), starredLater, { canRead: true, canManage: true }, null).patch, { status: "received" }); +}); + +test("a mixed undo restores eligible messages and reports the rest", () => { + const previous = state(); + const applied = state({ read: true }); + const records = [ + record(previous, applied, { id: "m1" }), + record(previous, applied, { id: "m2" }), + record(previous, applied, { id: "m3" }), + ]; + const current = new Map([ + ["m1", target({ id: "m1", read: true })], + ["m2", target({ id: "m2", read: false })], + ]); + const restored = []; + const skipped = []; + for (const item of records) { + const now = current.get(item.id); + if (!now) { + skipped.push(item.id); + continue; + } + const plan = m.planUndoRecord(item, now, { canRead: true, canManage: true }, null); + if (plan.patch) restored.push(item.id); + else skipped.push(plan.reason); + } + assert.deepEqual(restored, ["m1"]); + assert.deepEqual(skipped, ["stale", "m3"]); +}); + +test("signed undo tokens carry the exact server records and reject tampering or expiry", async () => { + const payload = { v: 1, issuedAt: Date.now(), action: "archive", records: [record(state(), state({ status: "archived" }))] }; + const token = await m.signUndoToken("test-secret", payload); + const verified = await m.verifyUndoToken("test-secret", token); + assert.deepEqual(verified.records, payload.records); + assert.equal(await m.verifyUndoToken("other-secret", token), null); + assert.equal(await m.verifyUndoToken("test-secret", `${token.slice(0, -2)}xx`), null); + assert.equal(await m.verifyUndoToken("test-secret", token, payload.issuedAt + 11 * 60_000), null); +}); + +function applyResponse(overrides = {}) { + return { + ok: true, + action: "read", + applied: [record(state(), state({ read: true }))], + skipped: [], + undoToken: "token", + ...overrides, + }; +} + +test("the executor reports a successful apply after the server confirms it", async () => { + const calls = []; + const applied = []; + const executor = new m.MessageActionExecutor( + async (body) => { calls.push(body); return applyResponse(); }, + { onApplied: (response, options) => applied.push({ response, options }) }, + ); + const result = await executor.run({ action: "read", messageIds: ["m1"] }); + assert.equal(result.applied.length, 1); + assert.equal(calls[0].op, "apply"); + assert.deepEqual(applied[0].options, { notify: true }); + assert.equal(m.getChangedRecords(result.applied).length, 1); + assert.deepEqual([...m.readPatchGroups(result.applied, "applied")], [[true, ["m1"]]]); +}); + +test("a future optimistic apply can patch before the request and roll back on failure", async () => { + const order = []; + const executor = new m.MessageActionExecutor( + async () => { + order.push("request"); + throw new Error("network down"); + }, + { + onApplyOptimistic: () => order.push("optimistic"), + onApplyFailed: () => order.push("rollback"), + }, + ); + await assert.rejects(executor.run({ action: "read", messageIds: ["m1"] }), /network down/); + assert.deepEqual(order, ["optimistic", "request", "rollback"]); +}); + +test("an apply failure does not run success hooks", async () => { + let applied = 0; + const executor = new m.MessageActionExecutor( + async () => { throw new Error("network down"); }, + { onApplied: () => { applied += 1; } }, + ); + await assert.rejects(executor.run({ action: "archive", messageIds: ["m1"] }), /network down/); + assert.equal(applied, 0); +}); + +test("undo runs an optimistic hook before the request and rolls back on failure", async () => { + const order = []; + const executor = new m.MessageActionExecutor( + async () => { + order.push("request"); + throw new Error("undo failed"); + }, + { + onUndoOptimistic: () => order.push("optimistic"), + onUndoFailed: () => order.push("failed"), + onResync: () => order.push("resync"), + }, + ); + await assert.rejects(executor.undo([record(state(), state({ read: true }))], "token"), /undo failed/); + assert.deepEqual(order, ["optimistic", "request", "failed", "resync"]); +}); + +test("undo resyncs when the server reports stale or missing messages", async () => { + const order = []; + const executor = new m.MessageActionExecutor( + async () => ({ ok: true, action: "read", restored: ["m1"], skipped: [{ id: "m2", reason: "stale" }] }), + { + onUndoOptimistic: () => order.push("optimistic"), + onUndoCompleted: () => order.push("completed"), + onResync: () => order.push("resync"), + }, + ); + const result = await executor.undo([record(state(), state({ read: true }))], "token"); + assert.deepEqual(result.restored, ["m1"]); + assert.deepEqual(order, ["optimistic", "completed", "resync"]); +}); + +test("actions on the same message are serialized, including an undo behind an apply", async () => { + const events = []; + let resolveApply; + const executor = new m.MessageActionExecutor(async (body) => { + events.push(`start:${body.op}`); + if (body.op === "apply") { + await new Promise((resolve) => { resolveApply = resolve; }); + events.push("end:apply"); + return applyResponse(); + } + events.push("undo"); + return { ok: true, action: "read", restored: ["m1"], skipped: [] }; + }); + const apply = executor.run({ action: "read", messageIds: ["m1"] }); + await Promise.resolve(); + const undo = executor.undo([record(state(), state({ read: true }))], "token"); + await Promise.resolve(); + assert.deepEqual(events, ["start:apply"]); + resolveApply(); + await Promise.all([apply, undo]); + assert.deepEqual(events, ["start:apply", "end:apply", "start:undo", "undo"]); +}); + +test("unrelated messages still run concurrently and refetching cannot interleave with a same-id undo", async () => { + const events = []; + let resolveFirst; + const executor = new m.MessageActionExecutor(async (body) => { + events.push(`${body.op}:${body.messageIds?.[0]}`); + if (body.messageIds?.[0] === "m1" && body.op === "apply") await new Promise((resolve) => { resolveFirst = resolve; }); + return body.op === "apply" ? applyResponse() : { ok: true, action: "read", restored: [], skipped: [] }; + }); + const first = executor.run({ action: "read", messageIds: ["m1"] }); + const second = executor.run({ action: "read", messageIds: ["m2"] }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(events.sort(), ["apply:m1", "apply:m2"]); + resolveFirst(); + await Promise.all([first, second]); +}); + +test("membership changes are distinguished from read/star-only patches", () => { + assert.equal(m.hasMembershipChange(record(state(), state({ read: true }))), false); + assert.equal(m.hasMembershipChange(record(state(), state({ status: "archived" }))), true); +}); + +test("a stale list response cannot overwrite a read patch made while it was in flight", async () => { + const originalFetch = globalThis.fetch; + let resolveStale; + let calls = 0; + globalThis.fetch = async () => { + calls += 1; + if (calls === 1) return new Promise((resolve) => { resolveStale = resolve; }); + return Response.json({ messages: [{ id: "m1", read: true }], total: 1, limit: 25, offset: 0 }); + }; + try { + const params = new URLSearchParams({ stale: "1" }); + const stale = cache.fetchMessageList(params, true); + await Promise.resolve(); + // A read undo/refetch invalidates the request map before the old response lands. + cache.invalidateMessageListRequests(); + resolveStale(Response.json({ messages: [{ id: "m1", read: false }], total: 1, limit: 25, offset: 0 })); + await stale; + assert.equal(cache.peekMessageList(params), undefined); + const fresh = await cache.fetchMessageList(params); + assert.equal(fresh.messages[0].read, true); + assert.equal(calls, 2); + cache.patchMessagesInCaches(["m1"], { read: false }); + assert.equal(cache.peekMessageList(params).messages[0].read, false); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("every catalog carries the undo keys with identical placeholders", () => { + const en = JSON.parse(readFileSync(join(root, "src/lib/i18n/en.json"), "utf8")); + const undoKeys = Object.keys(en).filter((key) => key.startsWith("undo.")); + assert.ok(undoKeys.length >= 17); + for (const file of readdirSync(join(root, "public", "locales")).filter((name) => name.endsWith(".json"))) { + const catalog = JSON.parse(readFileSync(join(root, "public", "locales", file), "utf8")); + for (const key of undoKeys) assert.equal(catalog[key], en[key], `${file}: ${key}`); + } +}); + +test("all message entry points use the shared action layer and keep undirected reads quiet", () => { + const read = (path) => readFileSync(join(root, path), "utf8"); + assert.match(read("src/components/messages/utils.ts"), /performMessageAction/); + assert.match(read("src/components/message-actions/utils.ts"), /performMessageAction/); + assert.match(read("src/components/dashboard-nav-utils.ts"), /performMessageAction/); + assert.match(read("src/components/messages/message-list-row-actions-utils.ts"), /performMessageAction/); + for (const path of [ + "src/components/messages/bulk-message-action-bar.tsx", + "src/components/message-actions/message-actions.tsx", + "src/components/messages/thread-message-actions.tsx", + ]) { + assert.match(read(path), /run(Bulk|Single)MessageAction/); + } + // Opening a message and expanding a thread are not explicit read toasts. + assert.match(read("src/components/mark-read.ts"), /\/read`/); + assert.doesNotMatch(read("src/components/mark-read.ts"), /undo-store|performMessageAction/); + assert.match(read("src/components/messages/conversation-thread.tsx"), /runSingleMessageAction\(message\.id, "read", \{ undo: false \}\)/); + // Block and unsubscribe outcomes are not offered as message undo. + assert.match(read("src/components/message-actions/message-actions.tsx"), /runSingleMessageAction\(messageId, "trash", \{ undo: false \}\)/); + // Star sends the desired state through the shared layer, and the legacy endpoint stays a toggle. + assert.match(read("src/app/api/messages/[messageId]/star/route.ts"), /payload\.starred \?\? !message\.starred/); + // Undo lives in its own toast stack, not the single-slot compose notice. + assert.match(read("src/app/(dashboard)/layout.tsx"), //); + assert.doesNotMatch(read("src/components/messages/undo-toasts.tsx"), /compose-context|useCompose/); +}); From c5d6f82455fe6fc5fe2200143a745da4d3ccc5bf Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 21:37:01 +0100 Subject: [PATCH 02/15] fix(messages): keep undo state optimistic across client caches --- .../messages/message-thread-cache.ts | 23 ++- src/components/messages/use-message-thread.ts | 19 ++- src/hooks/use-message-counts.ts | 3 +- src/hooks/use-messages.ts | 23 ++- src/hooks/utils.ts | 3 + src/lib/messages/actions/client.ts | 101 +++++++++---- src/lib/messages/actions/definitions.ts | 8 +- src/lib/messages/actions/executor.ts | 25 ++-- src/lib/messages/change-events.ts | 17 ++- src/lib/messages/detail-cache.ts | 11 ++ src/lib/messages/field-store.ts | 49 +++++++ tests/e2e/message-undo.spec.ts | 88 ++++++++++++ tests/message-action-undo.test.mjs | 135 +++++++++++++++++- 13 files changed, 450 insertions(+), 55 deletions(-) create mode 100644 src/lib/messages/field-store.ts create mode 100644 tests/e2e/message-undo.spec.ts diff --git a/src/components/messages/message-thread-cache.ts b/src/components/messages/message-thread-cache.ts index 18097ad3f..4576821f1 100644 --- a/src/components/messages/message-thread-cache.ts +++ b/src/components/messages/message-thread-cache.ts @@ -1,5 +1,6 @@ import { AUTH_SESSION_CHANGED_EVENT, authFetch } from "@/lib/auth/client"; -import { getMessagesChangedDetail, isReadOnlyChange } from "@/lib/messages/change-events"; +import { getMessagesChangedDetail } from "@/lib/messages/change-events"; +import { rememberMessageFields, rememberMessageRows } from "@/lib/messages/field-store"; import type { ThreadMessage, ThreadResponse } from "@/hooks/types"; const CACHE_TTL_MS = 60_000; @@ -31,6 +32,7 @@ function cacheThread(messageId: string, messages: ThreadMessage[]): void { if (messages.length > MAX_CACHED_MESSAGES || bodyChars(messages) > MAX_CACHED_BODY_CHARS) return; threadCache.delete(messageId); threadCache.set(messageId, { messages, expiresAt: Date.now() + CACHE_TTL_MS }); + rememberMessageRows(messages); if (threadCache.size > CACHE_LIMIT) { const oldest = threadCache.keys().next().value; if (oldest) threadCache.delete(oldest); @@ -90,6 +92,7 @@ export function patchMessageThreadFieldsInCaches( messages: cached.messages.map((message) => (ids.has(message.id) ? { ...message, ...patch } : message)), }); } + rememberMessageFields(messageIds, patch); } export function markMessageThreadReadInCaches(messageIds: string[], read: boolean): void { @@ -105,13 +108,23 @@ export function clearMessageThreadCache(): void { if (typeof window !== "undefined") { window.addEventListener(AUTH_SESSION_CHANGED_EVENT, clearMessageThreadCache); window.addEventListener("mailflare:messages-changed", (event) => { - if (!isReadOnlyChange(event)) { + const detail = getMessagesChangedDetail(event); + if (!detail?.kind) { clearMessageThreadCache(); return; } - const detail = getMessagesChangedDetail(event); - if (detail?.messageIds?.length) { - markMessageThreadReadInCaches(detail.messageIds, detail.read !== false); + if (detail.kind === "read") { + if (detail.messageIds?.length) markMessageThreadReadInCaches(detail.messageIds, detail.read !== false); + return; + } + for (const patch of detail.patches ?? []) { + patchMessageThreadFieldsInCaches([patch.id], { + ...(patch.read !== undefined ? { read: patch.read } : {}), + ...(patch.starred !== undefined ? { starred: patch.starred } : {}), + }); } + // A settled star patch still needs the server's folder membership; an + // optimistic one must keep the patched conversation on screen. + if (!detail.deferRefresh) clearMessageThreadCache(); }); } diff --git a/src/components/messages/use-message-thread.ts b/src/components/messages/use-message-thread.ts index 0b765ff61..69e25f53c 100644 --- a/src/components/messages/use-message-thread.ts +++ b/src/components/messages/use-message-thread.ts @@ -54,7 +54,22 @@ export function useMessageThread(messageId: string, threadId: string | null | un markMessageThreadReadInCaches(detail.messageIds, read); setMessages((current) => current.map((message) => (ids.has(message.id) ? { ...message, read } : message))); } - function scheduleLoad() { + function patchFieldState(event: Event) { + const detail = (event as CustomEvent<{ kind?: string; patches?: Array<{ id: string; read?: boolean; starred?: boolean }> }>).detail; + if (detail?.kind !== "patch" || !detail.patches?.length) return; + const patches = new Map(detail.patches.map((patch) => [patch.id, patch])); + setMessages((current) => current.map((message) => { + const patch = patches.get(message.id); + if (!patch) return message; + return { + ...message, + ...(patch.read !== undefined ? { read: patch.read } : {}), + ...(patch.starred !== undefined ? { starred: patch.starred } : {}), + }; + })); + } + function scheduleLoad(event?: Event) { + if ((event as CustomEvent<{ deferRefresh?: boolean }> | undefined)?.detail?.deferRefresh) return; if (document.visibilityState !== "visible") return; if (refreshTimer) window.clearTimeout(refreshTimer); refreshTimer = window.setTimeout(() => { @@ -64,10 +79,12 @@ export function useMessageThread(messageId: string, threadId: string | null | un } window.addEventListener("mailflare:messages-changed", scheduleLoad); window.addEventListener("mailflare:messages-changed", patchReadState); + window.addEventListener("mailflare:messages-changed", patchFieldState); return () => { cancelled = true; window.removeEventListener("mailflare:messages-changed", scheduleLoad); window.removeEventListener("mailflare:messages-changed", patchReadState); + window.removeEventListener("mailflare:messages-changed", patchFieldState); if (refreshTimer) window.clearTimeout(refreshTimer); }; }, [messageId, threadId]); diff --git a/src/hooks/use-message-counts.ts b/src/hooks/use-message-counts.ts index 0fdcd4e5a..1224030a1 100644 --- a/src/hooks/use-message-counts.ts +++ b/src/hooks/use-message-counts.ts @@ -44,7 +44,8 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) { } void loadCounts(); - function onMessagesChanged() { + function onMessagesChanged(event: Event) { + if ((event as CustomEvent<{ deferRefresh?: boolean }>).detail?.deferRefresh) return; clearMessageCountsCache(); if (document.visibilityState !== "visible") return; if (refreshTimer) window.clearTimeout(refreshTimer); diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts index e8b21e69e..8bf6825e6 100644 --- a/src/hooks/use-messages.ts +++ b/src/hooks/use-messages.ts @@ -69,12 +69,27 @@ export function useMessages( return ids.has(message.id) ? { ...message, read } : message; })); } + function patchFieldState(event: Event) { + const detail = (event as CustomEvent<{ kind?: string; patches?: Array<{ id: string; read?: boolean; starred?: boolean }> }>).detail; + if (detail?.kind !== "patch" || !detail.patches?.length) return; + const patches = new Map(detail.patches.map((patch) => [patch.id, patch])); + setMessages((current) => current.map((message) => { + const patch = patches.get(message.id); + if (!patch) return message; + const next = { ...message }; + if (patch.starred !== undefined) next.starred = patch.starred; + if (patch.read !== undefined && !message.threadMessageIds) next.read = patch.read; + return next; + })); + } function onMessagesChanged(event: Event) { - const readOnly = (event as CustomEvent<{ kind?: string }>).detail?.kind === "read"; + const detail = (event as CustomEvent<{ kind?: string; deferRefresh?: boolean }>).detail; + const readOnly = detail?.kind === "read"; // A read patch can overtake a list request that started before it. Bump - // the request number so that response can never repaint the old state; - // a quiet refetch then reconciles the page with the server. + // the request number so that response can never repaint the old state. requestNumber += 1; + // Optimistic undo read/star patches stay on screen until the request settles. + if (detail?.deferRefresh) return; if (!readOnly) { clearMessageListCache(); clearMessageCountsCache(); @@ -88,11 +103,13 @@ export function useMessages( } window.addEventListener("mailflare:messages-changed", onMessagesChanged); window.addEventListener("mailflare:messages-changed", patchReadState); + window.addEventListener("mailflare:messages-changed", patchFieldState); return () => { cancelled = true; window.removeEventListener("mailflare:messages-changed", onMessagesChanged); window.removeEventListener("mailflare:messages-changed", patchReadState); + window.removeEventListener("mailflare:messages-changed", patchFieldState); if (refreshTimer) window.clearTimeout(refreshTimer); }; }, [enabled, filters?.group, filters?.limit, filters?.offset, filters?.query, filters?.read, filters?.title, folder, folderId, mailboxId]); diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts index 72ff66c3c..5fc816681 100644 --- a/src/hooks/utils.ts +++ b/src/hooks/utils.ts @@ -2,6 +2,7 @@ import { authFetch } from "@/lib/auth/client"; import { parseSearchQuery } from "@/lib/search/query-utils"; import { getUserTimeZone } from "@/lib/time/utils"; import { patchCachedMessage } from "@/lib/messages/detail-cache"; +import { rememberMessageFields, rememberMessageRows } from "@/lib/messages/field-store"; import { isReadOnlyChange } from "@/lib/messages/change-events"; import type { MessageFilterOptions, MessageFolder } from "./types"; import type { MessageCounts, MessageListResponse } from "./types"; @@ -131,6 +132,7 @@ export function patchMessagesInCaches(messageIds: string[], patch: CachedMessage }); } for (const id of ids) patchCachedMessage(id, patch); + rememberMessageFields(messageIds, patch); } /** @@ -206,6 +208,7 @@ export async function fetchMessageList(params: URLSearchParams, force = false): const response = data as MessageListResponse; if (requestGeneration === messageCacheGeneration) { messageListCache.set(key, response); + rememberMessageRows(response.messages ?? []); } return response; }) diff --git a/src/lib/messages/actions/client.ts b/src/lib/messages/actions/client.ts index 1eb4e281f..889bdd1ea 100644 --- a/src/lib/messages/actions/client.ts +++ b/src/lib/messages/actions/client.ts @@ -1,7 +1,9 @@ "use client"; import { authFetch } from "@/lib/auth/client"; -import { dispatchMessagesChanged } from "@/lib/messages/change-events"; +import { dispatchMessagesChanged, type MessageFieldPatch } from "@/lib/messages/change-events"; +import { invalidateCachedMessageDetails } from "@/lib/messages/detail-cache"; +import { captureMessageFields, type KnownMessageFields } from "@/lib/messages/field-store"; import { patchMessagesInCaches } from "@/hooks/utils"; import { MessageActionExecutor, @@ -17,6 +19,7 @@ import { import { showUndoToast } from "./undo-store"; import type { MessageActionInput, + MessageActionRecord, MessageActionRequestOptions, MessageActionResponse, MessageActionTransportBody, @@ -39,50 +42,90 @@ async function sendMessageAction( return data as MessageActionResponse | UndoMessageActionResponse; } -function dispatchRead(ids: string[], read: boolean) { +/** + * Patches the caches and tells every mounted list/thread which ids changed. + * `deferRefresh` keeps the optimistic value on screen until the request that + * produced it settles; without it the consumers quietly re-read the server. + */ +function dispatchRead(ids: string[], read: boolean, deferRefresh: boolean) { if (ids.length === 0) return; patchMessagesInCaches(ids, { read }); - dispatchMessagesChanged({ kind: "read", messageIds: ids, read }); + dispatchMessagesChanged({ kind: "read", messageIds: ids, read, deferRefresh }); } -const defaultHooks: MessageActionExecutorHooks = { +function dispatchStarGroups(groups: Map, deferRefresh: boolean) { + if (groups.size === 0) return; + const patches: MessageFieldPatch[] = []; + for (const [starred, ids] of groups) { + if (ids.length === 0) continue; + patchMessagesInCaches(ids, { starred }); + for (const id of ids) patches.push({ id, starred }); + } + if (patches.length > 0) dispatchMessagesChanged({ kind: "patch", patches, deferRefresh }); +} + +function capturedPatches( + records: MessageActionRecord[], + captured: Map, +) { + const readGroups = new Map(); + const starGroups = new Map(); + for (const record of records) { + const known = captured.get(record.id); + if (known?.read !== undefined && record.previous.read !== record.applied.read) { + const ids = readGroups.get(known.read) ?? []; + ids.push(record.id); + readGroups.set(known.read, ids); + } + if (known?.starred !== undefined && record.previous.starred !== record.applied.starred) { + const ids = starGroups.get(known.starred) ?? []; + ids.push(record.id); + starGroups.set(known.starred, ids); + } + } + return { readGroups, starGroups }; +} + +function restoreCaptured( + records: MessageActionRecord[], + captured: Map, +) { + const { readGroups, starGroups } = capturedPatches(records, captured); + for (const [read, ids] of readGroups) dispatchRead(ids, read, true); + dispatchStarGroups(starGroups, true); +} + +export const defaultMessageActionHooks: MessageActionExecutorHooks = { onApplied(response: MessageActionResponse, options: MessageActionHookOptions) { const changed = getChangedRecords(response.applied); if (changed.length === 0) return; - for (const [read, ids] of readPatchGroups(changed, "applied")) { - patchMessagesInCaches(ids, { read }); - if (options.notify) dispatchMessagesChanged({ kind: "read", messageIds: ids, read }); - } - const starred = starPatchGroups(changed, "applied"); - for (const [value, ids] of starred) patchMessagesInCaches(ids, { starred: value }); - if (options.notify && (starred.size > 0 || changed.some(hasMembershipChange))) dispatchMessagesChanged(); + const deferRefresh = !options.notify; + for (const [read, ids] of readPatchGroups(changed, "applied")) dispatchRead(ids, read, deferRefresh); + dispatchStarGroups(starPatchGroups(changed, "applied"), deferRefresh); + if (options.notify && changed.some(hasMembershipChange)) dispatchMessagesChanged(); }, onUndoOptimistic(records) { - // Read/unread undo must feel immediate; other fields stay server-first. - for (const [read, ids] of readPatchGroups(records, "previous")) dispatchRead(ids, read); + for (const [read, ids] of readPatchGroups(records, "previous")) dispatchRead(ids, read, true); + dispatchStarGroups(starPatchGroups(records, "previous"), true); }, - onUndoCompleted(records, response) { - const restoredSet = new Set(response.restored); - const restored = records.filter((record) => restoredSet.has(record.id)); - for (const [read, ids] of readPatchGroups(restored, "previous")) dispatchRead(ids, read); - const starred = starPatchGroups(restored, "previous"); - for (const [value, ids] of starred) patchMessagesInCaches(ids, { starred: value }); - if (starred.size > 0 || restored.some(hasMembershipChange) || response.skipped.length > 0) { - dispatchMessagesChanged(); - } + onUndoCompleted(records, response, captured) { + // The optimistic patches already show the restored state. Records the + // server skipped must return to what was on screen before the undo click, + // not an older action's historical applied snapshot. + const skipped = new Set(response.skipped.map((item) => item.id)); + restoreCaptured(records.filter((record) => skipped.has(record.id)), captured); }, - onUndoFailed(records) { - // Roll the optimistic read patch back to what the failed action wrote. - for (const [read, ids] of readPatchGroups(records, "applied")) dispatchRead(ids, read); - for (const [value, ids] of starPatchGroups(records, "applied")) patchMessagesInCaches(ids, { starred: value }); - dispatchMessagesChanged(); + onUndoFailed(records, captured) { + restoreCaptured(records, captured); }, - onResync() { + onResync(messageIds) { + invalidateCachedMessageDetails(messageIds); dispatchMessagesChanged(); }, + captureCurrent: captureMessageFields, }; -export const messageActionExecutor = new MessageActionExecutor(sendMessageAction as MessageActionTransport, defaultHooks); +export const messageActionExecutor = new MessageActionExecutor(sendMessageAction as MessageActionTransport, defaultMessageActionHooks); /** Applies an explicit action and, unless suppressed, shows its independent undo toast. */ export async function performMessageAction( diff --git a/src/lib/messages/actions/definitions.ts b/src/lib/messages/actions/definitions.ts index b5835ca99..055bcfdcf 100644 --- a/src/lib/messages/actions/definitions.ts +++ b/src/lib/messages/actions/definitions.ts @@ -195,11 +195,13 @@ export function planUndoRecord( const needsManage = fields.some((field) => field === "status" || field === "folderId" || field === "snoozedUntil"); if (!access.canRead || (needsManage && !access.canManage)) return { id: record.id, reason: "forbidden" }; - if (!isValidReversibleStatus(record.previous.status)) return { id: record.id, reason: "invalid_target" }; - if (record.previous.folderId !== null) { + if (fields.includes("status") && !isValidReversibleStatus(record.previous.status)) { + return { id: record.id, reason: "invalid_target" }; + } + if (fields.includes("folderId") && record.previous.folderId !== null) { if (!folderMailboxId || folderMailboxId !== current.mailboxId) return { id: record.id, reason: "invalid_target" }; } - if (record.previous.snoozedUntil !== null) { + if (fields.includes("snoozedUntil") && record.previous.snoozedUntil !== null) { if (current.direction !== "inbound" || Number.isNaN(new Date(record.previous.snoozedUntil).getTime())) { return { id: record.id, reason: "invalid_target" }; } diff --git a/src/lib/messages/actions/executor.ts b/src/lib/messages/actions/executor.ts index 66e81dfe4..21e316e00 100644 --- a/src/lib/messages/actions/executor.ts +++ b/src/lib/messages/actions/executor.ts @@ -1,4 +1,5 @@ import { getChangedStateFields, recordHasChanges } from "./definitions"; +import type { KnownMessageFields } from "@/lib/messages/field-store"; import type { MessageActionInput, MessageActionRecord, @@ -29,10 +30,12 @@ export type MessageActionExecutorHooks = { onApplyOptimistic?: (input: MessageActionInput, options: MessageActionHookOptions) => void; onApplyFailed?: (input: MessageActionInput, options: MessageActionHookOptions) => void; onApplied?: (response: MessageActionResponse, options: MessageActionHookOptions) => void; - onUndoOptimistic?: (records: MessageActionRecord[]) => void; - onUndoCompleted?: (records: MessageActionRecord[], response: UndoMessageActionResponse) => void; - onUndoFailed?: (records: MessageActionRecord[]) => void; - onResync?: () => void; + /** Snapshots the tab's current read/star values before an optimistic undo patch. */ + captureCurrent?: (ids: string[]) => Map; + onUndoOptimistic?: (records: MessageActionRecord[], captured: Map) => void; + onUndoCompleted?: (records: MessageActionRecord[], response: UndoMessageActionResponse, captured: Map) => void; + onUndoFailed?: (records: MessageActionRecord[], captured: Map) => void; + onResync?: (messageIds: string[]) => void; }; /** @@ -74,20 +77,22 @@ export class MessageActionExecutor { async undo(records: MessageActionRecord[], token: string | undefined): Promise { if (!token) throw new MessageActionRequestError("This undo has expired", 410); - return this.withLocks(records.map((record) => record.id), async () => { - this.hooks.onUndoOptimistic?.(records); + const ids = records.map((record) => record.id); + return this.withLocks(ids, async () => { + const captured = this.hooks.captureCurrent?.(ids) ?? new Map(); + this.hooks.onUndoOptimistic?.(records, captured); try { const response = await this.transport({ op: "undo", token }); if (!response || response.ok !== true || !Array.isArray((response as UndoMessageActionResponse).restored)) { throw new MessageActionRequestError("Could not undo that change", 502); } const result = response as UndoMessageActionResponse; - this.hooks.onUndoCompleted?.(records, result); - if (result.skipped.length > 0) this.hooks.onResync?.(); + this.hooks.onUndoCompleted?.(records, result, captured); + this.hooks.onResync?.(ids); return result; } catch (error) { - this.hooks.onUndoFailed?.(records); - this.hooks.onResync?.(); + this.hooks.onUndoFailed?.(records, captured); + this.hooks.onResync?.(ids); throw error; } }); diff --git a/src/lib/messages/change-events.ts b/src/lib/messages/change-events.ts index 6f1c1e77b..0f2cf0120 100644 --- a/src/lib/messages/change-events.ts +++ b/src/lib/messages/change-events.ts @@ -1,9 +1,19 @@ export const MESSAGES_CHANGED_EVENT = "mailflare:messages-changed"; +export type MessageFieldPatch = { + id: string; + read?: boolean; + starred?: boolean; +}; + export type MessagesChangedDetail = { - kind?: "read"; + kind?: "read" | "patch"; messageIds?: string[]; read?: boolean; + /** Per-message field patches, used when a batch has mixed values. */ + patches?: MessageFieldPatch[]; + /** Keep mounted views optimistic until the action request settles. */ + deferRefresh?: boolean; }; export function dispatchMessagesChanged(detail?: MessagesChangedDetail): void { @@ -15,5 +25,8 @@ export function getMessagesChangedDetail(event: Event): MessagesChangedDetail | } export function isReadOnlyChange(event: Event): boolean { - return getMessagesChangedDetail(event)?.kind === "read"; + const detail = getMessagesChangedDetail(event); + if (detail?.kind === "read") return true; + if (detail?.kind !== "patch" || !detail.patches?.length) return false; + return detail.patches.every((patch) => patch.read !== undefined && patch.starred === undefined); } diff --git a/src/lib/messages/detail-cache.ts b/src/lib/messages/detail-cache.ts index d56527214..7eda522bc 100644 --- a/src/lib/messages/detail-cache.ts +++ b/src/lib/messages/detail-cache.ts @@ -1,4 +1,5 @@ import { AUTH_SESSION_CHANGED_EVENT, authFetch } from "@/lib/auth/client"; +import { rememberMessageFields } from "@/lib/messages/field-store"; import type { Message } from "@/hooks/types"; import type { CachedMessageDetail } from "./detail-cache-types"; @@ -11,6 +12,7 @@ let generation = 0; function cacheDetail(messageId: string, data: CachedMessageDetail) { detailCache.delete(messageId); detailCache.set(messageId, { data, expiresAt: Date.now() + CACHE_TTL_MS }); + if (data.message) rememberMessageFields([messageId], { read: data.message.read, starred: data.message.starred }); if (detailCache.size > CACHE_LIMIT) { const oldest = detailCache.keys().next().value; if (oldest) detailCache.delete(oldest); @@ -44,6 +46,15 @@ export function setCachedMessageRead(messageId: string, read: boolean): void { export function patchCachedMessage(messageId: string, patch: { read?: boolean; starred?: boolean }): void { const cached = getCachedMessageDetail(messageId); if (cached?.message) cacheDetail(messageId, { ...cached, message: { ...cached.message, ...patch } }); + rememberMessageFields([messageId], patch); +} + +/** Drops specific details after a failed or partially skipped undo, so the reader refetches them. */ +export function invalidateCachedMessageDetails(messageIds: string[]): void { + for (const id of messageIds) { + detailCache.delete(id); + detailRequests.delete(id); + } } /** Merge the row header into the cache; a missing body is fetched separately. */ diff --git a/src/lib/messages/field-store.ts b/src/lib/messages/field-store.ts new file mode 100644 index 000000000..4db099f47 --- /dev/null +++ b/src/lib/messages/field-store.ts @@ -0,0 +1,49 @@ +/** + * The latest read/star values this tab has seen for message ids. Action + * responses, list/thread/detail fetches and cache patches all feed it, so an + * undo can snapshot what was on screen before its optimistic patch instead of + * assuming an older action's historical "applied" state is still current. + */ +export type KnownMessageFields = { + read?: boolean; + starred?: boolean; +}; + +const knownFields = new Map(); + +export function rememberMessageFields(messageIds: string[], patch: KnownMessageFields): void { + if (patch.read === undefined && patch.starred === undefined) return; + for (const id of messageIds) { + const current = knownFields.get(id) ?? {}; + knownFields.set(id, { + ...current, + ...(patch.read !== undefined ? { read: patch.read } : {}), + ...(patch.starred !== undefined ? { starred: patch.starred } : {}), + }); + } +} + +export function rememberMessageRows(rows: Array<{ id: string; read?: boolean; starred?: boolean }>): void { + for (const row of rows) { + if (row.read === undefined && row.starred === undefined) continue; + rememberMessageFields([row.id], { + ...(row.read !== undefined ? { read: row.read } : {}), + ...(row.starred !== undefined ? { starred: row.starred } : {}), + }); + } +} + +/** Copies only fields this tab has actually observed; unknown ids stay unknown. */ +export function captureMessageFields(ids: string[]): Map { + const captured = new Map(); + for (const id of new Set(ids)) { + const fields = knownFields.get(id); + if (fields) captured.set(id, { ...fields }); + } + return captured; +} + +/** Test-only reset. */ +export function clearKnownMessageFieldsForTests(): void { + knownFields.clear(); +} diff --git a/tests/e2e/message-undo.spec.ts b/tests/e2e/message-undo.spec.ts new file mode 100644 index 000000000..1e1f6e62d --- /dev/null +++ b/tests/e2e/message-undo.spec.ts @@ -0,0 +1,88 @@ +import { expect, test, type APIRequestContext, type Page, type Route } from "@playwright/test"; + +const EMAIL = "admin@example.com"; +const PASSWORD = "demo-password-change-me"; + +async function prepareDatabase(request: APIRequestContext) { + const response = await request.post("/api/setup/prepare"); + // A configured installation answers 403. A local dev server without + // Cloudflare API credentials answers 503 even after the D1 migrations have + // been applied; the seed call below still proves the schema is usable. + if (response.status() === 403 || response.status() === 503) return; + const body = await response.json().catch(() => null); + expect(response.ok(), `POST /api/setup/prepare returned ${response.status()}: ${JSON.stringify(body)}`).toBe(true); +} + +async function resetDemo(request: APIRequestContext) { + const response = await request.post("/api/seed?reset=1"); + const body = await response.json().catch(() => null); + expect(response.ok(), `POST /api/seed?reset=1 returned ${response.status()}: ${JSON.stringify(body)}`).toBe(true); +} + +async function login(page: Page) { + await page.goto("/login"); + await page.waitForLoadState("networkidle"); + await page.getByLabel("Email").fill(EMAIL); + await page.getByLabel("Password").fill(PASSWORD); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + await page.waitForURL("**/inbox", { timeout: 30_000 }); +} + +test.beforeAll(async ({ request }) => { + await prepareDatabase(request); +}); + +test.afterEach(async ({ request }) => { + await resetDemo(request); +}); + +/** + * Regression: explicit row read/unread must show its applied state in the row, + * and Undo must restore the row optimistically while the undo request is still + * unresolved. A background list refetch during that window must not paint the + * server's pre-undo value back over it. + */ +test("row read undo is optimistic while the undo request is pending", async ({ page }) => { + await resetDemo(page.request); + await login(page); + await page.goto("/inbox"); + + const initialRow = page.locator('[role="listitem"]').filter({ + has: page.getByRole("button", { name: "Mark as unread" }), + }).first(); + await expect(initialRow).toBeVisible(); + const href = await initialRow.locator('a[href^="/inbox/"]').first().getAttribute("href"); + expect(href).toBeTruthy(); + const row = page.locator('[role="listitem"]').filter({ has: page.locator(`a[href="${href}"]`) }).first(); + await row.hover(); + await row.getByRole("button", { name: "Mark as unread" }).click(); + + // The action settled: the row is unread locally and the toast is available. + await expect(row.getByRole("button", { name: "Mark as read" })).toHaveCount(1); + await expect(page.getByRole("button", { name: "Undo" })).toBeVisible(); + + let resolveHeld: (route: Route) => void; + const held = new Promise((resolve) => { resolveHeld = resolve; }); + await page.route("**/api/messages/actions", async (route) => { + const body = route.request().postDataJSON(); + if (body?.op === "undo") { + resolveHeld(route); + return; + } + await route.continue(); + }); + + try { + await page.getByRole("button", { name: "Undo" }).click(); + // The request is deliberately unresolved. The row must already be read + // again, which is the exact state the old implementation lost. + await expect(row.getByRole("button", { name: "Mark as unread" })).toHaveCount(1, { timeout: 5_000 }); + } finally { + const route = await Promise.race([held, new Promise((resolve) => setTimeout(() => resolve(null), 100))]); + if (route) await route.continue().catch(() => undefined); + } + + // Once the server confirms, the refetch keeps the same restored value. + await expect(row.getByRole("button", { name: "Mark as unread" })).toHaveCount(1); + await expect(page.getByRole("button", { name: "Undo" })).toHaveCount(0); +}); diff --git a/tests/message-action-undo.test.mjs b/tests/message-action-undo.test.mjs index 0b7e97502..a31f7a3e6 100644 --- a/tests/message-action-undo.test.mjs +++ b/tests/message-action-undo.test.mjs @@ -19,6 +19,14 @@ await build({ MessageActionExecutor, MessageActionRequestError, getChangedRecords, readPatchGroups, hasMembershipChange, } from "./src/lib/messages/actions/executor.ts"; export { signUndoToken, verifyUndoToken } from "./src/lib/messages/actions/token.ts"; + export { defaultMessageActionHooks } from "./src/lib/messages/actions/client.ts"; + export { + fetchMessageList, peekMessageList, clearMessageListCache, invalidateMessageListRequests, + } from "./src/hooks/utils.ts"; + export { primeMessageDetail, getCachedMessageDetail } from "./src/lib/messages/detail-cache.ts"; + export { + captureMessageFields, rememberMessageFields, clearKnownMessageFieldsForTests, + } from "./src/lib/messages/field-store.ts"; `, resolveDir: root, sourcefile: "message-action-undo-entry.ts", @@ -121,6 +129,15 @@ test("undo rejects a foreign folder, a foreign mailbox and malformed snapshots", assert.equal(m.planUndoRecord(record(state({ status: "hacked" }), applied), target(), { canRead: true, canManage: true }, null).reason, "invalid_target"); }); +test("a read undo ignores a folder that was removed after the read action", () => { + const recordWithFolder = record( + state({ status: "received", folderId: "deleted-folder" }), + state({ status: "received", folderId: "deleted-folder", read: true }), + ); + const plan = m.planUndoRecord(recordWithFolder, target({ read: true, folderId: "deleted-folder" }), { canRead: true, canManage: true }, undefined); + assert.deepEqual(plan.patch, { read: false }); +}); + test("undo is skipped when a later action changed the same field", () => { const previous = state(); const applied = state({ status: "archived" }); @@ -179,6 +196,30 @@ function applyResponse(overrides = {}) { }; } +async function seedListCache(params, messages) { + m.clearMessageListCache(); + m.clearKnownMessageFieldsForTests(); + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => Response.json({ messages, total: messages.length, limit: 25, offset: 0 }); + try { + await m.fetchMessageList(params, true); + } finally { + globalThis.fetch = originalFetch; + } +} + +function captureEvents(fn) { + const events = []; + const previousWindow = globalThis.window; + globalThis.window = { dispatchEvent: (event) => { events.push(event.detail); } }; + try { + fn(); + } finally { + globalThis.window = previousWindow; + } + return events; +} + test("the executor reports a successful apply after the server confirms it", async () => { const calls = []; const applied = []; @@ -296,6 +337,94 @@ test("membership changes are distinguished from read/star-only patches", () => { assert.equal(m.hasMembershipChange(record(state(), state({ status: "archived" }))), true); }); +test("explicit read patches the list cache and emits an optimistic deferred event", async () => { + const params = new URLSearchParams({ case: "read-patch" }); + await seedListCache(params, [{ id: "m1", read: true, starred: false }]); + const unread = record(state({ read: true }), state({ read: false })); + const events = captureEvents(() => { + m.defaultMessageActionHooks.onApplied({ ok: true, action: "unread", applied: [unread], skipped: [] }, { notify: false }); + }); + assert.equal(m.peekMessageList(params).messages[0].read, false); + assert.deepEqual(events.at(-1), { kind: "read", messageIds: ["m1"], read: false, deferRefresh: true }); + assert.equal(m.captureMessageFields(["m1"]).get("m1").read, false); +}); + +test("failed older undo restores the pre-click value, never the historical applied value", async () => { + const params = new URLSearchParams({ case: "old-undo" }); + await seedListCache(params, [{ id: "m1", read: false, starred: false }]); + // An older "mark read" snapshot (previous false, applied true) after a newer + // "mark unread" has made the tab's current value false again. + const olderRead = record(state({ read: false }), state({ read: true })); + const captured = m.captureMessageFields(["m1"]); + assert.equal(captured.get("m1").read, false); + const events = captureEvents(() => { + m.defaultMessageActionHooks.onUndoOptimistic([olderRead], captured); + m.defaultMessageActionHooks.onUndoFailed([olderRead], captured); + }); + assert.equal(m.peekMessageList(params).messages[0].read, false); + assert.equal(events.at(-1).read, false); +}); + +test("skipped undo records return to the pre-click state instead of staying optimistic", async () => { + const params = new URLSearchParams({ case: "skipped-undo" }); + await seedListCache(params, [{ id: "m1", read: false, starred: false }]); + const unread = record(state({ read: true }), state({ read: false })); + const captured = m.captureMessageFields(["m1"]); + const events = captureEvents(() => { + m.defaultMessageActionHooks.onUndoOptimistic([unread], captured); + m.defaultMessageActionHooks.onUndoCompleted([unread], { + ok: true, + action: "unread", + restored: [], + skipped: [{ id: "m1", reason: "stale" }], + }, captured); + }); + assert.equal(m.peekMessageList(params).messages[0].read, false); + assert.equal(events.at(-1).read, false); +}); + +test("grouped thread unread counts are patched once, not on both optimistic and completed undo", async () => { + const params = new URLSearchParams({ case: "thread-undo" }); + await seedListCache(params, [{ + id: "m1", + read: false, + starred: false, + threadMessageIds: ["m1", "m2", "m3"], + threadUnread: 1, + }]); + const markRead = record(state({ read: false }), state({ read: true })); + const events = captureEvents(() => { + m.defaultMessageActionHooks.onApplied({ ok: true, action: "read", applied: [markRead], skipped: [] }, { notify: true }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 0); + m.defaultMessageActionHooks.onUndoOptimistic([markRead], new Map([["m1", { read: true }]])); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 1); + m.defaultMessageActionHooks.onUndoCompleted([markRead], { + ok: true, + action: "read", + restored: ["m1"], + skipped: [], + }, new Map([["m1", { read: true }]])); + }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 1); + assert.equal(events.length, 2); +}); + +test("star undo restores the mounted detail cache and emits a starred patch", () => { + m.clearKnownMessageFieldsForTests(); + m.primeMessageDetail({ id: "star-1", read: false, starred: false }); + const star = record(state({ starred: false }), state({ starred: true }), { id: "star-1" }); + const events = captureEvents(() => { + m.defaultMessageActionHooks.onApplied({ ok: true, action: "star", applied: [star], skipped: [] }, { notify: true }); + assert.equal(m.getCachedMessageDetail("star-1").message.starred, true); + const captured = m.captureMessageFields(["star-1"]); + m.defaultMessageActionHooks.onUndoOptimistic([star], captured); + assert.equal(m.getCachedMessageDetail("star-1").message.starred, false); + m.defaultMessageActionHooks.onUndoFailed([star], captured); + assert.equal(m.getCachedMessageDetail("star-1").message.starred, true); + }); + assert.ok(events.some((event) => event.kind === "patch" && event.patches?.[0]?.starred === false)); +}); + test("a stale list response cannot overwrite a read patch made while it was in flight", async () => { const originalFetch = globalThis.fetch; let resolveStale; @@ -328,9 +457,13 @@ test("every catalog carries the undo keys with identical placeholders", () => { const en = JSON.parse(readFileSync(join(root, "src/lib/i18n/en.json"), "utf8")); const undoKeys = Object.keys(en).filter((key) => key.startsWith("undo.")); assert.ok(undoKeys.length >= 17); + const placeholders = (text) => [...new Set([...text.matchAll(/\{(\w+)\}/g)].map((match) => match[1]))].sort(); for (const file of readdirSync(join(root, "public", "locales")).filter((name) => name.endsWith(".json"))) { const catalog = JSON.parse(readFileSync(join(root, "public", "locales", file), "utf8")); - for (const key of undoKeys) assert.equal(catalog[key], en[key], `${file}: ${key}`); + for (const key of undoKeys) { + assert.ok(typeof catalog[key] === "string" && catalog[key].trim().length > 0, `${file}: ${key} is missing`); + assert.deepEqual(placeholders(catalog[key]), placeholders(en[key]), `${file}: ${key} placeholders`); + } } }); From 700095ae08a8c151b515e9f40ad5071b8e683872 Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 21:44:53 +0100 Subject: [PATCH 03/15] fix(messages): sync mounted reader with action detail state --- .../(dashboard)/inbox/[messageId]/page.tsx | 49 +++++++++++++++---- src/lib/messages/actions/client.ts | 40 ++++++++++++--- src/lib/messages/detail-cache.ts | 16 ++++-- tests/message-action-undo.test.mjs | 13 ++++- 4 files changed, 97 insertions(+), 21 deletions(-) diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx index 889579c1a..0e80b0e34 100644 --- a/src/app/(dashboard)/inbox/[messageId]/page.tsx +++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx @@ -155,20 +155,51 @@ function MessageDetailContent({ messageId }: { messageId: string }) { }; }, [messageId]); - // A bulk read/unread action can include the message that is already open. - // Keep the mounted reader in sync with the cache instead of remounting it. + // Read, star and membership changes (including undo) can target the message + // that is already open. Keep the mounted reader in sync with the detail cache; + // if a failed/skipped undo invalidated it, fetch the server value explicitly. useEffect(() => { - function syncCachedReadState() { + let cancelled = false; + function syncCachedState() { const cached = getCachedMessageDetailForDisplay(messageId); - if (!cached?.message) return; - const cachedRead = cached.message.read; + if (!cached?.message) { + void fetchMessageDetail(messageId, true).then((nextData) => { + if (cancelled || !("message" in nextData) || !nextData.message) return; + const nextMessage = nextData.message; + setData((current) => { + if (!current?.message) return nextData; + // A read flip from opening this message may still be in flight. + const keepRead = current.message.read && !nextMessage.read; + return { ...nextData, message: keepRead ? { ...nextMessage, read: true } : nextMessage }; + }); + }).catch(() => undefined); + return; + } + const cachedMessage = cached.message; setData((current) => { - if (!current?.message || current.message.read === cachedRead) return current; - return { ...current, message: { ...current.message, read: cachedRead } }; + if (!current?.message) return current; + const next = { + read: cachedMessage.read, + starred: cachedMessage.starred, + status: cachedMessage.status, + folderId: cachedMessage.folderId, + snoozedUntil: cachedMessage.snoozedUntil, + }; + if ( + current.message.read === next.read + && current.message.starred === next.starred + && current.message.status === next.status + && current.message.folderId === next.folderId + && current.message.snoozedUntil === next.snoozedUntil + ) return current; + return { ...current, message: { ...current.message, ...next } }; }); } - window.addEventListener("mailflare:messages-changed", syncCachedReadState); - return () => window.removeEventListener("mailflare:messages-changed", syncCachedReadState); + window.addEventListener("mailflare:messages-changed", syncCachedState); + return () => { + cancelled = true; + window.removeEventListener("mailflare:messages-changed", syncCachedState); + }; }, [messageId]); async function retryBody() { diff --git a/src/lib/messages/actions/client.ts b/src/lib/messages/actions/client.ts index 889bdd1ea..2dd154cb4 100644 --- a/src/lib/messages/actions/client.ts +++ b/src/lib/messages/actions/client.ts @@ -2,7 +2,7 @@ import { authFetch } from "@/lib/auth/client"; import { dispatchMessagesChanged, type MessageFieldPatch } from "@/lib/messages/change-events"; -import { invalidateCachedMessageDetails } from "@/lib/messages/detail-cache"; +import { invalidateCachedMessageDetails, patchCachedMessageState } from "@/lib/messages/detail-cache"; import { captureMessageFields, type KnownMessageFields } from "@/lib/messages/field-store"; import { patchMessagesInCaches } from "@/hooks/utils"; import { @@ -95,10 +95,35 @@ function restoreCaptured( dispatchStarGroups(starGroups, true); } +function rememberAppliedDetails(records: MessageActionRecord[]) { + for (const record of records) { + patchCachedMessageState(record.id, { + status: record.applied.status, + read: record.applied.read, + starred: record.applied.starred, + folderId: record.applied.folderId, + snoozedUntil: record.applied.snoozedUntil, + }); + } +} + +function rememberPreviousDetails(records: MessageActionRecord[]) { + for (const record of records) { + patchCachedMessageState(record.id, { + status: record.previous.status, + read: record.previous.read, + starred: record.previous.starred, + folderId: record.previous.folderId, + snoozedUntil: record.previous.snoozedUntil, + }); + } +} + export const defaultMessageActionHooks: MessageActionExecutorHooks = { onApplied(response: MessageActionResponse, options: MessageActionHookOptions) { const changed = getChangedRecords(response.applied); if (changed.length === 0) return; + rememberAppliedDetails(changed); const deferRefresh = !options.notify; for (const [read, ids] of readPatchGroups(changed, "applied")) dispatchRead(ids, read, deferRefresh); dispatchStarGroups(starPatchGroups(changed, "applied"), deferRefresh); @@ -109,17 +134,18 @@ export const defaultMessageActionHooks: MessageActionExecutorHooks = { dispatchStarGroups(starPatchGroups(records, "previous"), true); }, onUndoCompleted(records, response, captured) { - // The optimistic patches already show the restored state. Records the - // server skipped must return to what was on screen before the undo click, - // not an older action's historical applied snapshot. + const restored = new Set(response.restored); + rememberPreviousDetails(records.filter((record) => restored.has(record.id))); const skipped = new Set(response.skipped.map((item) => item.id)); - restoreCaptured(records.filter((record) => skipped.has(record.id)), captured); + const skippedRecords = records.filter((record) => skipped.has(record.id)); + restoreCaptured(skippedRecords, captured); + invalidateCachedMessageDetails(skippedRecords.map((record) => record.id)); }, onUndoFailed(records, captured) { restoreCaptured(records, captured); + invalidateCachedMessageDetails(records.map((record) => record.id)); }, - onResync(messageIds) { - invalidateCachedMessageDetails(messageIds); + onResync() { dispatchMessagesChanged(); }, captureCurrent: captureMessageFields, diff --git a/src/lib/messages/detail-cache.ts b/src/lib/messages/detail-cache.ts index 7eda522bc..579315357 100644 --- a/src/lib/messages/detail-cache.ts +++ b/src/lib/messages/detail-cache.ts @@ -42,11 +42,21 @@ export function setCachedMessageRead(messageId: string, read: boolean): void { if (cached?.message) cacheDetail(messageId, { ...cached, message: { ...cached.message, read } }); } -/** Field-scoped detail patch for star toggles and undo; read still goes through setCachedMessageRead. */ -export function patchCachedMessage(messageId: string, patch: { read?: boolean; starred?: boolean }): void { +export type CachedMessageStatePatch = Partial>; + +/** Field-scoped detail patch for action/undo state; read and star also feed the field store. */ +export function patchCachedMessageState(messageId: string, patch: CachedMessageStatePatch): void { const cached = getCachedMessageDetail(messageId); if (cached?.message) cacheDetail(messageId, { ...cached, message: { ...cached.message, ...patch } }); - rememberMessageFields([messageId], patch); + rememberMessageFields([messageId], { + ...(patch.read !== undefined ? { read: patch.read } : {}), + ...(patch.starred !== undefined ? { starred: patch.starred } : {}), + }); +} + +/** Backwards-compatible read/star helper for callers that only own those fields. */ +export function patchCachedMessage(messageId: string, patch: { read?: boolean; starred?: boolean }): void { + patchCachedMessageState(messageId, patch); } /** Drops specific details after a failed or partially skipped undo, so the reader refetches them. */ diff --git a/tests/message-action-undo.test.mjs b/tests/message-action-undo.test.mjs index a31f7a3e6..9e5e30322 100644 --- a/tests/message-action-undo.test.mjs +++ b/tests/message-action-undo.test.mjs @@ -409,7 +409,7 @@ test("grouped thread unread counts are patched once, not on both optimistic and assert.equal(events.length, 2); }); -test("star undo restores the mounted detail cache and emits a starred patch", () => { +test("star undo keeps a valid detail cache on success and invalidates it on failure", () => { m.clearKnownMessageFieldsForTests(); m.primeMessageDetail({ id: "star-1", read: false, starred: false }); const star = record(state({ starred: false }), state({ starred: true }), { id: "star-1" }); @@ -419,8 +419,17 @@ test("star undo restores the mounted detail cache and emits a starred patch", () const captured = m.captureMessageFields(["star-1"]); m.defaultMessageActionHooks.onUndoOptimistic([star], captured); assert.equal(m.getCachedMessageDetail("star-1").message.starred, false); + m.defaultMessageActionHooks.onUndoCompleted([star], { + ok: true, + action: "star", + restored: ["star-1"], + skipped: [], + }, captured); + // A successful undo leaves the valid detail cache for the mounted reader. + assert.equal(m.getCachedMessageDetail("star-1").message.starred, false); m.defaultMessageActionHooks.onUndoFailed([star], captured); - assert.equal(m.getCachedMessageDetail("star-1").message.starred, true); + // A failed undo drops the detail so the reader explicitly fetches server truth. + assert.equal(m.getCachedMessageDetail("star-1"), undefined); }); assert.ok(events.some((event) => event.kind === "patch" && event.patches?.[0]?.starred === false)); }); From 7198705cc2ddf1c17aa2f5be7589161584a8e0e5 Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 21:52:02 +0100 Subject: [PATCH 04/15] feat(messages): polish undo toasts and queue accessibility --- public/locales/ar.json | 10 + public/locales/bn.json | 10 + public/locales/de.json | 10 + public/locales/es.json | 10 + public/locales/fa.json | 10 + public/locales/fr.json | 10 + public/locales/gu.json | 10 + public/locales/ha.json | 10 + public/locales/hi.json | 10 + public/locales/id.json | 10 + public/locales/it.json | 10 + public/locales/ja.json | 10 + public/locales/kn.json | 10 + public/locales/ko.json | 10 + public/locales/ml.json | 10 + public/locales/mr.json | 10 + public/locales/ms.json | 10 + public/locales/nl.json | 10 + public/locales/pa.json | 10 + public/locales/pl.json | 10 + public/locales/pt-BR.json | 10 + public/locales/pt-PT.json | 10 + public/locales/ru.json | 10 + public/locales/si.json | 10 + public/locales/sw.json | 10 + public/locales/ta.json | 10 + public/locales/te.json | 10 + public/locales/th.json | 10 + public/locales/tr.json | 10 + public/locales/uk.json | 10 + public/locales/ur.json | 10 + public/locales/vi.json | 10 + public/locales/zh-CN.json | 10 + src/components/messages/undo-toasts.tsx | 339 +++++++++++++++++++----- src/lib/i18n/en.json | 10 + src/lib/messages/actions/undo-store.ts | 335 ++++++++++++++++++++--- tests/message-undo-toast-store.test.mjs | 255 ++++++++++++++++++ tests/message-undo-toast-ui.test.mjs | 337 +++++++++++++++++++++++ 38 files changed, 1510 insertions(+), 96 deletions(-) create mode 100644 tests/message-undo-toast-store.test.mjs create mode 100644 tests/message-undo-toast-ui.test.mjs diff --git a/public/locales/ar.json b/public/locales/ar.json index b897b0b81..91c59233c 100644 --- a/public/locales/ar.json +++ b/public/locales/ar.json @@ -2515,6 +2515,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "إشعارات إجراءات الرسائل", + "undo.undoing": "جارٍ التراجع…", + "undo.retry": "إعادة المحاولة", + "undo.failed.expired": "انتهت صلاحية هذا التراجع.", + "undo.failed.unavailable": "لم تعد هذه الرسالة متاحة للتراجع.", + "undo.failed.stale": "لم يعد من الممكن التراجع عن هذا التغيير لأن الرسالة تغيّرت.", + "undo.failed.network": "فشل التراجع. تحقّق من اتصالك وحاول مرة أخرى.", + "undo.failed.server": "فشل التراجع. يرجى المحاولة مرة أخرى.", + "undo.partialRestored": "تمت استعادة {restored} من {total} رسائل. تعذّر التراجع عن البقية.", + "undo.successAnnouncement": "اكتمل التراجع: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/bn.json b/public/locales/bn.json index 44013978d..3675a4613 100644 --- a/public/locales/bn.json +++ b/public/locales/bn.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "বার্তা অ্যাকশন বিজ্ঞপ্তি", + "undo.undoing": "ফিরিয়ে আনা হচ্ছে…", + "undo.retry": "আবার চেষ্টা করুন", + "undo.failed.expired": "এই ফিরিয়ে আনার সময় শেষ হয়ে গেছে।", + "undo.failed.unavailable": "এই বার্তাটি আর ফিরিয়ে আনার জন্য উপলব্ধ নেই।", + "undo.failed.stale": "বার্তাটি পরিবর্তিত হওয়ায় এই পরিবর্তন আর ফিরিয়ে আনা যাবে না।", + "undo.failed.network": "ফিরিয়ে আনা ব্যর্থ হয়েছে। আপনার সংযোগ পরীক্ষা করে আবার চেষ্টা করুন।", + "undo.failed.server": "ফিরিয়ে আনা ব্যর্থ হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।", + "undo.partialRestored": "{total}টি বার্তার মধ্যে {restored}টি ফিরিয়ে আনা হয়েছে। বাকিগুলো ফিরিয়ে আনা যায়নি।", + "undo.successAnnouncement": "ফিরিয়ে আনা সম্পন্ন: {action}।", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/de.json b/public/locales/de.json index 1dec30811..cc5b8de20 100644 --- a/public/locales/de.json +++ b/public/locales/de.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Benachrichtigungen zu Nachrichtenaktionen", + "undo.undoing": "Wird rückgängig gemacht…", + "undo.retry": "Erneut versuchen", + "undo.failed.expired": "Dieses Rückgängigmachen ist abgelaufen.", + "undo.failed.unavailable": "Diese Nachricht kann nicht mehr rückgängig gemacht werden.", + "undo.failed.stale": "Diese Änderung kann nicht mehr rückgängig gemacht werden, da sich die Nachricht geändert hat.", + "undo.failed.network": "Rückgängig machen fehlgeschlagen. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut.", + "undo.failed.server": "Rückgängig machen fehlgeschlagen. Bitte versuchen Sie es erneut.", + "undo.partialRestored": "{restored} von {total} Nachrichten wiederhergestellt. Der Rest konnte nicht rückgängig gemacht werden.", + "undo.successAnnouncement": "Rückgängig gemacht: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/es.json b/public/locales/es.json index bd74c91d6..4222b583a 100644 --- a/public/locales/es.json +++ b/public/locales/es.json @@ -2470,6 +2470,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Notificaciones de acciones de mensajes", + "undo.undoing": "Deshaciendo…", + "undo.retry": "Reintentar", + "undo.failed.expired": "Esta acción ya no se puede deshacer.", + "undo.failed.unavailable": "Ese mensaje ya no está disponible para deshacer.", + "undo.failed.stale": "Ese cambio ya no se puede deshacer porque el mensaje ha cambiado.", + "undo.failed.network": "No se pudo deshacer. Comprueba tu conexión e inténtalo de nuevo.", + "undo.failed.server": "No se pudo deshacer. Inténtalo de nuevo.", + "undo.partialRestored": "Se restauraron {restored} de {total} mensajes. El resto no se pudo deshacer.", + "undo.successAnnouncement": "Deshacer completado: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/fa.json b/public/locales/fa.json index ad576c6fc..2868b0dc5 100644 --- a/public/locales/fa.json +++ b/public/locales/fa.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "اعلان‌های اقدامات پیام", + "undo.undoing": "در حال بازگرداندن…", + "undo.retry": "تلاش دوباره", + "undo.failed.expired": "مهلت این واگرد به پایان رسیده است.", + "undo.failed.unavailable": "آن پیام دیگر برای واگرد در دسترس نیست.", + "undo.failed.stale": "این تغییر دیگر قابل واگرد نیست زیرا پیام تغییر کرده است.", + "undo.failed.network": "واگرد ناموفق بود. اتصال خود را بررسی کنید و دوباره تلاش کنید.", + "undo.failed.server": "واگرد ناموفق بود. لطفاً دوباره تلاش کنید.", + "undo.partialRestored": "{restored} از {total} پیام بازگردانده شد. بقیه قابل واگرد نبودند.", + "undo.successAnnouncement": "واگرد کامل شد: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/fr.json b/public/locales/fr.json index 84965258b..7130e9821 100644 --- a/public/locales/fr.json +++ b/public/locales/fr.json @@ -2470,6 +2470,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Notifications d’actions sur les messages", + "undo.undoing": "Annulation…", + "undo.retry": "Réessayer", + "undo.failed.expired": "Cette annulation a expiré.", + "undo.failed.unavailable": "Ce message n’est plus disponible pour l’annulation.", + "undo.failed.stale": "Cette modification ne peut plus être annulée car le message a changé.", + "undo.failed.network": "L’annulation a échoué. Vérifiez votre connexion et réessayez.", + "undo.failed.server": "L’annulation a échoué. Veuillez réessayer.", + "undo.partialRestored": "{restored} messages sur {total} ont été restaurés. Le reste n’a pas pu être annulé.", + "undo.successAnnouncement": "Annulation terminée : {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/gu.json b/public/locales/gu.json index a5188be26..90b3d562e 100644 --- a/public/locales/gu.json +++ b/public/locales/gu.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "સંદેશ ક્રિયા સૂચનાઓ", + "undo.undoing": "પાછું ખેંચી રહ્યું છે…", + "undo.retry": "ફરી પ્રયાસ કરો", + "undo.failed.expired": "આ પાછું ખેંચવાની મુદત પૂરી થઈ ગઈ છે.", + "undo.failed.unavailable": "તે સંદેશ હવે પાછું ખેંચવા માટે ઉપલબ્ધ નથી.", + "undo.failed.stale": "સંદેશ બદલાયો હોવાથી આ ફેરફાર હવે પાછો ખેંચી શકાતો નથી.", + "undo.failed.network": "પાછું ખેંચવું નિષ્ફળ ગયું. તમારું કનેક્શન તપાસો અને ફરી પ્રયાસ કરો.", + "undo.failed.server": "પાછું ખેંચવું નિષ્ફળ ગયું. કૃપા કરીને ફરી પ્રયાસ કરો.", + "undo.partialRestored": "{total} માંથી {restored} સંદેશા પુનઃસ્થાપિત થયા. બાકીના પાછા ખેંચી શકાયા નથી.", + "undo.successAnnouncement": "પાછું ખેંચવું પૂર્ણ: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ha.json b/public/locales/ha.json index 396f5ddc9..2c4b4fbb6 100644 --- a/public/locales/ha.json +++ b/public/locales/ha.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Sanarwar ayyukan saƙo", + "undo.undoing": "Ana juyawa…", + "undo.retry": "Sake gwadawa", + "undo.failed.expired": "Wannan juyawa ya ƙare.", + "undo.failed.unavailable": "Wannan saƙon ba ya samuwa don juyawa.", + "undo.failed.stale": "Ba za a iya juyar da wannan canjin ba saboda saƙon ya canza.", + "undo.failed.network": "Juyawa ya kasa. Duba haɗin ku kuma sake gwadawa.", + "undo.failed.server": "Juyawa ya kasa. Don Allah sake gwadawa.", + "undo.partialRestored": "An dawo da {restored} daga cikin {total} saƙonni. Sauran ba a iya juyar da su ba.", + "undo.successAnnouncement": "An kammala juyawa: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/hi.json b/public/locales/hi.json index 01b9cc91a..073b8b1c7 100644 --- a/public/locales/hi.json +++ b/public/locales/hi.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "संदेश क्रिया सूचनाएँ", + "undo.undoing": "पूर्ववत किया जा रहा है…", + "undo.retry": "फिर से प्रयास करें", + "undo.failed.expired": "यह पूर्ववत करने की अवधि समाप्त हो गई है।", + "undo.failed.unavailable": "वह संदेश अब पूर्ववत करने के लिए उपलब्ध नहीं है।", + "undo.failed.stale": "संदेश बदल जाने के कारण यह परिवर्तन अब पूर्ववत नहीं किया जा सकता।", + "undo.failed.network": "पूर्ववत करना विफल रहा। अपना कनेक्शन जाँचें और फिर से प्रयास करें।", + "undo.failed.server": "पूर्ववत करना विफल रहा। कृपया फिर से प्रयास करें।", + "undo.partialRestored": "{total} में से {restored} संदेश बहाल किए गए। बाकी पूर्ववत नहीं किए जा सके।", + "undo.successAnnouncement": "पूर्ववत करना पूर्ण: {action}।", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/id.json b/public/locales/id.json index 51b757762..248b678c8 100644 --- a/public/locales/id.json +++ b/public/locales/id.json @@ -2437,6 +2437,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Notifikasi tindakan pesan", + "undo.undoing": "Membatalkan…", + "undo.retry": "Coba lagi", + "undo.failed.expired": "Pembatalan ini telah kedaluwarsa.", + "undo.failed.unavailable": "Pesan itu tidak lagi tersedia untuk dibatalkan.", + "undo.failed.stale": "Perubahan itu tidak dapat dibatalkan lagi karena pesannya telah berubah.", + "undo.failed.network": "Pembatalan gagal. Periksa koneksi Anda dan coba lagi.", + "undo.failed.server": "Pembatalan gagal. Silakan coba lagi.", + "undo.partialRestored": "{restored} dari {total} pesan dipulihkan. Sisanya tidak dapat dibatalkan.", + "undo.successAnnouncement": "Pembatalan selesai: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/it.json b/public/locales/it.json index 124a9d3a8..4d567c340 100644 --- a/public/locales/it.json +++ b/public/locales/it.json @@ -2470,6 +2470,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Notifiche azioni sui messaggi", + "undo.undoing": "Annullamento…", + "undo.retry": "Riprova", + "undo.failed.expired": "Questo annullamento è scaduto.", + "undo.failed.unavailable": "Quel messaggio non è più disponibile per l’annullamento.", + "undo.failed.stale": "Questa modifica non può più essere annullata perché il messaggio è cambiato.", + "undo.failed.network": "Annullamento non riuscito. Controlla la connessione e riprova.", + "undo.failed.server": "Annullamento non riuscito. Riprova.", + "undo.partialRestored": "{restored} messaggi su {total} ripristinati. Il resto non è stato possibile annullarlo.", + "undo.successAnnouncement": "Annullamento completato: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ja.json b/public/locales/ja.json index 624892bd6..b11b9d463 100644 --- a/public/locales/ja.json +++ b/public/locales/ja.json @@ -2437,6 +2437,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "メッセージ操作の通知", + "undo.undoing": "元に戻しています…", + "undo.retry": "再試行", + "undo.failed.expired": "この元に戻す操作は期限切れです。", + "undo.failed.unavailable": "そのメッセージは元に戻せなくなりました。", + "undo.failed.stale": "メッセージが変更されたため、この変更は元に戻せません。", + "undo.failed.network": "元に戻せませんでした。接続を確認して再試行してください。", + "undo.failed.server": "元に戻せませんでした。もう一度お試しください。", + "undo.partialRestored": "{total} 件中 {restored} 件のメッセージを復元しました。残りは元に戻せませんでした。", + "undo.successAnnouncement": "元に戻しました: {action}。", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/kn.json b/public/locales/kn.json index 3eb801e71..711967d11 100644 --- a/public/locales/kn.json +++ b/public/locales/kn.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "ಸಂದೇಶ ಕ್ರಿಯೆ ಅಧಿಸೂಚನೆಗಳು", + "undo.undoing": "ಹಿಂತಿರುಗಿಸಲಾಗುತ್ತಿದೆ…", + "undo.retry": "ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ", + "undo.failed.expired": "ಈ ಹಿಂತಿರುಗಿಸುವ ಅವಧಿ ಮುಗಿದಿದೆ.", + "undo.failed.unavailable": "ಆ ಸಂದೇಶವನ್ನು ಇನ್ನು ಹಿಂತಿರುಗಿಸಲು ಸಾಧ್ಯವಿಲ್ಲ.", + "undo.failed.stale": "ಸಂದೇಶ ಬದಲಾಗಿರುವುದರಿಂದ ಈ ಬದಲಾವಣೆಯನ್ನು ಇನ್ನು ಹಿಂತಿರುಗಿಸಲು ಸಾಧ್ಯವಿಲ್ಲ.", + "undo.failed.network": "ಹಿಂತಿರುಗಿಸುವುದು ವಿಫಲವಾಗಿದೆ. ನಿಮ್ಮ ಸಂಪರ್ಕವನ್ನು ಪರಿಶೀಲಿಸಿ ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ.", + "undo.failed.server": "ಹಿಂತಿರುಗಿಸುವುದು ವಿಫಲವಾಗಿದೆ. ದಯವಿಟ್ಟು ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ.", + "undo.partialRestored": "{total} ರಲ್ಲಿ {restored} ಸಂದೇಶಗಳನ್ನು ಮರುಸ್ಥಾಪಿಸಲಾಗಿದೆ. ಉಳಿದವನ್ನು ಹಿಂತಿರುಗಿಸಲಾಗಲಿಲ್ಲ.", + "undo.successAnnouncement": "ಹಿಂತಿರುಗಿಸುವುದು ಪೂರ್ಣಗೊಂಡಿದೆ: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ko.json b/public/locales/ko.json index f45e88d4d..5cce7911b 100644 --- a/public/locales/ko.json +++ b/public/locales/ko.json @@ -2451,6 +2451,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "메시지 작업 알림", + "undo.undoing": "실행 취소 중…", + "undo.retry": "다시 시도", + "undo.failed.expired": "이 실행 취소는 만료되었습니다.", + "undo.failed.unavailable": "해당 메시지는 더 이상 실행 취소할 수 없습니다.", + "undo.failed.stale": "메시지가 변경되어 이 변경 사항을 더 이상 실행 취소할 수 없습니다.", + "undo.failed.network": "실행 취소에 실패했습니다. 연결을 확인하고 다시 시도하세요.", + "undo.failed.server": "실행 취소에 실패했습니다. 다시 시도하세요.", + "undo.partialRestored": "{total}개 중 {restored}개 메시지를 복원했습니다. 나머지는 실행 취소할 수 없었습니다.", + "undo.successAnnouncement": "실행 취소 완료: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ml.json b/public/locales/ml.json index db0c24ca8..5250c204a 100644 --- a/public/locales/ml.json +++ b/public/locales/ml.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "സന്ദേശ പ്രവർത്തന അറിയിപ്പുകൾ", + "undo.undoing": "പഴയപടിയാക്കുന്നു…", + "undo.retry": "വീണ്ടും ശ്രമിക്കുക", + "undo.failed.expired": "ഈ പഴയപടിയാക്കൽ കാലഹരണപ്പെട്ടു.", + "undo.failed.unavailable": "ആ സന്ദേശം ഇനി പഴയപടിയാക്കാൻ ലഭ്യമല്ല.", + "undo.failed.stale": "സന്ദേശം മാറിയതിനാൽ ഈ മാറ്റം ഇനി പഴയപടിയാക്കാൻ കഴിയില്ല.", + "undo.failed.network": "പഴയപടിയാക്കൽ പരാജയപ്പെട്ടു. നിങ്ങളുടെ കണക്ഷൻ പരിശോധിച്ച് വീണ്ടും ശ്രമിക്കുക.", + "undo.failed.server": "പഴയപടിയാക്കൽ പരാജയപ്പെട്ടു. വീണ്ടും ശ്രമിക്കുക.", + "undo.partialRestored": "{total}-ൽ {restored} സന്ദേശങ്ങൾ പുനഃസ്ഥാപിച്ചു. ബാക്കിയുള്ളവ പഴയപടിയാക്കാൻ കഴിഞ്ഞില്ല.", + "undo.successAnnouncement": "പഴയപടിയാക്കൽ പൂർത്തിയായി: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/mr.json b/public/locales/mr.json index 8f0ffa166..4c1748a7c 100644 --- a/public/locales/mr.json +++ b/public/locales/mr.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "संदेश क्रिया सूचना", + "undo.undoing": "पूर्वस्थितीत आणत आहे…", + "undo.retry": "पुन्हा प्रयत्न करा", + "undo.failed.expired": "ही पूर्वस्थितीत आणण्याची मुदत संपली आहे.", + "undo.failed.unavailable": "ती संदेश आता पूर्वस्थितीत आणण्यासाठी उपलब्ध नाही.", + "undo.failed.stale": "संदेश बदलल्यामुळे हा बदल आता पूर्वस्थितीत आणता येत नाही.", + "undo.failed.network": "पूर्वस्थितीत आणणे अयशस्वी झाले. तुमचे कनेक्शन तपासा आणि पुन्हा प्रयत्न करा.", + "undo.failed.server": "पूर्वस्थितीत आणणे अयशस्वी झाले. कृपया पुन्हा प्रयत्न करा.", + "undo.partialRestored": "{total} पैकी {restored} संदेश पुनर्संचयित केले. उर्वरित पूर्वस्थितीत आणता आले नाहीत.", + "undo.successAnnouncement": "पूर्वस्थितीत आणणे पूर्ण: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ms.json b/public/locales/ms.json index f2c966d88..87f9e6718 100644 --- a/public/locales/ms.json +++ b/public/locales/ms.json @@ -2451,6 +2451,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Pemberitahuan tindakan mesej", + "undo.undoing": "Membatalkan…", + "undo.retry": "Cuba lagi", + "undo.failed.expired": "Pembatalan ini telah tamat tempoh.", + "undo.failed.unavailable": "Mesej itu tidak lagi tersedia untuk dibatalkan.", + "undo.failed.stale": "Perubahan itu tidak boleh dibatalkan lagi kerana mesej telah berubah.", + "undo.failed.network": "Pembatalan gagal. Semak sambungan anda dan cuba lagi.", + "undo.failed.server": "Pembatalan gagal. Sila cuba lagi.", + "undo.partialRestored": "{restored} daripada {total} mesej dipulihkan. Selebihnya tidak dapat dibatalkan.", + "undo.successAnnouncement": "Pembatalan selesai: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/nl.json b/public/locales/nl.json index 06b615e17..d96c7b7df 100644 --- a/public/locales/nl.json +++ b/public/locales/nl.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Meldingen over berichtacties", + "undo.undoing": "Ongedaan maken…", + "undo.retry": "Opnieuw proberen", + "undo.failed.expired": "Deze undo is verlopen.", + "undo.failed.unavailable": "Dat bericht is niet meer beschikbaar om ongedaan te maken.", + "undo.failed.stale": "Die wijziging kan niet meer ongedaan worden gemaakt omdat het bericht is gewijzigd.", + "undo.failed.network": "Ongedaan maken mislukt. Controleer je verbinding en probeer het opnieuw.", + "undo.failed.server": "Ongedaan maken mislukt. Probeer het opnieuw.", + "undo.partialRestored": "{restored} van {total} berichten hersteld. De rest kon niet ongedaan worden gemaakt.", + "undo.successAnnouncement": "Ongedaan maken voltooid: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/pa.json b/public/locales/pa.json index f87d5ff69..dc0fde623 100644 --- a/public/locales/pa.json +++ b/public/locales/pa.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "ਸੁਨੇਹਾ ਕਾਰਵਾਈ ਸੂਚਨਾਵਾਂ", + "undo.undoing": "ਵਾਪਸ ਕੀਤਾ ਜਾ ਰਿਹਾ ਹੈ…", + "undo.retry": "ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ", + "undo.failed.expired": "ਇਸ ਵਾਪਸੀ ਦੀ ਮਿਆਦ ਖਤਮ ਹੋ ਗਈ ਹੈ।", + "undo.failed.unavailable": "ਉਹ ਸੁਨੇਹਾ ਹੁਣ ਵਾਪਸ ਕਰਨ ਲਈ ਉਪਲਬਧ ਨਹੀਂ ਹੈ।", + "undo.failed.stale": "ਸੁਨੇਹਾ ਬਦਲਣ ਕਾਰਨ ਇਹ ਬਦਲਾਅ ਹੁਣ ਵਾਪਸ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ।", + "undo.failed.network": "ਵਾਪਸ ਕਰਨਾ ਅਸਫਲ ਰਿਹਾ। ਆਪਣਾ ਕਨੈਕਸ਼ਨ ਜਾਂਚੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।", + "undo.failed.server": "ਵਾਪਸ ਕਰਨਾ ਅਸਫਲ ਰਿਹਾ। ਕਿਰਪਾ ਕਰਕੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।", + "undo.partialRestored": "{total} ਵਿੱਚੋਂ {restored} ਸੁਨੇਹੇ ਬਹਾਲ ਕੀਤੇ ਗਏ। ਬਾਕੀ ਵਾਪਸ ਨਹੀਂ ਕੀਤੇ ਜਾ ਸਕੇ।", + "undo.successAnnouncement": "ਵਾਪਸ ਕਰਨਾ ਪੂਰਾ ਹੋਇਆ: {action}।", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/pl.json b/public/locales/pl.json index e4bd9e78e..56be45132 100644 --- a/public/locales/pl.json +++ b/public/locales/pl.json @@ -2485,6 +2485,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Powiadomienia o działaniach na wiadomościach", + "undo.undoing": "Cofanie…", + "undo.retry": "Spróbuj ponownie", + "undo.failed.expired": "To cofnięcie wygasło.", + "undo.failed.unavailable": "Ta wiadomość nie jest już dostępna do cofnięcia.", + "undo.failed.stale": "Tej zmiany nie można już cofnąć, ponieważ wiadomość została zmieniona.", + "undo.failed.network": "Cofnięcie nie powiodło się. Sprawdź połączenie i spróbuj ponownie.", + "undo.failed.server": "Cofnięcie nie powiodło się. Spróbuj ponownie.", + "undo.partialRestored": "Przywrócono {restored} z {total} wiadomości. Pozostałych nie udało się cofnąć.", + "undo.successAnnouncement": "Cofnięcie zakończone: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/pt-BR.json b/public/locales/pt-BR.json index cf4c3af46..b27a29f7b 100644 --- a/public/locales/pt-BR.json +++ b/public/locales/pt-BR.json @@ -2470,6 +2470,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Notificações de ações em mensagens", + "undo.undoing": "Desfazendo…", + "undo.retry": "Tentar novamente", + "undo.failed.expired": "Este desfazer expirou.", + "undo.failed.unavailable": "Essa mensagem não está mais disponível para desfazer.", + "undo.failed.stale": "Essa alteração não pode mais ser desfeita porque a mensagem foi alterada.", + "undo.failed.network": "Falha ao desfazer. Verifique sua conexão e tente novamente.", + "undo.failed.server": "Falha ao desfazer. Tente novamente.", + "undo.partialRestored": "{restored} de {total} mensagens restauradas. O restante não pôde ser desfeito.", + "undo.successAnnouncement": "Desfazer concluído: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/pt-PT.json b/public/locales/pt-PT.json index 58b948ec3..316d2504b 100644 --- a/public/locales/pt-PT.json +++ b/public/locales/pt-PT.json @@ -2470,6 +2470,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Notificações de ações em mensagens", + "undo.undoing": "A anular…", + "undo.retry": "Tentar novamente", + "undo.failed.expired": "Esta anulação expirou.", + "undo.failed.unavailable": "Essa mensagem já não está disponível para anular.", + "undo.failed.stale": "Essa alteração já não pode ser anulada porque a mensagem foi alterada.", + "undo.failed.network": "Falha ao anular. Verifique a ligação e tente novamente.", + "undo.failed.server": "Falha ao anular. Tente novamente.", + "undo.partialRestored": "{restored} de {total} mensagens restauradas. As restantes não puderam ser anuladas.", + "undo.successAnnouncement": "Anulação concluída: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ru.json b/public/locales/ru.json index 0547ab0ce..a830ce134 100644 --- a/public/locales/ru.json +++ b/public/locales/ru.json @@ -2485,6 +2485,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Уведомления о действиях с сообщениями", + "undo.undoing": "Отмена…", + "undo.retry": "Повторить", + "undo.failed.expired": "Срок отмены истёк.", + "undo.failed.unavailable": "Это сообщение больше недоступно для отмены.", + "undo.failed.stale": "Это изменение больше нельзя отменить, так как сообщение изменилось.", + "undo.failed.network": "Не удалось отменить. Проверьте подключение и повторите попытку.", + "undo.failed.server": "Не удалось отменить. Повторите попытку.", + "undo.partialRestored": "Восстановлено {restored} из {total} сообщений. Остальные отменить не удалось.", + "undo.successAnnouncement": "Отмена завершена: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/si.json b/public/locales/si.json index f0e3b7a6a..6a894744a 100644 --- a/public/locales/si.json +++ b/public/locales/si.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "පණිවිඩ ක්‍රියා දැනුම්දීම්", + "undo.undoing": "පෙරලමින්…", + "undo.retry": "නැවත උත්සාහ කරන්න", + "undo.failed.expired": "මෙම පෙරලීම කල් ඉකුත් වී ඇත.", + "undo.failed.unavailable": "එම පණිවිඩය තවදුරටත් පෙරලීමට ලබාගත නොහැක.", + "undo.failed.stale": "පණිවිඩය වෙනස් වී ඇති බැවින් මෙම වෙනස තවදුරටත් පෙරලිය නොහැක.", + "undo.failed.network": "පෙරලීම අසාර්ථක විය. ඔබගේ සම්බන්ධතාවය පරීක්ෂා කර නැවත උත්සාහ කරන්න.", + "undo.failed.server": "පෙරලීම අසාර්ථක විය. කරුණාකර නැවත උත්සාහ කරන්න.", + "undo.partialRestored": "පණිවිඩ {total} කින් {restored} ක් ප්‍රතිසාධනය කරන ලදී. ඉතිරිය පෙරලිය නොහැකි විය.", + "undo.successAnnouncement": "පෙරලීම සම්පූර්ණයි: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/sw.json b/public/locales/sw.json index 692415eba..1eaa8d9ed 100644 --- a/public/locales/sw.json +++ b/public/locales/sw.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Arifa za vitendo vya ujumbe", + "undo.undoing": "Inatendua…", + "undo.retry": "Jaribu tena", + "undo.failed.expired": "Utenduzi huu umeisha muda.", + "undo.failed.unavailable": "Ujumbe huo haupatikani tena ili utenduliwe.", + "undo.failed.stale": "Badiliko hili haliwezi kutenduliwa tena kwa sababu ujumbe umebadilika.", + "undo.failed.network": "Utenduzi umeshindwa. Angalia muunganisho wako na ujaribu tena.", + "undo.failed.server": "Utenduzi umeshindwa. Tafadhali jaribu tena.", + "undo.partialRestored": "Ujumbe {restored} kati ya {total} umerejeshwa. Uliobaki haukuweza kutenduliwa.", + "undo.successAnnouncement": "Utenduzi umekamilika: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ta.json b/public/locales/ta.json index 6b2ea58c2..07fd2e768 100644 --- a/public/locales/ta.json +++ b/public/locales/ta.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "செய்தி செயல் அறிவிப்புகள்", + "undo.undoing": "செயலிழக்கப்படுகிறது…", + "undo.retry": "மீண்டும் முயற்சிக்கவும்", + "undo.failed.expired": "இந்த செயலிழப்பு காலாவதியானது.", + "undo.failed.unavailable": "அந்தச் செய்தி இனி செயலிழக்கக் கிடைக்காது.", + "undo.failed.stale": "செய்தி மாறியதால் இந்த மாற்றத்தை இனி செயலிழக்க முடியாது.", + "undo.failed.network": "செயலிழக்க முடியவில்லை. உங்கள் இணைப்பைச் சரிபார்த்து மீண்டும் முயற்சிக்கவும்.", + "undo.failed.server": "செயலிழக்க முடியவில்லை. மீண்டும் முயற்சிக்கவும்.", + "undo.partialRestored": "{total} செய்திகளில் {restored} மீட்டெடுக்கப்பட்டன. மீதமுள்ளவை செயலிழக்க முடியவில்லை.", + "undo.successAnnouncement": "செயலிழப்பு முடிந்தது: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/te.json b/public/locales/te.json index ffaffee1b..d317c669d 100644 --- a/public/locales/te.json +++ b/public/locales/te.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "సందేశ చర్య నోటిఫికేషన్‌లు", + "undo.undoing": "చర్య రద్దు చేయబడుతోంది…", + "undo.retry": "మళ్లీ ప్రయత్నించండి", + "undo.failed.expired": "ఈ చర్య రద్దు గడువు ముగిసింది.", + "undo.failed.unavailable": "ఆ సందేశం ఇకపై చర్య రద్దు కోసం అందుబాటులో లేదు.", + "undo.failed.stale": "సందేశం మారినందున ఈ మార్పును ఇకపై రద్దు చేయలేరు.", + "undo.failed.network": "చర్య రద్దు విఫలమైంది. మీ కనెక్షన్‌ను తనిఖీ చేసి మళ్లీ ప్రయత్నించండి.", + "undo.failed.server": "చర్య రద్దు విఫలమైంది. దయచేసి మళ్లీ ప్రయత్నించండి.", + "undo.partialRestored": "{total} సందేశాలలో {restored} పునరుద్ధరించబడ్డాయి. మిగిలినవి రద్దు చేయలేకపోయాం.", + "undo.successAnnouncement": "చర్య రద్దు పూర్తయింది: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/th.json b/public/locales/th.json index 8709517ae..4e847fb11 100644 --- a/public/locales/th.json +++ b/public/locales/th.json @@ -2451,6 +2451,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "การแจ้งเตือนการดำเนินการกับข้อความ", + "undo.undoing": "กำลังเลิกทำ…", + "undo.retry": "ลองอีกครั้ง", + "undo.failed.expired": "การเลิกทำนี้หมดอายุแล้ว", + "undo.failed.unavailable": "ไม่สามารถเลิกทำข้อความนั้นได้อีกต่อไป", + "undo.failed.stale": "ไม่สามารถเลิกทำการเปลี่ยนแปลงนี้ได้อีกเนื่องจากข้อความถูกเปลี่ยนแล้ว", + "undo.failed.network": "เลิกทำไม่สำเร็จ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง", + "undo.failed.server": "เลิกทำไม่สำเร็จ โปรดลองอีกครั้ง", + "undo.partialRestored": "กู้คืนแล้ว {restored} จาก {total} ข้อความ ส่วนที่เหลือไม่สามารถเลิกทำได้", + "undo.successAnnouncement": "เลิกทำเสร็จสิ้น: {action}", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/tr.json b/public/locales/tr.json index 138e515cf..e76471561 100644 --- a/public/locales/tr.json +++ b/public/locales/tr.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Mesaj işlemi bildirimleri", + "undo.undoing": "Geri alınıyor…", + "undo.retry": "Yeniden dene", + "undo.failed.expired": "Bu geri alma işleminin süresi doldu.", + "undo.failed.unavailable": "O mesaj artık geri alınamaz.", + "undo.failed.stale": "Mesaj değiştiği için bu değişiklik artık geri alınamaz.", + "undo.failed.network": "Geri alma başarısız. Bağlantınızı kontrol edip yeniden deneyin.", + "undo.failed.server": "Geri alma başarısız. Lütfen yeniden deneyin.", + "undo.partialRestored": "{total} mesajdan {restored} tanesi geri yüklendi. Kalanlar geri alınamadı.", + "undo.successAnnouncement": "Geri alma tamamlandı: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/uk.json b/public/locales/uk.json index 3fde0edac..2a870fe5d 100644 --- a/public/locales/uk.json +++ b/public/locales/uk.json @@ -2485,6 +2485,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Сповіщення про дії з повідомленнями", + "undo.undoing": "Скасування…", + "undo.retry": "Повторити", + "undo.failed.expired": "Термін скасування минув.", + "undo.failed.unavailable": "Це повідомлення більше недоступне для скасування.", + "undo.failed.stale": "Цю зміну більше не можна скасувати, оскільки повідомлення змінилося.", + "undo.failed.network": "Не вдалося скасувати. Перевірте з’єднання та повторіть спробу.", + "undo.failed.server": "Не вдалося скасувати. Повторіть спробу.", + "undo.partialRestored": "Відновлено {restored} з {total} повідомлень. Решту скасувати не вдалося.", + "undo.successAnnouncement": "Скасування завершено: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/ur.json b/public/locales/ur.json index 6245aab05..bbe2b53d0 100644 --- a/public/locales/ur.json +++ b/public/locales/ur.json @@ -2455,6 +2455,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "پیغام کے اعمال کی اطلاعات", + "undo.undoing": "واپس کیا جا رہا ہے…", + "undo.retry": "دوبارہ کوشش کریں", + "undo.failed.expired": "اس واپسی کی مدت ختم ہو گئی ہے۔", + "undo.failed.unavailable": "وہ پیغام اب واپس کرنے کے لیے دستیاب نہیں ہے۔", + "undo.failed.stale": "پیغام تبدیل ہونے کی وجہ سے یہ تبدیلی اب واپس نہیں کی جا سکتی۔", + "undo.failed.network": "واپس کرنا ناکام رہا۔ اپنا کنکشن چیک کریں اور دوبارہ کوشش کریں۔", + "undo.failed.server": "واپس کرنا ناکام رہا۔ براہ کرم دوبارہ کوشش کریں۔", + "undo.partialRestored": "{total} میں سے {restored} پیغامات بحال ہوئے۔ باقی واپس نہیں کیے جا سکے۔", + "undo.successAnnouncement": "واپس کرنا مکمل: {action}۔", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/vi.json b/public/locales/vi.json index 8e67b84a6..9b5401e1b 100644 --- a/public/locales/vi.json +++ b/public/locales/vi.json @@ -2437,6 +2437,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "Thông báo thao tác tin nhắn", + "undo.undoing": "Đang hoàn tác…", + "undo.retry": "Thử lại", + "undo.failed.expired": "Thao tác hoàn tác này đã hết hạn.", + "undo.failed.unavailable": "Tin nhắn đó không còn khả dụng để hoàn tác.", + "undo.failed.stale": "Không thể hoàn tác thay đổi này nữa vì tin nhắn đã thay đổi.", + "undo.failed.network": "Hoàn tác không thành công. Kiểm tra kết nối và thử lại.", + "undo.failed.server": "Hoàn tác không thành công. Vui lòng thử lại.", + "undo.partialRestored": "Đã khôi phục {restored} trên {total} tin nhắn. Phần còn lại không thể hoàn tác.", + "undo.successAnnouncement": "Hoàn tác hoàn tất: {action}.", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.json index b75be4340..bfe8b1340 100644 --- a/public/locales/zh-CN.json +++ b/public/locales/zh-CN.json @@ -2437,6 +2437,16 @@ "undo.button": "Undo", "undo.dismiss": "Dismiss", "undo.failed": "Could not undo that change", + "undo.region": "邮件操作通知", + "undo.undoing": "正在撤销…", + "undo.retry": "重试", + "undo.failed.expired": "此撤销已过期。", + "undo.failed.unavailable": "该邮件已无法撤销。", + "undo.failed.stale": "邮件已更改,因此此更改无法再撤销。", + "undo.failed.network": "撤销失败。请检查网络连接并重试。", + "undo.failed.server": "撤销失败。请重试。", + "undo.partialRestored": "已恢复 {total} 封邮件中的 {restored} 封。其余邮件无法撤销。", + "undo.successAnnouncement": "撤销完成:{action}。", "undo.partial": "{applied} of {total} messages updated", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", diff --git a/src/components/messages/undo-toasts.tsx b/src/components/messages/undo-toasts.tsx index 39c1cfed5..47a5fc54b 100644 --- a/src/components/messages/undo-toasts.tsx +++ b/src/components/messages/undo-toasts.tsx @@ -1,17 +1,32 @@ "use client"; -import { useSyncExternalStore } from "react"; +import { useEffect, useRef, useState, useSyncExternalStore } from "react"; import { useLanguage } from "@/components/language-provider"; -import { undoMessageAction } from "@/lib/messages/actions/client"; -import type { ReversibleMessageAction } from "@/lib/messages/actions/types"; +import { Loader2 } from "@/components/icons"; +import { MessageActionRequestError, undoMessageAction } from "@/lib/messages/actions/client"; +import type { + MessageActionSkipped, + ReversibleMessageAction, +} from "@/lib/messages/actions/types"; import { beginUndoToast, + completeUndoToast, dismissUndoToast, failUndoToast, + getUndoAnnouncements, getUndoToasts, + partialUndoToast, + pauseUndoToast, + resumeUndoToast, subscribeUndoToasts, } from "@/lib/messages/actions/undo-store"; -import type { UndoToastEntry } from "@/lib/messages/actions/undo-store"; +import type { + UndoToastAnnouncement, + UndoToastEntry, + UndoToastFailure, + UndoToastFailureKind, +} from "@/lib/messages/actions/undo-store"; +import type { Translator } from "@/lib/i18n/utils"; import type { TranslationKey } from "@/lib/i18n/types"; import { cn } from "@/lib/utils"; @@ -29,72 +44,278 @@ const ACTION_LABELS: Record = { unsnooze: "undo.label.unsnooze", }; -const EMPTY: UndoToastEntry[] = []; +const FAILURE_LABELS: Record = { + expired: "undo.failed.expired", + unavailable: "undo.failed.unavailable", + stale: "undo.failed.stale", + network: "undo.failed.network", + server: "undo.failed.server", +}; + +const EMPTY_TOASTS: UndoToastEntry[] = []; +const EMPTY_ANNOUNCEMENTS: UndoToastAnnouncement[] = []; +const MODAL_SELECTOR = '[role="dialog"][aria-modal="true"], [aria-modal="true"], dialog[open], .dialog-overlay'; + +/** Modal layers sit at z-50 and trap focus; the passive undo stack must not compete with them. */ +function hasOpenModal() { + if (typeof document === "undefined") return false; + return !!document.querySelector(MODAL_SELECTOR); +} + +function subscribeModalState(onChange: () => void) { + if (typeof document === "undefined") return () => undefined; + const observer = new MutationObserver(onChange); + observer.observe(document.documentElement, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ["role", "aria-modal", "class", "open"], + }); + return () => observer.disconnect(); +} + +function useModalOpen() { + return useSyncExternalStore(subscribeModalState, hasOpenModal, () => false); +} + +function failureFromError(error: unknown): UndoToastFailure { + if (error instanceof MessageActionRequestError) { + if (error.status === 410) return { kind: "expired", retryable: false }; + if (error.status === 404) return { kind: "unavailable", retryable: false }; + if (error.status === 409 || error.status === 412 || error.status === 422) { + return { kind: "stale", retryable: false }; + } + if (error.status === 408 || error.status === 425 || error.status === 429 || error.status >= 500) { + return { kind: "server", retryable: true }; + } + return { kind: "server", retryable: false }; + } + // fetch rejects on a dropped connection; a later Retry can succeed. + return { kind: "network", retryable: true }; +} + +function failureFromSkipped(skipped: MessageActionSkipped[]): UndoToastFailure { + const reasons = new Set(skipped.map((item) => item.reason)); + if (reasons.has("failed")) return { kind: "server", retryable: true }; + if (reasons.has("stale")) return { kind: "stale", retryable: false }; + if (reasons.has("not_found") || reasons.has("forbidden") || reasons.has("invalid_target") || reasons.has("not_applicable")) { + return { kind: "unavailable", retryable: false }; + } + return { kind: "server", retryable: false }; +} + +function actionLabel(t: Translator, action: ReversibleMessageAction) { + return t(ACTION_LABELS[action]); +} + +function appliedText(t: Translator, action: ReversibleMessageAction, count: number, skipped = 0) { + const label = actionLabel(t, action); + const text = count > 1 ? t("undo.bulk", { action: label, count }) : label; + return skipped > 0 ? `${text}. ${t("undo.partial", { applied: count, total: count + skipped })}` : text; +} + +function announcementText(t: Translator, announcement: UndoToastAnnouncement) { + if (announcement.kind === "undo-success") { + return t("undo.successAnnouncement", { action: actionLabel(t, announcement.action) }); + } + if (announcement.kind === "undo-partial") { + return t("undo.partialRestored", { + restored: announcement.restored ?? 0, + total: announcement.count, + }); + } + if (announcement.kind === "undo-failed") { + const reason = announcement.failure ? t(FAILURE_LABELS[announcement.failure.kind]) : ""; + return reason || t("undo.failed"); + } + return appliedText(t, announcement.action, announcement.count, announcement.skipped); +} + +/** + * After a toast button removes its own toast, keyboard focus would fall back to + * the document. Return it to the stable main landmark instead of losing it. + */ +function restoreFocusAfterRemoval() { + if (typeof window === "undefined") return; + window.setTimeout(() => { + const active = document.activeElement; + if (active && active !== document.body && (active as HTMLElement).isConnected) return; + document.getElementById("main-content")?.focus({ preventScroll: true }); + }, 0); +} /** Independent stack for message-action undo; compose's single send notice is untouched. */ export function UndoToasts() { const { t } = useLanguage(); - const toasts = useSyncExternalStore(subscribeUndoToasts, getUndoToasts, () => EMPTY); - if (toasts.length === 0) return null; + const toasts = useSyncExternalStore(subscribeUndoToasts, getUndoToasts, () => EMPTY_TOASTS); + const announcements = useSyncExternalStore(subscribeUndoToasts, getUndoAnnouncements, () => EMPTY_ANNOUNCEMENTS); + const modalOpen = useModalOpen(); + const [polite, setPolite] = useState<{ text: string; sequence: number } | null>(null); + const [assertive, setAssertive] = useState<{ text: string; sequence: number } | null>(null); + // A late mount must not replay announcements that were already made. New + // announcements always carry a higher sequence and are announced normally. + const seenAnnouncement = useRef(announcements.at(-1)?.sequence ?? 0); + + useEffect(() => { + const latest = announcements.at(-1)?.sequence ?? 0; + const fresh = announcements.filter((item) => item.sequence > seenAnnouncement.current); + if (fresh.length === 0) return; + seenAnnouncement.current = latest; + const politeText = fresh + .filter((item) => item.kind !== "undo-failed" && item.kind !== "undo-partial") + .map((item) => announcementText(t, item)) + .join(" "); + const assertiveText = fresh + .filter((item) => item.kind === "undo-failed" || item.kind === "undo-partial") + .map((item) => announcementText(t, item)) + .join(" "); + if (politeText) setPolite({ text: politeText, sequence: latest }); + if (assertiveText) setAssertive({ text: assertiveText, sequence: latest }); + }, [announcements, t]); async function undo(entry: UndoToastEntry) { - if (entry.status !== "idle") return; - beginUndoToast(entry.id); + const current = getUndoToasts().find((item) => item.id === entry.id); + if (!current) return; + if (current.status !== "idle" && !(current.status === "failed" && current.failure?.retryable)) return; + beginUndoToast(current.id); try { - const result = await undoMessageAction(entry); - if (result.restored.length === 0) failUndoToast(entry.id); - else dismissUndoToast(entry.id); - } catch { - failUndoToast(entry.id); + const result = await undoMessageAction(current); + const total = current.records.length; + const restoredIds = new Set(result.restored); + const restored = current.records.filter((record) => restoredIds.has(record.id)).length; + const undoSkipCount = Math.max(result.skipped.length, total - restored); + if (restored === 0) { + const failure = failureFromSkipped(result.skipped); + failUndoToast(current.id, failure); + if (!failure.retryable) restoreFocusAfterRemoval(); + } else if (restored < total || result.skipped.length > 0) { + partialUndoToast(current.id, { + restored, + skipped: undoSkipCount, + skippedReasons: result.skipped.map((item) => item.reason), + }); + restoreFocusAfterRemoval(); + } else { + completeUndoToast(current.id); + restoreFocusAfterRemoval(); + } + } catch (error) { + const failure = failureFromError(error); + failUndoToast(current.id, failure); + // Retryable failures keep the same primary button, so focus stays put. + if (!failure.retryable) restoreFocusAfterRemoval(); } } + function dismiss(entry: UndoToastEntry) { + dismissUndoToast(entry.id); + restoreFocusAfterRemoval(); + } + return ( -
- {toasts.map((entry) => { - const label = t(ACTION_LABELS[entry.action]); - const text = entry.records.length > 1 - ? t("undo.bulk", { action: label, count: entry.records.length }) - : label; - return ( -
-
-

{entry.status === "failed" ? t("undo.failed") : text}

- {entry.skipped > 0 && entry.status !== "failed" && ( -

- {t("undo.partial", { applied: entry.records.length, total: entry.records.length + entry.skipped })} -

- )} -
- {entry.status !== "failed" && ( - - )} - -
- ); - })} -
+
+

{mainText}

+ {entry.context && !failed && !partial && ( +

{entry.context}

+ )} + {failed && entry.failure && ( +

+ {t(FAILURE_LABELS[entry.failure.kind])} +

+ )} + {partial && ( +

{label}

+ )} +
+ {primary && ( + + )} + + + ); + })} + + )} + ); } diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json index af1c34449..6fa2bb189 100644 --- a/src/lib/i18n/en.json +++ b/src/lib/i18n/en.json @@ -2459,8 +2459,18 @@ "attachment.downloadAllFlagged": "Some attachments are flagged as potentially dangerous. Download the archive anyway?", "undo.button": "Undo", "undo.dismiss": "Dismiss", + "undo.region": "Message action notifications", + "undo.undoing": "Undoing…", + "undo.retry": "Try again", "undo.failed": "Could not undo that change", + "undo.failed.expired": "This undo has expired.", + "undo.failed.unavailable": "That message is no longer available to undo.", + "undo.failed.stale": "That change can no longer be undone because the message changed.", + "undo.failed.network": "Undo failed. Check your connection and try again.", + "undo.failed.server": "Undo failed. Please try again.", "undo.partial": "{applied} of {total} messages updated", + "undo.partialRestored": "{restored} of {total} messages restored. The rest could not be undone.", + "undo.successAnnouncement": "Undo complete: {action}.", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", "undo.label.archive": "Archived", diff --git a/src/lib/messages/actions/undo-store.ts b/src/lib/messages/actions/undo-store.ts index ab63ae85c..c3e9a9ef1 100644 --- a/src/lib/messages/actions/undo-store.ts +++ b/src/lib/messages/actions/undo-store.ts @@ -1,49 +1,195 @@ "use client"; -import type { MessageActionRecord, ReversibleMessageAction } from "./types"; +import { AUTH_SESSION_CHANGED_EVENT } from "@/lib/auth/client"; +import type { + MessageActionRecord, + MessageActionSkipReason, + ReversibleMessageAction, +} from "./types"; -export type UndoToastStatus = "idle" | "undoing" | "failed"; +export type UndoToastStatus = "idle" | "undoing" | "failed" | "partial"; + +export type UndoToastFailureKind = + | "expired" + | "unavailable" + | "stale" + | "network" + | "server"; + +export type UndoToastFailure = { + kind: UndoToastFailureKind; + /** Only transient transport/server failures offer Retry; expiry and stale states do not. */ + retryable: boolean; +}; export type UndoToastEntry = { id: number; action: ReversibleMessageAction; records: MessageActionRecord[]; undoToken: string; + /** Messages the original action could not apply. */ skipped: number; status: UndoToastStatus; + /** Optional human-readable folder name or snooze time supplied by the caller. */ + context?: string; + failure?: UndoToastFailure; + /** Set when Undo restored only some of the action's messages. */ + restored?: number; + undoSkipped?: number; + undoSkippedReasons?: MessageActionSkipReason[]; }; -const UNDO_WINDOW_MS = 9000; -const FAILED_WINDOW_MS = 5000; -const MAX_TOASTS = 4; +export type UndoToastAnnouncementKind = + | "applied" + | "undo-success" + | "undo-partial" + | "undo-failed"; + +export type UndoToastAnnouncement = { + sequence: number; + kind: UndoToastAnnouncementKind; + action: ReversibleMessageAction; + count: number; + skipped?: number; + restored?: number; + failure?: UndoToastFailure; +}; + +export const UNDO_TOAST_LIMITS = Object.freeze({ + visible: 4, + /** Bounded FIFO spillover; a queued entry's countdown starts only when it becomes visible. */ + queued: 12, +}); + +/** Long enough to reach the notification with a keyboard, and it pauses while hovered, focused or hidden. */ +export const UNDO_WINDOW_MS = 20_000; + +const MAX_ANNOUNCEMENTS = 20; let entries: UndoToastEntry[] = []; +let queued: UndoToastEntry[] = []; +let announcements: UndoToastAnnouncement[] = []; let nextId = 0; -const timers = new Map(); +let nextAnnouncementId = 0; +let pageHidden = false; +let lifecycleBound = false; const listeners = new Set<() => void>(); +const timers = new Map(); +const remaining = new Map(); +const pauseReasons = new Map>(); function emit() { for (const listener of listeners) listener(); } -function setTimer(id: number, delay: number) { - if (typeof window === "undefined") return; - const existing = timers.get(id); - if (existing) window.clearTimeout(existing); - timers.set(id, window.setTimeout(() => { - timers.delete(id); - dismissUndoToast(id); - }, delay)); +function entryById(id: number): UndoToastEntry | undefined { + return entries.find((entry) => entry.id === id) ?? queued.find((entry) => entry.id === id); +} + +function replaceEntry(id: number, update: (entry: UndoToastEntry) => UndoToastEntry) { + entries = entries.map((entry) => (entry.id === id ? update(entry) : entry)); + queued = queued.map((entry) => (entry.id === id ? update(entry) : entry)); +} + +function announce(announcement: Omit) { + announcements = [ + ...announcements.slice(-(MAX_ANNOUNCEMENTS - 1)), + { ...announcement, sequence: ++nextAnnouncementId }, + ]; +} + +function timerIsHeld(id: number): boolean { + return pageHidden || (pauseReasons.get(id)?.size ?? 0) > 0; } function clearTimer(id: number) { if (typeof window === "undefined") return; const timer = timers.get(id); - if (timer) window.clearTimeout(timer); + if (timer) window.clearTimeout(timer.handle); timers.delete(id); + remaining.delete(id); +} + +function pauseTimer(id: number) { + const timer = timers.get(id); + if (!timer) return; + remaining.set(id, Math.max(0, timer.deadline - Date.now())); + window.clearTimeout(timer.handle); + timers.delete(id); +} + +function scheduleTimer(id: number, delay: number) { + if (typeof window === "undefined") return; + if (timerIsHeld(id)) { + remaining.set(id, delay); + return; + } + const existing = timers.get(id); + if (existing) window.clearTimeout(existing.handle); + remaining.set(id, delay); + const handle = window.setTimeout(() => { + timers.delete(id); + remaining.delete(id); + // A focused toast must never vanish from under the user. If focus arrived + // between the deadline and this callback, hold it until focus leaves. + if (isToastFocused(id)) { + remaining.set(id, 0); + pauseUndoToast(id, "focus"); + return; + } + dismissUndoToast(id); + }, delay); + timers.set(id, { handle, deadline: Date.now() + delay }); +} + +function isToastFocused(id: number): boolean { + if (typeof document === "undefined") return false; + const toast = document.querySelector(`[data-undo-toast-id="${id}"]`); + return !!toast && toast.contains(document.activeElement); +} + +function startVisibleTimer(id: number) { + scheduleTimer(id, UNDO_WINDOW_MS); +} + +function promoteQueued() { + if (queued.length === 0 || entries.length >= UNDO_TOAST_LIMITS.visible) return; + const promoted = queued[0]; + queued = queued.slice(1); + entries = [...entries, promoted]; + startVisibleTimer(promoted.id); +} + +function removeEntry(id: number) { + clearTimer(id); + pauseReasons.delete(id); + entries = entries.filter((entry) => entry.id !== id); + queued = queued.filter((entry) => entry.id !== id); + promoteQueued(); +} + +function updatePageHidden(hidden: boolean) { + if (pageHidden === hidden) return; + pageHidden = hidden; + for (const entry of entries) { + if (entry.status !== "idle") continue; + if (hidden) pauseTimer(entry.id); + else if (!timerIsHeld(entry.id)) scheduleTimer(entry.id, remaining.get(entry.id) ?? UNDO_WINDOW_MS); + } +} + +function bindLifecycle() { + if (lifecycleBound || typeof window === "undefined") return; + lifecycleBound = true; + pageHidden = typeof document !== "undefined" && document.hidden; + window.addEventListener(AUTH_SESSION_CHANGED_EVENT, resetUndoToasts); + if (typeof document !== "undefined") { + document.addEventListener("visibilitychange", () => updatePageHidden(document.hidden)); + } } export function subscribeUndoToasts(listener: () => void) { + bindLifecycle(); listeners.add(listener); return () => listeners.delete(listener); } @@ -52,53 +198,168 @@ export function getUndoToasts(): UndoToastEntry[] { return entries; } +/** Entries waiting for a visible slot. Their countdown has not started. */ +export function getQueuedUndoToasts(): UndoToastEntry[] { + return queued; +} + +export function getUndoAnnouncements(): UndoToastAnnouncement[] { + return announcements; +} + /** Adds an independent toast; compose's single send notice is never touched. */ export function showUndoToast(input: { action: ReversibleMessageAction; records: MessageActionRecord[]; undoToken?: string; skipped?: number; + /** Generic folder/snooze labels can add a folder name or time without new translation keys. */ + context?: string; }): number | null { if (!input.undoToken || input.records.length === 0 || typeof window === "undefined") return null; + bindLifecycle(); const id = ++nextId; - entries = [ - ...entries.slice(-(MAX_TOASTS - 1)), - { - id, - action: input.action, - records: input.records, - undoToken: input.undoToken, - skipped: input.skipped ?? 0, - status: "idle", - }, - ]; - setTimer(id, UNDO_WINDOW_MS); + const entry: UndoToastEntry = { + id, + action: input.action, + records: input.records, + undoToken: input.undoToken, + skipped: input.skipped ?? 0, + status: "idle", + ...(input.context ? { context: input.context } : {}), + }; + if (entries.length < UNDO_TOAST_LIMITS.visible) { + entries = [...entries, entry]; + startVisibleTimer(id); + } else { + // Keep the newest notices. The oldest queued entry is still an action the + // user just made, so this only happens after a long burst of read/star + // chatter; the visible stack itself is never silently replaced. + queued = [...queued, entry].slice(-UNDO_TOAST_LIMITS.queued); + } + announce({ + kind: "applied", + action: entry.action, + count: entry.records.length, + skipped: entry.skipped, + }); emit(); return id; } export function beginUndoToast(id: number) { + const entry = entryById(id); + if (!entry) return; clearTimer(id); - entries = entries.map((entry) => (entry.id === id ? { ...entry, status: "undoing" } : entry)); + pauseReasons.delete(id); + replaceEntry(id, (current) => ({ + ...current, + status: "undoing", + failure: undefined, + restored: undefined, + undoSkipped: undefined, + undoSkippedReasons: undefined, + })); emit(); } -export function failUndoToast(id: number) { - entries = entries.map((entry) => (entry.id === id ? { ...entry, status: "failed" } : entry)); - setTimer(id, FAILED_WINDOW_MS); +export function failUndoToast( + id: number, + failure: UndoToastFailure = { kind: "server", retryable: true }, +) { + const entry = entryById(id); + if (!entry) return; + clearTimer(id); + pauseReasons.delete(id); + replaceEntry(id, (current) => ({ + ...current, + status: "failed", + failure, + restored: undefined, + undoSkipped: undefined, + undoSkippedReasons: undefined, + })); + announce({ kind: "undo-failed", action: entry.action, count: entry.records.length, failure }); emit(); } -export function dismissUndoToast(id: number) { +/** Keeps a partial result visible instead of reporting full success. */ +export function partialUndoToast( + id: number, + result: { restored: number; skipped: number; skippedReasons?: MessageActionSkipReason[] }, +) { + const entry = entryById(id); + if (!entry) return; clearTimer(id); - entries = entries.filter((entry) => entry.id !== id); + pauseReasons.delete(id); + replaceEntry(id, (current) => ({ + ...current, + status: "partial", + failure: undefined, + restored: result.restored, + undoSkipped: result.skipped, + undoSkippedReasons: result.skippedReasons, + })); + announce({ + kind: "undo-partial", + action: entry.action, + count: entry.records.length, + restored: result.restored, + }); emit(); } -/** Test-only reset; the provider never calls this. */ -export function resetUndoToastsForTests() { - for (const id of timers.keys()) clearTimer(id); +/** Removes a successfully undone toast and announces the completion. */ +export function completeUndoToast(id: number) { + const entry = entryById(id); + if (!entry) return; + removeEntry(id); + announce({ kind: "undo-success", action: entry.action, count: entry.records.length }); + emit(); +} + +export function dismissUndoToast(id: number) { + if (!entryById(id)) return; + removeEntry(id); + emit(); +} + +export function pauseUndoToast(id: number, reason = "hold") { + const entry = entryById(id); + if (!entry || entry.status !== "idle") return; + const reasons = pauseReasons.get(id) ?? new Set(); + const wasHolding = reasons.size > 0; + reasons.add(reason); + pauseReasons.set(id, reasons); + if (!wasHolding) pauseTimer(id); +} + +export function resumeUndoToast(id: number, reason = "hold") { + const reasons = pauseReasons.get(id); + if (!reasons) return; + reasons.delete(reason); + if (reasons.size > 0) return; + pauseReasons.delete(id); + const entry = entryById(id); + if (!entry || entry.status !== "idle" || !entries.includes(entry) || timerIsHeld(id)) return; + scheduleTimer(id, remaining.get(id) ?? UNDO_WINDOW_MS); +} + +/** Clears every queue and timer on an account/session change. */ +export function resetUndoToasts() { + for (const id of [...timers.keys()]) clearTimer(id); entries = []; - nextId = 0; + queued = []; + announcements = []; + pauseReasons.clear(); + remaining.clear(); emit(); } + +/** Test-only reset; production keeps ids monotonic so late responses cannot hit a reused id. */ +export function resetUndoToastsForTests() { + resetUndoToasts(); + nextId = 0; + nextAnnouncementId = 0; + pageHidden = false; +} diff --git a/tests/message-undo-toast-store.test.mjs b/tests/message-undo-toast-store.test.mjs new file mode 100644 index 000000000..9c79cb6aa --- /dev/null +++ b/tests/message-undo-toast-store.test.mjs @@ -0,0 +1,255 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after, beforeEach } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-undo-toast-store-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +const dom = new JSDOM("", { url: "https://mail.example/", pretendToBeVisual: true }); +globalThis.window = dom.window; +globalThis.document = dom.window.document; +globalThis.HTMLElement = dom.window.HTMLElement; +globalThis.Node = dom.window.Node; +globalThis.Event = dom.window.Event; + +await build({ + stdin: { + contents: ` + export * from "./src/lib/messages/actions/undo-store.ts"; + export { AUTH_SESSION_CHANGED_EVENT } from "./src/lib/auth/client.ts"; + `, + resolveDir: root, + sourcefile: "undo-store-test-entry.ts", + }, + outfile: join(directory, "store.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + alias: { "@": join(root, "src") }, + logLevel: "silent", +}); + +const store = await import(pathToFileURL(join(directory, "store.mjs")).href); + +const originalNow = Date.now; +let now = 0; +let nextTimerId = 0; +let pendingTimers = []; + +window.setTimeout = (callback, delay = 0) => { + const id = ++nextTimerId; + pendingTimers.push({ id, at: now + Number(delay), callback }); + return id; +}; +window.clearTimeout = (id) => { + pendingTimers = pendingTimers.filter((timer) => timer.id !== id); +}; + +function advance(ms) { + now += ms; + for (;;) { + const due = pendingTimers + .filter((timer) => timer.at <= now) + .sort((a, b) => a.at - b.at || a.id - b.id)[0]; + if (!due) return; + pendingTimers = pendingTimers.filter((timer) => timer !== due); + due.callback(); + } +} + +Date.now = () => now; + +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); + +const record = (id) => ({ + id, + mailboxId: "mb1", + previous: state(), + applied: state({ read: true }), +}); + +const add = (id, action = "read", records = [record(`m${id}`)]) => + store.showUndoToast({ + action, + records, + undoToken: `token-${id}`, + }); + +beforeEach(() => { + pendingTimers = []; + document.body.replaceChildren(); + store.resetUndoToastsForTests(); +}); + +after(() => { + Date.now = originalNow; + dom.window.close(); + delete globalThis.window; + delete globalThis.document; + delete globalThis.HTMLElement; + delete globalThis.Node; + delete globalThis.Event; +}); + +test("an applied action starts a 20 second window and pauses while held", () => { + assert.equal(store.UNDO_WINDOW_MS, 20_000); + const id = add(1); + assert.ok(id); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), [id]); + + advance(5_000); + store.pauseUndoToast(id, "hover"); + advance(60_000); + assert.equal(store.getUndoToasts().length, 1, "a hovered toast stays"); + + store.resumeUndoToast(id, "hover"); + advance(14_999); + assert.equal(store.getUndoToasts().length, 1); + advance(1); + assert.equal(store.getUndoToasts().length, 0); +}); + +test("a hidden tab pauses every idle countdown until it becomes visible", () => { + const first = add(1); + const second = add(2); + advance(4_000); + + let hidden = true; + Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden }); + document.dispatchEvent(new window.Event("visibilitychange")); + advance(90_000); + assert.equal(store.getUndoToasts().length, 2, "nothing expires in the background"); + + hidden = false; + document.dispatchEvent(new window.Event("visibilitychange")); + advance(15_999); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), [first, second]); + advance(1); + assert.equal(store.getUndoToasts().length, 0); +}); + +test("expiry never removes a toast that owns keyboard focus", () => { + const id = add(1); + const holder = document.createElement("div"); + holder.dataset.undoToastId = String(id); + const button = document.createElement("button"); + button.textContent = "Undo"; + holder.appendChild(button); + document.body.appendChild(holder); + button.focus(); + + advance(store.UNDO_WINDOW_MS); + assert.equal(store.getUndoToasts().length, 1, "the focused toast remains"); + assert.equal(store.getUndoToasts()[0].status, "idle"); + + button.blur(); + store.resumeUndoToast(id, "focus"); + advance(0); + assert.equal(store.getUndoToasts().length, 0, "it expires after focus leaves"); +}); + +test("visible toasts stay capped while active entries queue, and queued timers start on promotion", () => { + const ids = [1, 2, 3, 4, 5, 6, 7].map((id) => add(id, id % 2 ? "read" : "star")); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids.slice(0, 4)); + assert.deepEqual(store.getQueuedUndoToasts().map((entry) => entry.id), ids.slice(4)); + assert.deepEqual(store.getQueuedUndoToasts().map((entry) => entry.action), ["read", "star", "read"]); + + advance(store.UNDO_WINDOW_MS); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids.slice(4)); + assert.deepEqual(store.getQueuedUndoToasts(), []); + + advance(store.UNDO_WINDOW_MS - 1); + assert.equal(store.getUndoToasts().length, 3); + advance(1); + assert.equal(store.getUndoToasts().length, 0); +}); + +test("the overflow queue is bounded but never replaces the visible stack", () => { + const ids = Array.from({ length: 4 + store.UNDO_TOAST_LIMITS.queued + 1 }, (_, index) => add(index + 1)); + assert.equal(store.getUndoToasts().length, store.UNDO_TOAST_LIMITS.visible); + assert.equal(store.getQueuedUndoToasts().length, store.UNDO_TOAST_LIMITS.queued); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids.slice(0, 4)); + assert.deepEqual( + store.getQueuedUndoToasts().map((entry) => entry.id), + ids.slice(5), + "only the oldest queued entry is dropped when the spillover is full", + ); +}); + +test("failed undos stay until dismissed, and retryable failures can start again", () => { + const id = add(1); + store.beginUndoToast(id); + assert.equal(store.getUndoToasts()[0].status, "undoing"); + + store.failUndoToast(id, { kind: "server", retryable: true }); + advance(120_000); + assert.equal(store.getUndoToasts().length, 1); + assert.deepEqual(store.getUndoToasts()[0].failure, { kind: "server", retryable: true }); + assert.equal(store.getUndoAnnouncements().at(-1).kind, "undo-failed"); + + store.beginUndoToast(id); + assert.equal(store.getUndoToasts()[0].status, "undoing"); + assert.equal(store.getUndoToasts()[0].failure, undefined); + + store.partialUndoToast(id, { restored: 3, skipped: 2, skippedReasons: ["failed"] }); + advance(120_000); + assert.equal(store.getUndoToasts()[0].status, "partial"); + assert.equal(store.getUndoToasts()[0].restored, 3); + assert.equal(store.getUndoToasts()[0].undoSkipped, 2); + assert.deepEqual(store.getUndoToasts()[0].undoSkippedReasons, ["failed"]); + assert.equal(store.getUndoAnnouncements().at(-1).kind, "undo-partial"); + + store.completeUndoToast(id); + assert.equal(store.getUndoToasts().length, 0); + assert.equal(store.getUndoAnnouncements().at(-1).kind, "undo-success"); +}); + +test("an auth session change clears visible and queued toasts, timers and announcements", () => { + const first = add(1); + const second = add(2); + add(3); + add(4); + add(5); + assert.equal(store.getUndoToasts().length, 4); + assert.equal(store.getQueuedUndoToasts().length, 1); + + window.dispatchEvent(new window.Event(store.AUTH_SESSION_CHANGED_EVENT)); + assert.equal(store.getUndoToasts().length, 0); + assert.equal(store.getQueuedUndoToasts().length, 0); + assert.equal(store.getUndoAnnouncements().length, 0); + advance(store.UNDO_WINDOW_MS); + assert.equal(store.getUndoToasts().length, 0, "old timers cannot resurrect the prior session"); + + const next = add(9); + assert.ok(next > first && next > second, "ids stay monotonic so a late response cannot hit a reused toast"); +}); + +test("the announcement log keeps applied, success, partial and failure events in order", () => { + const first = add(1); + const second = add(2, "star"); + assert.deepEqual(store.getUndoAnnouncements().map((item) => item.kind), ["applied", "applied"]); + + store.beginUndoToast(first); + store.completeUndoToast(first); + store.beginUndoToast(second); + store.partialUndoToast(second, { restored: 1, skipped: 0 }); + + const kinds = store.getUndoAnnouncements().map((item) => item.kind); + assert.deepEqual(kinds, ["applied", "applied", "undo-success", "undo-partial"]); + assert.equal(store.getUndoAnnouncements().at(-1).count, 1); +}); diff --git a/tests/message-undo-toast-ui.test.mjs b/tests/message-undo-toast-ui.test.mjs new file mode 100644 index 000000000..7c86efe99 --- /dev/null +++ b/tests/message-undo-toast-ui.test.mjs @@ -0,0 +1,337 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; +import { act } from "react"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-undo-toast-ui-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +const dom = new JSDOM("", { + url: "https://mail.example/inbox", + pretendToBeVisual: true, +}); +after(() => dom.window.close()); +for (const key of ["window", "document", "HTMLElement", "Element", "Node", "Event", "MouseEvent", "MutationObserver", "HTMLInputElement"]) { + globalThis[key] = key === "window" ? dom.window : dom.window[key]; +} +globalThis.IS_REACT_ACT_ENVIRONMENT = true; +globalThis.requestAnimationFrame = dom.window.requestAnimationFrame.bind(dom.window); +globalThis.cancelAnimationFrame = dom.window.cancelAnimationFrame.bind(dom.window); + +await build({ + stdin: { + contents: ` + import { createElement } from "react"; + import { createRoot } from "react-dom/client"; + import { act } from "react"; + import { LanguageProvider } from "@/components/language-provider"; + import { UndoToasts } from "@/components/messages/undo-toasts"; + import * as store from "@/lib/messages/actions/undo-store"; + export { MessageActionRequestError } from "@/lib/messages/actions/client"; + export { act }; + export function showUndoToast(input) { return store.showUndoToast(input); } + export function resetStore() { store.resetUndoToastsForTests(); } + export async function flush() { + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + } + export async function mount() { + document.body.replaceChildren(); + const main = document.createElement("main"); + main.id = "main-content"; + main.tabIndex = -1; + document.body.appendChild(main); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(async () => { + root.render(createElement(LanguageProvider, { initialLocale: "en" }, createElement(UndoToasts))); + }); + return { + container, + async unmount() { await act(async () => root.unmount()); }, + }; + } + `, + resolveDir: root, + loader: "tsx", + }, + outfile: join(directory, "ui.mjs"), + bundle: true, + platform: "browser", + format: "esm", + target: "es2022", + tsconfig: join(root, "tsconfig.json"), + external: ["react", "react-dom", "react-dom/client", "jsdom"], + alias: { "@": join(root, "src") }, + logLevel: "silent", + loader: { ".js": "jsx" }, + plugins: [ + { + name: "undo-client-stub", + setup(builder) { + builder.onResolve({ filter: /^@\/lib\/messages\/actions\/client$/ }, () => ({ path: "client", namespace: "undo-stub" })); + builder.onLoad({ filter: /.*/, namespace: "undo-stub" }, () => ({ + contents: ` + export class MessageActionRequestError extends Error { + constructor(message, status = 400) { + super(message); + this.status = status; + this.name = "MessageActionRequestError"; + } + } + export function undoMessageAction(entry) { + return globalThis.undoHandler(entry); + } + `, + loader: "js", + })); + }, + }, + { + name: "runtime-stubs", + setup(builder) { + builder.onLoad({ filter: /\.css$/ }, () => ({ contents: "", loader: "js" })); + }, + }, + ], +}); + +const ui = await import(pathToFileURL(join(directory, "ui.mjs")).href); +const { MessageActionRequestError } = ui; + +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); + +const record = (id, action = "read") => ({ + id, + mailboxId: "mb1", + previous: state(), + applied: action === "star" ? state({ starred: true }) : state({ read: true }), +}); + +function reset() { + ui.resetStore(); + globalThis.undoHandler = undefined; + document.body.replaceChildren(); +} + +function show({ action = "archive", records = [record("m1")], token = "token-1", context } = {}) { + return ui.showUndoToast({ action, records, undoToken: token, ...(context ? { context } : {}) }); +} + +async function mount(t) { + reset(); + const app = await ui.mount(); + t.after(async () => { await app.unmount(); reset(); }); + return app; +} + +function toast(container, id) { + return container.querySelector(`[data-undo-toast-id="${id}"]`); +} + +function buttonByText(container, text) { + return [...container.querySelectorAll("button")].find((button) => button.textContent.trim() === text); +} + +test("live regions stay mounted while empty and applied actions announce politely", async (t) => { + const app = await mount(t); + const status = app.container.querySelector('[role="status"]'); + const alert = app.container.querySelector('[role="alert"]'); + assert.ok(status, "polite live region is always mounted"); + assert.ok(alert, "assertive live region is always mounted"); + assert.equal(status.getAttribute("aria-live"), "polite"); + assert.equal(alert.getAttribute("aria-live"), "assertive"); + assert.equal(status.textContent, ""); + assert.equal(alert.textContent, ""); + + const id = await act(async () => show({ context: "Receipts" })); + await ui.flush(); + assert.match(status.textContent, /Archived/); + assert.equal(alert.textContent, ""); + + const card = toast(app.container, id); + assert.ok(card); + assert.match(card.textContent, /Receipts/); + const describedBy = card.querySelector("button").getAttribute("aria-describedby"); + assert.equal(describedBy, `undo-toast-${id}-message`); + assert.ok(card.querySelector(`#${describedBy}`)); +}); + +test("the stack anchors in the content column, clears the mobile compose button and is keyboard reachable", async (t) => { + const app = await mount(t); + await act(async () => show()); + await ui.flush(); + const region = app.container.querySelector('[role="region"]'); + assert.ok(region); + assert.equal(region.tabIndex, 0); + assert.equal(region.getAttribute("aria-label"), "Message action notifications"); + const classes = region.className; + assert.match(classes, /z-40/); + assert.match(classes, /--sidebar-width/); + assert.match(classes, /bottom-\[max\(5rem/); + assert.match(classes, /env\(safe-area-inset-bottom/); + + const close = app.container.querySelector('button[aria-label="Dismiss"]'); + assert.match(close.className, /h-6/); + assert.match(close.className, /w-6/); + assert.match(close.className, /focus-visible:ring-2/); +}); + +test("undo pending shows a spinner and busy label, and locks dismissal", async (t) => { + const app = await mount(t); + let finish; + globalThis.undoHandler = () => new Promise((resolve) => { finish = resolve; }); + const id = await act(async () => show()); + await ui.flush(); + + const card = toast(app.container, id); + const undo = buttonByText(card, "Undo"); + await act(async () => { undo.click(); }); + await ui.flush(); + + assert.equal(card.getAttribute("aria-busy"), "true"); + assert.match(card.textContent, /Undoing…/); + assert.equal(buttonByText(card, "Undoing…").getAttribute("aria-disabled"), "true"); + const close = card.querySelector('button[aria-label="Dismiss"]'); + assert.equal(close.disabled, true, "dismiss cannot pretend to cancel a request already in flight"); + assert.ok(card.querySelector(".animate-spin")); + + await act(async () => { finish({ ok: true, action: "archive", restored: ["m1"], skipped: [] }); }); + await ui.flush(); + assert.equal(toast(app.container, id), null); + assert.match(app.container.querySelector('[role="status"]').textContent, /Undo complete: Archived/); + assert.equal(document.activeElement, document.getElementById("main-content")); +}); + +test("a transient server failure persists and Retry starts the same undo again", async (t) => { + const app = await mount(t); + let attempt = 0; + globalThis.undoHandler = async () => { + attempt += 1; + if (attempt === 1) throw new MessageActionRequestError("Temporary failure", 503); + return { ok: true, action: "archive", restored: ["m1"], skipped: [] }; + }; + const id = await act(async () => show()); + await ui.flush(); + + await act(async () => { buttonByText(toast(app.container, id), "Undo").click(); }); + await ui.flush(); + const card = toast(app.container, id); + assert.ok(card, "a failed undo remains visible"); + assert.match(card.textContent, /Could not undo that change/); + assert.match(card.textContent, /Undo failed\. Please try again\./); + assert.match(app.container.querySelector('[role="alert"]').textContent, /Undo failed/); + const retry = buttonByText(card, "Try again"); + assert.ok(retry, "transient failures offer Retry"); + + await act(async () => { retry.click(); }); + await ui.flush(); + assert.equal(toast(app.container, id), null); + assert.equal(attempt, 2); + assert.match(app.container.querySelector('[role="status"]').textContent, /Undo complete/); +}); + +test("expired undos persist without Retry and announce the actual reason", async (t) => { + const app = await mount(t); + globalThis.undoHandler = async () => { throw new MessageActionRequestError("This undo has expired", 410); }; + const id = await act(async () => show()); + await ui.flush(); + + await act(async () => { buttonByText(toast(app.container, id), "Undo").click(); }); + await ui.flush(); + const card = toast(app.container, id); + assert.ok(card); + assert.match(card.textContent, /This undo has expired\./); + assert.equal(buttonByText(card, "Try again"), undefined); + assert.match(app.container.querySelector('[role="alert"]').textContent, /This undo has expired/); +}); + +test("stale skipped results stay persistent and do not pretend the action was undone", async (t) => { + const app = await mount(t); + globalThis.undoHandler = async () => ({ + ok: true, + action: "archive", + restored: [], + skipped: [{ id: "m1", reason: "stale" }], + }); + const id = await act(async () => show()); + await ui.flush(); + + await act(async () => { buttonByText(toast(app.container, id), "Undo").click(); }); + await ui.flush(); + const card = toast(app.container, id); + assert.ok(card); + assert.match(card.textContent, /message changed/); + assert.equal(buttonByText(card, "Try again"), undefined); + assert.match(app.container.querySelector('[role="alert"]').textContent, /message changed/); +}); + +test("a partial restore shows its own notice and announcement, not full success", async (t) => { + const app = await mount(t); + globalThis.undoHandler = async () => ({ + ok: true, + action: "archive", + restored: ["m1"], + skipped: [{ id: "m2", reason: "failed" }], + }); + const records = [record("m1"), record("m2")]; + const id = await act(async () => show({ records })); + await ui.flush(); + + await act(async () => { buttonByText(toast(app.container, id), "Undo").click(); }); + await ui.flush(); + const card = toast(app.container, id); + assert.ok(card, "a partial restore stays visible"); + assert.match(card.textContent, /1 of 2 messages restored\. The rest could not be undone\./); + assert.equal(buttonByText(card, "Try again"), undefined, "retrying the whole token is not offered after a partial restore"); + assert.match(app.container.querySelector('[role="alert"]').textContent, /1 of 2 messages restored/); + assert.doesNotMatch(app.container.querySelector('[role="status"]').textContent, /Undo complete/); +}); + +test("dismissing removes a toast and returns focus to main content", async (t) => { + const app = await mount(t); + const id = await act(async () => show()); + await ui.flush(); + const card = toast(app.container, id); + const close = card.querySelector('button[aria-label="Dismiss"]'); + close.focus(); + assert.equal(document.activeElement, close); + + await act(async () => { close.click(); }); + await ui.flush(); + assert.equal(toast(app.container, id), null); + assert.equal(document.activeElement, document.getElementById("main-content")); +}); + +test("the passive stack becomes inert and hidden from assistive tech while a modal is open", async (t) => { + const app = await mount(t); + await act(async () => show()); + await ui.flush(); + const region = app.container.querySelector('[role="region"]'); + assert.equal(region.hasAttribute("inert"), false); + + const overlay = document.createElement("div"); + overlay.className = "dialog-overlay"; + document.body.appendChild(overlay); + await ui.flush(); + assert.equal(region.hasAttribute("inert"), true); + assert.equal(region.getAttribute("aria-hidden"), "true"); + assert.match(region.textContent, /Archived/, "the toast remains visible under the modal layer"); + + overlay.remove(); + await ui.flush(); + assert.equal(region.hasAttribute("inert"), false); + assert.equal(region.getAttribute("aria-hidden"), null); +}); From 44d2e47088ae2418994585725735de6c4f9d35ee Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 21:56:38 +0100 Subject: [PATCH 05/15] fix(messages): make undo claims single-use and apply state CAS --- .../0012_message_action_undo_claims.sql | 8 + drizzle/migrations-mysql/meta/_journal.json | 7 + .../0012_message_action_undo_claims.sql | 7 + drizzle/migrations-pg/meta/_journal.json | 7 + .../0088_message_action_undo_claims.sql | 7 + drizzle/migrations/meta/_journal.json | 7 + server/runtime/scheduler.ts | 2 + src/db/schema/index.ts | 15 ++ src/lib/backups/export.ts | 4 + src/lib/messages/actions/claims.ts | 47 ++++ src/lib/messages/actions/service.ts | 208 +++++++++++------- src/lib/messages/actions/token.ts | 6 +- src/lib/messages/actions/types.d.ts | 6 +- src/lib/migrations/bundle-mysql.json | 7 + src/lib/migrations/bundle-postgres.json | 7 + tests/message-action-server-service.test.mjs | 192 ++++++++++++++++ tests/message-action-server.test.mjs | 158 +++++++++++++ tests/message-action-undo.test.mjs | 9 +- worker.ts | 2 + 19 files changed, 618 insertions(+), 88 deletions(-) create mode 100644 drizzle/migrations-mysql/0012_message_action_undo_claims.sql create mode 100644 drizzle/migrations-pg/0012_message_action_undo_claims.sql create mode 100644 drizzle/migrations/0088_message_action_undo_claims.sql create mode 100644 src/lib/messages/actions/claims.ts create mode 100644 tests/message-action-server-service.test.mjs create mode 100644 tests/message-action-server.test.mjs diff --git a/drizzle/migrations-mysql/0012_message_action_undo_claims.sql b/drizzle/migrations-mysql/0012_message_action_undo_claims.sql new file mode 100644 index 000000000..f9ea40dc3 --- /dev/null +++ b/drizzle/migrations-mysql/0012_message_action_undo_claims.sql @@ -0,0 +1,8 @@ +CREATE TABLE `message_action_undo_claims` ( + `nonce` varchar(191) NOT NULL, + `user_id` longtext NOT NULL, + `expires_at` bigint NOT NULL, + CONSTRAINT `message_action_undo_claims_nonce` PRIMARY KEY(`nonce`) +); +--> statement-breakpoint +CREATE INDEX `message_action_undo_claims_expires_idx` ON `message_action_undo_claims` (`expires_at`); diff --git a/drizzle/migrations-mysql/meta/_journal.json b/drizzle/migrations-mysql/meta/_journal.json index 4f666e098..4e2ea7f40 100644 --- a/drizzle/migrations-mysql/meta/_journal.json +++ b/drizzle/migrations-mysql/meta/_journal.json @@ -85,6 +85,13 @@ "when": 1793280382891, "tag": "0011_message_invite_response", "breakpoints": true + }, + { + "idx": 12, + "version": "5", + "when": 1794516478573, + "tag": "0012_message_action_undo_claims", + "breakpoints": true } ] } diff --git a/drizzle/migrations-pg/0012_message_action_undo_claims.sql b/drizzle/migrations-pg/0012_message_action_undo_claims.sql new file mode 100644 index 000000000..26aceb719 --- /dev/null +++ b/drizzle/migrations-pg/0012_message_action_undo_claims.sql @@ -0,0 +1,7 @@ +CREATE TABLE "message_action_undo_claims" ( + "nonce" text PRIMARY KEY NOT NULL, + "user_id" text NOT NULL, + "expires_at" bigint NOT NULL +); +--> statement-breakpoint +CREATE INDEX "message_action_undo_claims_expires_idx" ON "message_action_undo_claims" USING btree ("expires_at"); diff --git a/drizzle/migrations-pg/meta/_journal.json b/drizzle/migrations-pg/meta/_journal.json index 9812c047c..b885ca9c6 100644 --- a/drizzle/migrations-pg/meta/_journal.json +++ b/drizzle/migrations-pg/meta/_journal.json @@ -85,6 +85,13 @@ "when": 1793280382890, "tag": "0011_message_invite_response", "breakpoints": true + }, + { + "idx": 12, + "version": "7", + "when": 1794516478572, + "tag": "0012_message_action_undo_claims", + "breakpoints": true } ] } diff --git a/drizzle/migrations/0088_message_action_undo_claims.sql b/drizzle/migrations/0088_message_action_undo_claims.sql new file mode 100644 index 000000000..d06abf1d8 --- /dev/null +++ b/drizzle/migrations/0088_message_action_undo_claims.sql @@ -0,0 +1,7 @@ +CREATE TABLE `message_action_undo_claims` ( + `nonce` text PRIMARY KEY NOT NULL, + `user_id` text NOT NULL, + `expires_at` integer NOT NULL +); +--> statement-breakpoint +CREATE INDEX `message_action_undo_claims_expires_idx` ON `message_action_undo_claims` (`expires_at`); diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json index 1d7519670..549f32988 100644 --- a/drizzle/migrations/meta/_journal.json +++ b/drizzle/migrations/meta/_journal.json @@ -554,6 +554,13 @@ "when": 1793280382889, "tag": "0087_message_invite_response", "breakpoints": true + }, + { + "idx": 80, + "version": "6", + "when": 1794516478571, + "tag": "0088_message_action_undo_claims", + "breakpoints": true } ] } diff --git a/server/runtime/scheduler.ts b/server/runtime/scheduler.ts index db3739fc8..ca9aa9cc8 100644 --- a/server/runtime/scheduler.ts +++ b/server/runtime/scheduler.ts @@ -8,6 +8,7 @@ import { runFollowUpReminders } from "@/lib/follow-ups/service"; import { runCalendarReminders } from "@/lib/calendar/reminders"; import { sweepImportJobs } from "@/lib/import/jobs"; import { sweepOrphanedRawMail } from "@/lib/email/raw-sweeper"; +import { pruneExpiredMessageActionUndoClaims } from "@/lib/messages/actions/claims"; /** Fire the daily 02:00 UTC backup and the recurring maintenance jobs, matching the cron triggers in wrangler.jsonc. */ export function startScheduler(env: CloudflareEnv) { @@ -16,6 +17,7 @@ export function startScheduler(env: CloudflareEnv) { runAgentMaintenance(env).catch((error) => console.error("Agent maintenance failed", error)); runTrashRetention(env).catch((error) => console.error("Trash retention failed", error)); sweepImportJobs(env).catch((error) => console.error("Import job sweep failed", error)); + pruneExpiredMessageActionUndoClaims(env).catch((error) => console.error("Undo claim prune failed", error)); const now = new Date(); runFollowUpReminders(env, now).catch((error) => console.error("Follow-up reminders failed", error)); runCalendarReminders(env, now).catch((error) => console.error("Calendar reminders failed", error)); diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index c32de28e5..4f331af33 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -275,6 +275,21 @@ export const jmapChangeFloor = sqliteTable("jmap_change_floor", { seq: integer("seq").notNull().default(0), }); +/** + * Short-lived, single-use undo tokens. The nonce is consumed by the first + * authenticated undo request and only pruned after it expires; it is internal + * security state and deliberately excluded from backups. + */ +export const messageActionUndoClaims = sqliteTable( + "message_action_undo_claims", + { + nonce: text("nonce").primaryKey(), + userId: text("user_id").notNull(), + expiresAt: timestamp("expires_at").notNull(), + }, + (table) => [index("message_action_undo_claims_expires_idx").on(table.expiresAt)], +); + export const apiKeys = sqliteTable("api_keys", { id: text("id").primaryKey(), /** `device` keys come from a mobile sign-in (`/api/auth/device`) and are listed under Devices. */ diff --git a/src/lib/backups/export.ts b/src/lib/backups/export.ts index 532532677..26a091f88 100644 --- a/src/lib/backups/export.ts +++ b/src/lib/backups/export.ts @@ -54,6 +54,10 @@ export const INTERNAL_TABLES = [ "webauthn_challenges", "passkey_enrollment_grants", "auth_step_ups", + // Single-use undo-token consumption records. Restoring a stale claim would + // let an already-used undo token be replayed, and the table is rewritten by + // the installation that owns the tokens. + "message_action_undo_claims", ]; /** diff --git a/src/lib/messages/actions/claims.ts b/src/lib/messages/actions/claims.ts new file mode 100644 index 000000000..c6e51ef52 --- /dev/null +++ b/src/lib/messages/actions/claims.ts @@ -0,0 +1,47 @@ +import { and, eq, lt } from "drizzle-orm"; +import { getDb } from "@/db"; +import { messageActionUndoClaims } from "@/db/schema"; +import { isUniqueConstraintError } from "@/lib/database-errors"; + +/** Opportunistic and scheduled cleanup of spent/expired single-use undo tokens. */ +export async function pruneExpiredMessageActionUndoClaims(env: CloudflareEnv, now = new Date()): Promise { + await getDb(env).delete(messageActionUndoClaims).where(lt(messageActionUndoClaims.expiresAt, now)); +} + +/** + * Atomically consumes a token nonce. The primary key is the claim: exactly one + * insert wins, including across concurrent requests and workers. + * + * The claim is written before the restore writes. A crash in that window leaves + * the token consumed without restoring anything; the accepted small-blast + * tradeoff is that the UI reports an expired undo rather than risking a replay. + */ +export async function claimMessageActionUndoToken( + env: CloudflareEnv, + input: { nonce: string; userId: string; expiresAt: Date }, +): Promise<"claimed" | "duplicate"> { + const db = getDb(env); + await pruneExpiredMessageActionUndoClaims(env, new Date()); + try { + await db.insert(messageActionUndoClaims).values({ + nonce: input.nonce, + userId: input.userId, + expiresAt: input.expiresAt, + }); + return "claimed"; + } catch (error) { + if (isUniqueConstraintError(error)) return "duplicate"; + throw error; + } +} + +/** A claim is released only when the request failed before returning a settled outcome. */ +export async function releaseMessageActionUndoClaim( + env: CloudflareEnv, + input: { nonce: string; userId: string }, +): Promise { + await getDb(env).delete(messageActionUndoClaims).where(and( + eq(messageActionUndoClaims.nonce, input.nonce), + eq(messageActionUndoClaims.userId, input.userId), + )); +} diff --git a/src/lib/messages/actions/service.ts b/src/lib/messages/actions/service.ts index 7a6ee5534..b6f6e0282 100644 --- a/src/lib/messages/actions/service.ts +++ b/src/lib/messages/actions/service.ts @@ -1,4 +1,4 @@ -import { and, eq, inArray, isNull } from "drizzle-orm"; +import { and, eq, inArray, isNull, type SQL } from "drizzle-orm"; import type { AppDatabase } from "@/db"; import { getDb } from "@/db"; import { folders, messages } from "@/db/schema"; @@ -7,6 +7,7 @@ import { createAuditLogs } from "@/lib/mailboxes/audit"; import { getMailboxAccessLevel } from "@/lib/mailboxes/access"; import type { MailboxAccessLevel } from "@/lib/mailboxes/types"; import { applySpamFeedback } from "@/lib/spam/feedback"; +import { claimMessageActionUndoToken, releaseMessageActionUndoClaim } from "./claims"; import { actionNeedsManage, applySnapshotPatch, @@ -18,7 +19,7 @@ import { planUndoRecord, type MessageActionTarget, } from "./definitions"; -import { signUndoTokenForEnv, verifyUndoTokenForEnv } from "./token"; +import { MAX_UNDO_AGE_MS, signUndoTokenForEnv, verifyUndoTokenForEnv } from "./token"; import type { MessageActionInput, MessageActionRecord, @@ -95,6 +96,30 @@ function toDatabasePatch(patch: Partial) { }; } +function pickStatePatch( + fields: Array, + state: MessageStateSnapshot, +): Partial { + const patch: Partial = {}; + for (const field of fields) patch[field] = state[field] as never; + return patch; +} + +function stateCondition(field: keyof MessageStateSnapshot, expected: MessageStateSnapshot[keyof MessageStateSnapshot]): SQL { + if (field === "status") return eq(messages.status, expected as string); + if (field === "read") return eq(messages.read, expected as boolean); + if (field === "starred") return eq(messages.starred, expected as boolean); + if (field === "folderId") return expected === null ? isNull(messages.folderId) : eq(messages.folderId, expected as string); + return expected === null ? isNull(messages.snoozedUntil) : eq(messages.snoozedUntil, new Date(expected as string)); +} + +function stateConditions( + fields: Array, + state: MessageStateSnapshot, +): SQL[] { + return fields.map((field) => stateCondition(field, state[field])); +} + function validateSnoozeTime(value: string | null | undefined): string { if (typeof value !== "string") throw new MessageActionError("Choose a future snooze time"); const date = new Date(value); @@ -133,8 +158,6 @@ export async function applyMessageActionForUser( const accessByMailbox = await loadAccessMap(db, user, rows); const applied: MessageActionRecord[] = []; const skipped: MessageActionSkipped[] = []; - const confirmed = new Set(); - const updates = new Map; ids: string[] }>(); const seen = new Set(); for (const row of rows) { @@ -161,63 +184,76 @@ export async function applyMessageActionForUser( } const previous = snapshotMessageState(row); const next = applySnapshotPatch(previous, result.patch); + const changedFields = getChangedStateFields(previous, next); + const trainingAction = action === "spam" || (action === "inbox" && row.status === "spam"); + if (changedFields.length === 0 && !trainingAction) continue; - try { - if (action === "spam") { - const changed = await applySpamFeedback(env, user, row.id, "spam", access); + if (trainingAction) { + try { + const classification = action === "spam" ? "spam" : "ham"; + const changed = await applySpamFeedback(env, user, row.id, classification, access); if (!changed) { skipped.push({ id: row.id, reason: "not_applicable" }); continue; } - confirmed.add(row.id); + } catch { + skipped.push({ id: row.id, reason: "failed" }); + continue; + } + // Spam feedback writes status/folder itself and is deliberately kept + // outside the undo contract; no token is issued for these actions. + // The classifier-training counters are therefore not reversed on undo. + if (action === "inbox") { + try { + const updated = await db.update(messages) + .set(toDatabasePatch(pickStatePatch(changedFields, next))) + .where(eq(messages.id, row.id)) + .returning({ id: messages.id }); + if (updated.length === 0) { + skipped.push({ id: row.id, reason: "not_found" }); + continue; + } + } catch { + skipped.push({ id: row.id, reason: "failed" }); + continue; + } } - if (action === "inbox" && row.status === "spam") { - await applySpamFeedback(env, user, row.id, "ham", access); + if (recordHasChanges({ previous, applied: next })) { + applied.push({ id: row.id, mailboxId: row.mailboxId, previous, applied: next }); } - } catch { - skipped.push({ id: row.id, reason: "failed" }); continue; } - applied.push({ id: row.id, mailboxId: row.mailboxId, previous, applied: next }); - - // Spam feedback already wrote status/folder; every other path writes the full - // patch so the stored row is exactly the applied state the token promises. - if (action !== "spam") { - const patch = getChangedStateFields(previous, next).length > 0 ? result.patch : null; - if (patch) { - const key = JSON.stringify(patch); - const group = updates.get(key) ?? { patch, ids: [] }; - group.ids.push(row.id); - updates.set(key, group); - } else { - confirmed.add(row.id); + try { + // Compare-and-swap on every field this action writes. A concurrent + // change makes this row stale rather than signing a previous state the + // server never actually replaced. + const updated = await db.update(messages) + .set(toDatabasePatch(pickStatePatch(changedFields, next))) + .where(and(eq(messages.id, row.id), ...stateConditions(changedFields, previous))) + .returning({ id: messages.id }); + if (updated.length === 0) { + skipped.push({ id: row.id, reason: "stale" }); + continue; } + } catch { + skipped.push({ id: row.id, reason: "failed" }); + continue; } + applied.push({ id: row.id, mailboxId: row.mailboxId, previous, applied: next }); } for (const missing of ids.filter((id) => !seen.has(id))) { skipped.push({ id: missing, reason: "not_found" }); } - for (const group of updates.values()) { - for (let index = 0; index < group.ids.length; index += MESSAGE_ID_CHUNK) { - const chunk = group.ids.slice(index, index + MESSAGE_ID_CHUNK); - try { - await db.update(messages).set(toDatabasePatch(group.patch)).where(inArray(messages.id, chunk)); - for (const id of chunk) confirmed.add(id); - } catch { - for (const id of chunk) skipped.push({ id, reason: "failed" }); - } - } - } - - const confirmedApplied = applied.filter((record) => confirmed.has(record.id)); - if (confirmedApplied.length === 0 && skipped.some((item) => item.reason === "failed")) { + if (applied.length === 0 && skipped.some((item) => item.reason === "failed")) { throw new MessageActionError("Could not update messages", 500); } - const changedRecords = confirmedApplied.filter(recordHasChanges); + const changedRecords = applied.filter(recordHasChanges); + const hasTrainingRecord = action === "spam" + || (action === "inbox" && applied.some((record) => record.previous.status === "spam")); const auditRecords = action === "spam" ? [] : action === "inbox" @@ -232,31 +268,64 @@ export async function applyMessageActionForUser( }))); } - const undoToken = changedRecords.length > 0 + const undoToken = !hasTrainingRecord && changedRecords.length > 0 ? await signUndoTokenForEnv(env, { - v: 1, + v: 2, issuedAt: Date.now(), action, + userId: user.id, + nonce: crypto.randomUUID(), records: changedRecords, }) : undefined; - return { ok: true, action, applied: confirmedApplied, skipped, undoToken }; + return { ok: true, action, applied, skipped, undoToken }; } -/** Restores only the fields the signed action changed, and only while they still hold its result. */ +/** + * Restores only the fields the signed action changed, and only while they still + * hold its result. The one-time nonce claim blocks replay of a used token. The + * remaining accepted limit is a never-used token whose field changed away and + * back again (ABA): the value CAS cannot distinguish that, and a monotonic + * revision is deliberately deferred to keep this change small. + */ export async function undoMessageActionForUser( env: CloudflareEnv, user: SessionUser, token: string, ): Promise { const payload = await verifyUndoTokenForEnv(env, token); - if (!payload || !isReversibleMessageAction(payload.action)) { + if (!payload || !isReversibleMessageAction(payload.action) || payload.userId !== user.id) { throw new MessageActionError("This undo has expired", 410); } if (payload.records.length === 0) throw new MessageActionError("Nothing to undo"); if (payload.records.length > MAX_ACTION_MESSAGES) throw new MessageActionError("Too many messages to undo"); + const claimed = await claimMessageActionUndoToken(env, { + nonce: payload.nonce, + userId: user.id, + expiresAt: new Date(Date.now() + MAX_UNDO_AGE_MS), + }); + if (claimed === "duplicate") { + throw new MessageActionError("This undo has already been used", 410); + } + + try { + return await performUndoMessageAction(env, user, payload); + } catch (error) { + // A transient failure must not burn the one-time token: release it so the + // same signed retry can be attempted again. Field CAS makes a retry safe + // after any rows that were already restored. + await releaseMessageActionUndoClaim(env, { nonce: payload.nonce, userId: user.id }).catch(() => undefined); + throw error; + } +} + +async function performUndoMessageAction( + env: CloudflareEnv, + user: SessionUser, + payload: NonNullable>>, +): Promise { const records = [...new Map(payload.records.map((record) => [record.id, record])).values()]; const db = getDb(env); const ids = records.map((record) => record.id); @@ -273,12 +342,6 @@ export async function undoMessageActionForUser( const restored: string[] = []; const skipped: MessageActionSkipped[] = []; - const updates = new Map; - fields: (keyof MessageStateSnapshot)[]; - applied: MessageStateSnapshot; - ids: string[]; - }>(); for (const record of records) { const current = byId.get(record.id); @@ -297,40 +360,17 @@ export async function undoMessageActionForUser( skipped.push({ id: plan.id, reason: plan.reason }); continue; } - const key = JSON.stringify({ patch: plan.patch, applied: plan.fields.map((field) => record.applied[field]) }); - const group = updates.get(key) ?? { patch: plan.patch, fields: plan.fields, applied: record.applied, ids: [] }; - group.ids.push(record.id); - updates.set(key, group); - } - - for (const group of updates.values()) { - for (let index = 0; index < group.ids.length; index += MESSAGE_ID_CHUNK) { - const chunk = group.ids.slice(index, index + MESSAGE_ID_CHUNK); - const conditions = [inArray(messages.id, chunk)]; - for (const field of group.fields) { - const expected = group.applied[field]; - if (field === "status") conditions.push(eq(messages.status, expected as string)); - else if (field === "read") conditions.push(eq(messages.read, expected as boolean)); - else if (field === "starred") conditions.push(eq(messages.starred, expected as boolean)); - else if (field === "folderId") conditions.push(expected === null ? isNull(messages.folderId) : eq(messages.folderId, expected as string)); - else if (field === "snoozedUntil") conditions.push(expected === null ? isNull(messages.snoozedUntil) : eq(messages.snoozedUntil, new Date(expected as string))); - } - try { - // Compare-and-swap on the exact fields the action wrote, so a later - // change in another tab or request wins instead of being clobbered. - const updated = await db.update(messages) - .set(toDatabasePatch(group.patch)) - .where(and(...conditions)) - .returning({ id: messages.id }); - const updatedIds = new Set(updated.map((row) => row.id)); - for (const id of chunk) { - if (updatedIds.has(id)) restored.push(id); - else skipped.push({ id, reason: "stale" }); - } - } catch { - for (const id of chunk) skipped.push({ id, reason: "failed" }); - } + // One row at a time: the MySQL update/returning shim needs an exact + // per-row affected count, and every dialect gets a real field CAS. + const updated = await db.update(messages) + .set(toDatabasePatch(plan.patch)) + .where(and(eq(messages.id, record.id), ...stateConditions(plan.fields, record.applied))) + .returning({ id: messages.id }); + if (updated.length === 0) { + skipped.push({ id: record.id, reason: "stale" }); + continue; } + restored.push(record.id); } if (restored.length > 0) { diff --git a/src/lib/messages/actions/token.ts b/src/lib/messages/actions/token.ts index e4e9f646a..31cf49b41 100644 --- a/src/lib/messages/actions/token.ts +++ b/src/lib/messages/actions/token.ts @@ -1,8 +1,9 @@ import { getServerSecret } from "@/lib/security/server-secret"; import type { MessageUndoTokenPayload } from "./types"; -const TOKEN_VERSION = 1; -const MAX_UNDO_AGE_MS = 10 * 60_000; +// v2 binds the token to the session user and a single-use claim nonce. +const TOKEN_VERSION = 2; +export const MAX_UNDO_AGE_MS = 10 * 60_000; const CLOCK_SKEW_MS = 60_000; function bytesToBase64Url(bytes: Uint8Array): string { @@ -68,6 +69,7 @@ export async function verifyUndoToken( return null; } if (payload?.v !== TOKEN_VERSION || typeof payload.issuedAt !== "number" || !Array.isArray(payload.records)) return null; + if (typeof payload.userId !== "string" || !payload.userId || typeof payload.nonce !== "string" || !payload.nonce) return null; if (payload.issuedAt > now + CLOCK_SKEW_MS || payload.issuedAt < now - MAX_UNDO_AGE_MS) return null; return payload; } diff --git a/src/lib/messages/actions/types.d.ts b/src/lib/messages/actions/types.d.ts index dc9b00c35..65dd91851 100644 --- a/src/lib/messages/actions/types.d.ts +++ b/src/lib/messages/actions/types.d.ts @@ -69,9 +69,13 @@ export type UndoMessageActionResponse = { /** Payload carried by the signed undo token; never trusted from the request body directly. */ export type MessageUndoTokenPayload = { - v: 1; + v: 2; issuedAt: number; action: ReversibleMessageAction; + /** The session user who received the token; another user cannot redeem it. */ + userId: string; + /** Single-use claim key. */ + nonce: string; records: MessageActionRecord[]; }; diff --git a/src/lib/migrations/bundle-mysql.json b/src/lib/migrations/bundle-mysql.json index 449cc15fa..ecdbb2d44 100644 --- a/src/lib/migrations/bundle-mysql.json +++ b/src/lib/migrations/bundle-mysql.json @@ -336,6 +336,13 @@ "statements": [ "ALTER TABLE `messages` ADD `invite_response` text;" ] + }, + { + "name": "0012_message_action_undo_claims.sql", + "statements": [ + "CREATE TABLE `message_action_undo_claims` (\n\t`nonce` varchar(191) NOT NULL,\n\t`user_id` longtext NOT NULL,\n\t`expires_at` bigint NOT NULL,\n\tCONSTRAINT `message_action_undo_claims_nonce` PRIMARY KEY(`nonce`)\n);", + "CREATE INDEX `message_action_undo_claims_expires_idx` ON `message_action_undo_claims` (`expires_at`);" + ] } ] } diff --git a/src/lib/migrations/bundle-postgres.json b/src/lib/migrations/bundle-postgres.json index c90f46b74..13a0cf6ef 100644 --- a/src/lib/migrations/bundle-postgres.json +++ b/src/lib/migrations/bundle-postgres.json @@ -361,6 +361,13 @@ "statements": [ "ALTER TABLE \"messages\" ADD COLUMN \"invite_response\" text;" ] + }, + { + "name": "0012_message_action_undo_claims.sql", + "statements": [ + "CREATE TABLE \"message_action_undo_claims\" (\n\t\"nonce\" text PRIMARY KEY NOT NULL,\n\t\"user_id\" text NOT NULL,\n\t\"expires_at\" bigint NOT NULL\n);", + "CREATE INDEX \"message_action_undo_claims_expires_idx\" ON \"message_action_undo_claims\" USING btree (\"expires_at\");" + ] } ] } diff --git a/tests/message-action-server-service.test.mjs b/tests/message-action-server-service.test.mjs new file mode 100644 index 000000000..6456d7735 --- /dev/null +++ b/tests/message-action-server-service.test.mjs @@ -0,0 +1,192 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; +import Database from "better-sqlite3"; +import { drizzle } from "drizzle-orm/better-sqlite3"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-undo-service-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +await build({ + stdin: { + contents: ` + export { + applyMessageActionForUser, undoMessageActionForUser, MessageActionError, + } from "./src/lib/messages/actions/service.ts"; + `, + resolveDir: root, + sourcefile: "message-action-service-entry.ts", + }, + outfile: join(directory, "entry.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + logLevel: "silent", + plugins: [{ + name: "message-action-service-mocks", + setup(builder) { + const alias = (filter, namespace, contents) => { + builder.onResolve({ filter }, () => ({ path: namespace, namespace })); + builder.onLoad({ filter: /.*/, namespace }, () => ({ contents, loader: "js" })); + }; + alias(/^@\/db$/, "mock-db", "export function getDb() { return globalThis.__messageDb; }"); + alias(/^@\/lib\/mailboxes\/access$/, "mock-access", ` + export async function getMailboxAccessLevel() { + return { canRead: true, canManage: true }; + } + `); + alias(/^@\/lib\/mailboxes\/audit$/, "mock-audit", "export async function createAuditLogs() {}"); + alias(/^@\/lib\/spam\/feedback$/, "mock-spam", ` + export async function applySpamFeedback(_env, _user, messageId, classification) { + const status = classification === "spam" ? "spam" : "received"; + globalThis.__rawSqlite.prepare("UPDATE messages SET status = ?, folder_id = NULL WHERE id = ?").run(status, messageId); + return true; + } + `); + alias(/^@\/lib\/security\/server-secret$/, "mock-secret", "export async function getServerSecret() { return 'message-action-test-secret'; }"); + }, + }], +}); +const m = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +const sqlite = new Database(":memory:"); +sqlite.exec(` + CREATE TABLE messages ( + id text PRIMARY KEY NOT NULL, + mailbox_id text, + direction text NOT NULL, + status text NOT NULL, + read integer NOT NULL, + starred integer NOT NULL, + folder_id text, + snoozed_until integer + ); + CREATE TABLE folders ( + id text PRIMARY KEY NOT NULL, + mailbox_id text NOT NULL + ); + CREATE TABLE message_action_undo_claims ( + nonce text PRIMARY KEY NOT NULL, + user_id text NOT NULL, + expires_at integer NOT NULL + ); + CREATE INDEX message_action_undo_claims_expires_idx ON message_action_undo_claims (expires_at); +`); +globalThis.__messageDb = drizzle(sqlite); +globalThis.__rawSqlite = sqlite; +after(() => sqlite.close()); + +const user = { id: "user-1" }; + +function reset(message = {}) { + sqlite.exec("DELETE FROM messages; DELETE FROM message_action_undo_claims; DELETE FROM folders;"); + const row = { + id: "m1", + mailboxId: "mb1", + direction: "inbound", + status: "received", + read: 0, + starred: 0, + folderId: null, + snoozedUntil: null, + ...message, + }; + sqlite.prepare("INSERT INTO messages (id, mailbox_id, direction, status, read, starred, folder_id, snoozed_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + .run(row.id, row.mailboxId, row.direction, row.status, row.read, row.starred, row.folderId, row.snoozedUntil); + return row; +} + +function rowState(id = "m1") { + return sqlite.prepare("SELECT status, read, starred, folder_id, snoozed_until FROM messages WHERE id = ?").get(id); +} + +test("apply signs the server CAS result and undo restores it exactly once", async () => { + reset(); + const applied = await m.applyMessageActionForUser({}, user, { action: "archive", messageIds: ["m1"] }); + assert.equal(applied.applied.length, 1); + assert.ok(applied.undoToken); + assert.deepEqual(rowState(), { status: "archived", read: 0, starred: 0, folder_id: null, snoozed_until: null }); + + const undo = await m.undoMessageActionForUser({}, user, applied.undoToken); + assert.deepEqual(undo.restored, ["m1"]); + assert.equal(rowState().status, "received"); + await assert.rejects( + m.undoMessageActionForUser({}, user, applied.undoToken), + (error) => error instanceof m.MessageActionError && error.status === 410, + ); +}); + +test("undo tokens are bound to the user who received them", async () => { + reset(); + const applied = await m.applyMessageActionForUser({}, user, { action: "star", messageIds: ["m1"] }); + await assert.rejects( + m.undoMessageActionForUser({}, { id: "user-2" }, applied.undoToken), + (error) => error instanceof m.MessageActionError && error.status === 410, + ); + assert.equal(rowState().starred, 1); + const undo = await m.undoMessageActionForUser({}, user, applied.undoToken); + assert.deepEqual(undo.restored, ["m1"]); + assert.equal(rowState().starred, 0); +}); + +test("a mixed undo restores only rows still holding the action's applied state", async () => { + reset(); + sqlite.prepare("INSERT INTO messages (id, mailbox_id, direction, status, read, starred, folder_id, snoozed_until) VALUES ('m2', 'mb1', 'inbound', 'received', 0, 0, NULL, NULL)").run(); + const applied = await m.applyMessageActionForUser({}, user, { action: "read", messageIds: ["m1", "m2"] }); + assert.equal(applied.applied.length, 2); + sqlite.prepare("UPDATE messages SET read = 0 WHERE id = 'm2'").run(); + const undo = await m.undoMessageActionForUser({}, user, applied.undoToken); + assert.deepEqual(undo.restored, ["m1"]); + assert.deepEqual(undo.skipped, [{ id: "m2", reason: "stale" }]); + assert.equal(rowState("m1").read, 0); + assert.equal(rowState("m2").read, 0); + // A stale-only settle keeps the one-time claim consumed. + await assert.rejects( + m.undoMessageActionForUser({}, user, applied.undoToken), + (error) => error instanceof m.MessageActionError && error.status === 410, + ); +}); + +test("spam and inbox-from-spam apply normally but never issue an undo token", async () => { + reset(); + const spam = await m.applyMessageActionForUser({}, user, { action: "spam", messageIds: ["m1"] }); + assert.equal(spam.undoToken, undefined); + assert.equal(rowState().status, "spam"); + + reset({ status: "spam" }); + const inbox = await m.applyMessageActionForUser({}, user, { action: "inbox", messageIds: ["m1"] }); + assert.equal(inbox.undoToken, undefined); + assert.equal(rowState().status, "received"); +}); + +test("only actually changed rows are reported as applied", async () => { + reset({ status: "archived" }); + const applied = await m.applyMessageActionForUser({}, user, { action: "archive", messageIds: ["m1"] }); + assert.deepEqual(applied.applied, []); + assert.equal(applied.undoToken, undefined); +}); + +test("a CAS race rejects a stale archive snapshot instead of signing it", async () => { + reset(); + // Simulates the row being changed between the service's read and its CAS + // write: the conditional UPDATE affects no row, so nothing is signed. + sqlite.exec(` + CREATE TRIGGER block_archive BEFORE UPDATE OF status ON messages + WHEN OLD.id = 'm1' AND NEW.status = 'archived' + BEGIN + SELECT RAISE(IGNORE); + END; + `); + const applied = await m.applyMessageActionForUser({}, user, { action: "archive", messageIds: ["m1"] }); + assert.deepEqual(applied.applied, []); + assert.deepEqual(applied.skipped, [{ id: "m1", reason: "stale" }]); + assert.equal(applied.undoToken, undefined); + sqlite.exec("DROP TRIGGER block_archive"); +}); diff --git a/tests/message-action-server.test.mjs b/tests/message-action-server.test.mjs new file mode 100644 index 000000000..816411928 --- /dev/null +++ b/tests/message-action-server.test.mjs @@ -0,0 +1,158 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; +import Database from "better-sqlite3"; +import { drizzle } from "drizzle-orm/better-sqlite3"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-undo-server-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +await build({ + stdin: { + contents: ` + export { signUndoToken, verifyUndoToken } from "./src/lib/messages/actions/token.ts"; + export { + claimMessageActionUndoToken, releaseMessageActionUndoClaim, pruneExpiredMessageActionUndoClaims, + } from "./src/lib/messages/actions/claims.ts"; + export { planUndoRecord, getChangedStateFields } from "./src/lib/messages/actions/definitions.ts"; + `, + resolveDir: root, + sourcefile: "message-action-server-entry.ts", + }, + outfile: join(directory, "entry.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + logLevel: "silent", + plugins: [{ + name: "claims-db", + setup(builder) { + builder.onResolve({ filter: /^@\/db$/ }, () => ({ path: "claims-db", namespace: "mock" })); + builder.onLoad({ filter: /.*/, namespace: "mock" }, () => ({ + contents: `export function getDb() { return globalThis.__claimsDb; }`, + loader: "js", + })); + }, + }], +}); +const m = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +const sqlite = new Database(":memory:"); +sqlite.exec(` + CREATE TABLE message_action_undo_claims ( + nonce text PRIMARY KEY NOT NULL, + user_id text NOT NULL, + expires_at integer NOT NULL + ); + CREATE INDEX message_action_undo_claims_expires_idx ON message_action_undo_claims (expires_at); +`); +globalThis.__claimsDb = drizzle(sqlite); +after(() => sqlite.close()); + +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); +const record = (previous, applied) => ({ id: "m1", mailboxId: "mb1", previous, applied }); +const target = (overrides = {}) => ({ + id: "m1", + mailboxId: "mb1", + direction: "inbound", + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); + +test("token v2 carries the user and nonce and rejects old or tampered payloads", async () => { + const payload = { + v: 2, + issuedAt: Date.now(), + action: "read", + userId: "user-1", + nonce: "nonce-1", + records: [record(state(), state({ read: true }))], + }; + const token = await m.signUndoToken("secret", payload); + assert.deepEqual(await m.verifyUndoToken("secret", token), payload); + assert.equal(await m.verifyUndoToken("other-secret", token), null); + assert.equal(await m.verifyUndoToken("secret", `${token.slice(0, -2)}xx`), null); + assert.equal(await m.verifyUndoToken("secret", token, payload.issuedAt + 11 * 60_000), null); + // Tokens from the previous format are not accepted. + const oldToken = await m.signUndoToken("secret", { ...payload, v: 1 }); + assert.equal(await m.verifyUndoToken("secret", oldToken), null); +}); + +test("a claim nonce is single-use across users and can be released for a retry", async () => { + const expiresAt = new Date(Date.now() + 60_000); + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "retry-nonce", userId: "u1", expiresAt }), "claimed"); + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "retry-nonce", userId: "u2", expiresAt }), "duplicate"); + await m.releaseMessageActionUndoClaim({}, { nonce: "retry-nonce", userId: "u2" }); + // Releasing another user's claim must not remove the owner's claim. + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "retry-nonce", userId: "u1", expiresAt }), "duplicate"); + await m.releaseMessageActionUndoClaim({}, { nonce: "retry-nonce", userId: "u1" }); + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "retry-nonce", userId: "u1", expiresAt }), "claimed"); +}); + +test("expired claims are pruned opportunistically so a nonce can be reused after expiry", async () => { + const expired = new Date(Date.now() - 60_000); + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "expired-nonce", userId: "u1", expiresAt: expired }), "claimed"); + const future = new Date(Date.now() + 60_000); + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "expired-nonce", userId: "u1", expiresAt: future }), "claimed"); + await m.pruneExpiredMessageActionUndoClaims({}, new Date(Date.now() + 120_000)); + assert.equal(await m.claimMessageActionUndoToken({}, { nonce: "expired-nonce", userId: "u1", expiresAt: future }), "claimed"); +}); + +test("undo plans restore only changed fields and ignore removed folders for read-only undo", () => { + const archivePrevious = state({ status: "received", folderId: "folder-1" }); + const archiveApplied = state({ status: "archived", folderId: null }); + const plan = m.planUndoRecord( + record(archivePrevious, archiveApplied), + target({ status: "archived", folderId: null }), + { canRead: true, canManage: true }, + "mb1", + ); + assert.deepEqual(plan.patch, { status: "received", folderId: "folder-1" }); + assert.deepEqual(plan.fields, ["status", "folderId"]); + + const readPrevious = state({ folderId: "removed-folder" }); + const readApplied = state({ folderId: "removed-folder", read: true }); + const readPlan = m.planUndoRecord( + record(readPrevious, readApplied), + target({ folderId: "removed-folder", read: true }), + { canRead: true, canManage: true }, + undefined, + ); + assert.deepEqual(readPlan.patch, { read: false }); +}); + +test("every dialect carries the undo-claim table and bundle", async () => { + const files = { + sqlite: join(root, "drizzle/migrations/0086_message_action_undo_claims.sql"), + postgres: join(root, "drizzle/migrations-pg/0010_message_action_undo_claims.sql"), + mysql: join(root, "drizzle/migrations-mysql/0010_message_action_undo_claims.sql"), + }; + for (const [dialect, file] of Object.entries(files)) { + const sql = readFileSync(file, "utf8"); + assert.match(sql, /CREATE TABLE [`"]message_action_undo_claims[`"]/, dialect); + assert.match(sql, /nonce/, dialect); + assert.match(sql, /user_id/, dialect); + assert.match(sql, /expires_at/, dialect); + assert.match(sql, /message_action_undo_claims_expires_idx/, dialect); + } + const backupSource = readFileSync(join(root, "src/lib/backups/export.ts"), "utf8"); + assert.match(backupSource, /"message_action_undo_claims"/); +}); diff --git a/tests/message-action-undo.test.mjs b/tests/message-action-undo.test.mjs index 9e5e30322..a298daffa 100644 --- a/tests/message-action-undo.test.mjs +++ b/tests/message-action-undo.test.mjs @@ -176,7 +176,14 @@ test("a mixed undo restores eligible messages and reports the rest", () => { }); test("signed undo tokens carry the exact server records and reject tampering or expiry", async () => { - const payload = { v: 1, issuedAt: Date.now(), action: "archive", records: [record(state(), state({ status: "archived" }))] }; + const payload = { + v: 2, + issuedAt: Date.now(), + action: "archive", + userId: "user-1", + nonce: "nonce-1", + records: [record(state(), state({ status: "archived" }))], + }; const token = await m.signUndoToken("test-secret", payload); const verified = await m.verifyUndoToken("test-secret", token); assert.deepEqual(verified.records, payload.records); diff --git a/worker.ts b/worker.ts index 9e45e5ada..d07b0dbf0 100644 --- a/worker.ts +++ b/worker.ts @@ -16,6 +16,7 @@ import { } from "./worker-utils"; import { runWithD1Session } from "./src/lib/d1-session-context"; import { sweepOrphanedRawMail } from "./src/lib/email/raw-sweeper"; +import { pruneExpiredMessageActionUndoClaims } from "./src/lib/messages/actions/claims"; import { processImportJob, sweepImportJobs } from "./src/lib/import/jobs"; import { processWebhookRetry, type WebhookRetryMessage } from "./src/lib/email/webhooks"; import { resolveIncomingMail, forwardMessage } from "./src/lib/email/incoming"; @@ -161,6 +162,7 @@ export default { ctx.waitUntil(runFollowUpReminders(env, new Date(controller.scheduledTime))); ctx.waitUntil(runCalendarReminders(env, new Date(controller.scheduledTime))); ctx.waitUntil(sweepImportJobs(env, new Date(controller.scheduledTime))); + ctx.waitUntil(pruneExpiredMessageActionUndoClaims(env, new Date(controller.scheduledTime))); if (controller.cron === "0 2 * * *") ctx.waitUntil(runAccountRetention(env, new Date(controller.scheduledTime))); // Drive trash is emptied once a day, with the 02:00 UTC cron; the 5-minute cron is for queue-like upkeep. if (controller.cron === "0 2 * * *") ctx.waitUntil(runDriveTrashRetention(env, new Date(controller.scheduledTime))); From b0b9f83988a2ea51290746f2efc4a7a0419d9ec5 Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 21:58:03 +0100 Subject: [PATCH 06/15] chore(db): commit sqlite migration bundle --- src/lib/migrations/bundle.json | 813 +++++++++++++++++++++++++++++++++ 1 file changed, 813 insertions(+) create mode 100644 src/lib/migrations/bundle.json diff --git a/src/lib/migrations/bundle.json b/src/lib/migrations/bundle.json new file mode 100644 index 000000000..07d070870 --- /dev/null +++ b/src/lib/migrations/bundle.json @@ -0,0 +1,813 @@ +{ + "migrations": [ + { + "name": "0000_flowery_smasher.sql", + "statements": [ + "CREATE TABLE `api_keys` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`name` text NOT NULL,\n\t`prefix` text NOT NULL,\n\t`key_hash` text NOT NULL,\n\t`scopes` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`last_used_at` integer,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE TABLE `domains` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`hostname` text NOT NULL,\n\t`zone_id` text NOT NULL,\n\t`status` text DEFAULT 'pending' NOT NULL,\n\t`routing_status` text,\n\t`sending_subdomain_tag` text,\n\t`sending_enabled` integer DEFAULT false NOT NULL,\n\t`routing_enabled` integer DEFAULT false NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `domains_hostname_idx` ON `domains` (`hostname`);", + "CREATE INDEX `domains_user_idx` ON `domains` (`user_id`);", + "CREATE TABLE `mailboxes` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`domain_id` text NOT NULL,\n\t`local_part` text NOT NULL,\n\t`display_name` text,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `mailboxes_address_idx` ON `mailboxes` (`domain_id`,`local_part`);", + "CREATE TABLE `message_bodies` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`message_id` text NOT NULL,\n\t`text_body` text,\n\t`html_body` text,\n\t`raw_r2_key` text,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `message_bodies_message_id_unique` ON `message_bodies` (`message_id`);", + "CREATE TABLE `messages` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`mailbox_id` text,\n\t`direction` text NOT NULL,\n\t`provider_message_id` text,\n\t`from_addr` text NOT NULL,\n\t`to_addr` text NOT NULL,\n\t`subject` text,\n\t`snippet` text,\n\t`status` text DEFAULT 'received' NOT NULL,\n\t`thread_id` text,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE INDEX `messages_user_created_idx` ON `messages` (`user_id`,`created_at`);", + "CREATE INDEX `messages_mailbox_idx` ON `messages` (`mailbox_id`);", + "CREATE TABLE `outbound_jobs` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`message_id` text,\n\t`status` text DEFAULT 'queued' NOT NULL,\n\t`payload` text NOT NULL,\n\t`error` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE TABLE `routing_rules` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`domain_id` text NOT NULL,\n\t`pattern` text NOT NULL,\n\t`mailbox_id` text,\n\t`action` text DEFAULT 'store' NOT NULL,\n\t`forward_to` text,\n\t`priority` integer DEFAULT 0 NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE TABLE `sessions` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`token_hash` text NOT NULL,\n\t`expires_at` integer NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `sessions_token_hash_unique` ON `sessions` (`token_hash`);", + "CREATE TABLE `users` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`email` text NOT NULL,\n\t`password_hash` text NOT NULL,\n\t`name` text NOT NULL,\n\t`created_at` integer NOT NULL\n);", + "CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);", + "CREATE TABLE `webhook_deliveries` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`webhook_id` text NOT NULL,\n\t`event_type` text NOT NULL,\n\t`payload` text NOT NULL,\n\t`status` text DEFAULT 'pending' NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`webhook_id`) REFERENCES `webhooks`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE TABLE `webhooks` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`url` text NOT NULL,\n\t`secret` text NOT NULL,\n\t`events` text NOT NULL,\n\t`enabled` integer DEFAULT true NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);" + ] + }, + { + "name": "0001_add_reset_email.sql", + "statements": [ + "ALTER TABLE `users` ADD `reset_email` text;" + ] + }, + { + "name": "0002_add_message_read.sql", + "statements": [ + "ALTER TABLE `messages` ADD `read` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0003_add_contacts.sql", + "statements": [ + "CREATE TABLE `contacts` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`email` text NOT NULL,\n\t`display_name` text,\n\t`source` text DEFAULT 'inbound' NOT NULL,\n\t`last_seen_at` integer,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `contacts_user_email_idx` ON `contacts` (`user_id`,`email`);", + "CREATE INDEX `contacts_user_idx` ON `contacts` (`user_id`);" + ] + }, + { + "name": "0004_add_accounts.sql", + "statements": [ + "ALTER TABLE `users` ADD `role` text DEFAULT 'user' NOT NULL;", + "ALTER TABLE `users` ADD `created_by_user_id` text REFERENCES `users`(`id`) ON DELETE set null;", + "UPDATE `users`\nSET `role` = 'admin'\nWHERE `id` = (\n\tSELECT `id`\n\tFROM `users`\n\tORDER BY `created_at` ASC\n\tLIMIT 1\n);", + "CREATE INDEX `users_created_by_idx` ON `users` (`created_by_user_id`);" + ] + }, + { + "name": "0005_add_folders.sql", + "statements": [ + "CREATE TABLE `folders` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`mailbox_id` text NOT NULL,\n\t`name` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `folders_mailbox_name_idx` ON `folders` (`mailbox_id`,`name`);", + "CREATE INDEX `folders_user_idx` ON `folders` (`user_id`);", + "CREATE INDEX `folders_mailbox_idx` ON `folders` (`mailbox_id`);", + "ALTER TABLE `messages` ADD `folder_id` text REFERENCES `folders`(`id`) ON DELETE set null;", + "CREATE INDEX `messages_folder_idx` ON `messages` (`folder_id`);", + "ALTER TABLE `routing_rules` ADD `folder_id` text REFERENCES `folders`(`id`) ON DELETE set null;" + ] + }, + { + "name": "0006_add_rule_conditions.sql", + "statements": [ + "ALTER TABLE `routing_rules` ADD `match_field` text DEFAULT 'email' NOT NULL;", + "ALTER TABLE `routing_rules` ADD `match_operator` text DEFAULT 'contains' NOT NULL;", + "ALTER TABLE `routing_rules` ADD `match_value` text DEFAULT '' NOT NULL;", + "UPDATE `routing_rules`\nSET `match_value` = `pattern`\nWHERE `match_value` = '';" + ] + }, + { + "name": "0007_add_shared_mailboxes.sql", + "statements": [ + "ALTER TABLE `users` ADD `disabled` integer DEFAULT false NOT NULL;", + "ALTER TABLE `mailboxes` ADD `type` text DEFAULT 'personal' NOT NULL;", + "ALTER TABLE `mailboxes` ADD `disabled` integer DEFAULT false NOT NULL;", + "CREATE TABLE `mailbox_access` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`mailbox_id` text NOT NULL,\n\t`user_id` text NOT NULL,\n\t`permission` text DEFAULT 'read_only' NOT NULL,\n\t`created_by_user_id` text,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE UNIQUE INDEX `mailbox_access_mailbox_user_idx` ON `mailbox_access` (`mailbox_id`,`user_id`);", + "CREATE INDEX `mailbox_access_user_idx` ON `mailbox_access` (`user_id`);", + "CREATE INDEX `mailbox_access_mailbox_idx` ON `mailbox_access` (`mailbox_id`);", + "CREATE TABLE `audit_logs` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`actor_user_id` text,\n\t`target_user_id` text,\n\t`mailbox_id` text,\n\t`message_id` text,\n\t`action` text NOT NULL,\n\t`metadata` text,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,\n\tFOREIGN KEY (`target_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE set null,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE INDEX `audit_logs_actor_idx` ON `audit_logs` (`actor_user_id`);", + "CREATE INDEX `audit_logs_mailbox_idx` ON `audit_logs` (`mailbox_id`);", + "CREATE INDEX `audit_logs_created_idx` ON `audit_logs` (`created_at`);" + ] + }, + { + "name": "0008_add_message_attachments.sql", + "statements": [ + "CREATE TABLE `message_attachments` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`message_id` text NOT NULL,\n\t`filename` text NOT NULL,\n\t`content_type` text NOT NULL,\n\t`size` integer NOT NULL,\n\t`disposition` text DEFAULT 'attachment' NOT NULL,\n\t`content_id` text,\n\t`r2_key` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `message_attachments_r2_key_unique` ON `message_attachments` (`r2_key`);", + "CREATE INDEX `message_attachments_message_idx` ON `message_attachments` (`message_id`);" + ] + }, + { + "name": "0009_add_backups.sql", + "statements": [ + "CREATE TABLE `backup_settings` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`enabled` integer DEFAULT false NOT NULL,\n\t`schedule_type` text DEFAULT 'daily' NOT NULL,\n\t`schedule_value` integer,\n\t`retention_enabled` integer DEFAULT false NOT NULL,\n\t`retention_days` integer DEFAULT 30 NOT NULL,\n\t`updated_at` integer NOT NULL\n);", + "INSERT INTO `backup_settings` (`id`, `enabled`, `schedule_type`, `retention_enabled`, `retention_days`, `updated_at`)\nVALUES ('default', false, 'daily', false, 30, unixepoch());", + "CREATE TABLE `backups` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`status` text DEFAULT 'queued' NOT NULL,\n\t`trigger` text NOT NULL,\n\t`r2_key` text,\n\t`filename` text,\n\t`size` integer,\n\t`error` text,\n\t`created_by_user_id` text,\n\t`created_at` integer NOT NULL,\n\t`started_at` integer,\n\t`completed_at` integer,\n\tFOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE INDEX `backups_created_idx` ON `backups` (`created_at`);", + "CREATE INDEX `backups_status_idx` ON `backups` (`status`);" + ] + }, + { + "name": "0010_hard_squirrel_girl.sql", + "statements": [ + "ALTER TABLE `users` ADD `avatar_key` text;" + ] + }, + { + "name": "0011_add_folder_colors.sql", + "statements": [ + "ALTER TABLE `folders` ADD `color` text DEFAULT '#2563eb' NOT NULL;", + "ALTER TABLE `contacts` ADD `blocked` integer DEFAULT false NOT NULL;", + "ALTER TABLE `mailboxes` ADD `avatar_key` text;" + ] + }, + { + "name": "0012_add_app_settings.sql", + "statements": [ + "CREATE TABLE `app_settings` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`app_name` text DEFAULT 'Mailflare' NOT NULL,\n\t`icon_key` text,\n\t`updated_at` integer NOT NULL\n);", + "INSERT INTO `app_settings` (`id`, `app_name`, `updated_at`)\nVALUES ('default', 'Mailflare', unixepoch());" + ] + }, + { + "name": "0013_add_license_settings.sql", + "statements": [ + "CREATE TABLE `license_settings` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`instance_id` text NOT NULL,\n\t`instance_url` text,\n\t`license_key_hash` text,\n\t`plan` text DEFAULT 'community' NOT NULL,\n\t`state` text DEFAULT 'inactive' NOT NULL,\n\t`features` text DEFAULT '[]' NOT NULL,\n\t`activated_at` integer,\n\t`validated_at` integer,\n\t`updated_at` integer NOT NULL\n);", + "CREATE UNIQUE INDEX `license_settings_instance_id_unique` ON `license_settings` (`instance_id`);" + ] + }, + { + "name": "0014_add_account_permissions.sql", + "statements": [ + "ALTER TABLE `users` ADD `can_manage_mailboxes` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0015_add_forwarding_email.sql", + "statements": [ + "ALTER TABLE `users` ADD `forwarding_email` text;" + ] + }, + { + "name": "0016_add_message_snooze.sql", + "statements": [ + "ALTER TABLE `messages` ADD `snoozed_until` integer;" + ] + }, + { + "name": "0017_add_message_star.sql", + "statements": [ + "ALTER TABLE `messages` ADD `starred` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0018_add_mailbox_domain_aliases.sql", + "statements": [ + "ALTER TABLE `mailboxes` ADD `use_all_domains` integer DEFAULT true NOT NULL;" + ] + }, + { + "name": "0019_merge_message_bodies.sql", + "statements": [ + "ALTER TABLE `messages` ADD `text_body` text;", + "ALTER TABLE `messages` ADD `html_body` text;", + "ALTER TABLE `messages` ADD `raw_r2_key` text;", + "UPDATE `messages`\nSET\n `text_body` = (SELECT `text_body` FROM `message_bodies` WHERE `message_bodies`.`message_id` = `messages`.`id`),\n `html_body` = (SELECT `html_body` FROM `message_bodies` WHERE `message_bodies`.`message_id` = `messages`.`id`),\n `raw_r2_key` = (SELECT `raw_r2_key` FROM `message_bodies` WHERE `message_bodies`.`message_id` = `messages`.`id`);", + "DROP TABLE `message_bodies`;" + ] + }, + { + "name": "0020_add_calendar_templates_schedule.sql", + "statements": [ + "ALTER TABLE `outbound_jobs` ADD `scheduled_at` integer;", + "CREATE TABLE `email_templates` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,\n\t`name` text NOT NULL,\n\t`subject` text DEFAULT '' NOT NULL,\n\t`text_body` text DEFAULT '' NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);", + "CREATE INDEX `email_templates_user_idx` ON `email_templates` (`user_id`);", + "CREATE TABLE `calendar_events` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,\n\t`mailbox_id` text REFERENCES `mailboxes`(`id`) ON DELETE set null,\n\t`title` text NOT NULL,\n\t`description` text DEFAULT '' NOT NULL,\n\t`location` text DEFAULT '' NOT NULL,\n\t`attendees` text DEFAULT '[]' NOT NULL,\n\t`starts_at` integer NOT NULL,\n\t`ends_at` integer NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);", + "CREATE INDEX `calendar_events_user_starts_idx` ON `calendar_events` (`user_id`, `starts_at`);" + ] + }, + { + "name": "0021_add_api_keys_prefix_index.sql", + "statements": [ + "CREATE INDEX IF NOT EXISTS idx_api_keys_prefix ON api_keys(prefix);" + ] + }, + { + "name": "0021_add_mailbox_signature.sql", + "statements": [ + "ALTER TABLE `mailboxes` ADD `signature` text;" + ] + }, + { + "name": "0022_add_mailbox_auto_reply.sql", + "statements": [ + "ALTER TABLE `mailboxes` ADD `auto_reply_enabled` integer DEFAULT false NOT NULL;", + "ALTER TABLE `mailboxes` ADD `auto_reply_subject` text DEFAULT 'Out of office' NOT NULL;", + "ALTER TABLE `mailboxes` ADD `auto_reply_body` text DEFAULT '' NOT NULL;", + "CREATE TABLE `auto_reply_deliveries` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade,\n\t`recipient` text NOT NULL,\n\t`sent_at` integer NOT NULL\n);", + "CREATE UNIQUE INDEX `auto_reply_deliveries_mailbox_recipient_idx` ON `auto_reply_deliveries` (`mailbox_id`, `recipient`);", + "CREATE INDEX `auto_reply_deliveries_sent_idx` ON `auto_reply_deliveries` (`sent_at`);" + ] + }, + { + "name": "0023_add_mailbox_aliases.sql", + "statements": [ + "CREATE TABLE `mailbox_aliases` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade,\n\t`domain_id` text NOT NULL REFERENCES `domains`(`id`) ON DELETE cascade,\n\t`local_part` text NOT NULL,\n\t`created_at` integer NOT NULL\n);", + "CREATE UNIQUE INDEX `mailbox_aliases_address_idx` ON `mailbox_aliases` (`domain_id`, `local_part`);", + "CREATE INDEX `mailbox_aliases_mailbox_idx` ON `mailbox_aliases` (`mailbox_id`);" + ] + }, + { + "name": "0024_add_advanced_routing_and_webhook_retries.sql", + "statements": [ + "ALTER TABLE `routing_rules` ADD `scope` text DEFAULT 'mailbox' NOT NULL;", + "ALTER TABLE `routing_rules` ADD `name` text;", + "ALTER TABLE `routing_rules` ADD `enabled` integer DEFAULT true NOT NULL;", + "ALTER TABLE `routing_rules` ADD `keep_copy` integer DEFAULT false NOT NULL;", + "ALTER TABLE `routing_rules` ADD `reject_reason` text;", + "ALTER TABLE `routing_rules` ADD `last_matched_at` integer;", + "ALTER TABLE `routing_rules` ADD `match_count` integer DEFAULT 0 NOT NULL;", + "CREATE INDEX `routing_rules_domain_scope_idx` ON `routing_rules` (`domain_id`,`scope`,`enabled`);", + "CREATE INDEX `routing_rules_mailbox_idx` ON `routing_rules` (`mailbox_id`);", + "CREATE INDEX `routing_rules_priority_idx` ON `routing_rules` (`priority`);", + "ALTER TABLE `webhooks` ADD `description` text;", + "ALTER TABLE `webhooks` ADD `max_attempts` integer DEFAULT 5 NOT NULL;", + "ALTER TABLE `webhook_deliveries` ADD `response_status` integer;", + "ALTER TABLE `webhook_deliveries` ADD `error` text;", + "ALTER TABLE `webhook_deliveries` ADD `duration_ms` integer;", + "ALTER TABLE `webhook_deliveries` ADD `last_attempt_at` integer;", + "ALTER TABLE `webhook_deliveries` ADD `next_retry_at` integer;", + "CREATE INDEX `webhook_deliveries_webhook_idx` ON `webhook_deliveries` (`webhook_id`,`created_at`);", + "CREATE INDEX `webhook_deliveries_status_idx` ON `webhook_deliveries` (`status`);" + ] + }, + { + "name": "0025_add_threading_and_cc_bcc.sql", + "statements": [ + "ALTER TABLE `messages` ADD `cc_addr` text;", + "ALTER TABLE `messages` ADD `bcc_addr` text;", + "ALTER TABLE `messages` ADD `in_reply_to` text;", + "ALTER TABLE `messages` ADD `references_header` text;", + "CREATE INDEX `messages_thread_idx` ON `messages` (`mailbox_id`,`thread_id`);", + "CREATE INDEX `messages_provider_message_idx` ON `messages` (`mailbox_id`,`provider_message_id`);" + ] + }, + { + "name": "0026_add_contact_avatars.sql", + "statements": [ + "ALTER TABLE `contacts` ADD `avatar_key` text;" + ] + }, + { + "name": "0027_add_domain_sending_intent.sql", + "statements": [ + "ALTER TABLE `domains` ADD `sending_requested` integer DEFAULT false NOT NULL;", + "UPDATE `domains`\nSET `sending_requested` = true\nWHERE `sending_enabled` = true OR `sending_subdomain_tag` IS NOT NULL;" + ] + }, + { + "name": "0028_add_keyboard_shortcuts_setting.sql", + "statements": [ + "ALTER TABLE `users` ADD `keyboard_shortcuts_enabled` integer DEFAULT true NOT NULL;" + ] + }, + { + "name": "0029_add_spam_protection.sql", + "statements": [ + "ALTER TABLE `users` ADD `spam_protection_enabled` integer DEFAULT true NOT NULL;", + "ALTER TABLE `messages` ADD `spam_score` integer;", + "ALTER TABLE `messages` ADD `spam_verdict` text;", + "ALTER TABLE `messages` ADD `spam_signals` text;", + "ALTER TABLE `messages` ADD `spam_analyzed_at` integer;", + "ALTER TABLE `messages` ADD `spam_analysis_error` text;", + "CREATE INDEX `messages_raw_r2_key_idx` ON `messages` (`raw_r2_key`);", + "CREATE TABLE `spam_token_stats` (\n\t`mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade,\n\t`token` text NOT NULL,\n\t`spam_count` integer DEFAULT 0 NOT NULL,\n\t`ham_count` integer DEFAULT 0 NOT NULL,\n\t`updated_at` integer NOT NULL\n);", + "CREATE UNIQUE INDEX `spam_token_stats_mailbox_token_idx` ON `spam_token_stats` (`mailbox_id`, `token`);", + "CREATE INDEX `spam_token_stats_mailbox_idx` ON `spam_token_stats` (`mailbox_id`);", + "CREATE TABLE `spam_reputation` (\n\t`mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade,\n\t`type` text NOT NULL,\n\t`key` text NOT NULL,\n\t`messages_seen` integer DEFAULT 0 NOT NULL,\n\t`spam_count` integer DEFAULT 0 NOT NULL,\n\t`ham_count` integer DEFAULT 0 NOT NULL,\n\t`first_seen_at` integer NOT NULL,\n\t`last_seen_at` integer NOT NULL\n);", + "CREATE UNIQUE INDEX `spam_reputation_mailbox_type_key_idx` ON `spam_reputation` (`mailbox_id`, `type`, `key`);", + "CREATE INDEX `spam_reputation_mailbox_idx` ON `spam_reputation` (`mailbox_id`);", + "CREATE TABLE `spam_feedback` (\n\t`message_id` text PRIMARY KEY NOT NULL REFERENCES `messages`(`id`) ON DELETE cascade,\n\t`mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade,\n\t`actor_user_id` text REFERENCES `users`(`id`) ON DELETE set null,\n\t`classification` text NOT NULL,\n\t`training_tokens` text NOT NULL,\n\t`reputation_keys` text NOT NULL,\n\t`tokenizer_version` integer DEFAULT 1 NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);", + "CREATE INDEX `spam_feedback_mailbox_idx` ON `spam_feedback` (`mailbox_id`);" + ] + }, + { + "name": "0030_add_message_search_index.sql", + "statements": [ + "CREATE VIRTUAL TABLE `messages_fts` USING fts5(\n\t`subject`,\n\t`from_addr`,\n\t`to_addr`,\n\t`cc_addr`,\n\t`text_body`,\n\t`html_body`,\n\tcontent='messages',\n\tcontent_rowid='rowid',\n\ttokenize='unicode61 remove_diacritics 2'\n);", + "CREATE TRIGGER `messages_fts_ai` AFTER INSERT ON `messages` BEGIN\n\tINSERT INTO `messages_fts`(`rowid`, `subject`, `from_addr`, `to_addr`, `cc_addr`, `text_body`, `html_body`)\n\tVALUES (new.`rowid`, new.`subject`, new.`from_addr`, new.`to_addr`, new.`cc_addr`, new.`text_body`, new.`html_body`);\nEND;", + "CREATE TRIGGER `messages_fts_ad` AFTER DELETE ON `messages` BEGIN\n\tINSERT INTO `messages_fts`(`messages_fts`, `rowid`, `subject`, `from_addr`, `to_addr`, `cc_addr`, `text_body`, `html_body`)\n\tVALUES ('delete', old.`rowid`, old.`subject`, old.`from_addr`, old.`to_addr`, old.`cc_addr`, old.`text_body`, old.`html_body`);\nEND;", + "CREATE TRIGGER `messages_fts_au` AFTER UPDATE OF `subject`, `from_addr`, `to_addr`, `cc_addr`, `text_body`, `html_body` ON `messages` BEGIN\n\tINSERT INTO `messages_fts`(`messages_fts`, `rowid`, `subject`, `from_addr`, `to_addr`, `cc_addr`, `text_body`, `html_body`)\n\tVALUES ('delete', old.`rowid`, old.`subject`, old.`from_addr`, old.`to_addr`, old.`cc_addr`, old.`text_body`, old.`html_body`);\n\tINSERT INTO `messages_fts`(`rowid`, `subject`, `from_addr`, `to_addr`, `cc_addr`, `text_body`, `html_body`)\n\tVALUES (new.`rowid`, new.`subject`, new.`from_addr`, new.`to_addr`, new.`cc_addr`, new.`text_body`, new.`html_body`);\nEND;", + "INSERT INTO `messages_fts`(`messages_fts`) VALUES ('rebuild');" + ] + }, + { + "name": "0031_add_password_reset_and_mfa.sql", + "statements": [ + "ALTER TABLE `users` ADD `totp_secret` text;", + "ALTER TABLE `users` ADD `totp_enabled` integer DEFAULT false NOT NULL;", + "ALTER TABLE `users` ADD `totp_confirmed_at` integer;", + "CREATE TABLE `password_reset_tokens` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,\n\t`token_hash` text NOT NULL UNIQUE,\n\t`expires_at` integer NOT NULL,\n\t`used_at` integer,\n\t`created_at` integer NOT NULL\n);", + "CREATE INDEX `password_reset_tokens_user_idx` ON `password_reset_tokens` (`user_id`);", + "CREATE TABLE `mfa_recovery_codes` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,\n\t`code_hash` text NOT NULL UNIQUE,\n\t`used_at` integer,\n\t`created_at` integer NOT NULL\n);", + "CREATE INDEX `mfa_recovery_codes_user_idx` ON `mfa_recovery_codes` (`user_id`);", + "CREATE TABLE `login_challenges` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,\n\t`token_hash` text NOT NULL UNIQUE,\n\t`expires_at` integer NOT NULL,\n\t`created_at` integer NOT NULL\n);" + ] + }, + { + "name": "0032_add_agentic_mail.sql", + "statements": [ + "CREATE TABLE `mailbox_agent_settings` (`mailbox_id` text PRIMARY KEY NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade, `enabled` integer NOT NULL DEFAULT 1, `auto_draft_enabled` integer NOT NULL DEFAULT 0, `reviewer_user_id` text REFERENCES `users`(`id`) ON DELETE set null, `instructions` text NOT NULL DEFAULT '', `daily_limit` integer NOT NULL DEFAULT 25, `updated_at` integer NOT NULL);", + "CREATE TABLE `agent_conversations` (`id` text PRIMARY KEY NOT NULL, `user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade, `mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade, `title` text NOT NULL DEFAULT 'New conversation', `created_at` integer NOT NULL, `updated_at` integer NOT NULL);", + "CREATE INDEX `agent_conversations_owner_idx` ON `agent_conversations` (`user_id`, `mailbox_id`, `updated_at`);", + "CREATE TABLE `agent_chat_messages` (`id` text PRIMARY KEY NOT NULL, `conversation_id` text NOT NULL REFERENCES `agent_conversations`(`id`) ON DELETE cascade, `role` text NOT NULL, `content` text NOT NULL, `tool_name` text, `created_at` integer NOT NULL);", + "CREATE INDEX `agent_chat_messages_conversation_idx` ON `agent_chat_messages` (`conversation_id`, `created_at`);", + "CREATE TABLE `agent_jobs` (`id` text PRIMARY KEY NOT NULL, `mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade, `source_message_id` text NOT NULL REFERENCES `messages`(`id`) ON DELETE cascade, `reviewer_user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade, `status` text NOT NULL DEFAULT 'pending', `attempts` integer NOT NULL DEFAULT 0, `next_attempt_at` integer NOT NULL, `lease_until` integer, `draft_id` text REFERENCES `messages`(`id`) ON DELETE set null, `reason` text, `created_at` integer NOT NULL);", + "CREATE UNIQUE INDEX `agent_jobs_source_idx` ON `agent_jobs` (`mailbox_id`, `source_message_id`);", + "CREATE INDEX `agent_jobs_due_idx` ON `agent_jobs` (`status`, `next_attempt_at`);", + "CREATE TABLE `agent_draft_metadata` (`draft_id` text PRIMARY KEY NOT NULL REFERENCES `messages`(`id`) ON DELETE cascade, `mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade, `origin` text NOT NULL, `source_message_id` text REFERENCES `messages`(`id`) ON DELETE set null, `revision` integer NOT NULL DEFAULT 1, `human_edited_at` integer, `created_at` integer NOT NULL);", + "CREATE TABLE `agent_send_approvals` (`id` text PRIMARY KEY NOT NULL, `draft_id` text NOT NULL REFERENCES `messages`(`id`) ON DELETE cascade, `mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade, `user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade, `request_key_id` text REFERENCES `api_keys`(`id`) ON DELETE set null, `revision` integer NOT NULL, `payload_hash` text NOT NULL, `status` text NOT NULL DEFAULT 'pending', `claimed_at` integer, `message_id` text, `expires_at` integer NOT NULL, `created_at` integer NOT NULL);", + "CREATE INDEX `agent_send_approvals_user_idx` ON `agent_send_approvals` (`user_id`, `status`);", + "CREATE UNIQUE INDEX `agent_send_approvals_delivery_idx` ON `agent_send_approvals` (`draft_id`) WHERE `status` IN ('claimed', 'sent', 'unknown');", + "CREATE TABLE `mcp_key_mailboxes` (`key_id` text NOT NULL REFERENCES `api_keys`(`id`) ON DELETE cascade, `mailbox_id` text NOT NULL REFERENCES `mailboxes`(`id`) ON DELETE cascade);", + "CREATE UNIQUE INDEX `mcp_key_mailbox_idx` ON `mcp_key_mailboxes` (`key_id`, `mailbox_id`);", + "ALTER TABLE `api_keys` ADD `kind` text NOT NULL DEFAULT 'legacy';" + ] + }, + { + "name": "0033_add_agent_provider_settings.sql", + "statements": [ + "ALTER TABLE `app_settings` ADD `agent_provider` text;", + "ALTER TABLE `app_settings` ADD `agent_preset` text;", + "ALTER TABLE `app_settings` ADD `agent_base_url` text;", + "ALTER TABLE `app_settings` ADD `agent_api_key` text;", + "ALTER TABLE `app_settings` ADD `agent_model` text;" + ] + }, + { + "name": "0034_add_agent_enabled.sql", + "statements": [ + "ALTER TABLE `app_settings` ADD `agent_enabled` integer DEFAULT 1 NOT NULL;" + ] + }, + { + "name": "0035_add_mailbox_agent_model.sql", + "statements": [ + "ALTER TABLE `mailbox_agent_settings` ADD `model_id` text;" + ] + }, + { + "name": "0036_add_agent_ai_usage.sql", + "statements": [ + "ALTER TABLE `app_settings` ADD `agent_model_rates` text;", + "CREATE TABLE `agent_ai_usage` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`provider` text NOT NULL,\n\t`model` text NOT NULL,\n\t`source` text NOT NULL,\n\t`input_tokens` integer,\n\t`output_tokens` integer,\n\t`cost_usd_micros` integer\n);", + "CREATE INDEX `agent_ai_usage_created_idx` ON `agent_ai_usage` (`created_at`);" + ] + }, + { + "name": "0037_generalize_ai_usage.sql", + "statements": [ + "ALTER TABLE `agent_ai_usage` RENAME TO `ai_usage`;", + "DROP INDEX `agent_ai_usage_created_idx`;", + "CREATE INDEX `ai_usage_created_idx` ON `ai_usage` (`created_at`);" + ] + }, + { + "name": "0038_scope_standard_api_keys.sql", + "statements": [ + "ALTER TABLE api_keys ADD COLUMN mailbox_scope_enabled integer NOT NULL DEFAULT 0;" + ] + }, + { + "name": "0039_add_backup_table_groups.sql", + "statements": [ + "ALTER TABLE backup_settings ADD COLUMN excluded_table_groups text NOT NULL DEFAULT '[]';" + ] + }, + { + "name": "0040_add_agent_draft_schedule.sql", + "statements": [ + "ALTER TABLE `agent_draft_metadata` ADD `scheduled_at` integer;" + ] + }, + { + "name": "0041_add_calendar_event_color.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `color` text NOT NULL DEFAULT 'blue';" + ] + }, + { + "name": "0042_add_jmap_mailbox_revisions.sql", + "statements": [ + "CREATE TABLE `jmap_mailbox_revisions` (\n\t`mailbox_id` text PRIMARY KEY NOT NULL,\n\t`revision` integer NOT NULL DEFAULT 0\n);", + "CREATE INDEX `mailboxes_user_idx` ON `mailboxes` (`user_id`);", + "CREATE TRIGGER `jmap_messages_ai` AFTER INSERT ON `messages`\nWHEN NEW.mailbox_id IS NOT NULL BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_messages_au` AFTER UPDATE ON `messages`\nWHEN NEW.mailbox_id IS NOT NULL BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_messages_au_old` AFTER UPDATE OF mailbox_id ON `messages`\nWHEN OLD.mailbox_id IS NOT NULL AND OLD.mailbox_id IS NOT NEW.mailbox_id BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_messages_ad` AFTER DELETE ON `messages`\nWHEN OLD.mailbox_id IS NOT NULL BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_folders_ai` AFTER INSERT ON `folders` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_folders_au` AFTER UPDATE ON `folders` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_folders_au_old` AFTER UPDATE OF mailbox_id ON `folders`\nWHEN OLD.mailbox_id IS NOT NEW.mailbox_id BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_folders_ad` AFTER DELETE ON `folders` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_mailboxes_au` AFTER UPDATE ON `mailboxes` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_mailbox_aliases_ai` AFTER INSERT ON `mailbox_aliases` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_mailbox_aliases_au` AFTER UPDATE ON `mailbox_aliases` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (NEW.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_mailbox_aliases_au_old` AFTER UPDATE OF mailbox_id ON `mailbox_aliases`\nWHEN OLD.mailbox_id IS NOT NEW.mailbox_id BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;", + "CREATE TRIGGER `jmap_mailbox_aliases_ad` AFTER DELETE ON `mailbox_aliases` BEGIN\n\tINSERT INTO jmap_mailbox_revisions (mailbox_id, revision) VALUES (OLD.mailbox_id, 1)\n\tON CONFLICT(mailbox_id) DO UPDATE SET revision = revision + 1;\nEND;" + ] + }, + { + "name": "0043_cloud_attachment_links.sql", + "statements": [ + "ALTER TABLE app_settings ADD COLUMN outbound_attachment_max_mb integer NOT NULL DEFAULT 25;", + "CREATE TABLE shared_attachment_links (\n\tid text PRIMARY KEY NOT NULL,\n\tattachment_id text NOT NULL UNIQUE REFERENCES message_attachments(id) ON DELETE CASCADE,\n\texpires_at integer NOT NULL,\n\tcreated_at integer NOT NULL\n);" + ] + }, + { + "name": "0044_add_calendar_repeat.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `repeat` text NOT NULL DEFAULT 'none';", + "ALTER TABLE `calendar_events` ADD `repeat_until` integer;" + ] + }, + { + "name": "0045_add_calendar_repeat_days.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `repeat_days` text NOT NULL DEFAULT '[]';", + "ALTER TABLE `calendar_events` ADD `repeat_anchor_day` integer;" + ] + }, + { + "name": "0046_add_calendar_excluded_occurrences.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `excluded_occurrences` text NOT NULL DEFAULT '[]';" + ] + }, + { + "name": "0047_add_calendar_time_zone.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `time_zone` text;" + ] + }, + { + "name": "0047_add_message_list_indexes.sql", + "statements": [ + "CREATE INDEX IF NOT EXISTS `messages_inbox_page_idx` ON `messages` (`mailbox_id`, `status`, `folder_id`, `created_at` DESC, `id` DESC);", + "CREATE INDEX IF NOT EXISTS `messages_thread_key_idx` ON `messages` (`mailbox_id`, `status`, `folder_id`, coalesce(`thread_id`, `id`), `created_at`);", + "CREATE INDEX IF NOT EXISTS `messages_mailbox_thread_key_idx` ON `messages` (`mailbox_id`, coalesce(`thread_id`, `id`));" + ] + }, + { + "name": "0048_add_user_time_zone.sql", + "statements": [ + "ALTER TABLE `users` ADD `time_zone` text;" + ] + }, + { + "name": "0049_add_booking_events.sql", + "statements": [ + "CREATE TABLE `booking_events` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL REFERENCES `users`(`id`) ON DELETE cascade,\n\t`name` text NOT NULL,\n\t`slug` text NOT NULL DEFAULT '',\n\t`description` text NOT NULL DEFAULT '',\n\t`color` text NOT NULL DEFAULT '#2563eb',\n\t`host_ids` text NOT NULL DEFAULT '[]',\n\t`duration_minutes` integer NOT NULL,\n\t`location` text NOT NULL DEFAULT '',\n\t`weekdays` text NOT NULL DEFAULT '[1,2,3,4,5]',\n\t`start_time` text NOT NULL DEFAULT '09:00',\n\t`end_time` text NOT NULL DEFAULT '17:00',\n\t`time_ranges` text NOT NULL DEFAULT '[{\"startTime\":\"09:00\",\"endTime\":\"17:00\"}]',\n\t`time_zone` text NOT NULL DEFAULT 'UTC',\n\t`enabled` integer NOT NULL DEFAULT 1,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);", + "CREATE INDEX `booking_events_user_idx` ON `booking_events` (`user_id`);", + "CREATE UNIQUE INDEX `booking_events_user_slug_idx` ON `booking_events` (`user_id`, `slug`);", + "ALTER TABLE `users` ADD COLUMN `booking_username` text;", + "CREATE UNIQUE INDEX `users_booking_username_idx` ON `users` (`booking_username`);" + ] + }, + { + "name": "0050_add_primary_admin.sql", + "statements": [ + "ALTER TABLE `users` ADD `is_primary_admin` integer DEFAULT false NOT NULL;", + "ALTER TABLE `users` ADD `can_manage_domains` integer DEFAULT false NOT NULL;", + "ALTER TABLE `users` ADD `can_manage_users` integer DEFAULT false NOT NULL;", + "UPDATE `users` SET `is_primary_admin` = 1\nWHERE `id` = (\n SELECT `id` FROM `users` WHERE `role` = 'admin'\n ORDER BY `disabled` ASC, `created_at` ASC LIMIT 1\n);", + "UPDATE `users` SET `is_primary_admin` = 1\nWHERE `role` = 'admin'\n AND `id` = (\n SELECT `id` FROM `users` WHERE `role` = 'admin'\n ORDER BY `disabled` ASC, `created_at` ASC LIMIT 1\n )\n AND NOT EXISTS (SELECT 1 FROM `users` WHERE `is_primary_admin` = 1);" + ] + }, + { + "name": "0050_add_show_full_recipient_addresses.sql", + "statements": [ + "ALTER TABLE `users` ADD `show_full_recipient_addresses` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0051_add_outbound_provider.sql", + "statements": [ + "ALTER TABLE `domains` ADD `sending_provider` text DEFAULT 'none' NOT NULL;", + "UPDATE `domains` SET `sending_provider` = 'cloudflare' WHERE `sending_requested` = 1 OR `sending_enabled` = 1 OR `sending_subdomain_tag` IS NOT NULL;", + "ALTER TABLE `app_settings` ADD `resend_api_key` text;" + ] + }, + { + "name": "0052_add_receiving_provider.sql", + "statements": [ + "ALTER TABLE `domains` ADD `receiving_provider` text DEFAULT 'cloudflare' NOT NULL;", + "ALTER TABLE `app_settings` ADD `aws_config` text;", + "ALTER TABLE `app_settings` ADD `ses_receiving` text;", + "ALTER TABLE `app_settings` ADD `resend_webhook_id` text;", + "ALTER TABLE `app_settings` ADD `resend_webhook_secret` text;" + ] + }, + { + "name": "0053_add_trash_retention.sql", + "statements": [ + "ALTER TABLE `users` ADD `trash_retention_days` integer;", + "ALTER TABLE `messages` ADD `trashed_at` integer;", + "CREATE INDEX `messages_trashed_at_idx` ON `messages` (`trashed_at`);", + "UPDATE `messages` SET `trashed_at` = CAST(strftime('%s', 'now') AS integer) WHERE `status` IN ('trash', 'spam');", + "CREATE TRIGGER `messages_trashed_at_ai` AFTER INSERT ON `messages` WHEN new.`status` IN ('trash', 'spam') BEGIN\n\tUPDATE `messages` SET `trashed_at` = CAST(strftime('%s', 'now') AS integer) WHERE `rowid` = new.`rowid`;\nEND;", + "CREATE TRIGGER `messages_trashed_at_au` AFTER UPDATE OF `status` ON `messages` WHEN (new.`status` IN ('trash', 'spam')) <> (old.`status` IN ('trash', 'spam')) BEGIN\n\tUPDATE `messages` SET `trashed_at` = CASE WHEN new.`status` IN ('trash', 'spam') THEN CAST(strftime('%s', 'now') AS integer) ELSE NULL END WHERE `rowid` = new.`rowid`;\nEND;" + ] + }, + { + "name": "0054_add_push_subscriptions.sql", + "statements": [ + "CREATE TABLE `push_subscriptions` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`session_id` text NOT NULL,\n\t`endpoint` text NOT NULL,\n\t`p256dh` text NOT NULL,\n\t`auth` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `push_subscriptions_endpoint_idx` ON `push_subscriptions` (`endpoint`);", + "CREATE INDEX `push_subscriptions_user_idx` ON `push_subscriptions` (`user_id`);", + "CREATE INDEX `push_subscriptions_session_idx` ON `push_subscriptions` (`session_id`);" + ] + }, + { + "name": "0055_add_drive.sql", + "statements": [ + "CREATE TABLE `drive_items` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`owner_id` text NOT NULL,\n\t`parent_id` text,\n\t`kind` text NOT NULL,\n\t`name` text NOT NULL,\n\t`r2_key` text,\n\t`size` integer DEFAULT 0 NOT NULL,\n\t`content_type` text DEFAULT 'application/octet-stream' NOT NULL,\n\t`link_token` text,\n\t`trashed_at` integer,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tFOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE INDEX `drive_items_owner_parent_idx` ON `drive_items` (`owner_id`,`parent_id`);", + "CREATE UNIQUE INDEX `drive_items_link_token_idx` ON `drive_items` (`link_token`);", + "CREATE TABLE `drive_shares` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`item_id` text NOT NULL,\n\t`user_id` text NOT NULL,\n\t`role` text DEFAULT 'view' NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `drive_shares_item_user_idx` ON `drive_shares` (`item_id`,`user_id`);", + "CREATE INDEX `drive_shares_user_idx` ON `drive_shares` (`user_id`);" + ] + }, + { + "name": "0056_add_drive_upload_id.sql", + "statements": [ + "ALTER TABLE `drive_items` ADD `upload_id` text;" + ] + }, + { + "name": "0057_add_drive_resumable_uploads.sql", + "statements": [ + "ALTER TABLE `drive_items` ADD `upload_part_size` integer;", + "ALTER TABLE `drive_items` ADD `upload_fingerprint` text;", + "CREATE TABLE `drive_upload_parts` (\n\t`item_id` text NOT NULL,\n\t`part_number` integer NOT NULL,\n\t`etag` text NOT NULL,\n\tFOREIGN KEY (`item_id`) REFERENCES `drive_items`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `drive_upload_parts_idx` ON `drive_upload_parts` (`item_id`,`part_number`);" + ] + }, + { + "name": "0058_add_drive_storage_limit.sql", + "statements": [ + "ALTER TABLE `app_settings` ADD `drive_storage_limit_bytes` integer;" + ] + }, + { + "name": "0059_add_attachment_trash.sql", + "statements": [ + "ALTER TABLE `message_attachments` ADD `trashed_at` integer;" + ] + }, + { + "name": "0060_add_license_seat_limit.sql", + "statements": [ + "ALTER TABLE `license_settings` ADD `seat_limit` integer DEFAULT 1;" + ] + }, + { + "name": "0061_add_message_reply_to.sql", + "statements": [ + "ALTER TABLE `messages` ADD `reply_to` text;" + ] + }, + { + "name": "0062_add_remote_content_settings.sql", + "statements": [ + "ALTER TABLE `users` ADD `remote_content_mode` text DEFAULT 'allow' NOT NULL;", + "ALTER TABLE `contacts` ADD `remote_content_allowed` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0063_add_account_deletion.sql", + "statements": [ + "ALTER TABLE `users` ADD `last_sign_in_at` integer;", + "ALTER TABLE `users` ADD `deleted_at` integer;" + ] + }, + { + "name": "0064_add_jmap_changes_and_devices.sql", + "statements": [ + "CREATE TABLE `jmap_changes` (\n\t`seq` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t`mailbox_id` text NOT NULL,\n\t`object_type` text NOT NULL,\n\t`object_id` text NOT NULL,\n\t`thread_id` text,\n\t`change` text NOT NULL,\n\t`created_at` integer DEFAULT (unixepoch()) NOT NULL\n);", + "CREATE INDEX `jmap_changes_mailbox_seq_idx` ON `jmap_changes` (`mailbox_id`,`seq`);", + "CREATE TABLE `jmap_change_floor` (\n\t`id` integer PRIMARY KEY NOT NULL,\n\t`seq` integer DEFAULT 0 NOT NULL\n);", + "INSERT INTO `jmap_change_floor` (`id`, `seq`) VALUES (1, 0);", + "CREATE TRIGGER `jmap_changes_messages_ai` AFTER INSERT ON `messages`\nWHEN NEW.mailbox_id IS NOT NULL BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created');\nEND;", + "CREATE TRIGGER `jmap_changes_messages_au` AFTER UPDATE ON `messages`\nWHEN NEW.mailbox_id IS NOT NULL AND OLD.mailbox_id IS NEW.mailbox_id BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\tVALUES (NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'updated');\nEND;", + "CREATE TRIGGER `jmap_changes_messages_au_moved` AFTER UPDATE OF mailbox_id ON `messages`\nWHEN OLD.mailbox_id IS NOT NEW.mailbox_id BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\tSELECT OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed' WHERE OLD.mailbox_id IS NOT NULL;\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\tSELECT NEW.mailbox_id, 'email', NEW.id, coalesce(NEW.thread_id, NEW.id), 'created' WHERE NEW.mailbox_id IS NOT NULL;\nEND;", + "CREATE TRIGGER `jmap_changes_messages_ad` AFTER DELETE ON `messages`\nWHEN OLD.mailbox_id IS NOT NULL BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, thread_id, change)\n\tVALUES (OLD.mailbox_id, 'email', OLD.id, coalesce(OLD.thread_id, OLD.id), 'destroyed');\nEND;", + "CREATE TRIGGER `jmap_changes_folders_ai` AFTER INSERT ON `folders` BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.mailbox_id, 'mailbox', NEW.id, 'created');\nEND;", + "CREATE TRIGGER `jmap_changes_folders_au` AFTER UPDATE ON `folders` BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change)\n\tSELECT OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed' WHERE OLD.mailbox_id IS NOT NEW.mailbox_id;\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change)\n\tVALUES (NEW.mailbox_id, 'mailbox', NEW.id, CASE WHEN OLD.mailbox_id IS NEW.mailbox_id THEN 'updated' ELSE 'created' END);\nEND;", + "CREATE TRIGGER `jmap_changes_folders_ad` AFTER DELETE ON `folders` BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (OLD.mailbox_id, 'mailbox', OLD.id, 'destroyed');\nEND;", + "CREATE TRIGGER `jmap_changes_mailboxes_au` AFTER UPDATE ON `mailboxes` BEGIN\n\tINSERT INTO jmap_changes (mailbox_id, object_type, object_id, change) VALUES (NEW.id, 'mailbox', NEW.id, 'updated');\nEND;", + "CREATE TABLE `push_devices` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`api_key_id` text NOT NULL,\n\t`platform` text NOT NULL,\n\t`token` text NOT NULL,\n\t`environment` text DEFAULT 'production' NOT NULL,\n\t`topic` text NOT NULL,\n\t`public_key` text,\n\t`previews` integer DEFAULT true NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`api_key_id`) REFERENCES `api_keys`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `push_devices_platform_token_idx` ON `push_devices` (`platform`,`token`);", + "CREATE INDEX `push_devices_user_idx` ON `push_devices` (`user_id`);" + ] + }, + { + "name": "0065_push_devices_per_user.sql", + "statements": [ + "DROP INDEX `push_devices_platform_token_idx`;", + "CREATE UNIQUE INDEX `push_devices_platform_token_user_idx` ON `push_devices` (`platform`,`token`,`user_id`);", + "ALTER TABLE `push_devices` ADD `client_ref` text;" + ] + }, + { + "name": "0066_add_domain_dns_skipped.sql", + "statements": [ + "ALTER TABLE `domains` ADD `dns_skipped` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0068_add_message_tracking.sql", + "statements": [ + "CREATE TABLE `message_tracking` (\n\t`token` text PRIMARY KEY NOT NULL,\n\t`message_id` text NOT NULL,\n\t`open_count` integer DEFAULT 0 NOT NULL,\n\t`first_opened_at` integer,\n\t`last_opened_at` integer,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `message_tracking_message_idx` ON `message_tracking` (`message_id`);", + "CREATE TABLE `message_opens` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`token` text NOT NULL,\n\t`opened_at` integer NOT NULL,\n\t`client` text,\n\t`device` text,\n\t`country` text,\n\t`city` text,\n\t`automated` integer DEFAULT false NOT NULL,\n\tFOREIGN KEY (`token`) REFERENCES `message_tracking`(`token`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE INDEX `message_opens_token_idx` ON `message_opens` (`token`,`opened_at`);" + ] + }, + { + "name": "0069_add_domain_tracking_hosts.sql", + "statements": [ + "CREATE TABLE `domain_tracking_hosts` (\n\t`domain_id` text PRIMARY KEY NOT NULL,\n\t`hostname` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`domain_id`) REFERENCES `domains`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `domain_tracking_hosts_hostname_idx` ON `domain_tracking_hosts` (`hostname`);" + ] + }, + { + "name": "0070_add_spam_intelligence_settings.sql", + "statements": [ + "ALTER TABLE `app_settings` ADD `spamhaus_dqs_key` text;", + "ALTER TABLE `app_settings` ADD `abusech_auth_key` text;", + "ALTER TABLE `app_settings` ADD `spam_domain_age_check` integer DEFAULT true NOT NULL;", + "ALTER TABLE `app_settings` ADD `spam_brands` text;" + ] + }, + { + "name": "0071_add_follow_ups.sql", + "statements": [ + "CREATE TABLE `follow_ups` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`message_id` text NOT NULL,\n\t`user_id` text NOT NULL,\n\t`due_at` integer NOT NULL,\n\t`status` text DEFAULT 'pending' NOT NULL,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `follow_ups_message_idx` ON `follow_ups` (`message_id`);", + "CREATE INDEX `follow_ups_status_due_idx` ON `follow_ups` (`status`,`due_at`);", + "CREATE INDEX `follow_ups_user_status_idx` ON `follow_ups` (`user_id`,`status`);" + ] + }, + { + "name": "0072_add_user_compose_preferences.sql", + "statements": [ + "CREATE TABLE `user_compose_preferences` (\n\t`user_id` text PRIMARY KEY NOT NULL,\n\t`track_opens_default` integer DEFAULT false NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);" + ] + }, + { + "name": "0073_add_undo_send_seconds.sql", + "statements": [ + "ALTER TABLE `user_compose_preferences` ADD `undo_send_seconds` integer DEFAULT 15 NOT NULL;" + ] + }, + { + "name": "0074_add_counts_conversation_indexes.sql", + "statements": [ + "CREATE INDEX IF NOT EXISTS `messages_counts_cover_idx` ON `messages` (`mailbox_id`, `folder_id`, `direction`, `status`, `read`, `starred`, `snoozed_until`);", + "CREATE INDEX IF NOT EXISTS `messages_conv_cover_idx` ON `messages` (`mailbox_id`, `status`, coalesce(`thread_id`, `id`), `created_at`, `id`, `snoozed_until`);" + ] + }, + { + "name": "0075_index_fk_columns.sql", + "statements": [ + "CREATE INDEX IF NOT EXISTS `users_created_by_idx` ON `users` (`created_by_user_id`);", + "CREATE INDEX IF NOT EXISTS `mailbox_access_created_by_idx` ON `mailbox_access` (`created_by_user_id`);", + "CREATE INDEX IF NOT EXISTS `api_keys_user_idx` ON `api_keys` (`user_id`);", + "CREATE INDEX IF NOT EXISTS `spam_feedback_actor_user_idx` ON `spam_feedback` (`actor_user_id`);", + "CREATE INDEX IF NOT EXISTS `outbound_jobs_user_idx` ON `outbound_jobs` (`user_id`);", + "CREATE INDEX IF NOT EXISTS `outbound_jobs_message_idx` ON `outbound_jobs` (`message_id`);", + "CREATE INDEX IF NOT EXISTS `calendar_events_mailbox_idx` ON `calendar_events` (`mailbox_id`);", + "CREATE INDEX IF NOT EXISTS `routing_rules_user_idx` ON `routing_rules` (`user_id`);", + "CREATE INDEX IF NOT EXISTS `routing_rules_folder_idx` ON `routing_rules` (`folder_id`);", + "CREATE INDEX IF NOT EXISTS `webhooks_user_idx` ON `webhooks` (`user_id`);", + "CREATE INDEX IF NOT EXISTS `sessions_user_idx` ON `sessions` (`user_id`);", + "CREATE INDEX IF NOT EXISTS `push_devices_api_key_idx` ON `push_devices` (`api_key_id`);", + "CREATE INDEX IF NOT EXISTS `login_challenges_user_idx` ON `login_challenges` (`user_id`);", + "CREATE INDEX IF NOT EXISTS `audit_logs_message_id_idx` ON `audit_logs` (`message_id`);", + "CREATE INDEX IF NOT EXISTS `audit_logs_target_user_idx` ON `audit_logs` (`target_user_id`);", + "CREATE INDEX IF NOT EXISTS `backups_created_by_idx` ON `backups` (`created_by_user_id`);", + "CREATE INDEX IF NOT EXISTS `mailbox_agent_settings_reviewer_idx` ON `mailbox_agent_settings` (`reviewer_user_id`);", + "CREATE INDEX IF NOT EXISTS `agent_conversations_mailbox_idx` ON `agent_conversations` (`mailbox_id`);", + "CREATE INDEX IF NOT EXISTS `agent_jobs_source_message_idx` ON `agent_jobs` (`source_message_id`);", + "CREATE INDEX IF NOT EXISTS `agent_jobs_draft_idx` ON `agent_jobs` (`draft_id`);", + "CREATE INDEX IF NOT EXISTS `agent_jobs_reviewer_idx` ON `agent_jobs` (`reviewer_user_id`);", + "CREATE INDEX IF NOT EXISTS `agent_draft_meta_source_msg_idx` ON `agent_draft_metadata` (`source_message_id`);", + "CREATE INDEX IF NOT EXISTS `agent_draft_metadata_mailbox_idx` ON `agent_draft_metadata` (`mailbox_id`);", + "CREATE INDEX IF NOT EXISTS `agent_send_approvals_request_key_idx` ON `agent_send_approvals` (`request_key_id`);", + "CREATE INDEX IF NOT EXISTS `agent_send_approvals_mailbox_idx` ON `agent_send_approvals` (`mailbox_id`);", + "CREATE INDEX IF NOT EXISTS `agent_send_approvals_draft_idx` ON `agent_send_approvals` (`draft_id`);", + "CREATE INDEX IF NOT EXISTS `mcp_key_mailboxes_mailbox_idx` ON `mcp_key_mailboxes` (`mailbox_id`);" + ] + }, + { + "name": "0076_add_navigation_cover_index.sql", + "statements": [ + "CREATE INDEX IF NOT EXISTS `messages_nav_cover_idx` ON `messages` (`mailbox_id`, `status`, `folder_id`, `created_at` DESC, `id` DESC, `direction`, `read`, `thread_id`, `snoozed_until`);" + ] + }, + { + "name": "0077_add_import_jobs.sql", + "statements": [ + "CREATE TABLE `import_jobs` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`mailbox_id` text NOT NULL,\n\t`kind` text NOT NULL,\n\t`label` text NOT NULL,\n\t`status` text DEFAULT 'queued' NOT NULL,\n\t`total` integer DEFAULT 0 NOT NULL,\n\t`processed` integer DEFAULT 0 NOT NULL,\n\t`imported` integer DEFAULT 0 NOT NULL,\n\t`skipped` integer DEFAULT 0 NOT NULL,\n\t`spec` text NOT NULL,\n\t`cursor` text DEFAULT '{}' NOT NULL,\n\t`errors` text DEFAULT '[]' NOT NULL,\n\t`error_count` integer DEFAULT 0 NOT NULL,\n\t`error` text,\n\t`created_at` integer NOT NULL,\n\t`started_at` integer,\n\t`updated_at` integer NOT NULL,\n\t`finished_at` integer,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE INDEX `import_jobs_user_idx` ON `import_jobs` (`user_id`,`created_at`);", + "CREATE INDEX `import_jobs_status_idx` ON `import_jobs` (`status`,`updated_at`);" + ] + }, + { + "name": "0078_add_calendar_reminders.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `reminder_minutes` integer;", + "ALTER TABLE `calendar_events` ADD `last_reminded_start` integer;" + ] + }, + { + "name": "0079_remote_content_ask.sql", + "statements": [ + "UPDATE `users` SET `remote_content_mode` = 'ask' WHERE `remote_content_mode` = 'allow';" + ] + }, + { + "name": "0080_passkeys_and_step_up_grants.sql", + "statements": [ + "ALTER TABLE `users` ADD `require_second_factor` integer DEFAULT false NOT NULL;", + "ALTER TABLE `users` ADD `passkey_count` integer DEFAULT 0 NOT NULL;", + "ALTER TABLE `users` ADD `security_version` integer DEFAULT 0 NOT NULL;", + "UPDATE `users` SET `require_second_factor` = `totp_enabled`;", + "CREATE TABLE `passkey_credentials` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`credential_id` text NOT NULL,\n\t`credential_hash` text NOT NULL,\n\t`public_key` text NOT NULL,\n\t`counter` integer DEFAULT 0 NOT NULL,\n\t`transports` text,\n\t`device_type` text NOT NULL,\n\t`backed_up` integer DEFAULT false NOT NULL,\n\t`aaguid` text,\n\t`name` text NOT NULL,\n\t`last_used_at` integer,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `passkey_credentials_credential_hash_unique` ON `passkey_credentials` (`credential_hash`);", + "CREATE INDEX `passkey_credentials_user_idx` ON `passkey_credentials` (`user_id`);", + "CREATE TABLE `webauthn_challenges` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`ceremony_hash` text NOT NULL,\n\t`challenge` text NOT NULL,\n\t`purpose` text NOT NULL,\n\t`user_id` text,\n\t`binding_hash` text NOT NULL,\n\t`expires_at` integer NOT NULL,\n\t`used_at` integer,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `webauthn_challenges_ceremony_hash_unique` ON `webauthn_challenges` (`ceremony_hash`);", + "CREATE INDEX `webauthn_challenges_user_idx` ON `webauthn_challenges` (`user_id`);", + "CREATE INDEX `webauthn_challenges_expires_idx` ON `webauthn_challenges` (`expires_at`);", + "CREATE TABLE `passkey_enrollment_grants` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`token_hash` text NOT NULL,\n\t`kind` text NOT NULL,\n\t`created_by_user_id` text,\n\t`expires_at` integer NOT NULL,\n\t`used_at` integer,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE UNIQUE INDEX `passkey_enrollment_grants_token_hash_unique` ON `passkey_enrollment_grants` (`token_hash`);", + "CREATE INDEX `passkey_enrollment_grants_user_idx` ON `passkey_enrollment_grants` (`user_id`);", + "CREATE TABLE `auth_step_ups` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`session_hash` text NOT NULL,\n\t`token_hash` text NOT NULL,\n\t`purpose` text NOT NULL,\n\t`target_user_id` text,\n\t`security_version` integer DEFAULT 0 NOT NULL,\n\t`actor_security_version` integer DEFAULT 0 NOT NULL,\n\t`expires_at` integer NOT NULL,\n\t`used_at` integer,\n\t`created_at` integer NOT NULL,\n\tFOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade\n);", + "CREATE UNIQUE INDEX `auth_step_ups_token_hash_unique` ON `auth_step_ups` (`token_hash`);", + "CREATE INDEX `auth_step_ups_user_idx` ON `auth_step_ups` (`user_id`);", + "CREATE TRIGGER `passkey_credentials_count_insert` AFTER INSERT ON `passkey_credentials`\nBEGIN\n\tUPDATE `users` SET `passkey_count` = `passkey_count` + 1 WHERE `id` = NEW.`user_id`;\nEND;", + "CREATE TRIGGER `passkey_credentials_count_delete` AFTER DELETE ON `passkey_credentials`\nBEGIN\n\tUPDATE `users` SET `passkey_count` = `passkey_count` - 1 WHERE `id` = OLD.`user_id`;\n\tUPDATE `users` SET `require_second_factor` = 0\n\tWHERE `id` = OLD.`user_id`\n\t\tAND `passkey_count` = 0\n\t\tAND `totp_enabled` = 0\n\t\tAND `deleted_at` IS NULL;\n\tSELECT RAISE(ABORT, 'last-auth-method')\n\tWHERE (SELECT `passkey_count` FROM `users` WHERE `id` = OLD.`user_id`) = 0\n\t\tAND (SELECT `deleted_at` FROM `users` WHERE `id` = OLD.`user_id`) IS NULL\n\t\tAND (SELECT `password_hash` FROM `users` WHERE `id` = OLD.`user_id`) = '!passkey-only';\nEND;", + "CREATE TRIGGER `users_last_password_update` BEFORE UPDATE OF `password_hash` ON `users`\nWHEN NEW.`password_hash` = '!passkey-only' AND NEW.`passkey_count` = 0\nBEGIN\n\tSELECT RAISE(ABORT, 'last-auth-method');\nEND;", + "CREATE TRIGGER `users_require_second_factor_update` BEFORE UPDATE OF `require_second_factor` ON `users`\nWHEN NEW.`require_second_factor` = 1 AND NEW.`passkey_count` = 0 AND NEW.`totp_enabled` = 0 AND NEW.`deleted_at` IS NULL\nBEGIN\n\tSELECT RAISE(ABORT, 'second-factor-unavailable');\nEND;" + ] + }, + { + "name": "0081_add_feature_access.sql", + "statements": [ + "ALTER TABLE `users` ADD `calendar_enabled` integer DEFAULT true NOT NULL;", + "ALTER TABLE `users` ADD `drive_enabled` integer DEFAULT true NOT NULL;" + ] + }, + { + "name": "0082_add_api_key_sha256.sql", + "statements": [ + "ALTER TABLE `api_keys` ADD `key_sha256` text;", + "CREATE UNIQUE INDEX `api_keys_key_sha256_idx` ON `api_keys` (`key_sha256`);" + ] + }, + { + "name": "0083_add_message_has_unsubscribe.sql", + "statements": [ + "ALTER TABLE `messages` ADD `has_unsubscribe` integer DEFAULT false NOT NULL;" + ] + }, + { + "name": "0084_add_conversation_notes.sql", + "statements": [ + "CREATE TABLE `conversation_notes` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`mailbox_id` text NOT NULL,\n\t`thread_key` text NOT NULL,\n\t`message_id` text,\n\t`html` text NOT NULL,\n\t`author_user_id` text,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL,\n\tFOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade,\n\tFOREIGN KEY (`message_id`) REFERENCES `messages`(`id`) ON UPDATE no action ON DELETE set null,\n\tFOREIGN KEY (`author_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null\n);", + "CREATE INDEX `conversation_notes_mailbox_thread_idx` ON `conversation_notes` (`mailbox_id`,`thread_key`,`created_at`);", + "CREATE INDEX `conversation_notes_message_idx` ON `conversation_notes` (`message_id`);", + "CREATE INDEX `conversation_notes_author_idx` ON `conversation_notes` (`author_user_id`);" + ] + }, + { + "name": "0085_calendar_invitations.sql", + "statements": [ + "ALTER TABLE `calendar_events` ADD `response_status` text;", + "ALTER TABLE `calendar_events` ADD `invite_message_id` text;", + "ALTER TABLE `calendar_events` ADD `attendee_responses` text;", + "ALTER TABLE `calendar_events` ADD `invite_sender` text;", + "ALTER TABLE `calendar_events` ADD `invite_sequence` integer;" + ] + }, + { + "name": "0086_message_action_undo_claims.sql", + "statements": [ + "CREATE TABLE `message_action_undo_claims` (\n\t`nonce` text PRIMARY KEY NOT NULL,\n\t`user_id` text NOT NULL,\n\t`expires_at` integer NOT NULL\n);", + "CREATE INDEX `message_action_undo_claims_expires_idx` ON `message_action_undo_claims` (`expires_at`);" + ] + } + ] +} From 0c2a5ac722280b432590e712432c1c76b2bfc56b Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 22:00:52 +0100 Subject: [PATCH 07/15] fix(messages): keep claims after partial undo progress --- src/lib/messages/actions/service.ts | 68 ++++++++++----- tests/message-action-server-service.test.mjs | 90 +++++++++++++++++++- 2 files changed, 134 insertions(+), 24 deletions(-) diff --git a/src/lib/messages/actions/service.ts b/src/lib/messages/actions/service.ts index b6f6e0282..ab9f6cd07 100644 --- a/src/lib/messages/actions/service.ts +++ b/src/lib/messages/actions/service.ts @@ -310,13 +310,17 @@ export async function undoMessageActionForUser( throw new MessageActionError("This undo has already been used", 410); } + // Once any row has been restored, the token must never be released: a retry + // could replay that already-used record. Partial outcomes therefore keep the + // claim and return the committed receipts. Only zero-progress failures release + // it so an otherwise safe retry can succeed. + const progress = { restored: 0 }; try { - return await performUndoMessageAction(env, user, payload); + return await performUndoMessageAction(env, user, payload, progress); } catch (error) { - // A transient failure must not burn the one-time token: release it so the - // same signed retry can be attempted again. Field CAS makes a retry safe - // after any rows that were already restored. - await releaseMessageActionUndoClaim(env, { nonce: payload.nonce, userId: user.id }).catch(() => undefined); + if (progress.restored === 0) { + await releaseMessageActionUndoClaim(env, { nonce: payload.nonce, userId: user.id }).catch(() => undefined); + } throw error; } } @@ -325,6 +329,7 @@ async function performUndoMessageAction( env: CloudflareEnv, user: SessionUser, payload: NonNullable>>, + progress: { restored: number }, ): Promise { const records = [...new Map(payload.records.map((record) => [record.id, record])).values()]; const db = getDb(env); @@ -362,29 +367,46 @@ async function performUndoMessageAction( } // One row at a time: the MySQL update/returning shim needs an exact // per-row affected count, and every dialect gets a real field CAS. - const updated = await db.update(messages) - .set(toDatabasePatch(plan.patch)) - .where(and(eq(messages.id, record.id), ...stateConditions(plan.fields, record.applied))) - .returning({ id: messages.id }); - if (updated.length === 0) { - skipped.push({ id: record.id, reason: "stale" }); - continue; + try { + const updated = await db.update(messages) + .set(toDatabasePatch(plan.patch)) + .where(and(eq(messages.id, record.id), ...stateConditions(plan.fields, record.applied))) + .returning({ id: messages.id }); + if (updated.length === 0) { + skipped.push({ id: record.id, reason: "stale" }); + continue; + } + restored.push(record.id); + progress.restored += 1; + } catch { + // A failed row is reported; earlier restores stay committed and are + // audited below. Zero-progress failure throws so the caller can retry. + skipped.push({ id: record.id, reason: "failed" }); } - restored.push(record.id); + } + + if (restored.length === 0 && skipped.some((item) => item.reason === "failed")) { + throw new MessageActionError("Could not restore messages", 500); } if (restored.length > 0) { const restoredSet = new Set(restored); - await createAuditLogs(env, records - .filter((record) => restoredSet.has(record.id)) - .map((record) => ({ - actorUserId: user.id, - messageId: record.id, - action: getChangedStateFields(record.previous, record.applied).every((field) => field === "read" || field === "starred") - ? "email.read" - : "email.delete", - metadata: { undoOf: payload.action }, - }))); + try { + await createAuditLogs(env, records + .filter((record) => restoredSet.has(record.id)) + .map((record) => ({ + actorUserId: user.id, + messageId: record.id, + action: getChangedStateFields(record.previous, record.applied).every((field) => field === "read" || field === "starred") + ? "email.read" + : "email.delete", + metadata: { undoOf: payload.action }, + }))); + } catch (error) { + // The restore already committed. Audit failure must not make the claim + // look retryable and risk a replay. + console.error("Message undo audit failed", error); + } } return { ok: true, action: payload.action, restored, skipped }; diff --git a/tests/message-action-server-service.test.mjs b/tests/message-action-server-service.test.mjs index 6456d7735..0a5021a8a 100644 --- a/tests/message-action-server-service.test.mjs +++ b/tests/message-action-server-service.test.mjs @@ -42,7 +42,14 @@ await build({ return { canRead: true, canManage: true }; } `); - alias(/^@\/lib\/mailboxes\/audit$/, "mock-audit", "export async function createAuditLogs() {}"); + alias(/^@\/lib\/mailboxes\/audit$/, "mock-audit", ` + export async function createAuditLogs(_env, inputs) { + if (globalThis.__failUndoAudit && inputs.some((input) => input.metadata?.undoOf)) { + throw new Error("injected audit failure"); + } + (globalThis.__undoAudits ??= []).push(...inputs); + } + `); alias(/^@\/lib\/spam\/feedback$/, "mock-spam", ` export async function applySpamFeedback(_env, _user, messageId, classification) { const status = classification === "spam" ? "spam" : "received"; @@ -87,6 +94,8 @@ const user = { id: "user-1" }; function reset(message = {}) { sqlite.exec("DELETE FROM messages; DELETE FROM message_action_undo_claims; DELETE FROM folders;"); + globalThis.__undoAudits = []; + globalThis.__failUndoAudit = false; const row = { id: "m1", mailboxId: "mb1", @@ -173,6 +182,85 @@ test("only actually changed rows are reported as applied", async () => { assert.equal(applied.undoToken, undefined); }); +test("a partial transient undo keeps the claim, reports the failed row, and audits restores", async () => { + reset(); + sqlite.prepare("INSERT INTO messages (id, mailbox_id, direction, status, read, starred, folder_id, snoozed_until) VALUES ('m2', 'mb1', 'inbound', 'received', 0, 0, NULL, NULL)").run(); + const applied = await m.applyMessageActionForUser({}, user, { action: "read", messageIds: ["m1", "m2"] }); + globalThis.__undoAudits = []; + sqlite.exec(` + CREATE TRIGGER fail_m2_restore BEFORE UPDATE OF read ON messages + WHEN OLD.id = 'm2' AND OLD.read = 1 AND NEW.read = 0 + BEGIN + SELECT RAISE(ABORT, 'injected restore failure'); + END; + `); + let undo; + try { + undo = await m.undoMessageActionForUser({}, user, applied.undoToken); + } finally { + sqlite.exec("DROP TRIGGER fail_m2_restore"); + } + assert.deepEqual(undo.restored, ["m1"]); + assert.deepEqual(undo.skipped, [{ id: "m2", reason: "failed" }]); + assert.equal(rowState("m1").read, 0); + assert.equal(rowState("m2").read, 1); + assert.deepEqual(globalThis.__undoAudits.map((entry) => entry.messageId), ["m1"]); + assert.equal(globalThis.__undoAudits[0].metadata.undoOf, "read"); + // The committed restore makes the token non-retryable. + await assert.rejects( + m.undoMessageActionForUser({}, user, applied.undoToken), + (error) => error instanceof m.MessageActionError && error.status === 410, + ); +}); + +test("a zero-progress transient undo releases the claim so a clean retry works", async () => { + reset(); + sqlite.prepare("INSERT INTO messages (id, mailbox_id, direction, status, read, starred, folder_id, snoozed_until) VALUES ('m2', 'mb1', 'inbound', 'received', 0, 0, NULL, NULL)").run(); + const applied = await m.applyMessageActionForUser({}, user, { action: "read", messageIds: ["m1", "m2"] }); + sqlite.exec(` + CREATE TRIGGER fail_all_restore BEFORE UPDATE OF read ON messages + WHEN OLD.read = 1 AND NEW.read = 0 + BEGIN + SELECT RAISE(ABORT, 'injected restore failure'); + END; + `); + try { + await assert.rejects( + m.undoMessageActionForUser({}, user, applied.undoToken), + (error) => error instanceof m.MessageActionError && error.status === 500, + ); + } finally { + sqlite.exec("DROP TRIGGER fail_all_restore"); + } + assert.equal(rowState("m1").read, 1); + const retry = await m.undoMessageActionForUser({}, user, applied.undoToken); + assert.deepEqual(retry.restored.sort(), ["m1", "m2"]); + assert.equal(rowState("m1").read, 0); + assert.equal(rowState("m2").read, 0); +}); + +test("an audit failure after a committed restore does not release the claim", async () => { + reset(); + const applied = await m.applyMessageActionForUser({}, user, { action: "read", messageIds: ["m1"] }); + globalThis.__undoAudits = []; + globalThis.__failUndoAudit = true; + let undo; + const originalError = console.error; + console.error = () => undefined; + try { + undo = await m.undoMessageActionForUser({}, user, applied.undoToken); + } finally { + console.error = originalError; + globalThis.__failUndoAudit = false; + } + assert.deepEqual(undo.restored, ["m1"]); + assert.equal(rowState("m1").read, 0); + await assert.rejects( + m.undoMessageActionForUser({}, user, applied.undoToken), + (error) => error instanceof m.MessageActionError && error.status === 410, + ); +}); + test("a CAS race rejects a stale archive snapshot instead of signing it", async () => { reset(); // Simulates the row being changed between the service's read and its CAS From f256e64a4c1af78b1b122e6d199c01d651f18360 Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 22:16:55 +0100 Subject: [PATCH 08/15] fix(messages): keep undo overlays across client fetches --- .../(dashboard)/inbox/[messageId]/page.tsx | 3 + .../messages/message-thread-cache.ts | 33 +- src/components/messages/use-message-thread.ts | 16 +- src/hooks/use-message-counts.ts | 37 ++- src/hooks/use-messages.ts | 108 +++++-- src/hooks/utils.ts | 147 +++++++-- src/lib/messages/actions/client.ts | 295 ++++++++++++----- src/lib/messages/actions/executor.ts | 45 ++- src/lib/messages/change-events.ts | 10 +- src/lib/messages/detail-cache.ts | 40 ++- src/lib/messages/field-store.ts | 283 ++++++++++++++++- tests/e2e/message-undo.spec.ts | 99 ++++++ tests/message-action-pending-caches.test.mjs | 298 ++++++++++++++++++ tests/message-action-pending-hooks.test.mjs | 228 ++++++++++++++ tests/message-action-pending-timeout.test.mjs | 156 +++++++++ tests/message-action-undo.test.mjs | 4 +- 16 files changed, 1620 insertions(+), 182 deletions(-) create mode 100644 tests/message-action-pending-caches.test.mjs create mode 100644 tests/message-action-pending-hooks.test.mjs create mode 100644 tests/message-action-pending-timeout.test.mjs diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx index 0e80b0e34..f8bcf252b 100644 --- a/src/app/(dashboard)/inbox/[messageId]/page.tsx +++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx @@ -36,6 +36,7 @@ import { SenderCheckNotice } from "@/components/messages/sender-check-notice"; import { useMessageThread } from "@/components/messages/use-message-thread"; import { useLatestMessagesFirst } from "@/components/messages/use-latest-messages-first"; import { useMessageListVisibility } from "@/components/messages/message-list-visibility"; +import { subscribePendingOverlay } from "@/lib/messages/field-store"; import { splitEmailAddressList } from "@/lib/email/address"; import { findInviteAttachment } from "@/lib/calendar/invite-attachment"; import { formatRecipientAddressList, type RecipientAddressStyle } from "@/lib/email/recipient-display"; @@ -196,9 +197,11 @@ function MessageDetailContent({ messageId }: { messageId: string }) { }); } window.addEventListener("mailflare:messages-changed", syncCachedState); + const unsubscribePending = subscribePendingOverlay(syncCachedState); return () => { cancelled = true; window.removeEventListener("mailflare:messages-changed", syncCachedState); + unsubscribePending(); }; }, [messageId]); diff --git a/src/components/messages/message-thread-cache.ts b/src/components/messages/message-thread-cache.ts index 4576821f1..28554d53e 100644 --- a/src/components/messages/message-thread-cache.ts +++ b/src/components/messages/message-thread-cache.ts @@ -1,6 +1,10 @@ import { AUTH_SESSION_CHANGED_EVENT, authFetch } from "@/lib/auth/client"; import { getMessagesChangedDetail } from "@/lib/messages/change-events"; -import { rememberMessageFields, rememberMessageRows } from "@/lib/messages/field-store"; +import { + applyPendingToMessages, + rememberMessageFields, + rememberMessageRows, +} from "@/lib/messages/field-store"; import type { ThreadMessage, ThreadResponse } from "@/hooks/types"; const CACHE_TTL_MS = 60_000; @@ -30,9 +34,10 @@ function bodyChars(messages: ThreadMessage[]): number { function cacheThread(messageId: string, messages: ThreadMessage[]): void { if (messages.length > MAX_CACHED_MESSAGES || bodyChars(messages) > MAX_CACHED_BODY_CHARS) return; + const pendingMessages = applyPendingToMessages(messages); threadCache.delete(messageId); - threadCache.set(messageId, { messages, expiresAt: Date.now() + CACHE_TTL_MS }); - rememberMessageRows(messages); + threadCache.set(messageId, { messages: pendingMessages, expiresAt: Date.now() + CACHE_TTL_MS }); + rememberMessageRows(pendingMessages); if (threadCache.size > CACHE_LIMIT) { const oldest = threadCache.keys().next().value; if (oldest) threadCache.delete(oldest); @@ -49,7 +54,7 @@ export function getCachedMessageThread(messageId: string | null | undefined): Th } threadCache.delete(messageId); threadCache.set(messageId, cached); - return cached.messages; + return applyPendingToMessages(cached.messages); } export function fetchMessageThread(messageId: string): Promise { @@ -66,7 +71,7 @@ export function fetchMessageThread(messageId: string): Promise if (requestGeneration !== generation) throw new MessageThreadInvalidatedError(); const messages = data.messages ?? []; cacheThread(messageId, messages); - return messages; + return applyPendingToMessages(messages); }) .finally(() => { if (threadRequests.get(messageId) === request) threadRequests.delete(messageId); @@ -87,10 +92,11 @@ export function patchMessageThreadFieldsInCaches( threadRequests.clear(); for (const [messageId, cached] of threadCache) { if (!cached.messages.some((message) => ids.has(message.id))) continue; - threadCache.set(messageId, { - ...cached, - messages: cached.messages.map((message) => (ids.has(message.id) ? { ...message, ...patch } : message)), - }); + const messages = applyPendingToMessages(cached.messages.map((message) => ( + ids.has(message.id) ? { ...message, ...patch } : message + ))); + threadCache.set(messageId, { ...cached, messages }); + rememberMessageRows(messages); } rememberMessageFields(messageIds, patch); } @@ -99,6 +105,12 @@ export function markMessageThreadReadInCaches(messageIds: string[], read: boolea patchMessageThreadFieldsInCaches(messageIds, { read }); } +/** Drops in-flight thread requests while keeping an already-patched cache. */ +export function invalidateMessageThreadRequests(): void { + generation += 1; + threadRequests.clear(); +} + export function clearMessageThreadCache(): void { generation += 1; threadCache.clear(); @@ -123,8 +135,5 @@ if (typeof window !== "undefined") { ...(patch.starred !== undefined ? { starred: patch.starred } : {}), }); } - // A settled star patch still needs the server's folder membership; an - // optimistic one must keep the patched conversation on screen. - if (!detail.deferRefresh) clearMessageThreadCache(); }); } diff --git a/src/components/messages/use-message-thread.ts b/src/components/messages/use-message-thread.ts index 69e25f53c..eaa9e6ccd 100644 --- a/src/components/messages/use-message-thread.ts +++ b/src/components/messages/use-message-thread.ts @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import type { ThreadMessage } from "@/hooks/types"; +import { applyPendingToMessages, subscribePendingOverlay } from "@/lib/messages/field-store"; import { fetchMessageThread, getCachedMessageThread, @@ -35,7 +36,7 @@ export function useMessageThread(messageId: string, threadId: string | null | un setLoading(true); try { const next = await fetchMessageThread(messageId); - if (!cancelled && version === loadVersion) setMessages(next); + if (!cancelled && version === loadVersion) setMessages(applyPendingToMessages(next)); } catch (error) { // A newer load is queued; keep the conversation on screen. if (!cancelled && version === loadVersion && !isMessageThreadInvalidated(error)) setMessages([]); @@ -52,13 +53,13 @@ export function useMessageThread(messageId: string, threadId: string | null | un const ids = new Set(detail.messageIds); const read = detail.read !== false; markMessageThreadReadInCaches(detail.messageIds, read); - setMessages((current) => current.map((message) => (ids.has(message.id) ? { ...message, read } : message))); + setMessages((current) => applyPendingToMessages(current.map((message) => (ids.has(message.id) ? { ...message, read } : message)))); } function patchFieldState(event: Event) { const detail = (event as CustomEvent<{ kind?: string; patches?: Array<{ id: string; read?: boolean; starred?: boolean }> }>).detail; if (detail?.kind !== "patch" || !detail.patches?.length) return; const patches = new Map(detail.patches.map((patch) => [patch.id, patch])); - setMessages((current) => current.map((message) => { + setMessages((current) => applyPendingToMessages(current.map((message) => { const patch = patches.get(message.id); if (!patch) return message; return { @@ -66,10 +67,9 @@ export function useMessageThread(messageId: string, threadId: string | null | un ...(patch.read !== undefined ? { read: patch.read } : {}), ...(patch.starred !== undefined ? { starred: patch.starred } : {}), }; - })); + }))); } - function scheduleLoad(event?: Event) { - if ((event as CustomEvent<{ deferRefresh?: boolean }> | undefined)?.detail?.deferRefresh) return; + function scheduleLoad() { if (document.visibilityState !== "visible") return; if (refreshTimer) window.clearTimeout(refreshTimer); refreshTimer = window.setTimeout(() => { @@ -77,6 +77,9 @@ export function useMessageThread(messageId: string, threadId: string | null | un void load(); }, 150); } + const unsubscribePending = subscribePendingOverlay(() => { + setMessages((current) => applyPendingToMessages(current)); + }); window.addEventListener("mailflare:messages-changed", scheduleLoad); window.addEventListener("mailflare:messages-changed", patchReadState); window.addEventListener("mailflare:messages-changed", patchFieldState); @@ -85,6 +88,7 @@ export function useMessageThread(messageId: string, threadId: string | null | un window.removeEventListener("mailflare:messages-changed", scheduleLoad); window.removeEventListener("mailflare:messages-changed", patchReadState); window.removeEventListener("mailflare:messages-changed", patchFieldState); + unsubscribePending(); if (refreshTimer) window.clearTimeout(refreshTimer); }; }, [messageId, threadId]); diff --git a/src/hooks/use-message-counts.ts b/src/hooks/use-message-counts.ts index 1224030a1..336084e61 100644 --- a/src/hooks/use-message-counts.ts +++ b/src/hooks/use-message-counts.ts @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import type { MessageCounts, MessageCountsDelta } from "./types"; +import { hasPendingOverlay, subscribePendingOverlay } from "@/lib/messages/field-store"; import { clearMessageCountsCache, fetchMessageCounts } from "./utils"; const REFRESH_DEBOUNCE_MS = 150; @@ -37,16 +38,15 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) { setIsLoading(true); try { const nextCounts = await fetchMessageCounts(mailboxId); - if (!cancelled && currentRequest === requestNumber) setCounts(nextCounts ?? emptyCounts); + if (!cancelled && currentRequest === requestNumber && !hasPendingOverlay()) { + setCounts(nextCounts ?? emptyCounts); + } } finally { if (!cancelled && currentRequest === requestNumber) setIsLoading(false); } } - void loadCounts(); - function onMessagesChanged(event: Event) { - if ((event as CustomEvent<{ deferRefresh?: boolean }>).detail?.deferRefresh) return; - clearMessageCountsCache(); + function scheduleCountsLoad() { if (document.visibilityState !== "visible") return; if (refreshTimer) window.clearTimeout(refreshTimer); refreshTimer = window.setTimeout(() => { @@ -55,6 +55,19 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) { void loadCounts(); }, REFRESH_DEBOUNCE_MS); } + + // A pending undo has not settled on the server yet. Keep the optimistic + // one-shot delta on screen and fetch authoritative counts only afterwards. + if (hasPendingOverlay()) { + clearMessageCountsCache(); + } else { + void loadCounts(); + } + function onMessagesChanged() { + if (hasPendingOverlay()) return; + clearMessageCountsCache(); + scheduleCountsLoad(); + } function onMessageCountsDelta(event: Event) { const detail = (event as CustomEvent).detail; if (!detail?.inboxUnreadDelta) return; @@ -69,6 +82,19 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) { }, })); } + const unsubscribePending = subscribePendingOverlay(() => { + // Invalidate a load that started before the overlay changed so its + // server value cannot land on top of the optimistic state. + requestNumber += 1; + clearMessageCountsCache(); + if (hasPendingOverlay()) { + if (refreshTimer) window.clearTimeout(refreshTimer); + refreshTimer = null; + setIsLoading(false); + return; + } + scheduleCountsLoad(); + }); window.addEventListener("mailflare:messages-changed", onMessagesChanged); window.addEventListener("mailflare:message-counts-changed", onMessagesChanged); window.addEventListener("mailflare:message-counts-delta", onMessageCountsDelta); @@ -78,6 +104,7 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) { window.removeEventListener("mailflare:messages-changed", onMessagesChanged); window.removeEventListener("mailflare:message-counts-changed", onMessagesChanged); window.removeEventListener("mailflare:message-counts-delta", onMessageCountsDelta); + unsubscribePending(); if (refreshTimer) window.clearTimeout(refreshTimer); }; }, [enabled, mailboxId]); diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts index 8bf6825e6..40ed59971 100644 --- a/src/hooks/use-messages.ts +++ b/src/hooks/use-messages.ts @@ -1,5 +1,7 @@ import { useEffect, useState } from "react"; import type { Message, MessageFilterOptions, MessageFolder } from "./types"; +import { applyPendingToMessages, getKnownThreadUnread, subscribePendingOverlay } from "@/lib/messages/field-store"; +import type { ThreadUnreadTarget } from "@/lib/messages/field-store"; import { clearMessageCountsCache, clearMessageListCache, @@ -10,6 +12,37 @@ import { const REFRESH_DEBOUNCE_MS = 150; +function clampThreadUnread(value: number, size: number): number { + return Math.min(size, Math.max(0, Math.trunc(value))); +} + +/** + * Grouped rows use an absolute aggregate. If the event carries a target (or + * the shared store already knows one), apply it; otherwise fall back to only + * the members that can still change, so a repeated read/unread is a no-op. + */ +function patchThreadRow( + message: Message, + ids: Set, + read: boolean, + explicitTarget: number | undefined, +): Message { + if (!message.threadMessageIds?.length) { + return ids.has(message.id) ? { ...message, read } : message; + } + const size = message.threadMessageIds.length; + const current = clampThreadUnread(message.threadUnread ?? 0, size); + const target = explicitTarget ?? getKnownThreadUnread(message.id) ?? (() => { + const flipped = message.threadMessageIds.reduce((total, id) => total + (ids.has(id) ? 1 : 0), 0); + const possible = read ? current : size - current; + return current + (read ? -Math.min(flipped, possible) : Math.min(flipped, possible)); + })(); + const threadUnread = clampThreadUnread(target, size); + const nextRead = threadUnread === 0; + if (message.threadUnread === threadUnread && message.read === nextRead) return message; + return { ...message, read: nextRead, threadUnread }; +} + export function useMessages( folder: MessageFolder, mailboxId?: string | null, @@ -41,7 +74,7 @@ export function useMessages( const params = getMessageQueryParams(folder, mailboxId, filters, folderId); const data = await fetchMessageList(params, force); if (!cancelled && currentRequest === requestNumber) { - setMessages(data.messages ?? []); + setMessages(applyPendingToMessages(data.messages ?? [])); setTotal(data.total ?? 0); setLimit(data.limit ?? filters?.limit ?? 25); setOffset(data.offset ?? filters?.offset ?? 0); @@ -53,43 +86,72 @@ export function useMessages( void loadMessages(false, !peekMessageList(getMessageQueryParams(folder, mailboxId, filters, folderId))); function patchReadState(event: Event) { - const detail = (event as CustomEvent<{ kind?: string; messageIds?: string[]; read?: boolean }>).detail; + const detail = (event as CustomEvent<{ + kind?: string; + messageIds?: string[]; + read?: boolean; + threadTargets?: ThreadUnreadTarget[]; + }>).detail; if (detail?.kind !== "read" || !detail.messageIds?.length) return; const ids = new Set(detail.messageIds); const read = detail.read !== false; - setMessages((current) => current.map((message) => { - if (message.threadMessageIds) { - // Only the flipped members change a conversation row's unread count. - const threadSize = message.threadMessageIds.length; - const flipped = message.threadMessageIds.reduce((total, id) => total + (ids.has(id) ? 1 : 0), 0); - if (!flipped) return message; - const threadUnread = Math.min(threadSize, Math.max(0, (message.threadUnread ?? 0) + (read ? -flipped : flipped))); - return { ...message, read: threadUnread === 0, threadUnread }; - } - return ids.has(message.id) ? { ...message, read } : message; - })); + const targets = new Map((detail.threadTargets ?? []).map((target) => [target.id, target.threadUnread])); + setMessages((current) => applyPendingToMessages(current.map((message) => ( + patchThreadRow(message, ids, read, targets.get(message.id)) + )))); } function patchFieldState(event: Event) { - const detail = (event as CustomEvent<{ kind?: string; patches?: Array<{ id: string; read?: boolean; starred?: boolean }> }>).detail; + const detail = (event as CustomEvent<{ + kind?: string; + patches?: Array<{ id: string; read?: boolean; starred?: boolean }>; + threadTargets?: ThreadUnreadTarget[]; + }>).detail; if (detail?.kind !== "patch" || !detail.patches?.length) return; const patches = new Map(detail.patches.map((patch) => [patch.id, patch])); - setMessages((current) => current.map((message) => { + const targets = new Map((detail.threadTargets ?? []).map((target) => [target.id, target.threadUnread])); + setMessages((current) => applyPendingToMessages(current.map((message) => { + if (message.threadMessageIds?.length) { + const memberPatches = message.threadMessageIds + .map((id) => patches.get(id)) + .filter((patch): patch is { id: string; read?: boolean; starred?: boolean } => !!patch); + if (memberPatches.length === 0) return message; + const next = { ...message }; + let changed = false; + const starred = memberPatches.find((patch) => patch.starred !== undefined)?.starred; + if (starred !== undefined && next.starred !== starred) { + next.starred = starred; + changed = true; + } + const readPatch = memberPatches.find((patch) => patch.read !== undefined); + if (readPatch?.read !== undefined) { + const target = targets.get(message.id); + const threadUnread = target !== undefined + ? clampThreadUnread(target, message.threadMessageIds.length) + : getKnownThreadUnread(message.id) ?? next.threadUnread ?? 0; + const read = threadUnread === 0; + if (next.threadUnread !== threadUnread || next.read !== read) { + next.threadUnread = threadUnread; + next.read = read; + changed = true; + } + } + return changed ? next : message; + } const patch = patches.get(message.id); if (!patch) return message; const next = { ...message }; if (patch.starred !== undefined) next.starred = patch.starred; - if (patch.read !== undefined && !message.threadMessageIds) next.read = patch.read; + if (patch.read !== undefined) next.read = patch.read; return next; - })); + }))); } function onMessagesChanged(event: Event) { - const detail = (event as CustomEvent<{ kind?: string; deferRefresh?: boolean }>).detail; + const detail = (event as CustomEvent<{ kind?: string }>).detail; const readOnly = detail?.kind === "read"; // A read patch can overtake a list request that started before it. Bump - // the request number so that response can never repaint the old state. + // the request number so that response can never repaint the old state; + // a pending overlay is applied before fetchMessageList caches it. requestNumber += 1; - // Optimistic undo read/star patches stay on screen until the request settles. - if (detail?.deferRefresh) return; if (!readOnly) { clearMessageListCache(); clearMessageCountsCache(); @@ -101,6 +163,9 @@ export function useMessages( void loadMessages(true); }, REFRESH_DEBOUNCE_MS); } + const unsubscribePending = subscribePendingOverlay(() => { + setMessages((current) => applyPendingToMessages(current)); + }); window.addEventListener("mailflare:messages-changed", onMessagesChanged); window.addEventListener("mailflare:messages-changed", patchReadState); window.addEventListener("mailflare:messages-changed", patchFieldState); @@ -110,6 +175,7 @@ export function useMessages( window.removeEventListener("mailflare:messages-changed", onMessagesChanged); window.removeEventListener("mailflare:messages-changed", patchReadState); window.removeEventListener("mailflare:messages-changed", patchFieldState); + unsubscribePending(); if (refreshTimer) window.clearTimeout(refreshTimer); }; }, [enabled, filters?.group, filters?.limit, filters?.offset, filters?.query, filters?.read, filters?.title, folder, folderId, mailboxId]); diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts index 5fc816681..78cb0514e 100644 --- a/src/hooks/utils.ts +++ b/src/hooks/utils.ts @@ -2,8 +2,14 @@ import { authFetch } from "@/lib/auth/client"; import { parseSearchQuery } from "@/lib/search/query-utils"; import { getUserTimeZone } from "@/lib/time/utils"; import { patchCachedMessage } from "@/lib/messages/detail-cache"; -import { rememberMessageFields, rememberMessageRows } from "@/lib/messages/field-store"; -import { isReadOnlyChange } from "@/lib/messages/change-events"; +import { + applyPendingToMessageList, + applyPendingToMessages, + getThreadUnreadTargets, + rememberMessageRows, + type ThreadUnreadTarget, +} from "@/lib/messages/field-store"; +import { isReadOnlyChange, type MessageFieldPatch } from "@/lib/messages/change-events"; import type { MessageFilterOptions, MessageFolder } from "./types"; import type { MessageCounts, MessageListResponse } from "./types"; @@ -102,37 +108,116 @@ export type CachedMessagePatch = { starred?: boolean; }; +export type MessageCachePatchOptions = { + /** Pre-click grouped targets used when rolling back a failed/skipped undo. */ + threadTargets?: Iterable; +}; + +function groupFieldPatches(fields: MessageFieldPatch[]): Map { + const patches = new Map(); + for (const field of fields) { + if (field.read === undefined && field.starred === undefined) continue; + const current = patches.get(field.id) ?? {}; + if (field.read !== undefined) current.read = field.read; + if (field.starred !== undefined) current.starred = field.starred; + patches.set(field.id, current); + } + return patches; +} + /** - * Mirror a field-scoped change into every cached list page and detail. Used by - * optimistic reads, star toggles and undo, so a remount never repaints the - * state the action just replaced. + * Mirrors field changes into every cached list page and detail. Grouped rows + * receive an absolute unread target computed from actual member transitions, + * so applying the same desired value twice cannot move the count twice. */ -export function patchMessagesInCaches(messageIds: string[], patch: CachedMessagePatch) { - if (messageIds.length === 0) return; - const ids = new Set(messageIds); +export function patchMessageFieldsInCaches( + fields: MessageFieldPatch[], + options: MessageCachePatchOptions = {}, +): ThreadUnreadTarget[] { + const patches = groupFieldPatches(fields); + if (patches.size === 0) return []; + const computedTargets = getThreadUnreadTargets([...patches].map(([id, patch]) => ({ + id, + ...(patch.read !== undefined ? { read: patch.read } : {}), + }))); + const forcedTargets = options.threadTargets + ? new Map([...options.threadTargets].map((target) => [target.id, target.threadUnread])) + : null; + const targets = computedTargets.map((target) => ({ + id: target.id, + threadUnread: Math.max(0, Math.trunc(forcedTargets?.get(target.id) ?? target.threadUnread)), + })); + if (forcedTargets) { + for (const [id, threadUnread] of forcedTargets) { + if (!targets.some((target) => target.id === id)) { + targets.push({ id, threadUnread: Math.max(0, Math.trunc(threadUnread)) }); + } + } + } + const targetsById = new Map(targets.map((target) => [target.id, target.threadUnread])); + const ids = new Set(patches.keys()); invalidateMessageListRequests(); for (const [key, response] of messageListCache) { - if (!response.messages?.some((message) => ids.has(message.id) - || message.threadMessageIds?.some((id) => ids.has(id)))) continue; - messageListCache.set(key, { - ...response, - messages: response.messages.map((message) => { - if (message.threadMessageIds) { - const threadSize = message.threadMessageIds.length; - const flipped = message.threadMessageIds.reduce((total, id) => total + (ids.has(id) ? 1 : 0), 0); - if (!flipped) return message; - if (patch.read !== undefined) { - const threadUnread = Math.min(threadSize, Math.max(0, (message.threadUnread ?? 0) + (patch.read ? -flipped : flipped))); - return { ...message, read: threadUnread === 0, threadUnread, ...(patch.starred !== undefined ? { starred: patch.starred } : {}) }; + if (!response.messages?.some((message) => patches.has(message.id) + || message.threadMessageIds?.some((id) => ids.has(id)) + || targetsById.has(message.id))) continue; + const messages = response.messages.map((message) => { + const direct = patches.get(message.id); + if (message.threadMessageIds?.length) { + const threadTarget = targetsById.get(message.id); + const memberPatch = message.threadMessageIds + .map((id) => patches.get(id)) + .find((patch): patch is CachedMessagePatch => !!patch); + const next = { ...message }; + let changed = false; + if (threadTarget !== undefined) { + const threadUnread = Math.min(message.threadMessageIds.length, threadTarget); + if (next.threadUnread !== threadUnread) { + next.threadUnread = threadUnread; + changed = true; } - return patch.starred !== undefined ? { ...message, starred: patch.starred } : message; + const read = threadUnread === 0; + if (next.read !== read) { + next.read = read; + changed = true; + } + } + const starred = direct?.starred ?? memberPatch?.starred; + if (starred !== undefined && next.starred !== starred) { + next.starred = starred; + changed = true; } - return ids.has(message.id) ? { ...message, ...patch } : message; - }), + return changed ? next : message; + } + if (!direct) return message; + const next = { ...message, ...direct }; + return next.read === message.read && next.starred === message.starred ? message : next; }); + // Apply any still-active operation before the row reaches a consumer or + // the cache; a generic refresh while an undo request is pending must not + // see the server's pre-undo value. + const pendingMessages = applyPendingToMessages(messages); + messageListCache.set(key, { ...response, messages: pendingMessages }); + rememberMessageRows(pendingMessages); } - for (const id of ids) patchCachedMessage(id, patch); - rememberMessageFields(messageIds, patch); + for (const [id, patch] of patches) patchCachedMessage(id, patch); + return targets; +} + +/** + * Mirror a field-scoped change into every cached list page and detail. Used by + * optimistic reads, star toggles and undo, so a remount never repaints the + * state the action just replaced. + */ +export function patchMessagesInCaches( + messageIds: string[], + patch: CachedMessagePatch, + options: MessageCachePatchOptions = {}, +): ThreadUnreadTarget[] { + return patchMessageFieldsInCaches( + messageIds.map((id) => ({ id, ...patch })), + options, + ); } /** @@ -194,18 +279,24 @@ export async function fetchMessageCounts(mailboxId?: string | null, force = fals } export function peekMessageList(params: URLSearchParams): MessageListResponse | undefined { - return messageListCache.get(params.toString()); + const response = messageListCache.get(params.toString()); + return response ? applyPendingToMessageList(response) : undefined; } export async function fetchMessageList(params: URLSearchParams, force = false): Promise { const key = params.toString(); - if (!force && messageListCache.has(key)) return messageListCache.get(key) ?? {}; + if (!force && messageListCache.has(key)) { + return applyPendingToMessageList(messageListCache.get(key) ?? {}); + } if (!force && messageListRequests.has(key)) return messageListRequests.get(key) ?? {}; const requestGeneration = messageCacheGeneration; const request = authFetch(`/api/messages?${key}`) .then((res) => res.json()) .then((data) => { - const response = data as MessageListResponse; + // Apply the overlay before the response reaches state or cache. Any + // generic refresh that started while an undo is pending therefore sees + // the optimistic value even if it lands after the optimistic patch. + const response = applyPendingToMessageList(data as MessageListResponse); if (requestGeneration === messageCacheGeneration) { messageListCache.set(key, response); rememberMessageRows(response.messages ?? []); diff --git a/src/lib/messages/actions/client.ts b/src/lib/messages/actions/client.ts index 2dd154cb4..b7ed5b6d8 100644 --- a/src/lib/messages/actions/client.ts +++ b/src/lib/messages/actions/client.ts @@ -2,17 +2,26 @@ import { authFetch } from "@/lib/auth/client"; import { dispatchMessagesChanged, type MessageFieldPatch } from "@/lib/messages/change-events"; -import { invalidateCachedMessageDetails, patchCachedMessageState } from "@/lib/messages/detail-cache"; -import { captureMessageFields, type KnownMessageFields } from "@/lib/messages/field-store"; -import { patchMessagesInCaches } from "@/hooks/utils"; +import { invalidateCachedMessageDetails, invalidateMessageDetailRequests, patchCachedMessageState, type CachedMessageStatePatch } from "@/lib/messages/detail-cache"; +import { + captureMessageFields, + captureThreadUnread, + clearPendingOverlay, + setPendingOverlay, + type KnownMessageFields, + type PendingOverlayMessage, + type ThreadUnreadTarget, +} from "@/lib/messages/field-store"; +import { clearMessageListCache, invalidateMessageListRequests, patchMessageFieldsInCaches } from "@/hooks/utils"; +import { clearMessageThreadCache, invalidateMessageThreadRequests } from "@/components/messages/message-thread-cache"; +import { getChangedStateFields } from "./definitions"; import { MessageActionExecutor, MessageActionRequestError, getChangedRecords, hasMembershipChange, - readPatchGroups, - starPatchGroups, type MessageActionExecutorHooks, + type MessageActionHookContext, type MessageActionHookOptions, type MessageActionTransport, } from "./executor"; @@ -27,128 +36,256 @@ import type { } from "./types"; import type { UndoToastEntry } from "./undo-store"; +const DEFAULT_PENDING_OWNER = "message-action:direct"; +const DEFAULT_MESSAGE_ACTION_TIMEOUT_MS = 30_000; +let messageActionTimeoutMs = DEFAULT_MESSAGE_ACTION_TIMEOUT_MS; + +/** Test-only override so the bounded transport timeout needs no 30s wait. */ +export function setMessageActionTransportTimeoutForTests(timeoutMs: number): void { + messageActionTimeoutMs = Math.max(1, Math.trunc(timeoutMs)); +} + async function sendMessageAction( body: MessageActionTransportBody, ): Promise { - const response = await authFetch("/api/messages/actions", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); - const data = (await response.json().catch(() => ({}))) as { error?: string }; - if (!response.ok) { - throw new MessageActionRequestError(data.error ?? "Unable to update message", response.status); + const controller = new AbortController(); + let timedOut = false; + const timeout = setTimeout(() => { + timedOut = true; + controller.abort(); + }, messageActionTimeoutMs); + try { + const response = await authFetch("/api/messages/actions", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: controller.signal, + }); + const data = (await response.json().catch(() => ({}))) as { error?: string }; + if (!response.ok) { + throw new MessageActionRequestError(data.error ?? "Unable to update message", response.status); + } + return data as MessageActionResponse | UndoMessageActionResponse; + } catch (error) { + if (timedOut || (error instanceof Error && error.name === "AbortError")) { + throw new MessageActionRequestError("The server did not respond in time", 408); + } + throw error; + } finally { + clearTimeout(timeout); } - return data as MessageActionResponse | UndoMessageActionResponse; } /** - * Patches the caches and tells every mounted list/thread which ids changed. - * `deferRefresh` keeps the optimistic value on screen until the request that - * produced it settles; without it the consumers quietly re-read the server. + * Read/star fields changed by an action, in the requested direction. Membership + * fields stay server-first and are refreshed through the generic event. */ -function dispatchRead(ids: string[], read: boolean, deferRefresh: boolean) { - if (ids.length === 0) return; - patchMessagesInCaches(ids, { read }); - dispatchMessagesChanged({ kind: "read", messageIds: ids, read, deferRefresh }); -} - -function dispatchStarGroups(groups: Map, deferRefresh: boolean) { - if (groups.size === 0) return; - const patches: MessageFieldPatch[] = []; - for (const [starred, ids] of groups) { - if (ids.length === 0) continue; - patchMessagesInCaches(ids, { starred }); - for (const id of ids) patches.push({ id, starred }); +function changedFieldPatches( + records: MessageActionRecord[], + direction: "previous" | "applied", +): PendingOverlayMessage[] { + const fields: PendingOverlayMessage[] = []; + for (const record of records) { + const changed = new Set(getChangedStateFields(record.previous, record.applied)); + const entry: PendingOverlayMessage = { id: record.id }; + if (changed.has("read")) entry.read = record[direction].read; + if (changed.has("starred")) entry.starred = record[direction].starred; + if (entry.read !== undefined || entry.starred !== undefined) fields.push(entry); } - if (patches.length > 0) dispatchMessagesChanged({ kind: "patch", patches, deferRefresh }); + return fields; } -function capturedPatches( +/** The pre-click values to restore when the server rejects or skips the undo. */ +function capturedFieldPatches( records: MessageActionRecord[], captured: Map, -) { - const readGroups = new Map(); - const starGroups = new Map(); +): PendingOverlayMessage[] { + const fields: PendingOverlayMessage[] = []; for (const record of records) { + const changed = new Set(getChangedStateFields(record.previous, record.applied)); const known = captured.get(record.id); - if (known?.read !== undefined && record.previous.read !== record.applied.read) { - const ids = readGroups.get(known.read) ?? []; - ids.push(record.id); - readGroups.set(known.read, ids); - } - if (known?.starred !== undefined && record.previous.starred !== record.applied.starred) { - const ids = starGroups.get(known.starred) ?? []; - ids.push(record.id); - starGroups.set(known.starred, ids); + const entry: PendingOverlayMessage = { id: record.id }; + if (changed.has("read") && known?.read !== undefined) entry.read = known.read; + if (changed.has("starred") && known?.starred !== undefined) entry.starred = known.starred; + if (entry.read !== undefined || entry.starred !== undefined) fields.push(entry); + } + return fields; +} + +function dispatchFieldChanges(fields: MessageFieldPatch[], threadTargets: ThreadUnreadTarget[]): void { + const readGroups = new Map(); + const starPatches: MessageFieldPatch[] = []; + for (const field of fields) { + if (field.read !== undefined) { + const ids = readGroups.get(field.read) ?? []; + ids.push(field.id); + readGroups.set(field.read, ids); } + if (field.starred !== undefined) starPatches.push({ id: field.id, starred: field.starred }); } - return { readGroups, starGroups }; + for (const [read, ids] of readGroups) { + dispatchMessagesChanged({ kind: "read", messageIds: ids, read, threadTargets }); + } + if (starPatches.length > 0) { + dispatchMessagesChanged({ kind: "patch", patches: starPatches, threadTargets }); + } +} + +/** + * Patches caches then notifies mounted consumers. Grouped rows receive the + * absolute target computed while patching, so optimistic and completed paths + * cannot apply the same transition twice. + */ +function applyFieldChanges( + fields: PendingOverlayMessage[], + threadTargets?: Map, +): ThreadUnreadTarget[] { + if (fields.length === 0) return []; + const targets = patchMessageFieldsInCaches( + fields, + threadTargets ? { + threadTargets: [...threadTargets].map(([id, threadUnread]) => ({ id, threadUnread })), + } : undefined, + ); + dispatchFieldChanges(fields, targets); + return targets; } function restoreCaptured( records: MessageActionRecord[], captured: Map, + capturedThreads?: Map, ) { - const { readGroups, starGroups } = capturedPatches(records, captured); - for (const [read, ids] of readGroups) dispatchRead(ids, read, true); - dispatchStarGroups(starGroups, true); + const fields = capturedFieldPatches(records, captured); + const hasReadChange = fields.some((field) => field.read !== undefined); + applyFieldChanges(fields, hasReadChange ? capturedThreads : undefined); } -function rememberAppliedDetails(records: MessageActionRecord[]) { - for (const record of records) { - patchCachedMessageState(record.id, { - status: record.applied.status, - read: record.applied.read, - starred: record.applied.starred, - folderId: record.applied.folderId, - snoozedUntil: record.applied.snoozedUntil, - }); +function detailPatchFor( + record: MessageActionRecord, + direction: "previous" | "applied", +): CachedMessageStatePatch { + const patch: CachedMessageStatePatch = {}; + for (const field of getChangedStateFields(record.previous, record.applied)) { + switch (field) { + case "status": + patch.status = record[direction].status; + break; + case "read": + patch.read = record[direction].read; + break; + case "starred": + patch.starred = record[direction].starred; + break; + case "folderId": + patch.folderId = record[direction].folderId; + break; + case "snoozedUntil": + patch.snoozedUntil = record[direction].snoozedUntil; + break; + } } + return patch; +} + +function rememberAppliedDetails(records: MessageActionRecord[]) { + for (const record of records) patchCachedMessageState(record.id, detailPatchFor(record, "applied")); } function rememberPreviousDetails(records: MessageActionRecord[]) { - for (const record of records) { - patchCachedMessageState(record.id, { - status: record.previous.status, - read: record.previous.read, - starred: record.previous.starred, - folderId: record.previous.folderId, - snoozedUntil: record.previous.snoozedUntil, - }); + for (const record of records) patchCachedMessageState(record.id, detailPatchFor(record, "previous")); +} + +/** + * A settled undo must not let a response that started while the optimistic + * target was active land afterwards. Invalidate requests without dropping a + * valid patched cache; the generic resync then performs one authoritative fetch. + */ +function invalidatePendingResponses(messageIds: string[]) { + invalidateMessageListRequests(); + invalidateMessageThreadRequests(); + invalidateMessageDetailRequests(messageIds); +} + +/** + * A timeout or dropped connection may have reached the server after the client + * stopped waiting. The undo claim makes replay safe, but the local state cannot + * know which side committed, so an authoritative refetch replaces any guess. + */ +function isUncertainActionFailure(error: unknown): boolean { + if (error === undefined) return false; + if (error instanceof MessageActionRequestError) { + return error.status === 408 || error.status >= 500; } + return true; +} + +function invalidateUncertainState(messageIds: string[]) { + clearMessageListCache(); + clearMessageThreadCache(); + invalidateCachedMessageDetails(messageIds); + invalidatePendingResponses(messageIds); } export const defaultMessageActionHooks: MessageActionExecutorHooks = { - onApplied(response: MessageActionResponse, options: MessageActionHookOptions) { + onApplied(response: MessageActionResponse, options: MessageActionHookOptions, context?: MessageActionHookContext) { + clearPendingOverlay(context?.pendingOwner ?? DEFAULT_PENDING_OWNER); const changed = getChangedRecords(response.applied); if (changed.length === 0) return; + applyFieldChanges(changedFieldPatches(changed, "applied")); rememberAppliedDetails(changed); - const deferRefresh = !options.notify; - for (const [read, ids] of readPatchGroups(changed, "applied")) dispatchRead(ids, read, deferRefresh); - dispatchStarGroups(starPatchGroups(changed, "applied"), deferRefresh); if (options.notify && changed.some(hasMembershipChange)) dispatchMessagesChanged(); }, - onUndoOptimistic(records) { - for (const [read, ids] of readPatchGroups(records, "previous")) dispatchRead(ids, read, true); - dispatchStarGroups(starPatchGroups(records, "previous"), true); + onApplyFailed(input, _options, context, error) { + clearPendingOverlay(context?.pendingOwner ?? DEFAULT_PENDING_OWNER); + if (!isUncertainActionFailure(error)) return; + invalidateUncertainState(input.messageIds); + dispatchMessagesChanged(); }, - onUndoCompleted(records, response, captured) { + onUndoOptimistic(records, _captured, context) { + const owner = context?.pendingOwner ?? DEFAULT_PENDING_OWNER; + const fields = changedFieldPatches(records, "previous"); + if (fields.length === 0) return; + // Patch the underlying caches first, then lay the same absolute values + // over every future ingress while the undo request is unresolved. + const targets = patchMessageFieldsInCaches(fields); + setPendingOverlay(owner, { messages: fields, threads: targets }); + dispatchFieldChanges(fields, targets); + }, + onUndoCompleted(records, response, captured, context) { + // The optimistic patches already show the restored state. Records the + // server skipped must return to what was on screen before the undo click, + // not an older action's historical applied snapshot. + clearPendingOverlay(context?.pendingOwner ?? DEFAULT_PENDING_OWNER); const restored = new Set(response.restored); - rememberPreviousDetails(records.filter((record) => restored.has(record.id))); const skipped = new Set(response.skipped.map((item) => item.id)); + const restoredRecords = records.filter((record) => restored.has(record.id)); const skippedRecords = records.filter((record) => skipped.has(record.id)); - restoreCaptured(skippedRecords, captured); - invalidateCachedMessageDetails(skippedRecords.map((record) => record.id)); + const unaccounted = records.filter((record) => !restored.has(record.id) && !skipped.has(record.id)); + rememberPreviousDetails(restoredRecords); + const rollback = [...skippedRecords, ...unaccounted]; + restoreCaptured(rollback, captured, context?.capturedThreadUnread); + invalidateCachedMessageDetails(rollback.map((record) => record.id)); + invalidatePendingResponses(records.map((record) => record.id)); }, - onUndoFailed(records, captured) { - restoreCaptured(records, captured); - invalidateCachedMessageDetails(records.map((record) => record.id)); + onUndoFailed(records, captured, context, error) { + clearPendingOverlay(context?.pendingOwner ?? DEFAULT_PENDING_OWNER); + const ids = records.map((record) => record.id); + if (isUncertainActionFailure(error)) { + // The timeout may have committed the undo on the server. Do not paint + // the historical pre-click value; let the resync fetch decide. + invalidateUncertainState(ids); + return; + } + restoreCaptured(records, captured, context?.capturedThreadUnread); + invalidateCachedMessageDetails(ids); + invalidatePendingResponses(ids); }, onResync() { dispatchMessagesChanged(); }, captureCurrent: captureMessageFields, + captureThreadUnread, }; export const messageActionExecutor = new MessageActionExecutor(sendMessageAction as MessageActionTransport, defaultMessageActionHooks); diff --git a/src/lib/messages/actions/executor.ts b/src/lib/messages/actions/executor.ts index 21e316e00..39cb8d3a6 100644 --- a/src/lib/messages/actions/executor.ts +++ b/src/lib/messages/actions/executor.ts @@ -26,15 +26,24 @@ export type MessageActionTransport = ( export type MessageActionHookOptions = { notify: boolean }; +export type MessageActionHookContext = { + /** Unique owner key for the pending overlay written by this operation. */ + pendingOwner: string; + /** Grouped unread aggregates captured before the optimistic patch. */ + capturedThreadUnread?: Map; +}; + export type MessageActionExecutorHooks = { - onApplyOptimistic?: (input: MessageActionInput, options: MessageActionHookOptions) => void; - onApplyFailed?: (input: MessageActionInput, options: MessageActionHookOptions) => void; - onApplied?: (response: MessageActionResponse, options: MessageActionHookOptions) => void; + onApplyOptimistic?: (input: MessageActionInput, options: MessageActionHookOptions, context: MessageActionHookContext) => void; + onApplyFailed?: (input: MessageActionInput, options: MessageActionHookOptions, context: MessageActionHookContext, error: unknown) => void; + onApplied?: (response: MessageActionResponse, options: MessageActionHookOptions, context: MessageActionHookContext) => void; /** Snapshots the tab's current read/star values before an optimistic undo patch. */ captureCurrent?: (ids: string[]) => Map; - onUndoOptimistic?: (records: MessageActionRecord[], captured: Map) => void; - onUndoCompleted?: (records: MessageActionRecord[], response: UndoMessageActionResponse, captured: Map) => void; - onUndoFailed?: (records: MessageActionRecord[], captured: Map) => void; + /** Snapshots grouped unread aggregates before an optimistic undo patch. */ + captureThreadUnread?: (ids: string[]) => Map; + onUndoOptimistic?: (records: MessageActionRecord[], captured: Map, context: MessageActionHookContext) => void; + onUndoCompleted?: (records: MessageActionRecord[], response: UndoMessageActionResponse, captured: Map, context: MessageActionHookContext) => void; + onUndoFailed?: (records: MessageActionRecord[], captured: Map, context: MessageActionHookContext, error: unknown) => void; onResync?: (messageIds: string[]) => void; }; @@ -45,6 +54,7 @@ export type MessageActionExecutorHooks = { */ export class MessageActionExecutor { private readonly tails = new Map>(); + private nextOperationId = 0; constructor( private readonly transport: MessageActionTransport, @@ -54,20 +64,22 @@ export class MessageActionExecutor { async run(input: MessageActionInput, options: { notify?: boolean } = {}): Promise { return this.withLocks(input.messageIds, async () => { const hookOptions = { notify: options.notify !== false }; - this.hooks.onApplyOptimistic?.(input, hookOptions); + const context = { pendingOwner: `message-action:apply:${++this.nextOperationId}` }; + this.hooks.onApplyOptimistic?.(input, hookOptions, context); let response: MessageActionResponse | UndoMessageActionResponse; try { response = await this.transport({ op: "apply", ...input }); } catch (error) { - this.hooks.onApplyFailed?.(input, hookOptions); + this.hooks.onApplyFailed?.(input, hookOptions, context, error); throw error; } if (!response || response.ok !== true || !("applied" in response) || !Array.isArray(response.applied) || !Array.isArray(response.skipped)) { - this.hooks.onApplyFailed?.(input, hookOptions); - throw new MessageActionRequestError("Unable to update message", 502); + const failure = new MessageActionRequestError("Unable to update message", 502); + this.hooks.onApplyFailed?.(input, hookOptions, context, failure); + throw failure; } const result = response as MessageActionResponse; - this.hooks.onApplied?.(result, hookOptions); + this.hooks.onApplied?.(result, hookOptions, context); if (result.applied.length === 0 && result.skipped.length > 0) { throw new MessageActionRequestError("No accessible messages", 404, result.skipped.length); } @@ -80,18 +92,23 @@ export class MessageActionExecutor { const ids = records.map((record) => record.id); return this.withLocks(ids, async () => { const captured = this.hooks.captureCurrent?.(ids) ?? new Map(); - this.hooks.onUndoOptimistic?.(records, captured); + const capturedThreadUnread = this.hooks.captureThreadUnread?.(ids); + const context = { + pendingOwner: `message-action:undo:${++this.nextOperationId}`, + capturedThreadUnread, + }; + this.hooks.onUndoOptimistic?.(records, captured, context); try { const response = await this.transport({ op: "undo", token }); if (!response || response.ok !== true || !Array.isArray((response as UndoMessageActionResponse).restored)) { throw new MessageActionRequestError("Could not undo that change", 502); } const result = response as UndoMessageActionResponse; - this.hooks.onUndoCompleted?.(records, result, captured); + this.hooks.onUndoCompleted?.(records, result, captured, context); this.hooks.onResync?.(ids); return result; } catch (error) { - this.hooks.onUndoFailed?.(records, captured); + this.hooks.onUndoFailed?.(records, captured, context, error); this.hooks.onResync?.(ids); throw error; } diff --git a/src/lib/messages/change-events.ts b/src/lib/messages/change-events.ts index 0f2cf0120..8b3e5a2e2 100644 --- a/src/lib/messages/change-events.ts +++ b/src/lib/messages/change-events.ts @@ -1,3 +1,5 @@ +import type { ThreadUnreadTarget } from "./field-store"; + export const MESSAGES_CHANGED_EVENT = "mailflare:messages-changed"; export type MessageFieldPatch = { @@ -12,8 +14,12 @@ export type MessagesChangedDetail = { read?: boolean; /** Per-message field patches, used when a batch has mixed values. */ patches?: MessageFieldPatch[]; - /** Keep mounted views optimistic until the action request settles. */ - deferRefresh?: boolean; + /** + * Absolute grouped unread targets for rows touched by this event. Consumers + * apply the target instead of incrementing a count they may already have + * changed, so a repeated desired value and a second event are both no-ops. + */ + threadTargets?: ThreadUnreadTarget[]; }; export function dispatchMessagesChanged(detail?: MessagesChangedDetail): void { diff --git a/src/lib/messages/detail-cache.ts b/src/lib/messages/detail-cache.ts index 579315357..216ebb6ac 100644 --- a/src/lib/messages/detail-cache.ts +++ b/src/lib/messages/detail-cache.ts @@ -1,5 +1,5 @@ import { AUTH_SESSION_CHANGED_EVENT, authFetch } from "@/lib/auth/client"; -import { rememberMessageFields } from "@/lib/messages/field-store"; +import { applyPendingToMessage, rememberMessageFields } from "@/lib/messages/field-store"; import type { Message } from "@/hooks/types"; import type { CachedMessageDetail } from "./detail-cache-types"; @@ -7,12 +7,21 @@ const CACHE_TTL_MS = 5 * 60_000; const CACHE_LIMIT = 50; const detailCache = new Map(); const detailRequests = new Map>(); +/** Per-message invalidation marker for requests that started before an undo settled. */ +const detailRevisions = new Map(); let generation = 0; +function applyPendingDetail(data: CachedMessageDetail): CachedMessageDetail { + if (!data.message) return data; + const message = applyPendingToMessage(data.message); + return message === data.message ? data : { ...data, message }; +} + function cacheDetail(messageId: string, data: CachedMessageDetail) { + const nextData = applyPendingDetail(data); detailCache.delete(messageId); - detailCache.set(messageId, { data, expiresAt: Date.now() + CACHE_TTL_MS }); - if (data.message) rememberMessageFields([messageId], { read: data.message.read, starred: data.message.starred }); + detailCache.set(messageId, { data: nextData, expiresAt: Date.now() + CACHE_TTL_MS }); + if (nextData.message) rememberMessageFields([messageId], { read: nextData.message.read, starred: nextData.message.starred }); if (detailCache.size > CACHE_LIMIT) { const oldest = detailCache.keys().next().value; if (oldest) detailCache.delete(oldest); @@ -23,6 +32,7 @@ export function clearMessageDetailCache() { generation += 1; detailCache.clear(); detailRequests.clear(); + detailRevisions.clear(); } export function getCachedMessageDetail(messageId: string): CachedMessageDetail | undefined { @@ -34,7 +44,7 @@ export function getCachedMessageDetail(messageId: string): CachedMessageDetail | } detailCache.delete(messageId); detailCache.set(messageId, cached); - return cached.data; + return applyPendingDetail(cached.data); } export function setCachedMessageRead(messageId: string, read: boolean): void { @@ -59,9 +69,27 @@ export function patchCachedMessage(messageId: string, patch: { read?: boolean; s patchCachedMessageState(messageId, patch); } +function bumpDetailRevision(messageId: string): void { + detailRevisions.set(messageId, (detailRevisions.get(messageId) ?? 0) + 1); +} + +/** Drops in-flight detail responses without throwing away an already-patched cache. */ +export function invalidateMessageDetailRequests(messageIds?: string[]): void { + if (!messageIds) { + generation += 1; + detailRequests.clear(); + return; + } + for (const id of messageIds) { + bumpDetailRevision(id); + detailRequests.delete(id); + } +} + /** Drops specific details after a failed or partially skipped undo, so the reader refetches them. */ export function invalidateCachedMessageDetails(messageIds: string[]): void { for (const id of messageIds) { + bumpDetailRevision(id); detailCache.delete(id); detailRequests.delete(id); } @@ -85,12 +113,14 @@ export async function fetchCachedMessageDetail(messageId: string, force = false) if (!force && cached) return cached; if (detailRequests.has(messageId)) return detailRequests.get(messageId) ?? {}; const requestGeneration = generation; + const requestRevision = detailRevisions.get(messageId) ?? 0; const request = authFetch(`/api/messages/${messageId}`, { cache: "no-store" }) .then(async (response) => { const data = await response.json() as CachedMessageDetail; if (requestGeneration !== generation) throw new Error("Message request invalidated"); + if (requestRevision !== (detailRevisions.get(messageId) ?? 0)) throw new Error("Message request invalidated"); if (response.ok && !data.error) cacheDetail(messageId, data); - return data; + return applyPendingDetail(data); }) .finally(() => { if (detailRequests.get(messageId) === request) detailRequests.delete(messageId); }); detailRequests.set(messageId, request); diff --git a/src/lib/messages/field-store.ts b/src/lib/messages/field-store.ts index 4db099f47..de0701005 100644 --- a/src/lib/messages/field-store.ts +++ b/src/lib/messages/field-store.ts @@ -3,13 +3,65 @@ * responses, list/thread/detail fetches and cache patches all feed it, so an * undo can snapshot what was on screen before its optimistic patch instead of * assuming an older action's historical "applied" state is still current. + * + * A pending overlay sits on top of that state for operations whose server + * request is still in flight. Every list/thread/detail ingress applies it + * before reading or writing a cache, so a generic refetch cannot repaint the + * server's pre-undo value while the undo is unresolved. */ export type KnownMessageFields = { read?: boolean; starred?: boolean; }; +export type PendingOverlayMessage = KnownMessageFields & { + id: string; +}; + +/** Absolute unread target for a grouped conversation row. */ +export type ThreadUnreadTarget = { + id: string; + threadUnread: number; +}; + +export type PendingOverlayEntries = { + messages?: PendingOverlayMessage[]; + threads?: ThreadUnreadTarget[]; +}; + +type KnownThread = { + messageIds: string[]; + threadUnread: number; +}; + +type PendingLayer = { + sequence: number; + messages: Map; + threads: Map; +}; + +type PendingRow = { + id: string; + read?: boolean; + starred?: boolean; + threadMessageIds?: string[]; + threadUnread?: number; +}; + const knownFields = new Map(); +const knownThreads = new Map(); +const pendingLayers = new Map(); +const pendingListeners = new Set<() => void>(); +let pendingSequence = 0; + +function clampCount(value: number, size: number): number { + if (!Number.isFinite(value)) return 0; + return Math.min(size, Math.max(0, Math.trunc(value))); +} + +function notifyPendingListeners(): void { + for (const listener of [...pendingListeners]) listener(); +} export function rememberMessageFields(messageIds: string[], patch: KnownMessageFields): void { if (patch.read === undefined && patch.starred === undefined) return; @@ -23,22 +75,235 @@ export function rememberMessageFields(messageIds: string[], patch: KnownMessageF } } -export function rememberMessageRows(rows: Array<{ id: string; read?: boolean; starred?: boolean }>): void { +export function rememberMessageRows(rows: Array<{ + id: string; + read?: boolean; + starred?: boolean; + threadMessageIds?: string[]; + threadUnread?: number; +}>): void { for (const row of rows) { - if (row.read === undefined && row.starred === undefined) continue; - rememberMessageFields([row.id], { - ...(row.read !== undefined ? { read: row.read } : {}), - ...(row.starred !== undefined ? { starred: row.starred } : {}), - }); + if (row.read !== undefined || row.starred !== undefined) { + rememberMessageFields([row.id], { + ...(row.read !== undefined ? { read: row.read } : {}), + ...(row.starred !== undefined ? { starred: row.starred } : {}), + }); + } + if (row.threadMessageIds?.length) { + const messageIds = [...new Set(row.threadMessageIds)]; + knownThreads.set(row.id, { + messageIds, + threadUnread: clampCount(row.threadUnread ?? 0, messageIds.length), + }); + } + } +} + +function pendingFieldsFor(messageId: string): KnownMessageFields { + const fields: KnownMessageFields = {}; + for (const layer of pendingLayers.values()) { + const pending = layer.messages.get(messageId); + if (!pending) continue; + if (pending.read !== undefined) fields.read = pending.read; + if (pending.starred !== undefined) fields.starred = pending.starred; + } + return fields; +} + +function pendingThreadUnreadFor(rowId: string): number | undefined { + let threadUnread: number | undefined; + for (const layer of pendingLayers.values()) { + const target = layer.threads.get(rowId); + if (target !== undefined) threadUnread = target; + } + return threadUnread; +} + +/** Latest known value including any active pending operation. */ +export function getVisibleMessageFields(messageId: string): KnownMessageFields { + return { ...(knownFields.get(messageId) ?? {}), ...pendingFieldsFor(messageId) }; +} + +/** Latest visible unread aggregate for a grouped conversation row. */ +export function getKnownThreadUnread(rowId: string): number | undefined { + const pending = pendingThreadUnreadFor(rowId); + if (pending !== undefined) return pending; + return knownThreads.get(rowId)?.threadUnread; +} + +/** Applies every active owner's overlay; later owners win field by field. */ +export function applyPendingToMessage(message: T): T { + let read = message.read; + let starred = message.starred; + let threadUnread = message.threadUnread; + let changed = false; + + for (const layer of pendingLayers.values()) { + const fields = layer.messages.get(message.id); + if (fields?.read !== undefined && read !== fields.read) { + read = fields.read; + changed = true; + } + if (fields?.starred !== undefined && starred !== fields.starred) { + starred = fields.starred; + changed = true; + } + const target = layer.threads.get(message.id); + if (target !== undefined && message.threadMessageIds?.length) { + const nextUnread = clampCount(target, message.threadMessageIds.length); + if (threadUnread !== nextUnread) { + threadUnread = nextUnread; + changed = true; + } + } } + + if (!changed) return message; + const next = { ...message } as T; + if (message.read !== undefined || read !== undefined) next.read = read; + if (message.starred !== undefined || starred !== undefined) next.starred = starred; + if (threadUnread !== undefined) { + next.threadUnread = threadUnread; + if (message.threadMessageIds?.length) next.read = threadUnread === 0; + } + return next; +} + +export function applyPendingToMessages(messages: T[]): T[] { + let changed = false; + const next = messages.map((message) => { + const applied = applyPendingToMessage(message); + if (applied !== message) changed = true; + return applied; + }); + return changed ? next : messages; +} + +export function applyPendingToMessageList(response: T): T { + if (!response.messages?.length) return response; + const messages = applyPendingToMessages(response.messages); + return messages === response.messages ? response : { ...response, messages }; +} + +export function setPendingOverlay(owner: string, entries: PendingOverlayEntries): void { + if (!owner) return; + const messages = new Map(); + for (const entry of entries.messages ?? []) { + if (entry.read === undefined && entry.starred === undefined) continue; + const fields = messages.get(entry.id) ?? {}; + if (entry.read !== undefined) fields.read = entry.read; + if (entry.starred !== undefined) fields.starred = entry.starred; + messages.set(entry.id, fields); + } + const threads = new Map(); + for (const entry of entries.threads ?? []) { + if (!Number.isFinite(entry.threadUnread)) continue; + threads.set(entry.id, Math.max(0, Math.trunc(entry.threadUnread))); + } + if (messages.size === 0 && threads.size === 0) { + clearPendingOverlay(owner); + return; + } + const existing = pendingLayers.get(owner); + pendingLayers.set(owner, { + // Updating the same owner keeps its original place: a newer operation + // still owns the field it wrote more recently. + sequence: existing?.sequence ?? ++pendingSequence, + messages, + threads, + }); + notifyPendingListeners(); +} + +export function clearPendingOverlay(owner: string): boolean { + if (!pendingLayers.delete(owner)) return false; + notifyPendingListeners(); + return true; +} + +export function hasPendingOverlay(): boolean { + return pendingLayers.size > 0; +} + +export function getPendingOverlayOwners(): string[] { + return [...pendingLayers.keys()]; +} + +export function subscribePendingOverlay(listener: () => void): () => void { + pendingListeners.add(listener); + return () => pendingListeners.delete(listener); +} + +/** + * Absolute unread targets for every known grouped row touched by these field + * patches. Counts only real member transitions: a repeated desired value is a + * no-op, and unknown members are bounded by the row's current aggregate. + */ +export function getThreadUnreadTargets(fields: PendingOverlayMessage[]): ThreadUnreadTarget[] { + const reads = new Map(); + for (const field of fields) { + if (field.read !== undefined) reads.set(field.id, field.read); + } + if (reads.size === 0) return []; + + const targets: ThreadUnreadTarget[] = []; + for (const [rowId, row] of knownThreads) { + if (!row.messageIds.some((id) => reads.has(id))) continue; + const currentUnread = clampCount(getKnownThreadUnread(rowId) ?? row.threadUnread, row.messageIds.length); + let directToRead = 0; + let directToUnread = 0; + let unknownUnread = 0; + let unknownRead = 0; + let knownUnread = 0; + let knownRead = 0; + + for (const id of row.messageIds) { + const visible = getVisibleMessageFields(id).read; + if (visible === false) knownUnread += 1; + if (visible === true) knownRead += 1; + const desired = reads.get(id); + if (desired === undefined) continue; + if (visible === undefined) { + if (desired) unknownUnread += 1; + else unknownRead += 1; + } else if (visible !== desired) { + if (desired) directToRead += 1; + else directToUnread += 1; + } + } + + const unknownUnreadAvailable = Math.max(0, currentUnread - knownUnread); + const unknownReadAvailable = Math.max(0, row.messageIds.length - currentUnread - knownRead); + const toRead = directToRead + Math.min(unknownUnread, unknownUnreadAvailable); + const toUnread = directToUnread + Math.min(unknownRead, unknownReadAvailable); + const target = clampCount(currentUnread - toRead + toUnread, row.messageIds.length); + targets.push({ id: rowId, threadUnread: target }); + } + return targets; +} + +/** Convenience wrapper for one desired read value applied to a set of ids. */ +export function getThreadReadTargets(messageIds: string[], read: boolean): ThreadUnreadTarget[] { + return getThreadUnreadTargets([...new Set(messageIds)].map((id) => ({ id, read }))); +} + +/** Pre-click grouped unread aggregates for rollback after a failed undo. */ +export function captureThreadUnread(ids: string[]): Map { + const messageIds = new Set(ids); + const captured = new Map(); + for (const [rowId, row] of knownThreads) { + if (!row.messageIds.some((id) => messageIds.has(id))) continue; + captured.set(rowId, clampCount(getKnownThreadUnread(rowId) ?? row.threadUnread, row.messageIds.length)); + } + return captured; } /** Copies only fields this tab has actually observed; unknown ids stay unknown. */ export function captureMessageFields(ids: string[]): Map { const captured = new Map(); for (const id of new Set(ids)) { - const fields = knownFields.get(id); - if (fields) captured.set(id, { ...fields }); + const fields = getVisibleMessageFields(id); + if (fields.read !== undefined || fields.starred !== undefined) captured.set(id, fields); } return captured; } @@ -46,4 +311,6 @@ export function captureMessageFields(ids: string[]): Map { + window.dispatchEvent(new CustomEvent("mailflare:messages-changed", { detail: { realtime: true } })); + }); + await page.waitForTimeout(400); + await expect(row.getByRole("button", { name: "Mark as unread" })).toHaveCount(1); } finally { const route = await Promise.race([held, new Promise((resolve) => setTimeout(() => resolve(null), 100))]); if (route) await route.continue().catch(() => undefined); @@ -86,3 +94,94 @@ test("row read undo is optimistic while the undo request is pending", async ({ p await expect(row.getByRole("button", { name: "Mark as unread" })).toHaveCount(1); await expect(page.getByRole("button", { name: "Undo" })).toHaveCount(0); }); + +/** + * Regression: a settled undo must leave the row action usable, including a + * second read on the same message. + */ +test("a row read still works after the previous undo settled", async ({ page }) => { + await resetDemo(page.request); + await login(page); + await page.goto("/inbox"); + + const initialRow = page.locator('[role="listitem"]').filter({ + has: page.getByRole("button", { name: "Mark as read" }), + }).first(); + await expect(initialRow).toBeVisible(); + const href = await initialRow.locator('a[href^="/inbox/"]').first().getAttribute("href"); + expect(href).toBeTruthy(); + const row = page.locator('[role="listitem"]').filter({ has: page.locator(`a[href="${href}"]`) }).first(); + + await row.hover(); + await row.getByRole("button", { name: "Mark as read" }).click(); + await expect(row.getByRole("button", { name: "Mark as unread" })).toHaveCount(1); + await expect(page.getByRole("button", { name: "Undo" })).toBeVisible(); + + await page.getByRole("button", { name: "Undo" }).click(); + await expect(row.getByRole("button", { name: "Mark as read" })).toHaveCount(1); + await expect(page.getByRole("button", { name: "Undo" })).toHaveCount(0); + + await row.hover(); + await row.getByRole("button", { name: "Mark as read" }).click(); + await expect(row.getByRole("button", { name: "Mark as unread" })).toHaveCount(1); + await expect(page.getByRole("button", { name: "Undo" })).toBeVisible(); +}); + +/** + * Regression: the reader's star state must follow the optimistic undo, and the + * detail cache must stay usable for a later star action. + */ +test("reader star undo is optimistic while held and a later star still works", async ({ page }) => { + await resetDemo(page.request); + await login(page); + await page.goto("/inbox"); + + const initialRow = page.locator('[role="listitem"]').filter({ + has: page.getByRole("button", { name: "Mark as unread" }), + }).first(); + await expect(initialRow).toBeVisible(); + const href = await initialRow.locator('a[href^="/inbox/"]').first().getAttribute("href"); + expect(href).toBeTruthy(); + await page.goto(href!); + const article = page.locator("article"); + await expect(article).toBeVisible(); + + const starButton = article.getByRole("button", { name: "Star", exact: true }); + await expect(starButton).toBeVisible(); + await starButton.click(); + await expect(article.getByRole("button", { name: "Remove star", exact: true })).toBeVisible(); + + let resolveHeld: (route: Route) => void; + const held = new Promise((resolve) => { resolveHeld = resolve; }); + await page.route("**/api/messages/actions", async (route) => { + const body = route.request().postDataJSON(); + if (body?.op === "undo") { + resolveHeld(route); + return; + } + await route.continue(); + }); + + try { + await page.getByRole("button", { name: "Undo" }).click(); + await expect(article.getByRole("button", { name: "Star", exact: true })).toBeVisible({ timeout: 5_000 }); + + await page.evaluate(() => { + window.dispatchEvent(new CustomEvent("mailflare:messages-changed", { detail: { realtime: true } })); + }); + await page.waitForTimeout(400); + await expect(article.getByRole("button", { name: "Star", exact: true })).toBeVisible(); + } finally { + const route = await Promise.race([held, new Promise((resolve) => setTimeout(() => resolve(null), 100))]); + if (route) await route.continue().catch(() => undefined); + } + + await expect(page.getByRole("button", { name: "Undo" })).toHaveCount(0); + await page.unroute("**/api/messages/actions"); + + // The successful undo kept the detail cache valid, so the next star action + // must reach the server and update the reader again. + await article.getByRole("button", { name: "Star", exact: true }).click(); + await expect(article.getByRole("button", { name: "Remove star", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Undo" })).toBeVisible(); +}); diff --git a/tests/message-action-pending-caches.test.mjs b/tests/message-action-pending-caches.test.mjs new file mode 100644 index 000000000..cd0bd3735 --- /dev/null +++ b/tests/message-action-pending-caches.test.mjs @@ -0,0 +1,298 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after, beforeEach } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-action-pending-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +const listeners = new Map(); +globalThis.window = { + addEventListener(type, listener) { + const current = listeners.get(type) ?? []; + current.push(listener); + listeners.set(type, current); + }, + removeEventListener(type, listener) { + listeners.set(type, (listeners.get(type) ?? []).filter((item) => item !== listener)); + }, + dispatchEvent(event) { + for (const listener of listeners.get(event.type) ?? []) listener(event); + return true; + }, + location: { assign() {} }, +}; +globalThis.localStorage = { + getItem() { return null; }, + setItem() {}, + removeItem() {}, +}; +globalThis.document = { visibilityState: "visible", hidden: false, addEventListener() {}, removeEventListener() {} }; + +await build({ + stdin: { + contents: ` + export { defaultMessageActionHooks } from "./src/lib/messages/actions/client.ts"; + export { MessageActionExecutor } from "./src/lib/messages/actions/executor.ts"; + export { + fetchMessageList, peekMessageList, clearMessageListCache, invalidateMessageListRequests, + patchMessagesInCaches, patchMessageFieldsInCaches, markMessagesReadInCaches, + } from "./src/hooks/utils.ts"; + export { + fetchMessageCounts, clearMessageCountsCache, + } from "./src/hooks/utils.ts"; + export { + primeMessageDetail, getCachedMessageDetail, fetchCachedMessageDetail, + invalidateCachedMessageDetails, invalidateMessageDetailRequests, clearMessageDetailCache, + } from "./src/lib/messages/detail-cache.ts"; + export { + getCachedMessageThread, fetchMessageThread, clearMessageThreadCache, + patchMessageThreadFieldsInCaches, invalidateMessageThreadRequests, isMessageThreadInvalidated, + } from "./src/components/messages/message-thread-cache.ts"; + export { + captureMessageFields, captureThreadUnread, clearKnownMessageFieldsForTests, + setPendingOverlay, clearPendingOverlay, hasPendingOverlay, getPendingOverlayOwners, + applyPendingToMessages, getKnownThreadUnread, subscribePendingOverlay, + } from "./src/lib/messages/field-store.ts"; + `, + resolveDir: root, + sourcefile: "message-action-pending-entry.ts", + }, + outfile: join(directory, "entry.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" }, + logLevel: "silent", +}); +const m = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); +const record = (id, previous, applied) => ({ + id, + mailboxId: "mb1", + previous: state(previous), + applied: state(applied), +}); +const success = (restored, skipped = []) => ({ + ok: true, + action: "read", + restored, + skipped: skipped.map((id) => ({ id, reason: "stale" })), +}); + +const originalFetch = globalThis.fetch; +beforeEach(() => { + m.clearMessageListCache(); + m.clearMessageDetailCache(); + m.clearMessageThreadCache(); + m.clearKnownMessageFieldsForTests(); + globalThis.fetch = originalFetch; +}); + +after(() => { + globalThis.fetch = originalFetch; + delete globalThis.window; + delete globalThis.document; + delete globalThis.localStorage; +}); + +async function seedList(params, messages) { + globalThis.fetch = async () => Response.json({ messages, total: messages.length, limit: 25, offset: 0 }); + await m.fetchMessageList(params, true); +} + +async function seedThread(anchor, messages) { + globalThis.fetch = async () => Response.json({ threadId: "t1", messages }); + return m.fetchMessageThread(anchor); +} + +let resolveQueued; + +function deferredFetchResponse(payload) { + let resolve; + const fetch = new Promise((resolveResponse) => { + resolve = () => resolveResponse(Response.json(payload)); + }); + globalThis.fetch = () => fetch; + return resolve; +} + +test("a queued list response and a later generic refresh apply the held undo overlay", async () => { + const params = new URLSearchParams({ case: "held-undo" }); + await seedList(params, [{ id: "m1", read: true, starred: false }]); + const undo = record("m1", { read: false }, { read: true }); + const captured = m.captureMessageFields(["m1"]); + assert.equal(captured.get("m1").read, true); + + resolveQueued = deferredFetchResponse({ messages: [{ id: "m1", read: true }], total: 1, limit: 25, offset: 0 }); + const queued = m.fetchMessageList(params, true); + await Promise.resolve(); + m.defaultMessageActionHooks.onUndoOptimistic([undo], captured); + assert.equal(m.peekMessageList(params).messages[0].read, false); + assert.equal(m.hasPendingOverlay(), true); + + // This request was already in flight when the undo painted its value. + resolveQueued(); + const queuedResult = await queued; + assert.equal(queuedResult.messages[0].read, false, "queued response must not repaint the server value"); + + // A generic refresh started after the pending overlay is also safe. + globalThis.fetch = async () => Response.json({ messages: [{ id: "m1", read: true }], total: 1, limit: 25, offset: 0 }); + const refreshed = await m.fetchMessageList(params, true); + assert.equal(refreshed.messages[0].read, false); + assert.equal(m.peekMessageList(params).messages[0].read, false); + + m.defaultMessageActionHooks.onUndoFailed([undo], captured); + assert.equal(m.peekMessageList(params).messages[0].read, true, "failure rolls back to the pre-click value"); + assert.equal(m.hasPendingOverlay(), false); +}); + +test("a grouped row uses absolute targets and repeated desired values are no-ops", async () => { + const params = new URLSearchParams({ case: "grouped-idempotent" }); + await seedList(params, [{ + id: "m1", + read: false, + starred: false, + threadMessageIds: ["m1", "m2", "m3"], + threadUnread: 1, + }]); + const read = record("m1", { read: false }, { read: true }); + const unread = record("m1", { read: true }, { read: false }); + + m.defaultMessageActionHooks.onApplied({ ok: true, action: "read", applied: [read], skipped: [] }, { notify: true }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 0); + // The same desired value again cannot subtract another member. + m.defaultMessageActionHooks.onApplied({ ok: true, action: "read", applied: [read], skipped: [] }, { notify: true }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 0); + + m.defaultMessageActionHooks.onApplied({ ok: true, action: "unread", applied: [unread], skipped: [] }, { notify: true }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 1); + + // An older read undo wants false, which is already the current value. + const captured = m.captureMessageFields(["m1"]); + const capturedThreads = m.captureThreadUnread(["m1"]); + assert.equal(captured.get("m1").read, false); + assert.equal(capturedThreads.get("m1"), 1); + m.defaultMessageActionHooks.onUndoOptimistic([read], captured); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 1, "pending undo must not increment a repeated value"); + m.defaultMessageActionHooks.onUndoFailed([read], captured); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 1, "failed undo must roll back to the pre-click aggregate"); + assert.equal(m.hasPendingOverlay(), false); +}); + +test("grouped patching counts actual member transitions, not desired ids", async () => { + const params = new URLSearchParams({ case: "grouped-members" }); + await seedList(params, [{ + id: "m1", + read: false, + starred: false, + threadMessageIds: ["m1", "m2", "m3"], + threadUnread: 1, + }]); + m.patchMessagesInCaches(["m1", "m2", "m3"], { read: true }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 0); + m.patchMessagesInCaches(["m1", "m2", "m3"], { read: true }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 0); + m.patchMessagesInCaches(["m1", "m2", "m3"], { read: false }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 3); + m.patchMessagesInCaches(["m1", "m2", "m3"], { read: false }); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 3); +}); + +test("thread and detail ingress apply a pending overlay to fresh server responses", async () => { + const thread = [ + { id: "t1", read: true, starred: true, textBody: "", htmlBody: "", attachments: [] }, + ]; + await seedThread("anchor-1", thread); + const star = record("t1", { starred: false }, { starred: true }); + const captured = m.captureMessageFields(["t1"]); + m.defaultMessageActionHooks.onUndoOptimistic([star], captured); + assert.equal(m.getCachedMessageThread("anchor-1")[0].starred, false); + + m.clearMessageThreadCache(); + assert.equal(m.hasPendingOverlay(), true); + const refreshedThread = await m.fetchMessageThread("anchor-1"); + assert.equal(refreshedThread[0].starred, false); + assert.equal(m.getCachedMessageThread("anchor-1")[0].starred, false); + + m.primeMessageDetail({ id: "d1", read: true, starred: true, threadId: null }); + const detailStar = record("d1", { starred: false }, { starred: true }); + const detailCaptured = m.captureMessageFields(["d1"]); + m.defaultMessageActionHooks.onUndoOptimistic([detailStar], detailCaptured); + assert.equal(m.getCachedMessageDetail("d1").message.starred, false); + globalThis.fetch = async () => Response.json({ message: { id: "d1", read: true, starred: true } }); + const refreshedDetail = await m.fetchCachedMessageDetail("d1", true); + assert.equal(refreshedDetail.message.starred, false); + assert.equal(m.getCachedMessageDetail("d1").message.starred, false); +}); + +test("a settled undo invalidates every in-flight response without dropping the patched cache", async () => { + const params = new URLSearchParams({ case: "settled-inflight" }); + await seedList(params, [{ id: "m1", read: true, starred: false }]); + m.primeMessageDetail({ id: "d1", read: true, starred: false, threadId: null }); + const recordOne = record("m1", { read: false }, { read: true }); + const detailRecord = record("d1", { read: false }, { read: true }); + const captured = m.captureMessageFields(["m1", "d1"]); + const listOwner = { pendingOwner: "undo-list" }; + const detailOwner = { pendingOwner: "undo-detail" }; + m.defaultMessageActionHooks.onUndoOptimistic([recordOne], captured, listOwner); + m.defaultMessageActionHooks.onUndoOptimistic([detailRecord], captured, detailOwner); + + const resolveList = deferredFetchResponse({ + messages: [{ id: "m1", read: true }], total: 1, limit: 25, offset: 0, + }); + const listRequest = m.fetchMessageList(params, true); + await Promise.resolve(); + + const resolveThread = deferredFetchResponse({ + threadId: "t1", messages: [{ id: "t1", read: true, starred: true, textBody: "", htmlBody: "", attachments: [] }], + }); + const threadRequest = m.fetchMessageThread("missing-thread"); + const resolveDetail = deferredFetchResponse({ message: { id: "d1", read: true, starred: false } }); + const detailRequest = m.fetchCachedMessageDetail("d1", true); + await Promise.resolve(); + + m.defaultMessageActionHooks.onUndoCompleted([recordOne], success(["m1"]), captured, listOwner); + m.defaultMessageActionHooks.onUndoCompleted([detailRecord], success(["d1"]), captured, detailOwner); + + resolveList(); + await listRequest; + assert.equal(m.peekMessageList(params).messages[0].read, false, "stale list response cannot replace the patched cache"); + + resolveDetail(); + await assert.rejects(detailRequest, /invalidated/); + + resolveThread(); + await assert.rejects(threadRequest, (error) => m.isMessageThreadInvalidated(error)); +}); + +test("owner-scoped overlays clear independently and notify subscribers", () => { + let changes = 0; + const unsubscribe = m.subscribePendingOverlay(() => { changes += 1; }); + m.setPendingOverlay("one", { messages: [{ id: "a1", read: true }] }); + assert.equal(m.getKnownThreadUnread("row"), undefined); + assert.equal(m.applyPendingToMessages([{ id: "a1", read: false }])[0].read, true); + m.setPendingOverlay("two", { messages: [{ id: "a1", read: false }] }); + assert.equal(m.applyPendingToMessages([{ id: "a1", read: true }])[0].read, false, "later owner wins"); + m.clearPendingOverlay("two"); + assert.equal(m.applyPendingToMessages([{ id: "a1", read: false }])[0].read, true); + assert.deepEqual(m.getPendingOverlayOwners(), ["one"]); + m.clearPendingOverlay("one"); + assert.equal(m.hasPendingOverlay(), false); + assert.ok(changes >= 4); + unsubscribe(); +}); diff --git a/tests/message-action-pending-hooks.test.mjs b/tests/message-action-pending-hooks.test.mjs new file mode 100644 index 000000000..bd8733a8f --- /dev/null +++ b/tests/message-action-pending-hooks.test.mjs @@ -0,0 +1,228 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; +import { JSDOM } from "jsdom"; +import { act } from "react"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-action-pending-hooks-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +const dom = new JSDOM("", { + url: "https://mail.example/inbox", + pretendToBeVisual: true, +}); +for (const key of ["window", "document", "HTMLElement", "Element", "Node", "Event", "CustomEvent", "MouseEvent"]) { + globalThis[key] = key === "window" ? dom.window : dom.window[key]; +} +globalThis.localStorage = dom.window.localStorage; +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +await build({ + stdin: { + contents: ` + import { createElement } from "react"; + import { createRoot } from "react-dom/client"; + import { act } from "react"; + import { useMessages } from "@/hooks/use-messages"; + import { useMessageCounts } from "@/hooks/use-message-counts"; + import { defaultMessageActionHooks } from "@/lib/messages/actions/client"; + import { + fetchMessageList, clearMessageListCache, clearMessageCountsCache, + peekMessageList, fetchMessageCounts, + } from "@/hooks/utils"; + import { + captureMessageFields, captureThreadUnread, clearKnownMessageFieldsForTests, hasPendingOverlay, + } from "@/lib/messages/field-store"; + export { act }; + export { defaultMessageActionHooks } from "@/lib/messages/actions/client"; + export { captureMessageFields, captureThreadUnread, hasPendingOverlay, clearKnownMessageFieldsForTests }; + export async function seed(params, messages, counts) { + clearMessageListCache(); + clearMessageCountsCache(); + clearKnownMessageFieldsForTests(); + await fetchMessageList(params, true); + await fetchMessageCounts(null, true); + return { list: peekMessageList(params), counts }; + } + function Probe() { + const { messages } = useMessages("inbox", null, { limit: 25, offset: 0, group: "thread" }); + const { counts } = useMessageCounts(null); + const row = messages[0]; + return createElement("div", { + "data-read": row ? String(row.read) : "missing", + "data-thread-unread": row ? String(row.threadUnread) : "missing", + "data-inbox-unread": String(counts.folders.inbox.unread), + }); + } + export async function mount() { + document.body.replaceChildren(); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(async () => { + root.render(createElement(Probe)); + }); + return { + container, + async unmount() { await act(async () => root.unmount()); }, + }; + } + export async function settle(ms = 250) { + await act(async () => { await new Promise((resolve) => setTimeout(resolve, ms)); }); + } + `, + resolveDir: root, + loader: "tsx", + }, + outfile: join(directory, "hooks.mjs"), + bundle: true, + platform: "browser", + format: "esm", + target: "es2022", + tsconfig: join(root, "tsconfig.json"), + external: ["react", "react-dom", "react-dom/client", "jsdom"], + alias: { "@": join(root, "src") }, + logLevel: "silent", + loader: { ".js": "jsx" }, + plugins: [ + { + name: "runtime-stubs", + setup(builder) { + builder.onLoad({ filter: /\.css$/ }, () => ({ contents: "", loader: "js" })); + }, + }, + ], +}); +const m = await import(pathToFileURL(join(directory, "hooks.mjs")).href); + +const originalFetch = globalThis.fetch; +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); +const record = (id, previous, applied) => ({ + id, + mailboxId: "mb1", + previous: state(previous), + applied: state(applied), +}); +const emptyCounts = (inboxUnread) => ({ + folders: { + inbox: { total: 1, unread: inboxUnread }, + starred: { total: 0, unread: 0 }, + snoozed: { total: 0, unread: 0 }, + sent: { total: 0, unread: 0 }, + scheduled: { total: 0, unread: 0 }, + drafts: { total: 0, unread: 0 }, + archived: { total: 0, unread: 0 }, + spam: { total: 0, unread: 0 }, + trash: { total: 0, unread: 0 }, + }, + customFolders: {}, + mailboxes: [], +}); + +test("mounted list and counts consumers keep the optimistic undo through refresh and reconcile after settle", async () => { + const params = new URLSearchParams({ + timeZone: "UTC", + direction: "inbound", + status: "received", + limit: "25", + offset: "0", + group: "thread", + }); + let listCalls = 0; + let countCalls = 0; + let serverRead = true; + let serverThreadUnread = 0; + let serverInboxUnread = 0; + globalThis.fetch = async (input) => { + const url = String(input); + if (url.includes("/api/messages/counts")) { + countCalls += 1; + return Response.json({ counts: emptyCounts(serverInboxUnread) }); + } + listCalls += 1; + return Response.json({ + messages: [{ + id: "m1", + read: serverRead, + starred: false, + threadMessageIds: ["m1", "m2"], + threadUnread: serverThreadUnread, + }], + total: 1, + limit: 25, + offset: 0, + }); + }; + await m.seed(params, [], emptyCounts(0)); + const app = await m.mount(); + const read = () => app.container.querySelector("div").dataset; + assert.equal(read().read, "true"); + assert.equal(read().threadUnread, "0"); + assert.equal(read().inboxUnread, "0"); + + const undo = record("m1", { read: false }, { read: true }); + const captured = m.captureMessageFields(["m1"]); + const capturedThreads = m.captureThreadUnread(["m1"]); + assert.equal(captured.get("m1").read, true); + assert.equal(capturedThreads.get("m1"), 0); + await act(async () => { + m.defaultMessageActionHooks.onUndoOptimistic([undo], captured); + }); + assert.equal(read().read, "false"); + assert.equal(read().threadUnread, "1"); + assert.equal(m.hasPendingOverlay(), true); + + // The server still has the pre-undo state. A generic realtime refresh while + // the undo request is unresolved must be overlaid. + serverRead = true; + serverThreadUnread = 0; + serverInboxUnread = 0; + const listCallsBefore = listCalls; + const countCallsBefore = countCalls; + await act(async () => { + window.dispatchEvent(new window.CustomEvent("mailflare:messages-changed", { detail: { realtime: true } })); + }); + await m.settle(); + assert.equal(listCalls, listCallsBefore + 1, "the list still performs the generic refresh"); + assert.equal(read().read, "false", "the held undo stays visible"); + assert.equal(read().threadUnread, "1"); + assert.equal(countCalls, countCallsBefore, "counts wait for the pending undo to settle"); + assert.equal(read().inboxUnread, "0"); + + // Once the undo settles, one authoritative fetch reconciles counts and list. + serverRead = false; + serverThreadUnread = 1; + serverInboxUnread = 1; + await act(async () => { + m.defaultMessageActionHooks.onUndoCompleted([undo], { + ok: true, + action: "read", + restored: ["m1"], + skipped: [], + }, captured); + m.defaultMessageActionHooks.onResync(); + }); + assert.equal(m.hasPendingOverlay(), false); + await m.settle(); + assert.equal(read().read, "false"); + assert.equal(read().threadUnread, "1"); + assert.equal(read().inboxUnread, "1"); + assert.ok(countCalls > countCallsBefore, "counts refetch after settle"); + await app.unmount(); +}); + +after(() => { + globalThis.fetch = originalFetch; + dom.window.close(); +}); diff --git a/tests/message-action-pending-timeout.test.mjs b/tests/message-action-pending-timeout.test.mjs new file mode 100644 index 000000000..f03f90547 --- /dev/null +++ b/tests/message-action-pending-timeout.test.mjs @@ -0,0 +1,156 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import test, { after, beforeEach } from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { build } from "esbuild"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = mkdtempSync(join(root, "node_modules", "mailflare-action-timeout-")); +after(() => rmSync(directory, { recursive: true, force: true })); + +const events = []; +const listeners = new Map(); +globalThis.window = { + addEventListener(type, listener) { + const current = listeners.get(type) ?? []; + current.push(listener); + listeners.set(type, current); + }, + removeEventListener(type, listener) { + listeners.set(type, (listeners.get(type) ?? []).filter((item) => item !== listener)); + }, + dispatchEvent(event) { + events.push(event.detail); + for (const listener of listeners.get(event.type) ?? []) listener(event); + return true; + }, + location: { assign() {} }, +}; +globalThis.localStorage = { + getItem() { return null; }, + setItem() {}, + removeItem() {}, +}; +globalThis.document = { visibilityState: "visible", hidden: false, addEventListener() {}, removeEventListener() {} }; + +await build({ + stdin: { + contents: ` + export { + messageActionExecutor, defaultMessageActionHooks, MessageActionRequestError, + setMessageActionTransportTimeoutForTests, + } from "./src/lib/messages/actions/client.ts"; + export { + fetchMessageList, peekMessageList, clearMessageListCache, clearMessageCountsCache, + } from "./src/hooks/utils.ts"; + export { + primeMessageDetail, getCachedMessageDetail, fetchCachedMessageDetail, clearMessageDetailCache, + } from "./src/lib/messages/detail-cache.ts"; + export { clearMessageThreadCache } from "./src/components/messages/message-thread-cache.ts"; + export { + captureMessageFields, clearKnownMessageFieldsForTests, hasPendingOverlay, + } from "./src/lib/messages/field-store.ts"; + `, + resolveDir: root, + sourcefile: "message-action-pending-timeout-entry.ts", + }, + outfile: join(directory, "entry.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node24", + tsconfig: join(root, "tsconfig.json"), + packages: "external", + alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" }, + logLevel: "silent", +}); +const m = await import(pathToFileURL(join(directory, "entry.mjs")).href); + +const state = (overrides = {}) => ({ + status: "received", + read: false, + starred: false, + folderId: null, + snoozedUntil: null, + ...overrides, +}); +const record = (previous, applied) => ({ + id: "m1", + mailboxId: "mb1", + previous: state(previous), + applied: state(applied), +}); + +const originalFetch = globalThis.fetch; +beforeEach(() => { + events.length = 0; + m.clearMessageListCache(); + m.clearMessageDetailCache(); + m.clearMessageThreadCache(); + m.clearKnownMessageFieldsForTests(); + globalThis.fetch = originalFetch; + m.setMessageActionTransportTimeoutForTests(20); +}); + +after(() => { + globalThis.fetch = originalFetch; + delete globalThis.window; + delete globalThis.document; + delete globalThis.localStorage; +}); + +async function seedList(params, messages) { + globalThis.fetch = async () => Response.json({ messages, total: messages.length, limit: 25, offset: 0 }); + await m.fetchMessageList(params, true); +} + +function holdUntilAborted() { + globalThis.fetch = (_input, init) => new Promise((_resolve, reject) => { + init.signal.addEventListener("abort", () => { + const error = new Error("The operation was aborted"); + error.name = "AbortError"; + reject(error); + }); + }); +} + +test("an apply timeout reports a retryable error, cleans up, and resyncs", async () => { + holdUntilAborted(); + const promise = m.messageActionExecutor.run({ action: "read", messageIds: ["m1"] }); + await assert.rejects(promise, (error) => { + assert.equal(error instanceof m.MessageActionRequestError, true); + assert.equal(error.status, 408, "the toast maps 408 to a retryable server failure"); + return true; + }); + assert.equal(m.hasPendingOverlay(), false); + const last = events.at(-1); + assert.equal(last ?? undefined, undefined, "the generic resync event carries no field patch"); +}); + +test("an undo timeout does not paint the historical pre-click state over an uncertain server result", async () => { + const params = new URLSearchParams({ case: "undo-timeout" }); + await seedList(params, [{ id: "m1", read: true, starred: false }]); + m.primeMessageDetail({ id: "m1", read: true, starred: false, threadId: null }); + const undo = record({ read: false }, { read: true }); + const captured = m.captureMessageFields(["m1"]); + assert.equal(captured.get("m1").read, true); + + holdUntilAborted(); + const promise = m.messageActionExecutor.undo([undo], "token"); + await assert.rejects(promise, (error) => { + assert.equal(error instanceof m.MessageActionRequestError, true); + assert.equal(error.status, 408); + return true; + }); + + assert.equal(m.hasPendingOverlay(), false); + assert.equal(m.peekMessageList(params), undefined, "the uncertain list cache is dropped for the resync"); + assert.equal(m.getCachedMessageDetail("m1"), undefined, "the reader cache is dropped for the resync"); + // The optimistic undo event is the only read patch. No historical rollback + // (read true) may follow a timeout, because the server may have committed. + const readEvents = events.filter((detail) => detail?.kind === "read"); + assert.equal(readEvents.length, 1); + assert.equal(readEvents[0].read, false); + assert.equal(events.at(-1) ?? undefined, undefined, "undo failure ends with the authoritative resync event"); +}); diff --git a/tests/message-action-undo.test.mjs b/tests/message-action-undo.test.mjs index a298daffa..5139e7690 100644 --- a/tests/message-action-undo.test.mjs +++ b/tests/message-action-undo.test.mjs @@ -344,7 +344,7 @@ test("membership changes are distinguished from read/star-only patches", () => { assert.equal(m.hasMembershipChange(record(state(), state({ status: "archived" }))), true); }); -test("explicit read patches the list cache and emits an optimistic deferred event", async () => { +test("explicit read patches the list cache and emits an optimistic read event", async () => { const params = new URLSearchParams({ case: "read-patch" }); await seedListCache(params, [{ id: "m1", read: true, starred: false }]); const unread = record(state({ read: true }), state({ read: false })); @@ -352,7 +352,7 @@ test("explicit read patches the list cache and emits an optimistic deferred even m.defaultMessageActionHooks.onApplied({ ok: true, action: "unread", applied: [unread], skipped: [] }, { notify: false }); }); assert.equal(m.peekMessageList(params).messages[0].read, false); - assert.deepEqual(events.at(-1), { kind: "read", messageIds: ["m1"], read: false, deferRefresh: true }); + assert.deepEqual(events.at(-1), { kind: "read", messageIds: ["m1"], read: false, threadTargets: [] }); assert.equal(m.captureMessageFields(["m1"]).get("m1").read, false); }); From a78ae239a89742c249db0282e64793f8972bb151 Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 22:23:10 +0100 Subject: [PATCH 09/15] fix(messages): keep undo notices reachable across overlays --- public/locales/ar.json | 35 ++--- public/locales/bn.json | 35 ++--- public/locales/de.json | 35 ++--- public/locales/es.json | 35 ++--- public/locales/fa.json | 35 ++--- public/locales/fr.json | 31 +++-- public/locales/gu.json | 35 ++--- public/locales/ha.json | 35 ++--- public/locales/hi.json | 35 ++--- public/locales/id.json | 35 ++--- public/locales/it.json | 35 ++--- public/locales/ja.json | 35 ++--- public/locales/kn.json | 35 ++--- public/locales/ko.json | 35 ++--- public/locales/ml.json | 35 ++--- public/locales/mr.json | 35 ++--- public/locales/ms.json | 35 ++--- public/locales/nl.json | 35 ++--- public/locales/pa.json | 35 ++--- public/locales/pl.json | 35 ++--- public/locales/pt-BR.json | 35 ++--- public/locales/pt-PT.json | 35 ++--- public/locales/ru.json | 35 ++--- public/locales/si.json | 35 ++--- public/locales/sw.json | 35 ++--- public/locales/ta.json | 35 ++--- public/locales/te.json | 35 ++--- public/locales/th.json | 35 ++--- public/locales/tr.json | 35 ++--- public/locales/uk.json | 35 ++--- public/locales/ur.json | 35 ++--- public/locales/vi.json | 35 ++--- public/locales/zh-CN.json | 35 ++--- src/components/messages/undo-toasts.tsx | 159 ++++++++++++++++------ src/lib/i18n/en.json | 1 + src/lib/messages/actions/undo-store.ts | 122 +++++++++++++++-- tests/message-undo-toast-store.test.mjs | 76 +++++++++++ tests/message-undo-toast-ui.test.mjs | 174 +++++++++++++++++++++++- 38 files changed, 1071 insertions(+), 612 deletions(-) diff --git a/public/locales/ar.json b/public/locales/ar.json index 91c59233c..2e9b07eac 100644 --- a/public/locales/ar.json +++ b/public/locales/ar.json @@ -2512,12 +2512,13 @@ "actions.unsubscribeDeleteConfirm": "نقل {count} من الرسائل القديمة لهذا المرسل إلى سلة المهملات؟", "actions.unsubscribeTrashDone": "تم إلغاء الاشتراك ونُقل {count} رسالة إلى سلة المهملات", "attachment.downloadAllFlagged": "بعض المرفقات معلَّمة بأنها قد تكون خطيرة. هل تريد تنزيل الأرشيف على أي حال؟", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "تراجع", + "undo.dismiss": "تجاهل", + "undo.failed": "تعذّر التراجع عن هذا التغيير", "undo.region": "إشعارات إجراءات الرسائل", "undo.undoing": "جارٍ التراجع…", "undo.retry": "إعادة المحاولة", + "undo.hidePending": "إخفاء الإشعار (يستمر التراجع)", "undo.failed.expired": "انتهت صلاحية هذا التراجع.", "undo.failed.unavailable": "لم تعد هذه الرسالة متاحة للتراجع.", "undo.failed.stale": "لم يعد من الممكن التراجع عن هذا التغيير لأن الرسالة تغيّرت.", @@ -2525,18 +2526,18 @@ "undo.failed.server": "فشل التراجع. يرجى المحاولة مرة أخرى.", "undo.partialRestored": "تمت استعادة {restored} من {total} رسائل. تعذّر التراجع عن البقية.", "undo.successAnnouncement": "اكتمل التراجع: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "تم تحديث {applied} من {total} رسائل", + "undo.bulk.one": "{action} · {count} رسالة", + "undo.bulk.other": "{action} · {count} رسائل", + "undo.label.archive": "تمت الأرشفة", + "undo.label.trash": "نُقل إلى المهملات", + "undo.label.spam": "نُقل إلى البريد العشوائي", + "undo.label.inbox": "نُقل إلى البريد الوارد", + "undo.label.folder": "نُقل إلى مجلد", + "undo.label.read": "تم وضع علامة كمقروء", + "undo.label.unread": "تم وضع علامة كغير مقروء", + "undo.label.star": "تم التمييز", + "undo.label.unstar": "أُزيل التمييز", + "undo.label.snooze": "تم التأجيل", + "undo.label.unsnooze": "أُلغي التأجيل" } diff --git a/public/locales/bn.json b/public/locales/bn.json index 3675a4613..d0f85a97c 100644 --- a/public/locales/bn.json +++ b/public/locales/bn.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "এই প্রেরকের {count}টি পুরনো ইমেইল ট্র্যাশে নেবেন?", "actions.unsubscribeTrashDone": "সাবস্ক্রিপশন বাতিল; {count}টি ইমেইল ট্র্যাশে গেছে", "attachment.downloadAllFlagged": "কিছু সংযুক্তি সম্ভাব্য বিপজ্জনক হিসেবে চিহ্নিত। তবুও আর্কাইভ ডাউনলোড করবেন?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "ফিরিয়ে আনুন", + "undo.dismiss": "খারিজ করুন", + "undo.failed": "এই পরিবর্তনটি ফিরিয়ে আনা যায়নি", "undo.region": "বার্তা অ্যাকশন বিজ্ঞপ্তি", "undo.undoing": "ফিরিয়ে আনা হচ্ছে…", "undo.retry": "আবার চেষ্টা করুন", + "undo.hidePending": "বিজ্ঞপ্তি লুকান (ফিরিয়ে আনা চলছে)", "undo.failed.expired": "এই ফিরিয়ে আনার সময় শেষ হয়ে গেছে।", "undo.failed.unavailable": "এই বার্তাটি আর ফিরিয়ে আনার জন্য উপলব্ধ নেই।", "undo.failed.stale": "বার্তাটি পরিবর্তিত হওয়ায় এই পরিবর্তন আর ফিরিয়ে আনা যাবে না।", @@ -2465,18 +2466,18 @@ "undo.failed.server": "ফিরিয়ে আনা ব্যর্থ হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।", "undo.partialRestored": "{total}টি বার্তার মধ্যে {restored}টি ফিরিয়ে আনা হয়েছে। বাকিগুলো ফিরিয়ে আনা যায়নি।", "undo.successAnnouncement": "ফিরিয়ে আনা সম্পন্ন: {action}।", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total}টির মধ্যে {applied}টি বার্তা আপডেট হয়েছে", + "undo.bulk.one": "{action} · {count}টি বার্তা", + "undo.bulk.other": "{action} · {count}টি বার্তা", + "undo.label.archive": "আর্কাইভ করা হয়েছে", + "undo.label.trash": "ট্র্যাশে সরানো হয়েছে", + "undo.label.spam": "স্প্যামে সরানো হয়েছে", + "undo.label.inbox": "ইনবক্সে সরানো হয়েছে", + "undo.label.folder": "ফোল্ডারে সরানো হয়েছে", + "undo.label.read": "পঠিত হিসেবে চিহ্নিত", + "undo.label.unread": "অপঠিত হিসেবে চিহ্নিত", + "undo.label.star": "স্টার করা হয়েছে", + "undo.label.unstar": "স্টার সরানো হয়েছে", + "undo.label.snooze": "স্নুজ করা হয়েছে", + "undo.label.unsnooze": "স্নুজ সরানো হয়েছে" } diff --git a/public/locales/de.json b/public/locales/de.json index cc5b8de20..e9cdbdd47 100644 --- a/public/locales/de.json +++ b/public/locales/de.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "{count} ältere E-Mails dieses Absenders in den Papierkorb verschieben?", "actions.unsubscribeTrashDone": "Abbestellt und {count} E-Mails in den Papierkorb verschoben", "attachment.downloadAllFlagged": "Einige Anhänge sind als potenziell gefährlich markiert. Archiv trotzdem herunterladen?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Rückgängig", + "undo.dismiss": "Ausblenden", + "undo.failed": "Diese Änderung konnte nicht rückgängig gemacht werden", "undo.region": "Benachrichtigungen zu Nachrichtenaktionen", "undo.undoing": "Wird rückgängig gemacht…", "undo.retry": "Erneut versuchen", + "undo.hidePending": "Benachrichtigung ausblenden (Rückgängigmachen läuft weiter)", "undo.failed.expired": "Dieses Rückgängigmachen ist abgelaufen.", "undo.failed.unavailable": "Diese Nachricht kann nicht mehr rückgängig gemacht werden.", "undo.failed.stale": "Diese Änderung kann nicht mehr rückgängig gemacht werden, da sich die Nachricht geändert hat.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "Rückgängig machen fehlgeschlagen. Bitte versuchen Sie es erneut.", "undo.partialRestored": "{restored} von {total} Nachrichten wiederhergestellt. Der Rest konnte nicht rückgängig gemacht werden.", "undo.successAnnouncement": "Rückgängig gemacht: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} von {total} Nachrichten aktualisiert", + "undo.bulk.one": "{action} · {count} Nachricht", + "undo.bulk.other": "{action} · {count} Nachrichten", + "undo.label.archive": "Archiviert", + "undo.label.trash": "In den Papierkorb verschoben", + "undo.label.spam": "In Spam verschoben", + "undo.label.inbox": "In den Posteingang verschoben", + "undo.label.folder": "In Ordner verschoben", + "undo.label.read": "Als gelesen markiert", + "undo.label.unread": "Als ungelesen markiert", + "undo.label.star": "Markiert", + "undo.label.unstar": "Markierung entfernt", + "undo.label.snooze": "Zurückgestellt", + "undo.label.unsnooze": "Zurückstellung aufgehoben" } diff --git a/public/locales/es.json b/public/locales/es.json index 4222b583a..1fea639f7 100644 --- a/public/locales/es.json +++ b/public/locales/es.json @@ -2467,12 +2467,13 @@ "actions.unsubscribeDeleteConfirm": "¿Mover {count} correos anteriores de este remitente a la Papelera?", "actions.unsubscribeTrashDone": "Dado de baja; {count} correos movidos a la Papelera", "attachment.downloadAllFlagged": "Algunos archivos adjuntos están marcados como potencialmente peligrosos. ¿Descargar el archivo de todos modos?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Deshacer", + "undo.dismiss": "Descartar", + "undo.failed": "No se pudo deshacer ese cambio", "undo.region": "Notificaciones de acciones de mensajes", "undo.undoing": "Deshaciendo…", "undo.retry": "Reintentar", + "undo.hidePending": "Ocultar notificación (la acción de deshacer continúa)", "undo.failed.expired": "Esta acción ya no se puede deshacer.", "undo.failed.unavailable": "Ese mensaje ya no está disponible para deshacer.", "undo.failed.stale": "Ese cambio ya no se puede deshacer porque el mensaje ha cambiado.", @@ -2480,18 +2481,18 @@ "undo.failed.server": "No se pudo deshacer. Inténtalo de nuevo.", "undo.partialRestored": "Se restauraron {restored} de {total} mensajes. El resto no se pudo deshacer.", "undo.successAnnouncement": "Deshacer completado: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} de {total} mensajes actualizados", + "undo.bulk.one": "{action} · {count} mensaje", + "undo.bulk.other": "{action} · {count} mensajes", + "undo.label.archive": "Archivado", + "undo.label.trash": "Movido a la papelera", + "undo.label.spam": "Movido a spam", + "undo.label.inbox": "Movido a la bandeja de entrada", + "undo.label.folder": "Movido a la carpeta", + "undo.label.read": "Marcado como leído", + "undo.label.unread": "Marcado como no leído", + "undo.label.star": "Marcado con estrella", + "undo.label.unstar": "Estrella quitada", + "undo.label.snooze": "Pospuesto", + "undo.label.unsnooze": "Pospuesto cancelado" } diff --git a/public/locales/fa.json b/public/locales/fa.json index 2868b0dc5..a8831b397 100644 --- a/public/locales/fa.json +++ b/public/locales/fa.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "آیا {count} ایمیل قدیمی این فرستنده به سطل زباله منتقل شود؟", "actions.unsubscribeTrashDone": "اشتراک لغو شد؛ {count} ایمیل به سطل زباله منتقل شد", "attachment.downloadAllFlagged": "برخی پیوست‌ها به‌عنوان بالقوه خطرناک پرچم‌گذاری شده‌اند. با این حال آرشیو دانلود شود؟", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "واگرد", + "undo.dismiss": "بستن", + "undo.failed": "آن تغییر قابل واگرد نبود", "undo.region": "اعلان‌های اقدامات پیام", "undo.undoing": "در حال بازگرداندن…", "undo.retry": "تلاش دوباره", + "undo.hidePending": "پنهان کردن اعلان (واگرد ادامه دارد)", "undo.failed.expired": "مهلت این واگرد به پایان رسیده است.", "undo.failed.unavailable": "آن پیام دیگر برای واگرد در دسترس نیست.", "undo.failed.stale": "این تغییر دیگر قابل واگرد نیست زیرا پیام تغییر کرده است.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "واگرد ناموفق بود. لطفاً دوباره تلاش کنید.", "undo.partialRestored": "{restored} از {total} پیام بازگردانده شد. بقیه قابل واگرد نبودند.", "undo.successAnnouncement": "واگرد کامل شد: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} از {total} پیام به‌روزرسانی شد", + "undo.bulk.one": "{action} · {count} پیام", + "undo.bulk.other": "{action} · {count} پیام", + "undo.label.archive": "بایگانی شد", + "undo.label.trash": "به زباله‌دان منتقل شد", + "undo.label.spam": "به هرزنامه منتقل شد", + "undo.label.inbox": "به صندوق ورودی منتقل شد", + "undo.label.folder": "به پوشه منتقل شد", + "undo.label.read": "خوانده‌شده علامت خورد", + "undo.label.unread": "خوانده‌نشده علامت خورد", + "undo.label.star": "ستاره‌دار شد", + "undo.label.unstar": "ستاره برداشته شد", + "undo.label.snooze": "به تعویق افتاد", + "undo.label.unsnooze": "تعویق لغو شد" } diff --git a/public/locales/fr.json b/public/locales/fr.json index 7130e9821..ba0d9c650 100644 --- a/public/locales/fr.json +++ b/public/locales/fr.json @@ -2467,12 +2467,13 @@ "actions.unsubscribeDeleteConfirm": "Déplacer {count} anciens e-mails de cet expéditeur dans la corbeille ?", "actions.unsubscribeTrashDone": "Désabonné, {count} e-mails placés dans la corbeille", "attachment.downloadAllFlagged": "Certaines pièces jointes sont signalées comme potentiellement dangereuses. Télécharger l'archive quand même ?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Annuler", + "undo.dismiss": "Ignorer", + "undo.failed": "Impossible d’annuler cette modification", "undo.region": "Notifications d’actions sur les messages", "undo.undoing": "Annulation…", "undo.retry": "Réessayer", + "undo.hidePending": "Masquer la notification (l’annulation continue)", "undo.failed.expired": "Cette annulation a expiré.", "undo.failed.unavailable": "Ce message n’est plus disponible pour l’annulation.", "undo.failed.stale": "Cette modification ne peut plus être annulée car le message a changé.", @@ -2480,18 +2481,18 @@ "undo.failed.server": "L’annulation a échoué. Veuillez réessayer.", "undo.partialRestored": "{restored} messages sur {total} ont été restaurés. Le reste n’a pas pu être annulé.", "undo.successAnnouncement": "Annulation terminée : {action}.", - "undo.partial": "{applied} of {total} messages updated", + "undo.partial": "{applied} messages sur {total} mis à jour", "undo.bulk.one": "{action} · {count} message", "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.label.archive": "Archivé", + "undo.label.trash": "Déplacé vers la corbeille", + "undo.label.spam": "Déplacé vers le spam", + "undo.label.inbox": "Déplacé vers la boîte de réception", + "undo.label.folder": "Déplacé vers le dossier", + "undo.label.read": "Marqué comme lu", + "undo.label.unread": "Marqué comme non lu", + "undo.label.star": "Mis en favori", + "undo.label.unstar": "Retiré des favoris", + "undo.label.snooze": "Reporté", + "undo.label.unsnooze": "Report annulé" } diff --git a/public/locales/gu.json b/public/locales/gu.json index 90b3d562e..63217dfae 100644 --- a/public/locales/gu.json +++ b/public/locales/gu.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "આ મોકલનારના {count} જૂના ઇમેઇલ ટ્રેશમાં ખસેડવા?", "actions.unsubscribeTrashDone": "સભ્યતા રદ; {count} ઇમેઇલ ટ્રેશમાં ગયા", "attachment.downloadAllFlagged": "કેટલીક જોડાણો સંભવિત જોખમી તરીકે ચિહ્નિત છે. તેમ છતાં આર્કાઇવ ડાઉનલોડ કરવું?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "પૂર્વવત્ કરો", + "undo.dismiss": "બંધ કરો", + "undo.failed": "તે ફેરફાર પૂર્વવત્ કરી શકાયો નથી", "undo.region": "સંદેશ ક્રિયા સૂચનાઓ", "undo.undoing": "પાછું ખેંચી રહ્યું છે…", "undo.retry": "ફરી પ્રયાસ કરો", + "undo.hidePending": "સૂચના છુપાવો (પૂર્વવત્ કરવાનું ચાલુ છે)", "undo.failed.expired": "આ પાછું ખેંચવાની મુદત પૂરી થઈ ગઈ છે.", "undo.failed.unavailable": "તે સંદેશ હવે પાછું ખેંચવા માટે ઉપલબ્ધ નથી.", "undo.failed.stale": "સંદેશ બદલાયો હોવાથી આ ફેરફાર હવે પાછો ખેંચી શકાતો નથી.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "પાછું ખેંચવું નિષ્ફળ ગયું. કૃપા કરીને ફરી પ્રયાસ કરો.", "undo.partialRestored": "{total} માંથી {restored} સંદેશા પુનઃસ્થાપિત થયા. બાકીના પાછા ખેંચી શકાયા નથી.", "undo.successAnnouncement": "પાછું ખેંચવું પૂર્ણ: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} માંથી {applied} સંદેશા અપડેટ થયા", + "undo.bulk.one": "{action} · {count} સંદેશો", + "undo.bulk.other": "{action} · {count} સંદેશા", + "undo.label.archive": "આર્કાઇવ કર્યું", + "undo.label.trash": "ટ્રેશમાં ખસેડ્યું", + "undo.label.spam": "સ્પામમાં ખસેડ્યું", + "undo.label.inbox": "ઇનબોક્સમાં ખસેડ્યું", + "undo.label.folder": "ફોલ્ડરમાં ખસેડ્યું", + "undo.label.read": "વાંચેલા તરીકે ચિહ્નિત", + "undo.label.unread": "ન વાંચેલા તરીકે ચિહ્નિત", + "undo.label.star": "સ્ટાર કર્યું", + "undo.label.unstar": "સ્ટાર દૂર કર્યું", + "undo.label.snooze": "સ્નૂઝ કર્યું", + "undo.label.unsnooze": "સ્નૂઝ દૂર કર્યું" } diff --git a/public/locales/ha.json b/public/locales/ha.json index 2c4b4fbb6..39968f60b 100644 --- a/public/locales/ha.json +++ b/public/locales/ha.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "Aka mika saƙonni {count} na tsoho daga wannan mai aikawa zuwa Trash?", "actions.unsubscribeTrashDone": "An soke rajin; aka mika saƙonni {count} zuwa Trash", "attachment.downloadAllFlagged": "Wasu abubuwan da ake da su an yi su tambarin yiwuwa hadari. Duk da haka a sauke ajiya?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Juyawa", + "undo.dismiss": "Ajiye", + "undo.failed": "Ba a iya juyar da wannan canjin ba", "undo.region": "Sanarwar ayyukan saƙo", "undo.undoing": "Ana juyawa…", "undo.retry": "Sake gwadawa", + "undo.hidePending": "Ɓoye sanarwar (juyawa na ci gaba)", "undo.failed.expired": "Wannan juyawa ya ƙare.", "undo.failed.unavailable": "Wannan saƙon ba ya samuwa don juyawa.", "undo.failed.stale": "Ba za a iya juyar da wannan canjin ba saboda saƙon ya canza.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "Juyawa ya kasa. Don Allah sake gwadawa.", "undo.partialRestored": "An dawo da {restored} daga cikin {total} saƙonni. Sauran ba a iya juyar da su ba.", "undo.successAnnouncement": "An kammala juyawa: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "An sabunta {applied} daga cikin {total} saƙonni", + "undo.bulk.one": "{action} · saƙo {count}", + "undo.bulk.other": "{action} · saƙonni {count}", + "undo.label.archive": "An adana", + "undo.label.trash": "An matsa zuwa Shara", + "undo.label.spam": "An matsa zuwa Spam", + "undo.label.inbox": "An matsa zuwa Akwatin saƙo", + "undo.label.folder": "An matsa zuwa babban fayil", + "undo.label.read": "An yiwa alama a matsayin an karanta", + "undo.label.unread": "An yiwa alama a matsayin ba a karanta ba", + "undo.label.star": "An yiwa tauraro", + "undo.label.unstar": "An cire tauraro", + "undo.label.snooze": "An jinkirta", + "undo.label.unsnooze": "An soke jinkiri" } diff --git a/public/locales/hi.json b/public/locales/hi.json index 073b8b1c7..78056ae19 100644 --- a/public/locales/hi.json +++ b/public/locales/hi.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "इस प्रेषक के {count} पुराने ईमेल ट्रैश में ले जाएँ?", "actions.unsubscribeTrashDone": "सदस्यता रद्द; {count} ईमेल ट्रैश में ले जाए गए", "attachment.downloadAllFlagged": "कुछ अटैचमेंट संभावित रूप से खतरनाक चिह्नित हैं। फिर भी संग्रह डाउनलोड करें?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "पूर्ववत करें", + "undo.dismiss": "खारिज करें", + "undo.failed": "उस परिवर्तन को पूर्ववत नहीं किया जा सका", "undo.region": "संदेश क्रिया सूचनाएँ", "undo.undoing": "पूर्ववत किया जा रहा है…", "undo.retry": "फिर से प्रयास करें", + "undo.hidePending": "सूचना छिपाएँ (पूर्ववत करना जारी है)", "undo.failed.expired": "यह पूर्ववत करने की अवधि समाप्त हो गई है।", "undo.failed.unavailable": "वह संदेश अब पूर्ववत करने के लिए उपलब्ध नहीं है।", "undo.failed.stale": "संदेश बदल जाने के कारण यह परिवर्तन अब पूर्ववत नहीं किया जा सकता।", @@ -2465,18 +2466,18 @@ "undo.failed.server": "पूर्ववत करना विफल रहा। कृपया फिर से प्रयास करें।", "undo.partialRestored": "{total} में से {restored} संदेश बहाल किए गए। बाकी पूर्ववत नहीं किए जा सके।", "undo.successAnnouncement": "पूर्ववत करना पूर्ण: {action}।", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} में से {applied} संदेश अपडेट किए गए", + "undo.bulk.one": "{action} · {count} संदेश", + "undo.bulk.other": "{action} · {count} संदेश", + "undo.label.archive": "संग्रहीत", + "undo.label.trash": "ट्रैश में ले जाया गया", + "undo.label.spam": "स्पैम में ले जाया गया", + "undo.label.inbox": "इनबॉक्स में ले जाया गया", + "undo.label.folder": "फ़ोल्डर में ले जाया गया", + "undo.label.read": "पढ़ा गया के रूप में चिह्नित", + "undo.label.unread": "अपठित के रूप में चिह्नित", + "undo.label.star": "स्टार किया गया", + "undo.label.unstar": "स्टार हटाया गया", + "undo.label.snooze": "स्नूज़ किया गया", + "undo.label.unsnooze": "स्नूज़ हटाया गया" } diff --git a/public/locales/id.json b/public/locales/id.json index 248b678c8..84dc1da56 100644 --- a/public/locales/id.json +++ b/public/locales/id.json @@ -2434,12 +2434,13 @@ "actions.unsubscribeDeleteConfirm": "Pindahkan {count} email lama dari pengirim ini ke Sampah?", "actions.unsubscribeTrashDone": "Berhenti berlangganan; {count} email dipindahkan ke Sampah", "attachment.downloadAllFlagged": "Beberapa lampiran ditandai berpotensi berbahaya. Tetap unduh arsip?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Urungkan", + "undo.dismiss": "Tutup", + "undo.failed": "Perubahan itu tidak dapat diurungkan", "undo.region": "Notifikasi tindakan pesan", "undo.undoing": "Membatalkan…", "undo.retry": "Coba lagi", + "undo.hidePending": "Sembunyikan notifikasi (urungkan tetap berjalan)", "undo.failed.expired": "Pembatalan ini telah kedaluwarsa.", "undo.failed.unavailable": "Pesan itu tidak lagi tersedia untuk dibatalkan.", "undo.failed.stale": "Perubahan itu tidak dapat dibatalkan lagi karena pesannya telah berubah.", @@ -2447,18 +2448,18 @@ "undo.failed.server": "Pembatalan gagal. Silakan coba lagi.", "undo.partialRestored": "{restored} dari {total} pesan dipulihkan. Sisanya tidak dapat dibatalkan.", "undo.successAnnouncement": "Pembatalan selesai: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} dari {total} pesan diperbarui", + "undo.bulk.one": "{action} · {count} pesan", + "undo.bulk.other": "{action} · {count} pesan", + "undo.label.archive": "Diarsipkan", + "undo.label.trash": "Dipindahkan ke Sampah", + "undo.label.spam": "Dipindahkan ke Spam", + "undo.label.inbox": "Dipindahkan ke Kotak Masuk", + "undo.label.folder": "Dipindahkan ke folder", + "undo.label.read": "Ditandai sudah dibaca", + "undo.label.unread": "Ditandai belum dibaca", + "undo.label.star": "Ditandai bintang", + "undo.label.unstar": "Bintang dihapus", + "undo.label.snooze": "Ditunda", + "undo.label.unsnooze": "Penundaan dibatalkan" } diff --git a/public/locales/it.json b/public/locales/it.json index 4d567c340..ee8cc6c38 100644 --- a/public/locales/it.json +++ b/public/locales/it.json @@ -2467,12 +2467,13 @@ "actions.unsubscribeDeleteConfirm": "Spostare {count} email precedenti di questo mittente nel Cestino?", "actions.unsubscribeTrashDone": "Iscrizione annullata; {count} email spostate nel Cestino", "attachment.downloadAllFlagged": "Alcuni allegati sono segnalati come potenzialmente pericolosi. Scaricare comunque l'archivio?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Annulla", + "undo.dismiss": "Ignora", + "undo.failed": "Impossibile annullare la modifica", "undo.region": "Notifiche azioni sui messaggi", "undo.undoing": "Annullamento…", "undo.retry": "Riprova", + "undo.hidePending": "Nascondi notifica (l’annullamento continua)", "undo.failed.expired": "Questo annullamento è scaduto.", "undo.failed.unavailable": "Quel messaggio non è più disponibile per l’annullamento.", "undo.failed.stale": "Questa modifica non può più essere annullata perché il messaggio è cambiato.", @@ -2480,18 +2481,18 @@ "undo.failed.server": "Annullamento non riuscito. Riprova.", "undo.partialRestored": "{restored} messaggi su {total} ripristinati. Il resto non è stato possibile annullarlo.", "undo.successAnnouncement": "Annullamento completato: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} messaggi su {total} aggiornati", + "undo.bulk.one": "{action} · {count} messaggio", + "undo.bulk.other": "{action} · {count} messaggi", + "undo.label.archive": "Archiviato", + "undo.label.trash": "Spostato nel cestino", + "undo.label.spam": "Spostato nello spam", + "undo.label.inbox": "Spostato nella posta in arrivo", + "undo.label.folder": "Spostato nella cartella", + "undo.label.read": "Contrassegnato come letto", + "undo.label.unread": "Contrassegnato come non letto", + "undo.label.star": "Aggiunto ai preferiti", + "undo.label.unstar": "Rimosso dai preferiti", + "undo.label.snooze": "Posticipato", + "undo.label.unsnooze": "Posticipo annullato" } diff --git a/public/locales/ja.json b/public/locales/ja.json index b11b9d463..b5ec074c2 100644 --- a/public/locales/ja.json +++ b/public/locales/ja.json @@ -2434,12 +2434,13 @@ "actions.unsubscribeDeleteConfirm": "この差出人の過去のメール {count} 件をゴミ箱に移動しますか?", "actions.unsubscribeTrashDone": "登録解除し、{count} 件をゴミ箱に移動しました", "attachment.downloadAllFlagged": "一部の添付ファイルに危険の可能性のフラグがあります。それでもアーカイブをダウンロードしますか?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "元に戻す", + "undo.dismiss": "閉じる", + "undo.failed": "その変更を元に戻せませんでした", "undo.region": "メッセージ操作の通知", "undo.undoing": "元に戻しています…", "undo.retry": "再試行", + "undo.hidePending": "通知を隠す(元に戻す処理は続行中)", "undo.failed.expired": "この元に戻す操作は期限切れです。", "undo.failed.unavailable": "そのメッセージは元に戻せなくなりました。", "undo.failed.stale": "メッセージが変更されたため、この変更は元に戻せません。", @@ -2447,18 +2448,18 @@ "undo.failed.server": "元に戻せませんでした。もう一度お試しください。", "undo.partialRestored": "{total} 件中 {restored} 件のメッセージを復元しました。残りは元に戻せませんでした。", "undo.successAnnouncement": "元に戻しました: {action}。", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} 件中 {applied} 件のメッセージを更新しました", + "undo.bulk.one": "{action} · {count} 件のメッセージ", + "undo.bulk.other": "{action} · {count} 件のメッセージ", + "undo.label.archive": "アーカイブ済み", + "undo.label.trash": "ゴミ箱に移動しました", + "undo.label.spam": "スパムに移動しました", + "undo.label.inbox": "受信トレイに移動しました", + "undo.label.folder": "フォルダーに移動しました", + "undo.label.read": "既読にしました", + "undo.label.unread": "未読にしました", + "undo.label.star": "スターを付けました", + "undo.label.unstar": "スターを外しました", + "undo.label.snooze": "スヌーズしました", + "undo.label.unsnooze": "スヌーズを解除しました" } diff --git a/public/locales/kn.json b/public/locales/kn.json index 711967d11..285dadaee 100644 --- a/public/locales/kn.json +++ b/public/locales/kn.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "ಈ ಕಳುಹಿಸುವವರ {count} ಹಳೆಯ ಇಮెයిల್‌ಗಳನ್ನು ಟ್ರ್ಯಾಶ್‌ಗೆ ಸರಿಸಬೇಕೆ?", "actions.unsubscribeTrashDone": "ಚಂದಾದಾರಿಕೆ ರದ್ದಾಯಿತು; {count} ಇಮೆಯಿಲ್‌ಗಳು ಟ್ರ್ಯಾಶ್‌ಗೆ ಹೋದವು", "attachment.downloadAllFlagged": "ಕೆಲವು ಲಗತ್ತುಗಳು ಸಂಭಾವ್ಯ ಅಪಾಯಕಾರಿ ಎಂದು ಗುರುತಿಸಲಾಗಿವೆ. ಹೇಗೂ ಆರ್ಕೈವ್ ಡೌನ್‌ಲೋಡ್ ಮಾಡಬೇಕೆ?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "ಹಿಂತಿರುಗಿಸಿ", + "undo.dismiss": "ಮುಚ್ಚಿ", + "undo.failed": "ಆ ಬದಲಾವಣೆಯನ್ನು ಹಿಂತಿರುಗಿಸಲು ಸಾಧ್ಯವಾಗಲಿಲ್ಲ", "undo.region": "ಸಂದೇಶ ಕ್ರಿಯೆ ಅಧಿಸೂಚನೆಗಳು", "undo.undoing": "ಹಿಂತಿರುಗಿಸಲಾಗುತ್ತಿದೆ…", "undo.retry": "ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ", + "undo.hidePending": "ಅಧಿಸೂಚನೆಯನ್ನು ಮರೆಮಾಡಿ (ಹಿಂತಿರುಗಿಸುವುದು ಮುಂದುವರಿಯುತ್ತದೆ)", "undo.failed.expired": "ಈ ಹಿಂತಿರುಗಿಸುವ ಅವಧಿ ಮುಗಿದಿದೆ.", "undo.failed.unavailable": "ಆ ಸಂದೇಶವನ್ನು ಇನ್ನು ಹಿಂತಿರುಗಿಸಲು ಸಾಧ್ಯವಿಲ್ಲ.", "undo.failed.stale": "ಸಂದೇಶ ಬದಲಾಗಿರುವುದರಿಂದ ಈ ಬದಲಾವಣೆಯನ್ನು ಇನ್ನು ಹಿಂತಿರುಗಿಸಲು ಸಾಧ್ಯವಿಲ್ಲ.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "ಹಿಂತಿರುಗಿಸುವುದು ವಿಫಲವಾಗಿದೆ. ದಯವಿಟ್ಟು ಮತ್ತೆ ಪ್ರಯತ್ನಿಸಿ.", "undo.partialRestored": "{total} ರಲ್ಲಿ {restored} ಸಂದೇಶಗಳನ್ನು ಮರುಸ್ಥಾಪಿಸಲಾಗಿದೆ. ಉಳಿದವನ್ನು ಹಿಂತಿರುಗಿಸಲಾಗಲಿಲ್ಲ.", "undo.successAnnouncement": "ಹಿಂತಿರುಗಿಸುವುದು ಪೂರ್ಣಗೊಂಡಿದೆ: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} ರಲ್ಲಿ {applied} ಸಂದೇಶಗಳನ್ನು ನವೀಕರಿಸಲಾಗಿದೆ", + "undo.bulk.one": "{action} · {count} ಸಂದೇಶ", + "undo.bulk.other": "{action} · {count} ಸಂದೇಶಗಳು", + "undo.label.archive": "ಆರ್ಕೈವ್ ಮಾಡಲಾಗಿದೆ", + "undo.label.trash": "ಟ್ರ್ಯಾಶ್‌ಗೆ ಸರಿಸಲಾಗಿದೆ", + "undo.label.spam": "ಸ್ಪ್ಯಾಮ್‌ಗೆ ಸರಿಸಲಾಗಿದೆ", + "undo.label.inbox": "ಇನ್‌ಬಾಕ್ಸ್‌ಗೆ ಸರಿಸಲಾಗಿದೆ", + "undo.label.folder": "ಫೋಲ್ಡರ್‌ಗೆ ಸರಿಸಲಾಗಿದೆ", + "undo.label.read": "ಓದಿದೆ ಎಂದು ಗುರುತಿಸಲಾಗಿದೆ", + "undo.label.unread": "ಓದಿಲ್ಲ ಎಂದು ಗುರುತಿಸಲಾಗಿದೆ", + "undo.label.star": "ಸ್ಟಾರ್ ಮಾಡಲಾಗಿದೆ", + "undo.label.unstar": "ಸ್ಟಾರ್ ತೆಗೆದುಹಾಕಲಾಗಿದೆ", + "undo.label.snooze": "ಸ್ನೂಜ್ ಮಾಡಲಾಗಿದೆ", + "undo.label.unsnooze": "ಸ್ನೂಜ್ ರದ್ದುಗೊಳಿಸಲಾಗಿದೆ" } diff --git a/public/locales/ko.json b/public/locales/ko.json index 5cce7911b..047fd0080 100644 --- a/public/locales/ko.json +++ b/public/locales/ko.json @@ -2448,12 +2448,13 @@ "actions.unsubscribeDeleteConfirm": "이 발신자의 이전 이메일 {count}개를 휴지통으로 옮길까요?", "actions.unsubscribeTrashDone": "구독을 해지하고 이메일 {count}개를 휴지통으로 옮겼습니다", "attachment.downloadAllFlagged": "일부 첨부 파일이 잠재적으로 위험하다고 표시되었습니다. 그래도 아카이브를 다운로드할까요?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "실행 취소", + "undo.dismiss": "닫기", + "undo.failed": "해당 변경 사항을 실행 취소하지 못했습니다", "undo.region": "메시지 작업 알림", "undo.undoing": "실행 취소 중…", "undo.retry": "다시 시도", + "undo.hidePending": "알림 숨기기(실행 취소는 계속됨)", "undo.failed.expired": "이 실행 취소는 만료되었습니다.", "undo.failed.unavailable": "해당 메시지는 더 이상 실행 취소할 수 없습니다.", "undo.failed.stale": "메시지가 변경되어 이 변경 사항을 더 이상 실행 취소할 수 없습니다.", @@ -2461,18 +2462,18 @@ "undo.failed.server": "실행 취소에 실패했습니다. 다시 시도하세요.", "undo.partialRestored": "{total}개 중 {restored}개 메시지를 복원했습니다. 나머지는 실행 취소할 수 없었습니다.", "undo.successAnnouncement": "실행 취소 완료: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total}개 중 {applied}개 메시지 업데이트됨", + "undo.bulk.one": "{action} · 메시지 {count}개", + "undo.bulk.other": "{action} · 메시지 {count}개", + "undo.label.archive": "보관됨", + "undo.label.trash": "휴지통으로 이동됨", + "undo.label.spam": "스팸으로 이동됨", + "undo.label.inbox": "받은편지함으로 이동됨", + "undo.label.folder": "폴더로 이동됨", + "undo.label.read": "읽음으로 표시됨", + "undo.label.unread": "읽지 않음으로 표시됨", + "undo.label.star": "별표 표시됨", + "undo.label.unstar": "별표 해제됨", + "undo.label.snooze": "일시 보류됨", + "undo.label.unsnooze": "일시 보류 해제됨" } diff --git a/public/locales/ml.json b/public/locales/ml.json index 5250c204a..bd995fe54 100644 --- a/public/locales/ml.json +++ b/public/locales/ml.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "ഈ അയച്ചയാളുടെ {count} പഴയ ഇമെയിലുകൾ ട്രാഷിലേക്ക് മാറ്റണോ?", "actions.unsubscribeTrashDone": "സബ്‌സ്‌ക്രിപ്‌ഷൻ റദ്ദായി; {count} ഇമെയിലുകൾ ട്രാഷിലേക്ക് മാറ്റി", "attachment.downloadAllFlagged": "ചില അറ്റാച്ച്‌മെന്റുകൾ അപകടകരമെന്ന് അടയാളപ്പെടുത്തിയിരിക്കുന്നു. എങ്കിലും ആർക്കൈവ് ഡൗൺലോഡ് ചെയ്യണോ?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "പഴയപടിയാക്കുക", + "undo.dismiss": "അവസാനിപ്പിക്കുക", + "undo.failed": "ആ മാറ്റം പഴയപടിയാക്കാൻ കഴിഞ്ഞില്ല", "undo.region": "സന്ദേശ പ്രവർത്തന അറിയിപ്പുകൾ", "undo.undoing": "പഴയപടിയാക്കുന്നു…", "undo.retry": "വീണ്ടും ശ്രമിക്കുക", + "undo.hidePending": "അറിയിപ്പ് മറയ്ക്കുക (പഴയപടിയാക്കൽ തുടരുന്നു)", "undo.failed.expired": "ഈ പഴയപടിയാക്കൽ കാലഹരണപ്പെട്ടു.", "undo.failed.unavailable": "ആ സന്ദേശം ഇനി പഴയപടിയാക്കാൻ ലഭ്യമല്ല.", "undo.failed.stale": "സന്ദേശം മാറിയതിനാൽ ഈ മാറ്റം ഇനി പഴയപടിയാക്കാൻ കഴിയില്ല.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "പഴയപടിയാക്കൽ പരാജയപ്പെട്ടു. വീണ്ടും ശ്രമിക്കുക.", "undo.partialRestored": "{total}-ൽ {restored} സന്ദേശങ്ങൾ പുനഃസ്ഥാപിച്ചു. ബാക്കിയുള്ളവ പഴയപടിയാക്കാൻ കഴിഞ്ഞില്ല.", "undo.successAnnouncement": "പഴയപടിയാക്കൽ പൂർത്തിയായി: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total}-ൽ {applied} സന്ദേശങ്ങൾ അപ്ഡേറ്റ് ചെയ്തു", + "undo.bulk.one": "{action} · {count} സന്ദേശം", + "undo.bulk.other": "{action} · {count} സന്ദേശങ്ങൾ", + "undo.label.archive": "ആർക്കൈവ് ചെയ്തു", + "undo.label.trash": "ട്രാഷിലേക്ക് മാറ്റി", + "undo.label.spam": "സ്പാമിലേക്ക് മാറ്റി", + "undo.label.inbox": "ഇൻബോക്സിലേക്ക് മാറ്റി", + "undo.label.folder": "ഫോൾഡറിലേക്ക് മാറ്റി", + "undo.label.read": "വായിച്ചതായി അടയാളപ്പെടുത്തി", + "undo.label.unread": "വായിക്കാത്തതായി അടയാളപ്പെടുത്തി", + "undo.label.star": "സ്റ്റാർ ചെയ്തു", + "undo.label.unstar": "സ്റ്റാർ നീക്കി", + "undo.label.snooze": "സ്നൂസ് ചെയ്തു", + "undo.label.unsnooze": "സ്നൂസ് ഒഴിവാക്കി" } diff --git a/public/locales/mr.json b/public/locales/mr.json index 4c1748a7c..7063be771 100644 --- a/public/locales/mr.json +++ b/public/locales/mr.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "या प्रेषकाचे {count} जुने ईमेल ट्रॅशमध्ये हलवायचे?", "actions.unsubscribeTrashDone": "सदस्यता रद्द; {count} ईमेल ट्रॅशमध्ये गेले", "attachment.downloadAllFlagged": "काही अटॅचमेंट संभावित धोकादायक म्हणून चिन्हांकित आहेत. तरीही संग्रह डाउनलोड करायचा?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "पूर्वस्थितीत आणा", + "undo.dismiss": "बंद करा", + "undo.failed": "तो बदल पूर्वस्थितीत आणता आला नाही", "undo.region": "संदेश क्रिया सूचना", "undo.undoing": "पूर्वस्थितीत आणत आहे…", "undo.retry": "पुन्हा प्रयत्न करा", + "undo.hidePending": "सूचना लपवा (पूर्वस्थितीत आणणे सुरू आहे)", "undo.failed.expired": "ही पूर्वस्थितीत आणण्याची मुदत संपली आहे.", "undo.failed.unavailable": "ती संदेश आता पूर्वस्थितीत आणण्यासाठी उपलब्ध नाही.", "undo.failed.stale": "संदेश बदलल्यामुळे हा बदल आता पूर्वस्थितीत आणता येत नाही.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "पूर्वस्थितीत आणणे अयशस्वी झाले. कृपया पुन्हा प्रयत्न करा.", "undo.partialRestored": "{total} पैकी {restored} संदेश पुनर्संचयित केले. उर्वरित पूर्वस्थितीत आणता आले नाहीत.", "undo.successAnnouncement": "पूर्वस्थितीत आणणे पूर्ण: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} पैकी {applied} संदेश अद्ययावत केले", + "undo.bulk.one": "{action} · {count} संदेश", + "undo.bulk.other": "{action} · {count} संदेश", + "undo.label.archive": "संग्रहित", + "undo.label.trash": "कचऱ्यात हलवले", + "undo.label.spam": "स्पॅममध्ये हलवले", + "undo.label.inbox": "इनबॉक्समध्ये हलवले", + "undo.label.folder": "फोल्डरमध्ये हलवले", + "undo.label.read": "वाचले असे चिन्हांकित", + "undo.label.unread": "न वाचले असे चिन्हांकित", + "undo.label.star": "स्टार केले", + "undo.label.unstar": "स्टार काढले", + "undo.label.snooze": "स्नूझ केले", + "undo.label.unsnooze": "स्नूझ रद्द केले" } diff --git a/public/locales/ms.json b/public/locales/ms.json index 87f9e6718..0a6b773f9 100644 --- a/public/locales/ms.json +++ b/public/locales/ms.json @@ -2448,12 +2448,13 @@ "actions.unsubscribeDeleteConfirm": "Alihkan {count} e-mel lama daripada penghantar ini ke Sampah?", "actions.unsubscribeTrashDone": "Berhenti melanggan; {count} e-mel dialihkan ke Sampah", "attachment.downloadAllFlagged": "Some attachments are flagged as potentially dangerous. Download the archive anyway?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Buat asal", + "undo.dismiss": "Tutup", + "undo.failed": "Perubahan itu tidak dapat dibuat asal", "undo.region": "Pemberitahuan tindakan mesej", "undo.undoing": "Membatalkan…", "undo.retry": "Cuba lagi", + "undo.hidePending": "Sembunyikan pemberitahuan (buat asal diteruskan)", "undo.failed.expired": "Pembatalan ini telah tamat tempoh.", "undo.failed.unavailable": "Mesej itu tidak lagi tersedia untuk dibatalkan.", "undo.failed.stale": "Perubahan itu tidak boleh dibatalkan lagi kerana mesej telah berubah.", @@ -2461,18 +2462,18 @@ "undo.failed.server": "Pembatalan gagal. Sila cuba lagi.", "undo.partialRestored": "{restored} daripada {total} mesej dipulihkan. Selebihnya tidak dapat dibatalkan.", "undo.successAnnouncement": "Pembatalan selesai: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} daripada {total} mesej dikemas kini", + "undo.bulk.one": "{action} · {count} mesej", + "undo.bulk.other": "{action} · {count} mesej", + "undo.label.archive": "Diarkibkan", + "undo.label.trash": "Dipindahkan ke Tong Sampah", + "undo.label.spam": "Dipindahkan ke Spam", + "undo.label.inbox": "Dipindahkan ke Peti Masuk", + "undo.label.folder": "Dipindahkan ke folder", + "undo.label.read": "Ditandai sebagai dibaca", + "undo.label.unread": "Ditandai sebagai belum dibaca", + "undo.label.star": "Ditanda bintang", + "undo.label.unstar": "Bintang dibuang", + "undo.label.snooze": "Ditangguhkan", + "undo.label.unsnooze": "Penangguhan dibatalkan" } diff --git a/public/locales/nl.json b/public/locales/nl.json index d96c7b7df..496aa79d3 100644 --- a/public/locales/nl.json +++ b/public/locales/nl.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "{count} eerdere e-mails van deze afzender naar de prullenbak verplaatsen?", "actions.unsubscribeTrashDone": "Afgemeld en {count} e-mails naar de prullenbak verplaatst", "attachment.downloadAllFlagged": "Sommige bijlagen zijn gemarkeerd als mogelijk gevaarlijk. Het archief toch downloaden?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Ongedaan maken", + "undo.dismiss": "Sluiten", + "undo.failed": "Die wijziging kon niet ongedaan worden gemaakt", "undo.region": "Meldingen over berichtacties", "undo.undoing": "Ongedaan maken…", "undo.retry": "Opnieuw proberen", + "undo.hidePending": "Melding verbergen (ongedaan maken gaat door)", "undo.failed.expired": "Deze undo is verlopen.", "undo.failed.unavailable": "Dat bericht is niet meer beschikbaar om ongedaan te maken.", "undo.failed.stale": "Die wijziging kan niet meer ongedaan worden gemaakt omdat het bericht is gewijzigd.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "Ongedaan maken mislukt. Probeer het opnieuw.", "undo.partialRestored": "{restored} van {total} berichten hersteld. De rest kon niet ongedaan worden gemaakt.", "undo.successAnnouncement": "Ongedaan maken voltooid: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} van {total} berichten bijgewerkt", + "undo.bulk.one": "{action} · {count} bericht", + "undo.bulk.other": "{action} · {count} berichten", + "undo.label.archive": "Gearchiveerd", + "undo.label.trash": "Naar prullenbak verplaatst", + "undo.label.spam": "Naar spam verplaatst", + "undo.label.inbox": "Naar postvak in verplaatst", + "undo.label.folder": "Naar map verplaatst", + "undo.label.read": "Als gelezen gemarkeerd", + "undo.label.unread": "Als ongelezen gemarkeerd", + "undo.label.star": "Gemarkeerd met ster", + "undo.label.unstar": "Ster verwijderd", + "undo.label.snooze": "Uitgesteld", + "undo.label.unsnooze": "Uitstel opgeheven" } diff --git a/public/locales/pa.json b/public/locales/pa.json index dc0fde623..21ef44f3b 100644 --- a/public/locales/pa.json +++ b/public/locales/pa.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "ਇਸ ਭੇਜਣ ਵਾਲੇ ਦੇ {count} ਪੁਰਾਣੇ ਈਮੇਲ ਟ੍ਰੈਸ਼ ਵਿੱਚ ਭੇਜੀਏ?", "actions.unsubscribeTrashDone": "ਸਬਸਕ੍ਰਿਪਸ਼ਨ ਰੱਦ; {count} ਈਮੇਲ ਟ੍ਰੈਸ਼ ਵਿੱਚ ਭੇਜੇ ਗਏ", "attachment.downloadAllFlagged": "ਕੁਝ ਅਟੈਚਮੈਂਟ ਸੰਭਾਵੀ ਖ਼ਤਰਨਾਕ ਵਜੋਂ ਨਿਸ਼ਾਨਾਬੱਧ ਹਨ। ਫਿਰ ਵੀ ਆਰਕਾਈਵ ਡਾਊਨਲੋਡ ਕਰੀਏ?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "ਵਾਪਸ ਕਰੋ", + "undo.dismiss": "ਬੰਦ ਕਰੋ", + "undo.failed": "ਉਹ ਬਦਲਾਅ ਵਾਪਸ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਿਆ", "undo.region": "ਸੁਨੇਹਾ ਕਾਰਵਾਈ ਸੂਚਨਾਵਾਂ", "undo.undoing": "ਵਾਪਸ ਕੀਤਾ ਜਾ ਰਿਹਾ ਹੈ…", "undo.retry": "ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ", + "undo.hidePending": "ਸੂਚਨਾ ਲੁਕਾਓ (ਵਾਪਸ ਕਰਨਾ ਜਾਰੀ ਹੈ)", "undo.failed.expired": "ਇਸ ਵਾਪਸੀ ਦੀ ਮਿਆਦ ਖਤਮ ਹੋ ਗਈ ਹੈ।", "undo.failed.unavailable": "ਉਹ ਸੁਨੇਹਾ ਹੁਣ ਵਾਪਸ ਕਰਨ ਲਈ ਉਪਲਬਧ ਨਹੀਂ ਹੈ।", "undo.failed.stale": "ਸੁਨੇਹਾ ਬਦਲਣ ਕਾਰਨ ਇਹ ਬਦਲਾਅ ਹੁਣ ਵਾਪਸ ਨਹੀਂ ਕੀਤਾ ਜਾ ਸਕਦਾ।", @@ -2465,18 +2466,18 @@ "undo.failed.server": "ਵਾਪਸ ਕਰਨਾ ਅਸਫਲ ਰਿਹਾ। ਕਿਰਪਾ ਕਰਕੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।", "undo.partialRestored": "{total} ਵਿੱਚੋਂ {restored} ਸੁਨੇਹੇ ਬਹਾਲ ਕੀਤੇ ਗਏ। ਬਾਕੀ ਵਾਪਸ ਨਹੀਂ ਕੀਤੇ ਜਾ ਸਕੇ।", "undo.successAnnouncement": "ਵਾਪਸ ਕਰਨਾ ਪੂਰਾ ਹੋਇਆ: {action}।", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} ਵਿੱਚੋਂ {applied} ਸੁਨੇਹੇ ਅੱਪਡੇਟ ਕੀਤੇ", + "undo.bulk.one": "{action} · {count} ਸੁਨੇਹਾ", + "undo.bulk.other": "{action} · {count} ਸੁਨੇਹੇ", + "undo.label.archive": "ਆਰਕਾਈਵ ਕੀਤਾ", + "undo.label.trash": "ਰੱਦੀ ਵਿੱਚ ਭੇਜਿਆ", + "undo.label.spam": "ਸਪੈਮ ਵਿੱਚ ਭੇਜਿਆ", + "undo.label.inbox": "ਇਨਬਾਕਸ ਵਿੱਚ ਭੇਜਿਆ", + "undo.label.folder": "ਫੋਲਡਰ ਵਿੱਚ ਭੇਜਿਆ", + "undo.label.read": "ਪੜ੍ਹਿਆ ਵਜੋਂ ਨਿਸ਼ਾਨਬੱਧ", + "undo.label.unread": "ਨਾ ਪੜ੍ਹਿਆ ਵਜੋਂ ਨਿਸ਼ਾਨਬੱਧ", + "undo.label.star": "ਸਟਾਰ ਕੀਤਾ", + "undo.label.unstar": "ਸਟਾਰ ਹਟਾਇਆ", + "undo.label.snooze": "ਸਨੂਜ਼ ਕੀਤਾ", + "undo.label.unsnooze": "ਸਨੂਜ਼ ਰੱਦ ਕੀਤਾ" } diff --git a/public/locales/pl.json b/public/locales/pl.json index 56be45132..427084b77 100644 --- a/public/locales/pl.json +++ b/public/locales/pl.json @@ -2482,12 +2482,13 @@ "actions.unsubscribeDeleteConfirm": "Przenieść {count} wcześniejszych wiadomości tego nadawcy do Kosza?", "actions.unsubscribeTrashDone": "Wypisano; {count} wiadomości przeniesiono do Kosza", "attachment.downloadAllFlagged": "Niektóre załączniki są oznaczone jako potencjalnie niebezpieczne. Pobrać archiwum mimo to?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Cofnij", + "undo.dismiss": "Odrzuć", + "undo.failed": "Nie udało się cofnąć tej zmiany", "undo.region": "Powiadomienia o działaniach na wiadomościach", "undo.undoing": "Cofanie…", "undo.retry": "Spróbuj ponownie", + "undo.hidePending": "Ukryj powiadomienie (cofanie jest kontynuowane)", "undo.failed.expired": "To cofnięcie wygasło.", "undo.failed.unavailable": "Ta wiadomość nie jest już dostępna do cofnięcia.", "undo.failed.stale": "Tej zmiany nie można już cofnąć, ponieważ wiadomość została zmieniona.", @@ -2495,18 +2496,18 @@ "undo.failed.server": "Cofnięcie nie powiodło się. Spróbuj ponownie.", "undo.partialRestored": "Przywrócono {restored} z {total} wiadomości. Pozostałych nie udało się cofnąć.", "undo.successAnnouncement": "Cofnięcie zakończone: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "Zaktualizowano {applied} z {total} wiadomości", + "undo.bulk.one": "{action} · {count} wiadomość", + "undo.bulk.other": "{action} · {count} wiadomości", + "undo.label.archive": "Zarchiwizowano", + "undo.label.trash": "Przeniesiono do kosza", + "undo.label.spam": "Przeniesiono do spamu", + "undo.label.inbox": "Przeniesiono do skrzynki odbiorczej", + "undo.label.folder": "Przeniesiono do folderu", + "undo.label.read": "Oznaczono jako przeczytane", + "undo.label.unread": "Oznaczono jako nieprzeczytane", + "undo.label.star": "Oznaczono gwiazdką", + "undo.label.unstar": "Usunięto gwiazdkę", + "undo.label.snooze": "Odłożono", + "undo.label.unsnooze": "Anulowano odłożenie" } diff --git a/public/locales/pt-BR.json b/public/locales/pt-BR.json index b27a29f7b..cd90a50c7 100644 --- a/public/locales/pt-BR.json +++ b/public/locales/pt-BR.json @@ -2467,12 +2467,13 @@ "actions.unsubscribeDeleteConfirm": "Mover {count} e-mails antigos deste remetente para a Lixeira?", "actions.unsubscribeTrashDone": "Inscrição cancelada; {count} e-mails movidos para a Lixeira", "attachment.downloadAllFlagged": "Alguns anexos estão marcados como potencialmente perigosos. Baixar o arquivo mesmo assim?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Desfazer", + "undo.dismiss": "Dispensar", + "undo.failed": "Não foi possível desfazer essa alteração", "undo.region": "Notificações de ações em mensagens", "undo.undoing": "Desfazendo…", "undo.retry": "Tentar novamente", + "undo.hidePending": "Ocultar notificação (o desfazer continua)", "undo.failed.expired": "Este desfazer expirou.", "undo.failed.unavailable": "Essa mensagem não está mais disponível para desfazer.", "undo.failed.stale": "Essa alteração não pode mais ser desfeita porque a mensagem foi alterada.", @@ -2480,18 +2481,18 @@ "undo.failed.server": "Falha ao desfazer. Tente novamente.", "undo.partialRestored": "{restored} de {total} mensagens restauradas. O restante não pôde ser desfeito.", "undo.successAnnouncement": "Desfazer concluído: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} de {total} mensagens atualizadas", + "undo.bulk.one": "{action} · {count} mensagem", + "undo.bulk.other": "{action} · {count} mensagens", + "undo.label.archive": "Arquivado", + "undo.label.trash": "Movido para a lixeira", + "undo.label.spam": "Movido para spam", + "undo.label.inbox": "Movido para a caixa de entrada", + "undo.label.folder": "Movido para a pasta", + "undo.label.read": "Marcado como lido", + "undo.label.unread": "Marcado como não lido", + "undo.label.star": "Favoritado", + "undo.label.unstar": "Removido dos favoritos", + "undo.label.snooze": "Adiado", + "undo.label.unsnooze": "Adiamento cancelado" } diff --git a/public/locales/pt-PT.json b/public/locales/pt-PT.json index 316d2504b..81475ade1 100644 --- a/public/locales/pt-PT.json +++ b/public/locales/pt-PT.json @@ -2467,12 +2467,13 @@ "actions.unsubscribeDeleteConfirm": "Mover {count} e-mails anteriores deste remetente para o Lixo?", "actions.unsubscribeTrashDone": "Subscrição anulada; {count} e-mails movidos para o Lixo", "attachment.downloadAllFlagged": "Alguns anexos estão marcados como potencialmente perigosos. Transferir o ficheiro mesmo assim?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Anular", + "undo.dismiss": "Dispensar", + "undo.failed": "Não foi possível anular essa alteração", "undo.region": "Notificações de ações em mensagens", "undo.undoing": "A anular…", "undo.retry": "Tentar novamente", + "undo.hidePending": "Ocultar notificação (a anulação continua)", "undo.failed.expired": "Esta anulação expirou.", "undo.failed.unavailable": "Essa mensagem já não está disponível para anular.", "undo.failed.stale": "Essa alteração já não pode ser anulada porque a mensagem foi alterada.", @@ -2480,18 +2481,18 @@ "undo.failed.server": "Falha ao anular. Tente novamente.", "undo.partialRestored": "{restored} de {total} mensagens restauradas. As restantes não puderam ser anuladas.", "undo.successAnnouncement": "Anulação concluída: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{applied} de {total} mensagens atualizadas", + "undo.bulk.one": "{action} · {count} mensagem", + "undo.bulk.other": "{action} · {count} mensagens", + "undo.label.archive": "Arquivado", + "undo.label.trash": "Movido para o lixo", + "undo.label.spam": "Movido para spam", + "undo.label.inbox": "Movido para a caixa de entrada", + "undo.label.folder": "Movido para a pasta", + "undo.label.read": "Marcado como lido", + "undo.label.unread": "Marcado como não lido", + "undo.label.star": "Marcado com estrela", + "undo.label.unstar": "Estrela removida", + "undo.label.snooze": "Adiado", + "undo.label.unsnooze": "Adiamento anulado" } diff --git a/public/locales/ru.json b/public/locales/ru.json index a830ce134..7cc73fd44 100644 --- a/public/locales/ru.json +++ b/public/locales/ru.json @@ -2482,12 +2482,13 @@ "actions.unsubscribeDeleteConfirm": "Переместить {count} писем от этого отправителя в корзину?", "actions.unsubscribeTrashDone": "Отписано; {count} писем перемещено в корзину", "attachment.downloadAllFlagged": "Некоторые вложения помечены как потенциально опасные. Всё равно скачать архив?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Отменить", + "undo.dismiss": "Закрыть", + "undo.failed": "Не удалось отменить это изменение", "undo.region": "Уведомления о действиях с сообщениями", "undo.undoing": "Отмена…", "undo.retry": "Повторить", + "undo.hidePending": "Скрыть уведомление (отмена продолжается)", "undo.failed.expired": "Срок отмены истёк.", "undo.failed.unavailable": "Это сообщение больше недоступно для отмены.", "undo.failed.stale": "Это изменение больше нельзя отменить, так как сообщение изменилось.", @@ -2495,18 +2496,18 @@ "undo.failed.server": "Не удалось отменить. Повторите попытку.", "undo.partialRestored": "Восстановлено {restored} из {total} сообщений. Остальные отменить не удалось.", "undo.successAnnouncement": "Отмена завершена: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "Обновлено {applied} из {total} сообщений", + "undo.bulk.one": "{action} · {count} сообщение", + "undo.bulk.other": "{action} · {count} сообщений", + "undo.label.archive": "Архивировано", + "undo.label.trash": "Перемещено в корзину", + "undo.label.spam": "Перемещено в спам", + "undo.label.inbox": "Перемещено во входящие", + "undo.label.folder": "Перемещено в папку", + "undo.label.read": "Отмечено как прочитанное", + "undo.label.unread": "Отмечено как непрочитанное", + "undo.label.star": "Добавлено в избранное", + "undo.label.unstar": "Удалено из избранного", + "undo.label.snooze": "Отложено", + "undo.label.unsnooze": "Отложенность снята" } diff --git a/public/locales/si.json b/public/locales/si.json index 6a894744a..839b79754 100644 --- a/public/locales/si.json +++ b/public/locales/si.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "මෙම යවන්නාගේ පැරණි විද්‍යුත් තැපෑල {count} කුණු කූඩයට ගෙනයාමටද?", "actions.unsubscribeTrashDone": "දායකත්වය අවලංගුයි; විද්‍යුත් තැපෑල {count} කුණු කූඩයට ගියේය", "attachment.downloadAllFlagged": "සමහර ඇමුණුම් අන්තරායන්හි ලෙස සලකුණු කර ඇත. තවදුරටත් සංරක්ෂණාගාරය බාගන්නවාද?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "පෙරලන්න", + "undo.dismiss": "වසන්න", + "undo.failed": "එම වෙනස පෙරලිය නොහැකි විය", "undo.region": "පණිවිඩ ක්‍රියා දැනුම්දීම්", "undo.undoing": "පෙරලමින්…", "undo.retry": "නැවත උත්සාහ කරන්න", + "undo.hidePending": "දැනුම්දීම සඟවන්න (පෙරලීම දිගටම සිදුවේ)", "undo.failed.expired": "මෙම පෙරලීම කල් ඉකුත් වී ඇත.", "undo.failed.unavailable": "එම පණිවිඩය තවදුරටත් පෙරලීමට ලබාගත නොහැක.", "undo.failed.stale": "පණිවිඩය වෙනස් වී ඇති බැවින් මෙම වෙනස තවදුරටත් පෙරලිය නොහැක.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "පෙරලීම අසාර්ථක විය. කරුණාකර නැවත උත්සාහ කරන්න.", "undo.partialRestored": "පණිවිඩ {total} කින් {restored} ක් ප්‍රතිසාධනය කරන ලදී. ඉතිරිය පෙරලිය නොහැකි විය.", "undo.successAnnouncement": "පෙරලීම සම්පූර්ණයි: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} කින් {applied} පණිවිඩ යාවත්කාලීන කරන ලදී", + "undo.bulk.one": "{action} · පණිවිඩ {count}", + "undo.bulk.other": "{action} · පණිවිඩ {count}", + "undo.label.archive": "සංරක්ෂිතයි", + "undo.label.trash": "කසළට ගෙන යන ලදී", + "undo.label.spam": "ස්පෑම් වෙත ගෙන යන ලදී", + "undo.label.inbox": "එන ලිපි වෙත ගෙන යන ලදී", + "undo.label.folder": "ෆෝල්ඩරයට ගෙන යන ලදී", + "undo.label.read": "කියවා ඇති ලෙස සලකුණු කරන ලදී", + "undo.label.unread": "නොකියවූ ලෙස සලකුණු කරන ලදී", + "undo.label.star": "තරු ලකුණු කරන ලදී", + "undo.label.unstar": "තරු ලකුණ ඉවත් කරන ලදී", + "undo.label.snooze": "කල් තැබූ", + "undo.label.unsnooze": "කල් තැබීම අවලංගු කරන ලදී" } diff --git a/public/locales/sw.json b/public/locales/sw.json index 1eaa8d9ed..c4f618628 100644 --- a/public/locales/sw.json +++ b/public/locales/sw.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "Uhamishe barua pepe {count} za zamu za mtumaji huyu kwenda Taka?", "actions.unsubscribeTrashDone": "Usajili umeondolewa; barua pepe {count} zimehamishiwa Taka", "attachment.downloadAllFlagged": "Baadhi ya viambatisho vimepigwa bendera kuwa hatari. Bila shaka upakue kumbukumbu?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Tendua", + "undo.dismiss": "Ondoa", + "undo.failed": "Imeshindwa kutendua badiliko hilo", "undo.region": "Arifa za vitendo vya ujumbe", "undo.undoing": "Inatendua…", "undo.retry": "Jaribu tena", + "undo.hidePending": "Ficha arifa (utenduzi unaendelea)", "undo.failed.expired": "Utenduzi huu umeisha muda.", "undo.failed.unavailable": "Ujumbe huo haupatikani tena ili utenduliwe.", "undo.failed.stale": "Badiliko hili haliwezi kutenduliwa tena kwa sababu ujumbe umebadilika.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "Utenduzi umeshindwa. Tafadhali jaribu tena.", "undo.partialRestored": "Ujumbe {restored} kati ya {total} umerejeshwa. Uliobaki haukuweza kutenduliwa.", "undo.successAnnouncement": "Utenduzi umekamilika: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "Ujumbe {applied} kati ya {total} umesasishwa", + "undo.bulk.one": "{action} · ujumbe {count}", + "undo.bulk.other": "{action} · ujumbe {count}", + "undo.label.archive": "Imehifadhiwa", + "undo.label.trash": "Imehamishwa hadi Takataka", + "undo.label.spam": "Imehamishwa hadi Spam", + "undo.label.inbox": "Imehamishwa hadi Kikasha", + "undo.label.folder": "Imehamishwa hadi folda", + "undo.label.read": "Imetiwa alama kuwa imesomwa", + "undo.label.unread": "Imetiwa alama kuwa haijasomwa", + "undo.label.star": "Imetiwa nyota", + "undo.label.unstar": "Nyota imeondolewa", + "undo.label.snooze": "Imeahirishwa", + "undo.label.unsnooze": "Uahirishaji umeghairiwa" } diff --git a/public/locales/ta.json b/public/locales/ta.json index 07fd2e768..8347d46ce 100644 --- a/public/locales/ta.json +++ b/public/locales/ta.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "இந்த அனுப்புநரின் {count} பழைய மின்னஞ்சல்களை குப்பைக்கு நகர்த்தவா?", "actions.unsubscribeTrashDone": "சந்தா நிறுத்தப்பட்டது; {count} மின்னஞ்சல்கள் குப்பைக்கு நகர்ந்தன", "attachment.downloadAllFlagged": "சில இணைப்புகள் ஆபத்தானதாகக் குறிக்கப்பட்டுள்ளன. இருந்தும் காப்பகத்தைப் பதிவிறக்கவா?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "செயலிழக்கச் செய்", + "undo.dismiss": "நிராகரி", + "undo.failed": "அந்த மாற்றத்தைச் செயலிழக்க முடியவில்லை", "undo.region": "செய்தி செயல் அறிவிப்புகள்", "undo.undoing": "செயலிழக்கப்படுகிறது…", "undo.retry": "மீண்டும் முயற்சிக்கவும்", + "undo.hidePending": "அறிவிப்பை மறை (செயலிழப்பு தொடர்கிறது)", "undo.failed.expired": "இந்த செயலிழப்பு காலாவதியானது.", "undo.failed.unavailable": "அந்தச் செய்தி இனி செயலிழக்கக் கிடைக்காது.", "undo.failed.stale": "செய்தி மாறியதால் இந்த மாற்றத்தை இனி செயலிழக்க முடியாது.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "செயலிழக்க முடியவில்லை. மீண்டும் முயற்சிக்கவும்.", "undo.partialRestored": "{total} செய்திகளில் {restored} மீட்டெடுக்கப்பட்டன. மீதமுள்ளவை செயலிழக்க முடியவில்லை.", "undo.successAnnouncement": "செயலிழப்பு முடிந்தது: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} இல் {applied} செய்திகள் புதுப்பிக்கப்பட்டன", + "undo.bulk.one": "{action} · {count} செய்தி", + "undo.bulk.other": "{action} · {count} செய்திகள்", + "undo.label.archive": "காப்பகப்படுத்தப்பட்டது", + "undo.label.trash": "குப்பைக்கு நகர்த்தப்பட்டது", + "undo.label.spam": "ஸ்பேமுக்கு நகர்த்தப்பட்டது", + "undo.label.inbox": "உள்ளகத்திற்கு நகர்த்தப்பட்டது", + "undo.label.folder": "கோப்புறைக்கு நகர்த்தப்பட்டது", + "undo.label.read": "படித்ததாகக் குறிக்கப்பட்டது", + "undo.label.unread": "படிக்காததாகக் குறிக்கப்பட்டது", + "undo.label.star": "நட்சத்திரமிட்டது", + "undo.label.unstar": "நட்சத்திரம் நீக்கப்பட்டது", + "undo.label.snooze": "தாமதப்படுத்தப்பட்டது", + "undo.label.unsnooze": "தாமதம் நீக்கப்பட்டது" } diff --git a/public/locales/te.json b/public/locales/te.json index d317c669d..a73107d3b 100644 --- a/public/locales/te.json +++ b/public/locales/te.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "ఈ పంపిణీదారి {count} పాత ఇమెయిల్‌లను ట్రాష్‌కు తరలించాలా?", "actions.unsubscribeTrashDone": "చందా రద్దైంది; {count} ఇమెయిల్‌లు ట్రాష్‌కు వెళ్లాయి", "attachment.downloadAllFlagged": "కొన్ని అటాచ్‌మెంట్‌లు ప్రమాదకరంగా గుర్తు పెట్టబడ్డాయి. అయినా ఆర్కైవ్ డౌన్‌లోడ్ చేయాలా?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "రద్దు చేయి", + "undo.dismiss": "మూసివేయి", + "undo.failed": "ఆ మార్పును రద్దు చేయలేకపోయాం", "undo.region": "సందేశ చర్య నోటిఫికేషన్‌లు", "undo.undoing": "చర్య రద్దు చేయబడుతోంది…", "undo.retry": "మళ్లీ ప్రయత్నించండి", + "undo.hidePending": "నోటిఫికేషన్ దాచు (రద్దు కొనసాగుతోంది)", "undo.failed.expired": "ఈ చర్య రద్దు గడువు ముగిసింది.", "undo.failed.unavailable": "ఆ సందేశం ఇకపై చర్య రద్దు కోసం అందుబాటులో లేదు.", "undo.failed.stale": "సందేశం మారినందున ఈ మార్పును ఇకపై రద్దు చేయలేరు.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "చర్య రద్దు విఫలమైంది. దయచేసి మళ్లీ ప్రయత్నించండి.", "undo.partialRestored": "{total} సందేశాలలో {restored} పునరుద్ధరించబడ్డాయి. మిగిలినవి రద్దు చేయలేకపోయాం.", "undo.successAnnouncement": "చర్య రద్దు పూర్తయింది: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total}లో {applied} సందేశాలు నవీకరించబడ్డాయి", + "undo.bulk.one": "{action} · {count} సందేశం", + "undo.bulk.other": "{action} · {count} సందేశాలు", + "undo.label.archive": "ఆర్కైవ్ చేయబడింది", + "undo.label.trash": "ట్రాష్కు తరలించబడింది", + "undo.label.spam": "స్పామ్కు తరలించబడింది", + "undo.label.inbox": "ఇన్బాక్స్కు తరలించబడింది", + "undo.label.folder": "ఫోల్డర్కు తరలించబడింది", + "undo.label.read": "చదివినట్లు గుర్తించబడింది", + "undo.label.unread": "చదవనట్లు గుర్తించబడింది", + "undo.label.star": "స్టార్ చేయబడింది", + "undo.label.unstar": "స్టార్ తీసివేయబడింది", + "undo.label.snooze": "వాయిదా వేయబడింది", + "undo.label.unsnooze": "వాయిదా రద్దు చేయబడింది" } diff --git a/public/locales/th.json b/public/locales/th.json index 4e847fb11..0c6a38c3c 100644 --- a/public/locales/th.json +++ b/public/locales/th.json @@ -2448,12 +2448,13 @@ "actions.unsubscribeDeleteConfirm": "ย้ายอีเมลเดิม {count} ฉบับจากผู้ส่งรายนี้ไปถังขยะ?", "actions.unsubscribeTrashDone": "ยกเลิกการสมัครรับแล้ว ย้าย {count} ฉบับไปถังขยะ", "attachment.downloadAllFlagged": "ไฟล์แนบบางไฟล์ถูกตั้งค่าสถานะว่าอาจเป็นอันตราย ดาวน์โหลดไฟล์เก็บถาวรต่อไหม", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "เลิกทำ", + "undo.dismiss": "ปิด", + "undo.failed": "ไม่สามารถเลิกทำการเปลี่ยนแปลงนั้นได้", "undo.region": "การแจ้งเตือนการดำเนินการกับข้อความ", "undo.undoing": "กำลังเลิกทำ…", "undo.retry": "ลองอีกครั้ง", + "undo.hidePending": "ซ่อนการแจ้งเตือน (การเลิกทำยังดำเนินต่อ)", "undo.failed.expired": "การเลิกทำนี้หมดอายุแล้ว", "undo.failed.unavailable": "ไม่สามารถเลิกทำข้อความนั้นได้อีกต่อไป", "undo.failed.stale": "ไม่สามารถเลิกทำการเปลี่ยนแปลงนี้ได้อีกเนื่องจากข้อความถูกเปลี่ยนแล้ว", @@ -2461,18 +2462,18 @@ "undo.failed.server": "เลิกทำไม่สำเร็จ โปรดลองอีกครั้ง", "undo.partialRestored": "กู้คืนแล้ว {restored} จาก {total} ข้อความ ส่วนที่เหลือไม่สามารถเลิกทำได้", "undo.successAnnouncement": "เลิกทำเสร็จสิ้น: {action}", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "อัปเดตแล้ว {applied} จาก {total} ข้อความ", + "undo.bulk.one": "{action} · {count} ข้อความ", + "undo.bulk.other": "{action} · {count} ข้อความ", + "undo.label.archive": "เก็บถาวรแล้ว", + "undo.label.trash": "ย้ายไปถังขยะแล้ว", + "undo.label.spam": "ย้ายไปสแปมแล้ว", + "undo.label.inbox": "ย้ายไปกล่องจดหมายแล้ว", + "undo.label.folder": "ย้ายไปโฟลเดอร์แล้ว", + "undo.label.read": "ทำเครื่องหมายว่าอ่านแล้ว", + "undo.label.unread": "ทำเครื่องหมายว่ายังไม่อ่าน", + "undo.label.star": "ติดดาวแล้ว", + "undo.label.unstar": "เอาดาวออกแล้ว", + "undo.label.snooze": "เลื่อนออกไปแล้ว", + "undo.label.unsnooze": "ยกเลิกการเลื่อนออกไปแล้ว" } diff --git a/public/locales/tr.json b/public/locales/tr.json index e76471561..27e80b758 100644 --- a/public/locales/tr.json +++ b/public/locales/tr.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "Bu gönderenin {count} eski e-postası Çöp Kutusuna taşınsın mı?", "actions.unsubscribeTrashDone": "Abonelikten çıkıldı; {count} e-posta Çöp Kutusuna taşındı", "attachment.downloadAllFlagged": "Bazı ekler potansiyel olarak tehlikeli olarak işaretlendi. Yine de arşiv indirilsin mi?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Geri al", + "undo.dismiss": "Kapat", + "undo.failed": "Bu değişiklik geri alınamadı", "undo.region": "Mesaj işlemi bildirimleri", "undo.undoing": "Geri alınıyor…", "undo.retry": "Yeniden dene", + "undo.hidePending": "Bildirimi gizle (geri alma devam ediyor)", "undo.failed.expired": "Bu geri alma işleminin süresi doldu.", "undo.failed.unavailable": "O mesaj artık geri alınamaz.", "undo.failed.stale": "Mesaj değiştiği için bu değişiklik artık geri alınamaz.", @@ -2465,18 +2466,18 @@ "undo.failed.server": "Geri alma başarısız. Lütfen yeniden deneyin.", "undo.partialRestored": "{total} mesajdan {restored} tanesi geri yüklendi. Kalanlar geri alınamadı.", "undo.successAnnouncement": "Geri alma tamamlandı: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} mesajdan {applied} tanesi güncellendi", + "undo.bulk.one": "{action} · {count} mesaj", + "undo.bulk.other": "{action} · {count} mesaj", + "undo.label.archive": "Arşivlendi", + "undo.label.trash": "Çöp kutusuna taşındı", + "undo.label.spam": "Spam'e taşındı", + "undo.label.inbox": "Gelen kutusuna taşındı", + "undo.label.folder": "Klasöre taşındı", + "undo.label.read": "Okundu olarak işaretlendi", + "undo.label.unread": "Okunmadı olarak işaretlendi", + "undo.label.star": "Yıldızlandı", + "undo.label.unstar": "Yıldız kaldırıldı", + "undo.label.snooze": "Ertelendi", + "undo.label.unsnooze": "Erteleme kaldırıldı" } diff --git a/public/locales/uk.json b/public/locales/uk.json index 2a870fe5d..e1e0e7869 100644 --- a/public/locales/uk.json +++ b/public/locales/uk.json @@ -2482,12 +2482,13 @@ "actions.unsubscribeDeleteConfirm": "Перемістити {count} листів від цього відправника до кошика?", "actions.unsubscribeTrashDone": "Відписано; {count} листів переміщено до кошика", "attachment.downloadAllFlagged": "Деякі вкладення позначено як потенційно небезпечні. Завантажити архів усе одно?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Скасувати", + "undo.dismiss": "Закрити", + "undo.failed": "Не вдалося скасувати цю зміну", "undo.region": "Сповіщення про дії з повідомленнями", "undo.undoing": "Скасування…", "undo.retry": "Повторити", + "undo.hidePending": "Приховати сповіщення (скасування триває)", "undo.failed.expired": "Термін скасування минув.", "undo.failed.unavailable": "Це повідомлення більше недоступне для скасування.", "undo.failed.stale": "Цю зміну більше не можна скасувати, оскільки повідомлення змінилося.", @@ -2495,18 +2496,18 @@ "undo.failed.server": "Не вдалося скасувати. Повторіть спробу.", "undo.partialRestored": "Відновлено {restored} з {total} повідомлень. Решту скасувати не вдалося.", "undo.successAnnouncement": "Скасування завершено: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "Оновлено {applied} з {total} повідомлень", + "undo.bulk.one": "{action} · {count} повідомлення", + "undo.bulk.other": "{action} · {count} повідомлень", + "undo.label.archive": "Архівовано", + "undo.label.trash": "Переміщено до кошика", + "undo.label.spam": "Переміщено до спаму", + "undo.label.inbox": "Переміщено до вхідних", + "undo.label.folder": "Переміщено до папки", + "undo.label.read": "Позначено як прочитане", + "undo.label.unread": "Позначено як непрочитане", + "undo.label.star": "Додано до обраного", + "undo.label.unstar": "Вилучено з обраного", + "undo.label.snooze": "Відкладено", + "undo.label.unsnooze": "Відкладення скасовано" } diff --git a/public/locales/ur.json b/public/locales/ur.json index bbe2b53d0..d85365fa0 100644 --- a/public/locales/ur.json +++ b/public/locales/ur.json @@ -2452,12 +2452,13 @@ "actions.unsubscribeDeleteConfirm": "اس مرسل کے {count} پرانے ای میلز کو ٹریش میں منتقل کریں؟", "actions.unsubscribeTrashDone": "سبسکرپشن ختم؛ {count} ای میلز ٹریش میں منتقل کر دی گئیں", "attachment.downloadAllFlagged": "بعض منسلکات کو ممکنہ طور پر خطرناک قرار دیا گیا ہے۔ پھر بھی آرکائیو ڈاؤن لوڈ کریں؟", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "واپس کریں", + "undo.dismiss": "برخاست کریں", + "undo.failed": "اس تبدیلی کو واپس نہیں کیا جا سکا", "undo.region": "پیغام کے اعمال کی اطلاعات", "undo.undoing": "واپس کیا جا رہا ہے…", "undo.retry": "دوبارہ کوشش کریں", + "undo.hidePending": "اطلاع چھپائیں (واپسی جاری ہے)", "undo.failed.expired": "اس واپسی کی مدت ختم ہو گئی ہے۔", "undo.failed.unavailable": "وہ پیغام اب واپس کرنے کے لیے دستیاب نہیں ہے۔", "undo.failed.stale": "پیغام تبدیل ہونے کی وجہ سے یہ تبدیلی اب واپس نہیں کی جا سکتی۔", @@ -2465,18 +2466,18 @@ "undo.failed.server": "واپس کرنا ناکام رہا۔ براہ کرم دوبارہ کوشش کریں۔", "undo.partialRestored": "{total} میں سے {restored} پیغامات بحال ہوئے۔ باقی واپس نہیں کیے جا سکے۔", "undo.successAnnouncement": "واپس کرنا مکمل: {action}۔", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "{total} میں سے {applied} پیغامات اپ ڈیٹ ہوئے", + "undo.bulk.one": "{action} · {count} پیغام", + "undo.bulk.other": "{action} · {count} پیغامات", + "undo.label.archive": "آرکائیو کیا گیا", + "undo.label.trash": "ردی میں منتقل کیا گیا", + "undo.label.spam": "اسپام میں منتقل کیا گیا", + "undo.label.inbox": "ان باکس میں منتقل کیا گیا", + "undo.label.folder": "فولڈر میں منتقل کیا گیا", + "undo.label.read": "پڑھا گیا نشان زد", + "undo.label.unread": "نہ پڑھا گیا نشان زد", + "undo.label.star": "ستارہ لگایا گیا", + "undo.label.unstar": "ستارہ ہٹایا گیا", + "undo.label.snooze": "ملتوی کیا گیا", + "undo.label.unsnooze": "التوا ختم کیا گیا" } diff --git a/public/locales/vi.json b/public/locales/vi.json index 9b5401e1b..6fb7c78f0 100644 --- a/public/locales/vi.json +++ b/public/locales/vi.json @@ -2434,12 +2434,13 @@ "actions.unsubscribeDeleteConfirm": "Chuyển {count} email cũ của người gửi này vào Thùng rác?", "actions.unsubscribeTrashDone": "Đã hủy đăng ký; {count} email đã chuyển vào Thùng rác", "attachment.downloadAllFlagged": "Một số tệp đính kèm bị gắn cờ là có khả năng nguy hiểm. Vẫn tải xuống tệp nén?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "Hoàn tác", + "undo.dismiss": "Bỏ qua", + "undo.failed": "Không thể hoàn tác thay đổi đó", "undo.region": "Thông báo thao tác tin nhắn", "undo.undoing": "Đang hoàn tác…", "undo.retry": "Thử lại", + "undo.hidePending": "Ẩn thông báo (hoàn tác vẫn tiếp tục)", "undo.failed.expired": "Thao tác hoàn tác này đã hết hạn.", "undo.failed.unavailable": "Tin nhắn đó không còn khả dụng để hoàn tác.", "undo.failed.stale": "Không thể hoàn tác thay đổi này nữa vì tin nhắn đã thay đổi.", @@ -2447,18 +2448,18 @@ "undo.failed.server": "Hoàn tác không thành công. Vui lòng thử lại.", "undo.partialRestored": "Đã khôi phục {restored} trên {total} tin nhắn. Phần còn lại không thể hoàn tác.", "undo.successAnnouncement": "Hoàn tác hoàn tất: {action}.", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "Đã cập nhật {applied} trên {total} tin nhắn", + "undo.bulk.one": "{action} · {count} tin nhắn", + "undo.bulk.other": "{action} · {count} tin nhắn", + "undo.label.archive": "Đã lưu trữ", + "undo.label.trash": "Đã chuyển vào Thùng rác", + "undo.label.spam": "Đã chuyển vào Spam", + "undo.label.inbox": "Đã chuyển vào Hộp thư đến", + "undo.label.folder": "Đã chuyển vào thư mục", + "undo.label.read": "Đã đánh dấu là đã đọc", + "undo.label.unread": "Đã đánh dấu là chưa đọc", + "undo.label.star": "Đã gắn dấu sao", + "undo.label.unstar": "Đã bỏ dấu sao", + "undo.label.snooze": "Đã tạm hoãn", + "undo.label.unsnooze": "Đã hủy tạm hoãn" } diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.json index bfe8b1340..c8a612786 100644 --- a/public/locales/zh-CN.json +++ b/public/locales/zh-CN.json @@ -2434,12 +2434,13 @@ "actions.unsubscribeDeleteConfirm": "将此发件人的 {count} 封旧邮件移至垃圾箱?", "actions.unsubscribeTrashDone": "已退订,并将 {count} 封邮件移至垃圾箱", "attachment.downloadAllFlagged": "部分附件被标记为可能存在危险。仍要下载该压缩包吗?", - "undo.button": "Undo", - "undo.dismiss": "Dismiss", - "undo.failed": "Could not undo that change", + "undo.button": "撤销", + "undo.dismiss": "忽略", + "undo.failed": "无法撤销该更改", "undo.region": "邮件操作通知", "undo.undoing": "正在撤销…", "undo.retry": "重试", + "undo.hidePending": "隐藏通知(撤销仍在继续)", "undo.failed.expired": "此撤销已过期。", "undo.failed.unavailable": "该邮件已无法撤销。", "undo.failed.stale": "邮件已更改,因此此更改无法再撤销。", @@ -2447,18 +2448,18 @@ "undo.failed.server": "撤销失败。请重试。", "undo.partialRestored": "已恢复 {total} 封邮件中的 {restored} 封。其余邮件无法撤销。", "undo.successAnnouncement": "撤销完成:{action}。", - "undo.partial": "{applied} of {total} messages updated", - "undo.bulk.one": "{action} · {count} message", - "undo.bulk.other": "{action} · {count} messages", - "undo.label.archive": "Archived", - "undo.label.trash": "Moved to Trash", - "undo.label.spam": "Moved to Spam", - "undo.label.inbox": "Moved to Inbox", - "undo.label.folder": "Moved to folder", - "undo.label.read": "Marked as read", - "undo.label.unread": "Marked as unread", - "undo.label.star": "Starred", - "undo.label.unstar": "Unstarred", - "undo.label.snooze": "Snoozed", - "undo.label.unsnooze": "Unsnoozed" + "undo.partial": "已更新 {applied}/{total} 封邮件", + "undo.bulk.one": "{action} · {count} 封邮件", + "undo.bulk.other": "{action} · {count} 封邮件", + "undo.label.archive": "已归档", + "undo.label.trash": "已移至垃圾箱", + "undo.label.spam": "已移至垃圾邮件", + "undo.label.inbox": "已移至收件箱", + "undo.label.folder": "已移至文件夹", + "undo.label.read": "已标记为已读", + "undo.label.unread": "已标记为未读", + "undo.label.star": "已加星标", + "undo.label.unstar": "已取消星标", + "undo.label.snooze": "已暂停", + "undo.label.unsnooze": "已取消暂停" } diff --git a/src/components/messages/undo-toasts.tsx b/src/components/messages/undo-toasts.tsx index 47a5fc54b..d02841fbc 100644 --- a/src/components/messages/undo-toasts.tsx +++ b/src/components/messages/undo-toasts.tsx @@ -15,9 +15,12 @@ import { failUndoToast, getUndoAnnouncements, getUndoToasts, + hideUndoToast, partialUndoToast, pauseUndoToast, + pauseUndoToasts, resumeUndoToast, + resumeUndoToasts, subscribeUndoToasts, } from "@/lib/messages/actions/undo-store"; import type { @@ -54,28 +57,41 @@ const FAILURE_LABELS: Record = { const EMPTY_TOASTS: UndoToastEntry[] = []; const EMPTY_ANNOUNCEMENTS: UndoToastAnnouncement[] = []; -const MODAL_SELECTOR = '[role="dialog"][aria-modal="true"], [aria-modal="true"], dialog[open], .dialog-overlay'; +const BLOCKING_OVERLAY_SELECTOR = [ + '[role="dialog"][aria-modal="true"]', + '[aria-modal="true"]', + "dialog[open]", + ".dialog-overlay", + '[data-mobile-menu][aria-expanded="true"]', +].join(", "); +const INTERACTION_SELECTOR = `${BLOCKING_OVERLAY_SELECTOR}, #main-content[inert], #main-content[aria-hidden="true"]`; -/** Modal layers sit at z-50 and trap focus; the passive undo stack must not compete with them. */ -function hasOpenModal() { +/** A modal or mobile sidebar owns focus and must not be bypassed by toast cleanup. */ +function hasBlockingOverlay() { if (typeof document === "undefined") return false; - return !!document.querySelector(MODAL_SELECTOR); + return !!document.querySelector(BLOCKING_OVERLAY_SELECTOR); } -function subscribeModalState(onChange: () => void) { +/** A modal, mobile sidebar, assistant full-size view or hidden main surface owns interaction. */ +function hasInteractionHold() { + if (typeof document === "undefined") return false; + return !!document.querySelector(INTERACTION_SELECTOR); +} + +function subscribeInteractionState(onChange: () => void) { if (typeof document === "undefined") return () => undefined; const observer = new MutationObserver(onChange); observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, - attributeFilter: ["role", "aria-modal", "class", "open"], + attributeFilter: ["role", "aria-modal", "class", "open", "aria-expanded", "aria-hidden", "inert"], }); return () => observer.disconnect(); } -function useModalOpen() { - return useSyncExternalStore(subscribeModalState, hasOpenModal, () => false); +function useInteractionHeld() { + return useSyncExternalStore(subscribeInteractionState, hasInteractionHold, () => false); } function failureFromError(error: unknown): UndoToastFailure { @@ -131,16 +147,47 @@ function announcementText(t: Translator, announcement: UndoToastAnnouncement) { return appliedText(t, announcement.action, announcement.count, announcement.skipped); } +function isAvailableSurface(element: HTMLElement) { + if (!element.isConnected || element.closest("[inert], [hidden], [aria-hidden=\"true\"]")) return false; + const style = window.getComputedStyle(element); + return style.display !== "none" && style.visibility !== "hidden"; +} + +function focusVisibleAppSurface() { + const selectors = ["#main-content", "#email-assistant-panel", "[data-mobile-menu]", "main", '[role="main"]']; + for (const selector of selectors) { + const element = document.querySelector(selector); + if (!element || !isAvailableSurface(element)) continue; + if (!element.hasAttribute("tabindex") && !["BUTTON", "A", "INPUT", "TEXTAREA", "SELECT"].includes(element.tagName)) { + element.tabIndex = -1; + } + element.focus({ preventScroll: true }); + return; + } +} + /** - * After a toast button removes its own toast, keyboard focus would fall back to - * the document. Return it to the stable main landmark instead of losing it. + * After a toast action changes focus ownership, keep keyboard focus in the + * remaining receipt; only fall back to a visible app surface when it disappears. */ -function restoreFocusAfterRemoval() { +function restoreFocusAfterAction(entryId: number) { if (typeof window === "undefined") return; window.setTimeout(() => { const active = document.activeElement; if (active && active !== document.body && (active as HTMLElement).isConnected) return; - document.getElementById("main-content")?.focus({ preventScroll: true }); + if (hasBlockingOverlay()) return; + const toast = document.querySelector(`[data-undo-toast-id="${entryId}"]`); + if (toast && isAvailableSurface(toast)) { + const dismiss = toast.querySelector("[data-undo-dismiss]"); + if (dismiss && !dismiss.hasAttribute("disabled") && !dismiss.hasAttribute("aria-disabled")) { + dismiss.focus({ preventScroll: true }); + return; + } + if (!toast.hasAttribute("tabindex")) toast.tabIndex = -1; + toast.focus({ preventScroll: true }); + return; + } + focusVisibleAppSurface(); }, 0); } @@ -149,13 +196,29 @@ export function UndoToasts() { const { t } = useLanguage(); const toasts = useSyncExternalStore(subscribeUndoToasts, getUndoToasts, () => EMPTY_TOASTS); const announcements = useSyncExternalStore(subscribeUndoToasts, getUndoAnnouncements, () => EMPTY_ANNOUNCEMENTS); - const modalOpen = useModalOpen(); + const interactionHeld = useInteractionHeld(); const [polite, setPolite] = useState<{ text: string; sequence: number } | null>(null); const [assertive, setAssertive] = useState<{ text: string; sequence: number } | null>(null); // A late mount must not replay announcements that were already made. New // announcements always carry a higher sequence and are announced normally. const seenAnnouncement = useRef(announcements.at(-1)?.sequence ?? 0); + useEffect(() => { + if (interactionHeld) { + pauseUndoToasts("interaction"); + resumeUndoToasts("region"); + } else { + resumeUndoToasts("interaction"); + } + return () => resumeUndoToasts("interaction"); + }, [interactionHeld]); + + useEffect(() => { + if (toasts.length === 0) resumeUndoToasts("region"); + }, [toasts.length]); + + useEffect(() => () => resumeUndoToasts("region"), []); + useEffect(() => { const latest = announcements.at(-1)?.sequence ?? 0; const fresh = announcements.filter((item) => item.sequence > seenAnnouncement.current); @@ -187,29 +250,34 @@ export function UndoToasts() { if (restored === 0) { const failure = failureFromSkipped(result.skipped); failUndoToast(current.id, failure); - if (!failure.retryable) restoreFocusAfterRemoval(); + if (!failure.retryable) restoreFocusAfterAction(current.id); } else if (restored < total || result.skipped.length > 0) { partialUndoToast(current.id, { restored, skipped: undoSkipCount, skippedReasons: result.skipped.map((item) => item.reason), }); - restoreFocusAfterRemoval(); + restoreFocusAfterAction(current.id); } else { completeUndoToast(current.id); - restoreFocusAfterRemoval(); + restoreFocusAfterAction(current.id); } } catch (error) { const failure = failureFromError(error); failUndoToast(current.id, failure); // Retryable failures keep the same primary button, so focus stays put. - if (!failure.retryable) restoreFocusAfterRemoval(); + if (!failure.retryable) restoreFocusAfterAction(current.id); } } function dismiss(entry: UndoToastEntry) { dismissUndoToast(entry.id); - restoreFocusAfterRemoval(); + restoreFocusAfterAction(entry.id); + } + + function hide(entry: UndoToastEntry) { + hideUndoToast(entry.id); + restoreFocusAfterAction(entry.id); } return ( @@ -225,10 +293,17 @@ export function UndoToasts() { role="region" aria-label={t("undo.region")} tabIndex={0} - inert={modalOpen} - aria-hidden={modalOpen || undefined} + inert={interactionHeld} + aria-hidden={interactionHeld || undefined} + onFocusCapture={() => pauseUndoToasts("region")} + onBlurCapture={(event) => { + const next = event.relatedTarget; + if (!next || !event.currentTarget.contains(next as Node)) { + resumeUndoToasts("region"); + } + }} className={cn( - "pointer-events-none fixed z-40 flex max-h-[calc(100dvh-6rem)] w-[calc(100vw-1.5rem)] flex-col gap-2 overflow-y-auto overscroll-contain rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600/60", + "pointer-events-none fixed z-30 flex max-h-[calc(100dvh-6rem)] w-[calc(100vw-1.5rem)] flex-col gap-2 overflow-y-auto overscroll-contain rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600/60", "inset-x-3 bottom-[max(5rem,calc(env(safe-area-inset-bottom,0px)+4.5rem))]", "md:bottom-4 md:w-[min(24rem,calc(100vw-var(--sidebar-width,260px)-2rem))] md:[inset-inline-end:auto] md:[inset-inline-start:calc(var(--sidebar-width,260px)+1rem)]", )} @@ -256,20 +331,13 @@ export function UndoToasts() { aria-labelledby={messageId} aria-busy={undoing || undefined} data-undo-toast-id={entry.id} - onFocusCapture={() => pauseUndoToast(entry.id, "focus")} - onBlurCapture={(event) => { - const next = event.relatedTarget; - if (!next || !(event.currentTarget as HTMLElement).contains(next as Node)) { - resumeUndoToast(entry.id, "focus"); - } - }} onPointerEnter={() => pauseUndoToast(entry.id, "hover")} onPointerLeave={() => resumeUndoToast(entry.id, "hover")} className={cn( "flex items-start gap-3 rounded-xl px-3 py-2.5 text-sm font-medium text-white shadow-lg ring-1 ring-black/10 backdrop-blur-sm", "pointer-events-auto focus-within:ring-2 focus-within:ring-white/80", failed ? "bg-red-700" : partial ? "bg-amber-800" : "bg-neutral-900/95", - modalOpen && "pointer-events-none", + interactionHeld && "pointer-events-none", )} >
@@ -301,16 +369,29 @@ export function UndoToasts() { {undoing ? t("undo.undoing") : retryable ? t("undo.retry") : t("undo.button")} )} - + {undoing ? ( + + ) : ( + + )}
); })} diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json index 6fa2bb189..38ae20dd7 100644 --- a/src/lib/i18n/en.json +++ b/src/lib/i18n/en.json @@ -2462,6 +2462,7 @@ "undo.region": "Message action notifications", "undo.undoing": "Undoing…", "undo.retry": "Try again", + "undo.hidePending": "Hide notification (undo continues)", "undo.failed": "Could not undo that change", "undo.failed.expired": "This undo has expired.", "undo.failed.unavailable": "That message is no longer available to undo.", diff --git a/src/lib/messages/actions/undo-store.ts b/src/lib/messages/actions/undo-store.ts index c3e9a9ef1..b9a9c9b15 100644 --- a/src/lib/messages/actions/undo-store.ts +++ b/src/lib/messages/actions/undo-store.ts @@ -32,6 +32,8 @@ export type UndoToastEntry = { status: UndoToastStatus; /** Optional human-readable folder name or snooze time supplied by the caller. */ context?: string; + /** Set only while this entry waits for a visible slot; bounds stale queue lifetime. */ + queuedAt?: number; failure?: UndoToastFailure; /** Set when Undo restored only some of the action's messages. */ restored?: number; @@ -64,6 +66,9 @@ export const UNDO_TOAST_LIMITS = Object.freeze({ /** Long enough to reach the notification with a keyboard, and it pauses while hovered, focused or hidden. */ export const UNDO_WINDOW_MS = 20_000; +/** Queued entries must be promoted before their signed token can expire (server maximum: 10 minutes). */ +export const QUEUE_MAX_AGE_MS = 8 * 60_000; + const MAX_ANNOUNCEMENTS = 20; let entries: UndoToastEntry[] = []; @@ -73,10 +78,12 @@ let nextId = 0; let nextAnnouncementId = 0; let pageHidden = false; let lifecycleBound = false; +let queueExpiryTimer: number | null = null; const listeners = new Set<() => void>(); const timers = new Map(); const remaining = new Map(); const pauseReasons = new Map>(); +const globalPauseReasons = new Set(); function emit() { for (const listener of listeners) listener(); @@ -98,8 +105,19 @@ function announce(announcement: Omit) { ]; } +function announceApplied(entry: UndoToastEntry) { + announce({ + kind: "applied", + action: entry.action, + count: entry.records.length, + skipped: entry.skipped, + }); +} + function timerIsHeld(id: number): boolean { - return pageHidden || (pauseReasons.get(id)?.size ?? 0) > 0; + return pageHidden + || globalPauseReasons.size > 0 + || (pauseReasons.get(id)?.size ?? 0) > 0; } function clearTimer(id: number) { @@ -154,10 +172,39 @@ function startVisibleTimer(id: number) { function promoteQueued() { if (queued.length === 0 || entries.length >= UNDO_TOAST_LIMITS.visible) return; - const promoted = queued[0]; + const promoted = { ...queued[0] }; + delete promoted.queuedAt; queued = queued.slice(1); entries = [...entries, promoted]; startVisibleTimer(promoted.id); + announceApplied(promoted); + scheduleQueueExpiry(); +} + +function clearQueueExpiry() { + if (queueExpiryTimer !== null && typeof window !== "undefined") { + window.clearTimeout(queueExpiryTimer); + } + queueExpiryTimer = null; +} + +function pruneExpiredQueued(now: number): boolean { + const next = queued.filter((entry) => now - (entry.queuedAt ?? now) < QUEUE_MAX_AGE_MS); + if (next.length === queued.length) return false; + queued = next; + return true; +} + +function scheduleQueueExpiry() { + clearQueueExpiry(); + if (typeof window === "undefined" || queued.length === 0) return; + const nextAt = Math.min(...queued.map((entry) => (entry.queuedAt ?? Date.now()) + QUEUE_MAX_AGE_MS)); + const delay = Math.max(0, nextAt - Date.now()); + queueExpiryTimer = window.setTimeout(() => { + queueExpiryTimer = null; + if (pruneExpiredQueued(Date.now())) emit(); + scheduleQueueExpiry(); + }, delay); } function removeEntry(id: number) { @@ -166,16 +213,19 @@ function removeEntry(id: number) { entries = entries.filter((entry) => entry.id !== id); queued = queued.filter((entry) => entry.id !== id); promoteQueued(); + scheduleQueueExpiry(); } function updatePageHidden(hidden: boolean) { if (pageHidden === hidden) return; pageHidden = hidden; + if (!hidden && pruneExpiredQueued(Date.now())) emit(); for (const entry of entries) { if (entry.status !== "idle") continue; if (hidden) pauseTimer(entry.id); else if (!timerIsHeld(entry.id)) scheduleTimer(entry.id, remaining.get(entry.id) ?? UNDO_WINDOW_MS); } + if (!hidden) scheduleQueueExpiry(); } function bindLifecycle() { @@ -207,6 +257,26 @@ export function getUndoAnnouncements(): UndoToastAnnouncement[] { return announcements; } +function oldestTerminalReceipt(): UndoToastEntry | undefined { + return entries + .filter((entry) => entry.status === "failed" || entry.status === "partial") + .sort((a, b) => a.id - b.id)[0]; +} + +function oldestRedundantTerminalReceipt(): UndoToastEntry | undefined { + const terminals = entries + .filter((entry) => entry.status === "failed" || entry.status === "partial") + .sort((a, b) => a.id - b.id); + return terminals.length > 1 ? terminals[0] : undefined; +} + +/** A receipt turning terminal must not leave an older actionable undo stuck in the queue. */ +function ensureQueuedVisible() { + if (queued.length === 0 || entries.length < UNDO_TOAST_LIMITS.visible) return; + const terminal = oldestRedundantTerminalReceipt(); + if (terminal) removeEntry(terminal.id); +} + /** Adds an independent toast; compose's single send notice is never touched. */ export function showUndoToast(input: { action: ReversibleMessageAction; @@ -228,21 +298,24 @@ export function showUndoToast(input: { status: "idle", ...(input.context ? { context: input.context } : {}), }; + if (entries.length >= UNDO_TOAST_LIMITS.visible) { + // Terminal receipts are acknowledgements, not live undo affordances. Under + // pressure the oldest one yields so a new action (or the queued action + // behind it) is actually reachable. + const terminal = oldestTerminalReceipt(); + if (terminal) removeEntry(terminal.id); + } if (entries.length < UNDO_TOAST_LIMITS.visible) { entries = [...entries, entry]; startVisibleTimer(id); + announceApplied(entry); } else { // Keep the newest notices. The oldest queued entry is still an action the // user just made, so this only happens after a long burst of read/star // chatter; the visible stack itself is never silently replaced. - queued = [...queued, entry].slice(-UNDO_TOAST_LIMITS.queued); + queued = [...queued, { ...entry, queuedAt: Date.now() }].slice(-UNDO_TOAST_LIMITS.queued); + scheduleQueueExpiry(); } - announce({ - kind: "applied", - action: entry.action, - count: entry.records.length, - skipped: entry.skipped, - }); emit(); return id; } @@ -280,6 +353,7 @@ export function failUndoToast( undoSkippedReasons: undefined, })); announce({ kind: "undo-failed", action: entry.action, count: entry.records.length, failure }); + ensureQueuedVisible(); emit(); } @@ -306,6 +380,7 @@ export function partialUndoToast( count: entry.records.length, restored: result.restored, }); + ensureQueuedVisible(); emit(); } @@ -313,8 +388,8 @@ export function partialUndoToast( export function completeUndoToast(id: number) { const entry = entryById(id); if (!entry) return; - removeEntry(id); announce({ kind: "undo-success", action: entry.action, count: entry.records.length }); + removeEntry(id); emit(); } @@ -324,6 +399,13 @@ export function dismissUndoToast(id: number) { emit(); } +/** Hides a pending notice without pretending the in-flight Undo was cancelled. */ +export function hideUndoToast(id: number) { + if (!entryById(id)) return; + removeEntry(id); + emit(); +} + export function pauseUndoToast(id: number, reason = "hold") { const entry = entryById(id); if (!entry || entry.status !== "idle") return; @@ -345,9 +427,28 @@ export function resumeUndoToast(id: number, reason = "hold") { scheduleTimer(id, remaining.get(id) ?? UNDO_WINDOW_MS); } +/** Holds every idle countdown while a modal, overlay, region focus or hidden app surface owns interaction. */ +export function pauseUndoToasts(reason = "hold") { + const wasHeld = globalPauseReasons.size > 0; + globalPauseReasons.add(reason); + if (wasHeld) return; + for (const entry of entries) { + if (entry.status === "idle") pauseTimer(entry.id); + } +} + +export function resumeUndoToasts(reason = "hold") { + if (!globalPauseReasons.delete(reason) || globalPauseReasons.size > 0) return; + for (const entry of entries) { + if (entry.status !== "idle" || timerIsHeld(entry.id)) continue; + scheduleTimer(entry.id, remaining.get(entry.id) ?? UNDO_WINDOW_MS); + } +} + /** Clears every queue and timer on an account/session change. */ export function resetUndoToasts() { for (const id of [...timers.keys()]) clearTimer(id); + clearQueueExpiry(); entries = []; queued = []; announcements = []; @@ -362,4 +463,5 @@ export function resetUndoToastsForTests() { nextId = 0; nextAnnouncementId = 0; pageHidden = false; + globalPauseReasons.clear(); } diff --git a/tests/message-undo-toast-store.test.mjs b/tests/message-undo-toast-store.test.mjs index 9c79cb6aa..da4445283 100644 --- a/tests/message-undo-toast-store.test.mjs +++ b/tests/message-undo-toast-store.test.mjs @@ -143,6 +143,21 @@ test("a hidden tab pauses every idle countdown until it becomes visible", () => assert.equal(store.getUndoToasts().length, 0); }); +test("a global interaction hold pauses every idle countdown until interaction ends", () => { + const first = add(1); + const second = add(2); + advance(3_000); + store.pauseUndoToasts("modal"); + advance(90_000); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), [first, second]); + + store.resumeUndoToasts("modal"); + advance(16_999); + assert.equal(store.getUndoToasts().length, 2); + advance(1); + assert.equal(store.getUndoToasts().length, 0); +}); + test("expiry never removes a toast that owns keyboard focus", () => { const id = add(1); const holder = document.createElement("div"); @@ -168,6 +183,7 @@ test("visible toasts stay capped while active entries queue, and queued timers s assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids.slice(0, 4)); assert.deepEqual(store.getQueuedUndoToasts().map((entry) => entry.id), ids.slice(4)); assert.deepEqual(store.getQueuedUndoToasts().map((entry) => entry.action), ["read", "star", "read"]); + assert.equal(store.getUndoAnnouncements().length, 4, "queued notices are not announced before they are visible"); advance(store.UNDO_WINDOW_MS); assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids.slice(4)); @@ -179,6 +195,66 @@ test("visible toasts stay capped while active entries queue, and queued timers s assert.equal(store.getUndoToasts().length, 0); }); +test("a queued notice is announced only when it takes a visible slot", () => { + const ids = [1, 2, 3, 4, 5].map((id) => add(id)); + assert.equal(store.getUndoAnnouncements().length, 4); + + store.dismissUndoToast(ids[0]); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids.slice(1)); + const announcement = store.getUndoAnnouncements().at(-1); + assert.equal(announcement.kind, "applied"); + assert.equal(announcement.action, "read"); +}); + +test("queued notices expire before their signed token can age out", () => { + for (const id of [1, 2, 3, 4]) add(id); + const queuedId = add(5); + assert.equal(store.getQueuedUndoToasts().length, 1); + assert.ok(store.QUEUE_MAX_AGE_MS <= 10 * 60_000); + assert.equal(store.getUndoAnnouncements().length, 4); + + store.pauseUndoToasts("test-hold"); + advance(store.QUEUE_MAX_AGE_MS - 1); + assert.deepEqual(store.getQueuedUndoToasts().map((entry) => entry.id), [queuedId]); + advance(1); + assert.equal(store.getQueuedUndoToasts().length, 0, "a stale queued token is not kept forever"); + assert.equal(store.getUndoToasts().length, 4); + assert.equal(store.getUndoAnnouncements().length, 4, "an entry that never became visible is not announced"); + store.resumeUndoToasts("test-hold"); +}); + +test("terminal receipts yield a visible slot when a new action needs one", () => { + const ids = [1, 2, 3, 4].map((id) => add(id)); + for (const id of ids) { + store.beginUndoToast(id); + store.failUndoToast(id, { kind: "stale", retryable: false }); + } + assert.equal(store.getUndoToasts().filter((entry) => entry.status === "failed").length, 4); + + const fresh = add(5); + assert.deepEqual( + store.getUndoToasts().map((entry) => entry.id), + [ids[1], ids[2], ids[3], fresh], + "the oldest failure acknowledgement is retired, the newest receipt remains", + ); + assert.equal(store.getUndoToasts().filter((entry) => entry.status === "failed").length, 3); + assert.equal(store.getUndoAnnouncements().at(-1).kind, "applied"); +}); + +test("a terminal receipt turning while an undo is queued promotes the active undo and keeps one ack", () => { + const ids = [1, 2, 3, 4].map((id) => add(id)); + const queuedId = add(5); + store.beginUndoToast(ids[0]); + store.failUndoToast(ids[0], { kind: "stale", retryable: false }); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), ids); + assert.equal(store.getQueuedUndoToasts()[0].id, queuedId, "the first failure receipt is acknowledged"); + + store.beginUndoToast(ids[1]); + store.failUndoToast(ids[1], { kind: "stale", retryable: false }); + assert.deepEqual(store.getUndoToasts().map((entry) => entry.id), [ids[1], ids[2], ids[3], queuedId]); + assert.equal(store.getQueuedUndoToasts().length, 0); +}); + test("the overflow queue is bounded but never replaces the visible stack", () => { const ids = Array.from({ length: 4 + store.UNDO_TOAST_LIMITS.queued + 1 }, (_, index) => add(index + 1)); assert.equal(store.getUndoToasts().length, store.UNDO_TOAST_LIMITS.visible); diff --git a/tests/message-undo-toast-ui.test.mjs b/tests/message-undo-toast-ui.test.mjs index 7c86efe99..817818aa4 100644 --- a/tests/message-undo-toast-ui.test.mjs +++ b/tests/message-undo-toast-ui.test.mjs @@ -145,6 +145,42 @@ function buttonByText(container, text) { return [...container.querySelectorAll("button")].find((button) => button.textContent.trim() === text); } +function installWindowClock() { + const originalSetTimeout = window.setTimeout; + const originalClearTimeout = window.clearTimeout; + const originalNow = Date.now; + let now = 1_000; + let nextId = 0; + let timers = []; + window.setTimeout = (callback, delay = 0) => { + const id = ++nextId; + timers.push({ id, at: now + Number(delay), callback }); + return id; + }; + window.clearTimeout = (id) => { + timers = timers.filter((timer) => timer.id !== id); + }; + Date.now = () => now; + return { + advance(ms) { + now += ms; + for (;;) { + const due = timers + .filter((timer) => timer.at <= now) + .sort((a, b) => a.at - b.at || a.id - b.id)[0]; + if (!due) return; + timers = timers.filter((timer) => timer !== due); + due.callback(); + } + }, + restore() { + window.setTimeout = originalSetTimeout; + window.clearTimeout = originalClearTimeout; + Date.now = originalNow; + }, + }; +} + test("live regions stay mounted while empty and applied actions announce politely", async (t) => { const app = await mount(t); const status = app.container.querySelector('[role="status"]'); @@ -178,7 +214,7 @@ test("the stack anchors in the content column, clears the mobile compose button assert.equal(region.tabIndex, 0); assert.equal(region.getAttribute("aria-label"), "Message action notifications"); const classes = region.className; - assert.match(classes, /z-40/); + assert.match(classes, /z-30/); assert.match(classes, /--sidebar-width/); assert.match(classes, /bottom-\[max\(5rem/); assert.match(classes, /env\(safe-area-inset-bottom/); @@ -189,7 +225,7 @@ test("the stack anchors in the content column, clears the mobile compose button assert.match(close.className, /focus-visible:ring-2/); }); -test("undo pending shows a spinner and busy label, and locks dismissal", async (t) => { +test("undo pending shows a spinner and busy label with a hide action", async (t) => { const app = await mount(t); let finish; globalThis.undoHandler = () => new Promise((resolve) => { finish = resolve; }); @@ -204,8 +240,9 @@ test("undo pending shows a spinner and busy label, and locks dismissal", async ( assert.equal(card.getAttribute("aria-busy"), "true"); assert.match(card.textContent, /Undoing…/); assert.equal(buttonByText(card, "Undoing…").getAttribute("aria-disabled"), "true"); - const close = card.querySelector('button[aria-label="Dismiss"]'); - assert.equal(close.disabled, true, "dismiss cannot pretend to cancel a request already in flight"); + const hide = card.querySelector('button[aria-label="Hide notification (undo continues)"]'); + assert.ok(hide, "a pending notice can be hidden without pretending to cancel it"); + assert.equal(hide.disabled, false); assert.ok(card.querySelector(".animate-spin")); await act(async () => { finish({ ok: true, action: "archive", restored: ["m1"], skipped: [] }); }); @@ -215,6 +252,27 @@ test("undo pending shows a spinner and busy label, and locks dismissal", async ( assert.equal(document.activeElement, document.getElementById("main-content")); }); +test("hiding a pending notice removes it while Undo continues", async (t) => { + const app = await mount(t); + let finish; + globalThis.undoHandler = () => new Promise((resolve) => { finish = resolve; }); + const id = await act(async () => show()); + await ui.flush(); + + await act(async () => { buttonByText(toast(app.container, id), "Undo").click(); }); + await ui.flush(); + const hide = toast(app.container, id).querySelector('button[aria-label="Hide notification (undo continues)"]'); + hide.focus(); + await act(async () => { hide.click(); }); + await ui.flush(); + assert.equal(toast(app.container, id), null); + assert.equal(document.activeElement, document.getElementById("main-content")); + + await act(async () => { finish({ ok: true, action: "archive", restored: ["m1"], skipped: [] }); }); + await ui.flush(); + assert.equal(toast(app.container, id), null); +}); + test("a transient server failure persists and Retry starts the same undo again", async (t) => { const app = await mount(t); let attempt = 0; @@ -255,6 +313,7 @@ test("expired undos persist without Retry and announce the actual reason", async assert.ok(card); assert.match(card.textContent, /This undo has expired\./); assert.equal(buttonByText(card, "Try again"), undefined); + assert.equal(document.activeElement, card.querySelector("[data-undo-dismiss]")); assert.match(app.container.querySelector('[role="alert"]').textContent, /This undo has expired/); }); @@ -296,6 +355,7 @@ test("a partial restore shows its own notice and announcement, not full success" assert.ok(card, "a partial restore stays visible"); assert.match(card.textContent, /1 of 2 messages restored\. The rest could not be undone\./); assert.equal(buttonByText(card, "Try again"), undefined, "retrying the whole token is not offered after a partial restore"); + assert.equal(document.activeElement, card.querySelector("[data-undo-dismiss]"), "focus stays on the receipt"); assert.match(app.container.querySelector('[role="alert"]').textContent, /1 of 2 messages restored/); assert.doesNotMatch(app.container.querySelector('[role="status"]').textContent, /Undo complete/); }); @@ -315,6 +375,112 @@ test("dismissing removes a toast and returns focus to main content", async (t) = assert.equal(document.activeElement, document.getElementById("main-content")); }); +test("focus falls back to a visible app surface when main is inert", async (t) => { + const app = await mount(t); + const assistant = document.createElement("section"); + assistant.id = "email-assistant-panel"; + document.body.appendChild(assistant); + const id = await act(async () => show()); + await ui.flush(); + const close = toast(app.container, id).querySelector('button[aria-label="Dismiss"]'); + close.focus(); + + await act(async () => { + close.click(); + const main = document.getElementById("main-content"); + main.setAttribute("inert", ""); + main.setAttribute("aria-hidden", "true"); + }); + await ui.flush(); + assert.equal(toast(app.container, id), null); + assert.equal(document.activeElement, assistant); + assistant.remove(); +}); + +test("focusing the notification region pauses every countdown", async (t) => { + const app = await mount(t); + const clock = installWindowClock(); + t.after(() => clock.restore()); + const id = await act(async () => show()); + await ui.flush(); + const region = app.container.querySelector('[role="region"]'); + region.focus(); + assert.equal(document.activeElement, region); + + await act(async () => { clock.advance(60_000); }); + assert.ok(toast(app.container, id), "a focused region holds all undo countdowns"); + + const outside = document.createElement("button"); + document.body.appendChild(outside); + outside.focus(); + await act(async () => { clock.advance(19_999); }); + assert.ok(toast(app.container, id)); + await act(async () => { clock.advance(1); }); + assert.equal(toast(app.container, id), null); + outside.remove(); +}); + +test("a modal, mobile sidebar or hidden main surface holds idle countdowns", async (t) => { + const app = await mount(t); + const clock = installWindowClock(); + t.after(() => clock.restore()); + const id = await act(async () => show()); + await ui.flush(); + const region = app.container.querySelector('[role="region"]'); + assert.equal(region.hasAttribute("inert"), false); + + const overlay = document.createElement("div"); + overlay.className = "dialog-overlay"; + document.body.appendChild(overlay); + await ui.flush(); + assert.equal(region.hasAttribute("inert"), true); + await act(async () => { clock.advance(60_000); }); + assert.ok(toast(app.container, id), "a modal holds the countdown"); + + const mobileMenu = document.createElement("button"); + mobileMenu.dataset.mobileMenu = ""; + mobileMenu.setAttribute("aria-expanded", "true"); + document.body.appendChild(mobileMenu); + overlay.remove(); + await ui.flush(); + assert.equal(region.hasAttribute("inert"), true, "the mobile sidebar still owns interaction"); + await act(async () => { clock.advance(60_000); }); + assert.ok(toast(app.container, id)); + + mobileMenu.setAttribute("aria-expanded", "false"); + await ui.flush(); + assert.equal(region.hasAttribute("inert"), false); + await act(async () => { clock.advance(19_999); }); + assert.ok(toast(app.container, id)); + await act(async () => { clock.advance(1); }); + assert.equal(toast(app.container, id), null); + mobileMenu.remove(); +}); + +test("an inert or hidden main surface also holds idle countdowns", async (t) => { + const app = await mount(t); + const clock = installWindowClock(); + t.after(() => clock.restore()); + const id = await act(async () => show()); + await ui.flush(); + const main = document.getElementById("main-content"); + main.setAttribute("inert", ""); + main.setAttribute("aria-hidden", "true"); + await ui.flush(); + const region = app.container.querySelector('[role="region"]'); + assert.equal(region.hasAttribute("inert"), true); + await act(async () => { clock.advance(60_000); }); + assert.ok(toast(app.container, id)); + + main.removeAttribute("inert"); + main.removeAttribute("aria-hidden"); + await ui.flush(); + await act(async () => { clock.advance(19_999); }); + assert.ok(toast(app.container, id)); + await act(async () => { clock.advance(1); }); + assert.equal(toast(app.container, id), null); +}); + test("the passive stack becomes inert and hidden from assistive tech while a modal is open", async (t) => { const app = await mount(t); await act(async () => show()); From d17e1def07ceb58543796fbf601f0177e29a43dc Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 22:32:48 +0100 Subject: [PATCH 10/15] fix(messages): isolate grouped member and reader undo state --- .../(dashboard)/inbox/[messageId]/page.tsx | 32 ++++++--- src/hooks/utils.ts | 12 ++-- src/lib/messages/actions/client.ts | 27 ++++++- src/lib/messages/actions/executor.ts | 11 +-- src/lib/messages/field-store.ts | 34 ++++++++- tests/e2e/message-undo.spec.ts | 43 ++++++++++++ tests/message-action-pending-caches.test.mjs | 70 ++++++++++++++++++- tests/message-action-pending-hooks.test.mjs | 4 +- 8 files changed, 206 insertions(+), 27 deletions(-) diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx index f8bcf252b..6e8dfb97f 100644 --- a/src/app/(dashboard)/inbox/[messageId]/page.tsx +++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx @@ -3,7 +3,7 @@ import { confirmDestructive } from "@/components/ui/confirm-dialog"; import { authFetch } from "@/lib/auth/client"; import { useParams } from "next/navigation"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ArrowDownToLine, Cloud, ExternalLink } from "@/components/icons"; import { useLanguage } from "@/components/language-provider"; import { formatUserDate } from "@/lib/time/utils"; @@ -102,6 +102,17 @@ function MessageDetailContent({ messageId }: { messageId: string }) { const isAnyPanelVisible = messageListVisible || assistantVisible; const { scrollRef, scrolled, handleScroll } = useMessageContentScroll(messageId, loading); const [unsubBannerDismissed, dismissUnsubBanner] = useMailingListBanner(messageId); + // A browser/server response can race the explicit read this reader sends when + // opening an unread message. Only that operation may preserve read=true. + const openingRead = useRef(false); + + function markMessageReadOnOpen(id: string) { + if (openingRead.current) return; + openingRead.current = true; + void markMessageRead(id).finally(() => { + openingRead.current = false; + }); + } useEffect(() => { let cancelled = false; @@ -111,7 +122,7 @@ function MessageDetailContent({ messageId }: { messageId: string }) { if (cachedData?.message) { setData(cachedData); setLoading(false); - if (!cachedData.message.read) void markMessageRead(cachedData.message.id); + if (!cachedData.message.read) markMessageReadOnOpen(cachedData.message.id); if (cachedData.body) { setBodyPending(false); if (cachedData.attachments !== undefined) return; @@ -126,9 +137,9 @@ function MessageDetailContent({ messageId }: { messageId: string }) { try { const full = await fetchMessageDetail(messageId, true); if (!cancelled) { - setData((current) => { - // A prefetched body may predate the read flip. - if (current?.message?.read && full.message) return { ...full, message: { ...full.message, read: true } }; + setData(() => { + // A prefetched body may predate the opening read request. + if (openingRead.current && full.message) return { ...full, message: { ...full.message, read: true } }; return full; }); setBodyPending(false); @@ -146,7 +157,7 @@ function MessageDetailContent({ messageId }: { messageId: string }) { if (!cancelled) { setData(nextData); setLoading(false); - if ("message" in nextData && nextData.message && !nextData.message.read) void markMessageRead(nextData.message.id); + if ("message" in nextData && nextData.message && !nextData.message.read) markMessageReadOnOpen(nextData.message.id); } } @@ -169,8 +180,9 @@ function MessageDetailContent({ messageId }: { messageId: string }) { const nextMessage = nextData.message; setData((current) => { if (!current?.message) return nextData; - // A read flip from opening this message may still be in flight. - const keepRead = current.message.read && !nextMessage.read; + // Only the explicit opening read may still be in flight; a + // legitimate unread/timeout result must remain unread. + const keepRead = openingRead.current; return { ...nextData, message: keepRead ? { ...nextMessage, read: true } : nextMessage }; }); }).catch(() => undefined); @@ -210,8 +222,8 @@ function MessageDetailContent({ messageId }: { messageId: string }) { setBodyError(false); try { const full = await fetchMessageDetail(messageId, true); - setData((current) => { - if (current?.message?.read && full.message) return { ...full, message: { ...full.message, read: true } }; + setData(() => { + if (openingRead.current && full.message) return { ...full, message: { ...full.message, read: true } }; return full; }); setBodyPending(false); diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts index 78cb0514e..15e393d99 100644 --- a/src/hooks/utils.ts +++ b/src/hooks/utils.ts @@ -135,11 +135,12 @@ export function patchMessageFieldsInCaches( options: MessageCachePatchOptions = {}, ): ThreadUnreadTarget[] { const patches = groupFieldPatches(fields); - if (patches.size === 0) return []; - const computedTargets = getThreadUnreadTargets([...patches].map(([id, patch]) => ({ - id, - ...(patch.read !== undefined ? { read: patch.read } : {}), - }))); + const computedTargets = patches.size === 0 + ? [] + : getThreadUnreadTargets([...patches].map(([id, patch]) => ({ + id, + ...(patch.read !== undefined ? { read: patch.read } : {}), + }))); const forcedTargets = options.threadTargets ? new Map([...options.threadTargets].map((target) => [target.id, target.threadUnread])) : null; @@ -154,6 +155,7 @@ export function patchMessageFieldsInCaches( } } } + if (patches.size === 0 && targets.length === 0) return []; const targetsById = new Map(targets.map((target) => [target.id, target.threadUnread])); const ids = new Set(patches.keys()); invalidateMessageListRequests(); diff --git a/src/lib/messages/actions/client.ts b/src/lib/messages/actions/client.ts index b7ed5b6d8..27be34494 100644 --- a/src/lib/messages/actions/client.ts +++ b/src/lib/messages/actions/client.ts @@ -7,6 +7,7 @@ import { captureMessageFields, captureThreadUnread, clearPendingOverlay, + forgetMessageFields, setPendingOverlay, type KnownMessageFields, type PendingOverlayMessage, @@ -140,24 +141,43 @@ function applyFieldChanges( fields: PendingOverlayMessage[], threadTargets?: Map, ): ThreadUnreadTarget[] { - if (fields.length === 0) return []; + if (fields.length === 0 && !threadTargets?.size) return []; const targets = patchMessageFieldsInCaches( fields, threadTargets ? { threadTargets: [...threadTargets].map(([id, threadUnread]) => ({ id, threadUnread })), } : undefined, ); - dispatchFieldChanges(fields, targets); + if (fields.length > 0) dispatchFieldChanges(fields, targets); return targets; } +function forgetUncapturedFields( + records: MessageActionRecord[], + captured: Map, +) { + const readIds: string[] = []; + const starredIds: string[] = []; + for (const record of records) { + const changed = new Set(getChangedStateFields(record.previous, record.applied)); + const known = captured.get(record.id); + if (changed.has("read") && known?.read === undefined) readIds.push(record.id); + if (changed.has("starred") && known?.starred === undefined) starredIds.push(record.id); + } + if (readIds.length > 0) forgetMessageFields(readIds, { read: true }); + if (starredIds.length > 0) forgetMessageFields(starredIds, { starred: true }); +} + function restoreCaptured( records: MessageActionRecord[], captured: Map, capturedThreads?: Map, ) { + forgetUncapturedFields(records, captured); const fields = capturedFieldPatches(records, captured); - const hasReadChange = fields.some((field) => field.read !== undefined); + const hasReadChange = records.some((record) => ( + getChangedStateFields(record.previous, record.applied).includes("read") + )); applyFieldChanges(fields, hasReadChange ? capturedThreads : undefined); } @@ -274,6 +294,7 @@ export const defaultMessageActionHooks: MessageActionExecutorHooks = { if (isUncertainActionFailure(error)) { // The timeout may have committed the undo on the server. Do not paint // the historical pre-click value; let the resync fetch decide. + forgetUncapturedFields(records, captured); invalidateUncertainState(ids); return; } diff --git a/src/lib/messages/actions/executor.ts b/src/lib/messages/actions/executor.ts index 39cb8d3a6..5c44f9617 100644 --- a/src/lib/messages/actions/executor.ts +++ b/src/lib/messages/actions/executor.ts @@ -1,5 +1,5 @@ import { getChangedStateFields, recordHasChanges } from "./definitions"; -import type { KnownMessageFields } from "@/lib/messages/field-store"; +import { getConversationLockKeys, type KnownMessageFields } from "@/lib/messages/field-store"; import type { MessageActionInput, MessageActionRecord, @@ -48,9 +48,10 @@ export type MessageActionExecutorHooks = { }; /** - * Serializes actions per message id while letting unrelated messages proceed - * in parallel. A second action on the same message (including an undo) waits - * for the first response, so snapshots and UI patches cannot interleave. + * Serializes actions per message id, extended to the whole known conversation. + * A second action on any member (including an undo) waits for the first + * response, so grouped aggregate snapshots and optimistic targets cannot + * overlap. Actions in unrelated conversations still proceed in parallel. */ export class MessageActionExecutor { private readonly tails = new Map>(); @@ -116,7 +117,7 @@ export class MessageActionExecutor { } private withLocks(ids: string[], task: () => Promise): Promise { - const keys = [...new Set(ids)]; + const keys = getConversationLockKeys(ids); const previous = keys .map((key) => this.tails.get(key)) .filter((tail): tail is Promise => !!tail); diff --git a/src/lib/messages/field-store.ts b/src/lib/messages/field-store.ts index de0701005..3a4934ef5 100644 --- a/src/lib/messages/field-store.ts +++ b/src/lib/messages/field-store.ts @@ -75,6 +75,17 @@ export function rememberMessageFields(messageIds: string[], patch: KnownMessageF } } +/** Drops optimistic member state when a rollback has no trusted snapshot. */ +export function forgetMessageFields(messageIds: string[], fields: KnownMessageFields): void { + for (const id of messageIds) { + const current = knownFields.get(id); + if (!current) continue; + if (fields.read) delete current.read; + if (fields.starred) delete current.starred; + if (current.read === undefined && current.starred === undefined) knownFields.delete(id); + } +} + export function rememberMessageRows(rows: Array<{ id: string; read?: boolean; @@ -83,9 +94,13 @@ export function rememberMessageRows(rows: Array<{ threadUnread?: number; }>): void { for (const row of rows) { - if (row.read !== undefined || row.starred !== undefined) { + const grouped = !!row.threadMessageIds?.length; + if ((row.read !== undefined && !grouped) || row.starred !== undefined) { rememberMessageFields([row.id], { - ...(row.read !== undefined ? { read: row.read } : {}), + // A grouped row's read flag is a conversation aggregate, not the + // anchor message's own state. Seeding it would make an unknown + // member look already-unread/read and corrupt later flips. + ...(row.read !== undefined && !grouped ? { read: row.read } : {}), ...(row.starred !== undefined ? { starred: row.starred } : {}), }); } @@ -99,6 +114,21 @@ export function rememberMessageRows(rows: Array<{ } } +/** + * Any action touching a member of a known conversation joins the same lock + * group. This keeps optimistic grouped aggregates and their rollback + * snapshots from overlapping inside one conversation. + */ +export function getConversationLockKeys(ids: string[]): string[] { + const keys = new Set(ids); + for (const [rowId, row] of knownThreads) { + if (!keys.has(rowId) && !row.messageIds.some((id) => keys.has(id))) continue; + keys.add(rowId); + for (const id of row.messageIds) keys.add(id); + } + return [...keys]; +} + function pendingFieldsFor(messageId: string): KnownMessageFields { const fields: KnownMessageFields = {}; for (const layer of pendingLayers.values()) { diff --git a/tests/e2e/message-undo.spec.ts b/tests/e2e/message-undo.spec.ts index 425cc5d85..1d955e4e8 100644 --- a/tests/e2e/message-undo.spec.ts +++ b/tests/e2e/message-undo.spec.ts @@ -185,3 +185,46 @@ test("reader star undo is optimistic while held and a later star still works", a await expect(article.getByRole("button", { name: "Remove star", exact: true })).toBeVisible(); await expect(page.getByRole("button", { name: "Undo" })).toBeVisible(); }); + +/** + * Regression: a failed/uncertain undo must not leave the reader showing the + * optimistic read=true after the server authoritatively reports unread. + */ +test("a failed undo accepts the authoritative unread reader state", async ({ page }) => { + await resetDemo(page.request); + await login(page); + await page.goto("/inbox"); + + const firstRow = page.locator('[role="listitem"]').first(); + await expect(firstRow).toBeVisible(); + const href = await firstRow.locator('a[href^="/inbox/"]').first().getAttribute("href"); + expect(href).toBeTruthy(); + await page.goto(href!); + const article = page.locator("article"); + await expect(article).toBeVisible(); + await page.waitForTimeout(400); + + // Make the message unread on the server, with its undo toast available. + await article.getByRole("button", { name: "More actions" }).click(); + await page.getByRole("menuitem", { name: "Mark as unread" }).click(); + await expect(page.getByRole("button", { name: "Undo" })).toBeVisible(); + await article.getByRole("button", { name: "More actions" }).click(); + await expect(page.getByRole("menuitem", { name: "Mark as read" })).toBeVisible(); + await page.keyboard.press("Escape"); + + // Abort the undo transport: this is the same uncertain path as a timeout. + // The server stays unread and the optimistic reader true must not survive. + await page.route("**/api/messages/actions", async (route) => { + const body = route.request().postDataJSON(); + if (body?.op === "undo") { + await route.abort("failed"); + return; + } + await route.continue(); + }); + + await page.getByRole("button", { name: "Undo" }).click(); + await page.waitForTimeout(1_000); + await article.getByRole("button", { name: "More actions" }).click(); + await expect(page.getByRole("menuitem", { name: "Mark as read" })).toBeVisible(); +}); diff --git a/tests/message-action-pending-caches.test.mjs b/tests/message-action-pending-caches.test.mjs index cd0bd3735..54ae7e906 100644 --- a/tests/message-action-pending-caches.test.mjs +++ b/tests/message-action-pending-caches.test.mjs @@ -35,7 +35,7 @@ globalThis.document = { visibilityState: "visible", hidden: false, addEventListe await build({ stdin: { contents: ` - export { defaultMessageActionHooks } from "./src/lib/messages/actions/client.ts"; + export { defaultMessageActionHooks, MessageActionRequestError } from "./src/lib/messages/actions/client.ts"; export { MessageActionExecutor } from "./src/lib/messages/actions/executor.ts"; export { fetchMessageList, peekMessageList, clearMessageListCache, invalidateMessageListRequests, @@ -56,6 +56,7 @@ await build({ captureMessageFields, captureThreadUnread, clearKnownMessageFieldsForTests, setPendingOverlay, clearPendingOverlay, hasPendingOverlay, getPendingOverlayOwners, applyPendingToMessages, getKnownThreadUnread, subscribePendingOverlay, + getVisibleMessageFields, getConversationLockKeys, } from "./src/lib/messages/field-store.ts"; `, resolveDir: root, @@ -280,6 +281,73 @@ test("a settled undo invalidates every in-flight response without dropping the p await assert.rejects(threadRequest, (error) => m.isMessageThreadInvalidated(error)); }); +test("a grouped aggregate read never seeds the anchor member's individual state", async () => { + const params = new URLSearchParams({ case: "grouped-anchor" }); + await seedList(params, [{ + id: "A", + read: false, + starred: false, + threadMessageIds: ["A", "B"], + threadUnread: 1, + }]); + assert.equal( + m.getVisibleMessageFields("A").read, + undefined, + "the row's aggregate read flag says nothing about the anchor member", + ); + assert.deepEqual(m.getConversationLockKeys(["A"]).sort(), ["A", "B"]); +}); + +test("undoes in one conversation serialize so a rejected aggregate is not stacked into the next", async () => { + const params = new URLSearchParams({ case: "conversation-lock" }); + await seedList(params, [{ + id: "m1", + read: true, + starred: false, + threadMessageIds: ["m1", "m2"], + threadUnread: 0, + }]); + const tokens = []; + let rejectFirst; + let resolveSecond; + const executor = new m.MessageActionExecutor((body) => { + tokens.push(body.token); + if (tokens.length === 1) { + return new Promise((_resolve, reject) => { + rejectFirst = () => reject(new m.MessageActionRequestError("stale", 409)); + }); + } + return new Promise((resolve) => { + resolveSecond = () => resolve({ ok: true, action: "read", restored: ["m2"], skipped: [] }); + }); + }, { + ...m.defaultMessageActionHooks, + onResync() {}, + }); + const firstUndo = record("m1", { read: false }, { read: true }); + const secondUndo = record("m2", { read: false }, { read: true }); + + const first = executor.undo([firstUndo], "token-a"); + const second = executor.undo([secondUndo], "token-b"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(tokens, ["token-a"], "the second conversation member waits for the first undo"); + + rejectFirst(); + await assert.rejects(first, /stale/); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(tokens, ["token-a", "token-b"], "the next undo starts against the rolled-back aggregate"); + assert.equal(m.getVisibleMessageFields("m1").read, undefined, "the failed undo left no optimistic anchor state"); + assert.equal(m.peekMessageList(params).messages[0].threadUnread, 1); + + resolveSecond(); + await second; + assert.equal( + m.peekMessageList(params).messages[0].threadUnread, + 1, + "the rejected first undo must not leave an extra unread behind", + ); +}); + test("owner-scoped overlays clear independently and notify subscribers", () => { let changes = 0; const unsubscribe = m.subscribePendingOverlay(() => { changes += 1; }); diff --git a/tests/message-action-pending-hooks.test.mjs b/tests/message-action-pending-hooks.test.mjs index bd8733a8f..d4ce516dc 100644 --- a/tests/message-action-pending-hooks.test.mjs +++ b/tests/message-action-pending-hooks.test.mjs @@ -37,7 +37,8 @@ await build({ import { captureMessageFields, captureThreadUnread, clearKnownMessageFieldsForTests, hasPendingOverlay, } from "@/lib/messages/field-store"; - export { act }; + import { primeMessageDetail } from "@/lib/messages/detail-cache"; + export { act, primeMessageDetail }; export { defaultMessageActionHooks } from "@/lib/messages/actions/client"; export { captureMessageFields, captureThreadUnread, hasPendingOverlay, clearKnownMessageFieldsForTests }; export async function seed(params, messages, counts) { @@ -171,6 +172,7 @@ test("mounted list and counts consumers keep the optimistic undo through refresh assert.equal(read().threadUnread, "0"); assert.equal(read().inboxUnread, "0"); + m.primeMessageDetail({ id: "m1", read: true, starred: false, threadId: null }); const undo = record("m1", { read: false }, { read: true }); const captured = m.captureMessageFields(["m1"]); const capturedThreads = m.captureThreadUnread(["m1"]); From bb2a5014b82bdd07aba2dd5819ef662e38a512bc Mon Sep 17 00:00:00 2001 From: Antonio Ivanovski Date: Thu, 12 Nov 2026 22:40:36 +0100 Subject: [PATCH 11/15] fix(messages): preserve undo timers through removal and compose --- src/components/compose/compose-form.tsx | 2 +- src/components/messages/undo-toasts.tsx | 41 ++++++++++++---- src/lib/messages/actions/undo-store.ts | 22 ++++++--- tests/message-undo-toast-store.test.mjs | 45 ++++++++++++++++++ tests/message-undo-toast-ui.test.mjs | 63 +++++++++++++++++++++++++ 5 files changed, 158 insertions(+), 15 deletions(-) diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsx index 61ec4ba8c..02daeb1fa 100644 --- a/src/components/compose/compose-form.tsx +++ b/src/components/compose/compose-form.tsx @@ -800,7 +800,7 @@ export function ComposeForm({ {toast.message} )} -
{ if (modalMode && !minimized && event.key === "Escape") { event.preventDefault(); setModalMode(false); } }} onDragEnterCapture={minimized ? undefined : onFileDragEnter} onDragOverCapture={minimized ? undefined : onFileDragOver} onDragLeaveCapture={minimized ? undefined : onFileDragLeave} onDropCapture={minimized ? undefined : onFileDrop}> + { if (modalMode && !minimized && event.key === "Escape") { event.preventDefault(); setModalMode(false); } }} onDragEnterCapture={minimized ? undefined : onFileDragEnter} onDragOverCapture={minimized ? undefined : onFileDragOver} onDragLeaveCapture={minimized ? undefined : onFileDragLeave} onDropCapture={minimized ? undefined : onFileDrop}> {draggingFiles && !minimized && (