{t("compose.dropFiles")}
diff --git a/src/components/compose/floating-composer.tsx b/src/components/compose/floating-composer.tsx
index d7126c7fa..9eee85515 100644
--- a/src/components/compose/floating-composer.tsx
+++ b/src/components/compose/floating-composer.tsx
@@ -81,7 +81,8 @@ function ComposeNoticeToast({ notice }: { notice: ComposeNotice }) {
role="status"
aria-atomic="false"
className={cn(
- "fixed right-6 top-6 z-[60] flex max-w-[calc(100vw-3rem)] items-center gap-4 rounded-lg px-4 py-3 text-sm font-medium text-white shadow-lg",
+ "fixed z-[60] flex max-w-[calc(100vw-3rem)] items-center gap-4 rounded-lg px-4 py-3 text-sm font-medium text-white shadow-lg",
+ "inset-x-6 bottom-[max(5rem,calc(env(safe-area-inset-bottom,0px)+4.5rem))] md:bottom-6 md:[inset-inline-end:auto] md:[inset-inline-start:calc(var(--sidebar-width,260px)+1.5rem)]",
notice.tone === "error" ? "bg-red-600" : notice.tone === "loading" ? "bg-neutral-800" : "bg-green-600",
)}
>
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 58241c6dd..366753ced 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -179,7 +179,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 });
@@ -294,7 +294,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}
@@ -615,7 +615,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
@@ -636,7 +639,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..8d0642f26 100644
--- a/src/components/messages/message-thread-cache.ts
+++ b/src/components/messages/message-thread-cache.ts
@@ -1,5 +1,10 @@
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 {
+ applyPendingToMessages,
+ rememberMessageFields,
+ rememberMessageRows,
+} from "@/lib/messages/field-store";
import type { ThreadMessage, ThreadResponse } from "@/hooks/types";
const CACHE_TTL_MS = 60_000;
@@ -29,8 +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 });
+ 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);
@@ -47,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
{
@@ -64,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);
@@ -73,16 +80,34 @@ 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);
+ // An in-flight request may predate this patch; drop it rather than cache stale fields.
+ 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)),
- });
+ const messages = applyPendingToMessages(cached.messages.map((message) => (
+ ids.has(message.id) ? { ...message, ...patch } : message
+ )));
+ threadCache.set(messageId, { ...cached, messages });
+ rememberMessageRows(messages);
}
+ rememberMessageFields(messageIds, patch);
+}
+
+export function markMessageThreadReadInCaches(messageIds: string[], read: boolean): void {
+ 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 {
@@ -94,13 +119,20 @@ 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 } : {}),
+ });
}
});
}
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..9829c043c
--- /dev/null
+++ b/src/components/messages/undo-toasts.tsx
@@ -0,0 +1,421 @@
+"use client";
+
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { useLanguage } from "@/components/language-provider";
+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,
+ hideUndoToast,
+ partialUndoToast,
+ pauseUndoToast,
+ pauseUndoToasts,
+ resumeUndoToast,
+ resumeUndoToasts,
+ subscribeUndoToasts,
+} 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";
+
+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 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 BLOCKING_OVERLAY_SELECTOR = [
+ '[role="dialog"][aria-modal="true"]',
+ '[aria-modal="true"]',
+ "dialog[open]",
+ ".dialog-overlay",
+ '[data-mobile-menu][aria-expanded="true"]',
+].join(", ");
+const COMPOSE_SELECTOR = "[data-compose-surface]";
+const INTERACTION_SELECTOR = `${BLOCKING_OVERLAY_SELECTOR}, #main-content[inert], #main-content[aria-hidden="true"]`;
+
+/** 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(BLOCKING_OVERLAY_SELECTOR);
+}
+
+/** 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 hasComposeSurface() {
+ if (typeof document === "undefined") return false;
+ return !!document.querySelector(COMPOSE_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", "aria-expanded", "aria-hidden", "inert", "data-compose-surface"],
+ });
+ return () => observer.disconnect();
+}
+
+function getToastHoldState() {
+ const interaction = hasInteractionHold() ? 1 : 0;
+ const composing = hasComposeSurface() ? 2 : 0;
+ return interaction | composing;
+}
+
+function useToastHolds() {
+ return useSyncExternalStore(subscribeInteractionState, getToastHoldState, () => 0);
+}
+
+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 };
+ }
+ 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);
+}
+
+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;
+ }
+}
+
+/** Keep keyboard focus in the remaining receipt, or fall back to the app surface. */
+function restoreFocusAfterAction(entryId: number) {
+ if (typeof window === "undefined") return;
+ window.setTimeout(() => {
+ const active = document.activeElement;
+ const activeInRegion = active instanceof HTMLElement && !!active.closest("[data-undo-region]");
+ if (active && active !== document.body && (active as HTMLElement).isConnected) {
+ if (!activeInRegion) resumeUndoToasts("region");
+ return;
+ }
+ if (hasBlockingOverlay()) {
+ resumeUndoToasts("region");
+ 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 });
+ if (!document.activeElement?.closest("[data-undo-region]")) resumeUndoToasts("region");
+ return;
+ }
+ if (!toast.hasAttribute("tabindex")) toast.tabIndex = -1;
+ toast.focus({ preventScroll: true });
+ if (!document.activeElement?.closest("[data-undo-region]")) resumeUndoToasts("region");
+ return;
+ }
+ resumeUndoToasts("region");
+ focusVisibleAppSurface();
+ }, 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_TOASTS);
+ const announcements = useSyncExternalStore(subscribeUndoToasts, getUndoAnnouncements, () => EMPTY_ANNOUNCEMENTS);
+ const holdState = useToastHolds();
+ const interactionHeld = (holdState & 1) !== 0;
+ const pauseHeld = holdState !== 0;
+ 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 already made.
+ const seenAnnouncement = useRef(announcements.at(-1)?.sequence ?? 0);
+
+ useEffect(() => {
+ if (pauseHeld) {
+ pauseUndoToasts("interaction");
+ resumeUndoToasts("region");
+ } else {
+ resumeUndoToasts("interaction");
+ }
+ return () => resumeUndoToasts("interaction");
+ }, [pauseHeld]);
+
+ 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);
+ 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) {
+ 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(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) restoreFocusAfterAction(current.id);
+ } else if (restored < total || result.skipped.length > 0) {
+ partialUndoToast(current.id, {
+ restored,
+ skipped: undoSkipCount,
+ skippedReasons: result.skipped.map((item) => item.reason),
+ });
+ restoreFocusAfterAction(current.id);
+ } else {
+ completeUndoToast(current.id);
+ restoreFocusAfterAction(current.id);
+ }
+ } catch (error) {
+ const failure = failureFromError(error);
+ failUndoToast(current.id, failure);
+ if (!failure.retryable) restoreFocusAfterAction(current.id);
+ }
+ }
+
+ function dismiss(entry: UndoToastEntry) {
+ dismissUndoToast(entry.id);
+ restoreFocusAfterAction(entry.id);
+ }
+
+ function hide(entry: UndoToastEntry) {
+ hideUndoToast(entry.id);
+ restoreFocusAfterAction(entry.id);
+ }
+
+ return (
+ <>
+
+ {polite && {polite.text}}
+
+
+ {assertive && {assertive.text}}
+
+ {toasts.length > 0 && (
+ 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-30 flex max-h-[calc(100dvh-6rem)] w-[calc(100vw-3rem)] 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-6 bottom-[max(5rem,calc(env(safe-area-inset-bottom,0px)+4.5rem))]",
+ "md:bottom-6 md:w-[min(24rem,calc(100vw-var(--sidebar-width,260px)-3rem))] md:[inset-inline-end:auto] md:[inset-inline-start:calc(var(--sidebar-width,260px)+1.5rem)]",
+ )}
+ >
+ {toasts.map((entry) => {
+ const label = actionLabel(t, entry.action);
+ const messageId = `undo-toast-${entry.id}-message`;
+ const failed = entry.status === "failed";
+ const partial = entry.status === "partial";
+ const undoing = entry.status === "undoing";
+ const retryable = failed && entry.failure?.retryable;
+ const primary = entry.status === "idle" || undoing || retryable;
+ const mainText = failed
+ ? t("undo.failed")
+ : partial
+ ? t("undo.partialRestored", {
+ restored: entry.restored ?? 0,
+ total: entry.records.length,
+ })
+ : appliedText(t, entry.action, entry.records.length, entry.skipped);
+ return (
+ 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",
+ interactionHeld && "pointer-events-none",
+ )}
+ >
+
+
{mainText}
+ {entry.context && !failed && !partial && (
+
{entry.context}
+ )}
+ {failed && entry.failure && (
+
+ {t(FAILURE_LABELS[entry.failure.kind])}
+
+ )}
+ {partial && (
+
{label}
+ )}
+
+ {primary && (
+
+ )}
+ {undoing ? (
+
+ ) : (
+
+ )}
+
+ );
+ })}
+
+ )}
+ >
+ );
+}
diff --git a/src/components/messages/use-message-thread.ts b/src/components/messages/use-message-thread.ts
index 506d0b85b..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,
@@ -21,7 +22,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 +36,40 @@ 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(applyPendingToMessages(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)));
+ setMessages((current) => applyPendingToMessages(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 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) => applyPendingToMessages(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() {
if (document.visibilityState !== "visible") return;
if (refreshTimer) window.clearTimeout(refreshTimer);
refreshTimer = window.setTimeout(() => {
@@ -59,12 +77,18 @@ 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);
return () => {
cancelled = true;
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/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/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/hooks/use-message-counts.ts b/src/hooks/use-message-counts.ts
index df3a3f779..5ce6faa3b 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 { registerMessageRefresh } from "./message-refresh";
import { clearMessageCountsCache, fetchMessageCounts } from "./utils";
@@ -38,16 +39,15 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) {
if (showLoading) setIsLoading(true);
try {
const nextCounts = await fetchMessageCounts(mailboxId, force);
- if (!cancelled && currentRequest === requestNumber) setCounts(nextCounts ?? emptyCounts);
+ if (!cancelled && currentRequest === requestNumber && !hasPendingOverlay()) {
+ setCounts(nextCounts ?? emptyCounts);
+ }
} finally {
if (!cancelled && currentRequest === requestNumber) setIsLoading(false);
}
}
- void loadCounts().catch(() => undefined);
- const unregisterRefresh = registerMessageRefresh(() => loadCounts(false, false));
- function onMessagesChanged() {
- clearMessageCountsCache();
+ function scheduleCountsLoad() {
if (document.visibilityState !== "visible") return;
if (refreshTimer) window.clearTimeout(refreshTimer);
refreshTimer = window.setTimeout(() => {
@@ -56,6 +56,20 @@ export function useMessageCounts(mailboxId?: string | null, enabled = true) {
void loadCounts().catch(() => undefined);
}, 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().catch(() => undefined);
+ }
+ const unregisterRefresh = registerMessageRefresh(() => loadCounts(false, false));
+ function onMessagesChanged() {
+ if (hasPendingOverlay()) return;
+ clearMessageCountsCache();
+ scheduleCountsLoad();
+ }
function onMessageCountsDelta(event: Event) {
const detail = (event as CustomEvent).detail;
if (!detail?.inboxUnreadDelta) return;
@@ -70,6 +84,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);
@@ -80,6 +107,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 f6f9e7d5d..c40b83520 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 { registerMessageRefresh } from "./message-refresh";
import {
clearMessageCountsCache,
@@ -11,6 +13,36 @@ 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. Prefer the event target or the shared
+ * store; otherwise change only members that can still flip.
+ */
+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,
@@ -42,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);
@@ -55,26 +87,70 @@ export function useMessages(
void loadMessages(false, !peekMessageList(getMessageQueryParams(folder, mailboxId, filters, folderId))).catch(() => undefined);
const unregisterRefresh = registerMessageRefresh(() => loadMessages());
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 };
+ 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 }>;
+ threadTargets?: ThreadUnreadTarget[];
+ }>).detail;
+ if (detail?.kind !== "patch" || !detail.patches?.length) return;
+ const patches = new Map(detail.patches.map((patch) => [patch.id, patch]));
+ 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;
}
- return ids.has(message.id) ? { ...message, read } : 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) next.read = patch.read;
+ return next;
+ })));
}
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;
+ 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.
+ requestNumber += 1;
if (!readOnly) {
clearMessageListCache();
clearMessageCountsCache();
@@ -86,14 +162,20 @@ export function useMessages(
void loadMessages(true).catch(() => undefined);
}, 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);
return () => {
cancelled = true;
unregisterRefresh();
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 4b8bebe60..5cb113ec3 100644
--- a/src/hooks/utils.ts
+++ b/src/hooks/utils.ts
@@ -1,8 +1,15 @@
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 { isReadOnlyChange } from "@/lib/messages/change-events";
+import { patchCachedMessage } from "@/lib/messages/detail-cache";
+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";
@@ -90,30 +97,115 @@ 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;
+};
+
+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 read/unread change into the cached lists and details, so a list
- * remounted later (or a detail reopened) never shows the old state.
+ * 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 markMessagesReadInCaches(messageIds: string[], read: boolean) {
- const ids = new Set(messageIds);
+export function patchMessageFieldsInCaches(
+ fields: MessageFieldPatch[],
+ options: MessageCachePatchOptions = {},
+): ThreadUnreadTarget[] {
+ const patches = groupFieldPatches(fields);
+ 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;
+ 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)) });
+ }
+ }
+ }
+ 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();
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;
- const threadUnread = Math.min(threadSize, Math.max(0, (message.threadUnread ?? 0) + (read ? -flipped : flipped)));
- return { ...message, read: threadUnread === 0, threadUnread };
+ 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;
+ }
+ const read = threadUnread === 0;
+ if (next.read !== read) {
+ next.read = read;
+ changed = true;
+ }
}
- return ids.has(message.id) ? { ...message, read } : message;
- }),
+ const starred = direct?.starred ?? memberPatch?.starred;
+ if (starred !== undefined && next.starred !== starred) {
+ next.starred = starred;
+ changed = true;
+ }
+ return changed ? next : message;
+ }
+ if (!direct) return message;
+ const next = { ...message, ...direct };
+ return next.read === message.read && next.starred === message.starred ? message : next;
});
+ // A refresh during a pending undo 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) setCachedMessageRead(id, read);
+ for (const [id, patch] of patches) patchCachedMessage(id, patch);
+ return targets;
+}
+
+export function markMessagesReadInCaches(messageIds: string[], read: boolean) {
+ patchMessageFieldsInCaches(messageIds.map((id) => ({ id, read })));
}
// Caches must drop on every change, including ones made while no list is mounted
@@ -168,12 +260,15 @@ 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}`)
@@ -182,9 +277,12 @@ export async function fetchMessageList(params: URLSearchParams, force = false):
return res.json();
})
.then((data) => {
- const response = data as MessageListResponse;
+ // Overlay before the response reaches state or cache, so a refresh that
+ // started while an undo is pending cannot repaint the server value.
+ const response = applyPendingToMessageList(data as MessageListResponse);
if (requestGeneration === messageCacheGeneration) {
messageListCache.set(key, response);
+ rememberMessageRows(response.messages ?? []);
}
return response;
})
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/i18n/en.json b/src/lib/i18n/en.json
index f25f84140..c09952c13 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -2459,5 +2459,33 @@
"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.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.",
+ "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",
+ "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/claims.ts b/src/lib/messages/actions/claims.ts
new file mode 100644
index 000000000..88b8daedb
--- /dev/null
+++ b/src/lib/messages/actions/claims.ts
@@ -0,0 +1,44 @@
+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: exactly one insert wins. The claim is
+ * written before the restore, so a crash in between 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/client.ts b/src/lib/messages/actions/client.ts
new file mode 100644
index 000000000..96afa3b09
--- /dev/null
+++ b/src/lib/messages/actions/client.ts
@@ -0,0 +1,351 @@
+"use client";
+
+import { authFetch } from "@/lib/auth/client";
+import { dispatchMessagesChanged, type MessageFieldPatch } from "@/lib/messages/change-events";
+import { invalidateCachedMessageDetails, invalidateMessageDetailRequests, patchCachedMessageState, type CachedMessageStatePatch } from "@/lib/messages/detail-cache";
+import {
+ captureMessageFields,
+ captureThreadUnread,
+ clearPendingOverlay,
+ forgetMessageFields,
+ getPendingThreadTargets,
+ getThreadRowIdsForMessages,
+ getThreadUnreadTargets,
+ invalidateThreadUnreadTargets,
+ rememberThreadUnreadTargets,
+ 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,
+ type MessageActionExecutorHooks,
+ type MessageActionHookContext,
+ type MessageActionHookOptions,
+ type MessageActionTransport,
+} from "./executor";
+import { showUndoToast } from "./undo-store";
+import type {
+ MessageActionInput,
+ MessageActionRecord,
+ MessageActionRequestOptions,
+ MessageActionResponse,
+ MessageActionTransportBody,
+ UndoMessageActionResponse,
+} 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 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);
+ }
+}
+
+/** Read/star fields changed by an action in the requested direction; membership stays server-first. */
+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);
+ }
+ return fields;
+}
+
+/** Pre-click values to restore when the server rejects or skips the undo. */
+function capturedFieldPatches(
+ records: MessageActionRecord[],
+ captured: 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);
+ 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 });
+ }
+ 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 consumers. Grouped rows get the absolute target
+ * computed while patching, so a transition cannot apply twice.
+ */
+function applyFieldChanges(
+ fields: PendingOverlayMessage[],
+ threadTargets?: Map,
+): ThreadUnreadTarget[] {
+ if (fields.length === 0 && !threadTargets?.size) return [];
+ const targets = patchMessageFieldsInCaches(
+ fields,
+ threadTargets ? {
+ threadTargets: [...threadTargets].map(([id, threadUnread]) => ({ id, threadUnread })),
+ } : undefined,
+ );
+ 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 commitWholeRollbackTargets(
+ records: MessageActionRecord[],
+ capturedThreads?: Map,
+): Map {
+ const rowIds = getThreadRowIdsForMessages(records.map((record) => record.id));
+ const captured = capturedThreads ?? new Map();
+ rememberThreadUnreadTargets(captured);
+ invalidateThreadUnreadTargets(rowIds.filter((rowId) => !captured.has(rowId)));
+ return captured;
+}
+
+/**
+ * Persists the settled aggregate even when its list row is no longer cached.
+ * Partial rollbacks extend the pending target with only the skipped transitions.
+ */
+function commitSettledTargets(
+ owner: string,
+ records: MessageActionRecord[],
+ restoredRecords: MessageActionRecord[],
+ rollback: MessageActionRecord[],
+ captured: Map,
+ capturedThreads?: Map,
+): Map {
+ if (restoredRecords.length === 0) {
+ return commitWholeRollbackTargets(records, capturedThreads);
+ }
+ const targets = new Map(getPendingThreadTargets(owner));
+ for (const target of getThreadUnreadTargets(capturedFieldPatches(rollback, captured))) {
+ targets.set(target.id, target.threadUnread);
+ }
+ const unknownReadIds = rollback
+ .filter((record) => (
+ getChangedStateFields(record.previous, record.applied).includes("read")
+ && captured.get(record.id)?.read === undefined
+ ))
+ .map((record) => record.id);
+ const unknownRows = getThreadRowIdsForMessages(unknownReadIds);
+ for (const rowId of unknownRows) targets.delete(rowId);
+ rememberThreadUnreadTargets(targets);
+ invalidateThreadUnreadTargets(unknownRows);
+ return targets;
+}
+
+function restoreCaptured(
+ records: MessageActionRecord[],
+ captured: Map,
+ capturedThreads?: Map,
+) {
+ forgetUncapturedFields(records, captured);
+ const fields = capturedFieldPatches(records, captured);
+ const hasReadChange = records.some((record) => (
+ getChangedStateFields(record.previous, record.applied).includes("read")
+ ));
+ applyFieldChanges(fields, hasReadChange ? capturedThreads : undefined);
+}
+
+function rememberDetailState(records: MessageActionRecord[], direction: "previous" | "applied") {
+ for (const record of records) {
+ const patch = Object.fromEntries(getChangedStateFields(record.previous, record.applied)
+ .map((field) => [field, record[direction][field]])) as CachedMessageStatePatch;
+ patchCachedMessageState(record.id, patch);
+ }
+}
+
+/** Request invalidation without dropping a patched cache; one resync fetch follows. */
+function invalidatePendingResponses(messageIds: string[]) {
+ invalidateMessageListRequests();
+ invalidateMessageThreadRequests();
+ invalidateMessageDetailRequests(messageIds);
+}
+
+/** A timeout or dropped connection may still have committed server-side. */
+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, context?: MessageActionHookContext) {
+ clearPendingOverlay(context?.pendingOwner ?? DEFAULT_PENDING_OWNER);
+ const changed = getChangedRecords(response.applied);
+ if (changed.length === 0) return;
+ applyFieldChanges(changedFieldPatches(changed, "applied"));
+ rememberDetailState(changed, "applied");
+ if (options.notify && changed.some(hasMembershipChange)) dispatchMessagesChanged();
+ },
+ onApplyFailed(input, _options, context, error) {
+ clearPendingOverlay(context?.pendingOwner ?? DEFAULT_PENDING_OWNER);
+ if (!isUncertainActionFailure(error)) return;
+ invalidateUncertainState(input.messageIds);
+ dispatchMessagesChanged();
+ },
+ onUndoOptimistic(records, _captured, context) {
+ const owner = context?.pendingOwner ?? DEFAULT_PENDING_OWNER;
+ const fields = changedFieldPatches(records, "previous");
+ if (fields.length === 0) return;
+ // Patch caches, then overlay the same values on every ingress while pending.
+ const targets = patchMessageFieldsInCaches(fields);
+ setPendingOverlay(owner, { messages: fields, threads: targets });
+ dispatchFieldChanges(fields, targets);
+ },
+ onUndoCompleted(records, response, captured, context) {
+ // Skipped records return to the pre-click screen, not an older applied snapshot.
+ const owner = context?.pendingOwner ?? DEFAULT_PENDING_OWNER;
+ const restored = new Set(response.restored);
+ 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));
+ const unaccounted = records.filter((record) => !restored.has(record.id) && !skipped.has(record.id));
+ const rollback = [...skippedRecords, ...unaccounted];
+ // Commit the settled aggregate before dropping the owner, since a later
+ // resync may clear every cached row before the next undo starts.
+ const settledTargets = commitSettledTargets(owner, records, restoredRecords, rollback, captured, context?.capturedThreadUnread);
+ clearPendingOverlay(owner);
+ rememberDetailState(restoredRecords, "previous");
+ // A mixed result keeps restored members; only skipped transitions roll back.
+ restoreCaptured(rollback, captured, settledTargets);
+ invalidateCachedMessageDetails(rollback.map((record) => record.id));
+ invalidatePendingResponses(records.map((record) => record.id));
+ },
+ onUndoFailed(records, captured, context, error) {
+ const owner = context?.pendingOwner ?? DEFAULT_PENDING_OWNER;
+ const ids = records.map((record) => record.id);
+ if (isUncertainActionFailure(error)) {
+ clearPendingOverlay(owner);
+ // The undo may have committed; let the resync fetch decide.
+ forgetUncapturedFields(records, captured);
+ invalidateThreadUnreadTargets(getThreadRowIdsForMessages(ids));
+ invalidateUncertainState(ids);
+ return;
+ }
+ const settledTargets = commitWholeRollbackTargets(records, context?.capturedThreadUnread);
+ clearPendingOverlay(owner);
+ restoreCaptured(records, captured, settledTargets);
+ invalidateCachedMessageDetails(ids);
+ invalidatePendingResponses(ids);
+ },
+ onResync() {
+ dispatchMessagesChanged();
+ },
+ captureCurrent: captureMessageFields,
+ captureThreadUnread,
+};
+
+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(
+ 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..b94223d96
--- /dev/null
+++ b/src/lib/messages/actions/definitions.ts
@@ -0,0 +1,199 @@
+import type {
+ MessageActionSkipReason,
+ MessageStateField,
+ MessageStateSnapshot,
+ ReversibleMessageAction,
+} from "./types";
+
+const REVERSIBLE_MESSAGE_STATUSES = new Set(["received", "sent", "draft", "queued", "failed", "trash", "spam", "archived"]);
+
+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";
+}
+
+/** 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 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 reversible fields an action writes for one message; never ownership, bodies or attachments. */
+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.has(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 };
+
+/**
+ * Restores only the fields the action changed, and only while they still hold
+ * its result, so a later action is never clobbered.
+ */
+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 (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 (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" };
+ }
+ }
+
+ 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 };
+}
diff --git a/src/lib/messages/actions/executor.ts b/src/lib/messages/actions/executor.ts
new file mode 100644
index 000000000..9e76c115a
--- /dev/null
+++ b/src/lib/messages/actions/executor.ts
@@ -0,0 +1,151 @@
+import { getChangedStateFields, recordHasChanges } from "./definitions";
+import { getConversationLockKeys, type KnownMessageFields } from "@/lib/messages/field-store";
+import type {
+ MessageActionInput,
+ MessageActionRecord,
+ MessageActionResponse,
+ MessageActionTransportBody,
+ 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 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, 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;
+ /** 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;
+};
+
+/**
+ * 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>();
+ private nextOperationId = 0;
+
+ 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 };
+ 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, context, error);
+ throw error;
+ }
+ if (!response || response.ok !== true || !("applied" in response) || !Array.isArray(response.applied) || !Array.isArray(response.skipped)) {
+ 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, context);
+ 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);
+ const ids = records.map((record) => record.id);
+ return this.withLocks(ids, async () => {
+ const captured = this.hooks.captureCurrent?.(ids) ?? new Map();
+ 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, context);
+ this.hooks.onResync?.(ids);
+ return result;
+ } catch (error) {
+ this.hooks.onUndoFailed?.(records, captured, context, error);
+ this.hooks.onResync?.(ids);
+ throw error;
+ }
+ });
+ }
+
+ private withLocks(ids: string[], task: () => Promise): Promise {
+ const keys = getConversationLockKeys(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 hasMembershipChange(record: MessageActionRecord): boolean {
+ return getChangedStateFields(record.previous, record.applied)
+ .some((field) => field === "status" || field === "folderId" || field === "snoozedUntil");
+}
diff --git a/src/lib/messages/actions/service.ts b/src/lib/messages/actions/service.ts
new file mode 100644
index 000000000..5baf2a8e8
--- /dev/null
+++ b/src/lib/messages/actions/service.ts
@@ -0,0 +1,515 @@
+import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
+import type { AppDatabase } from "@/db";
+import { getDb } from "@/db";
+import { schemaDialect } from "@/db/dialect";
+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 { claimMessageActionUndoToken, releaseMessageActionUndoClaim } from "./claims";
+import {
+ actionNeedsManage,
+ getChangedStateFields,
+ getMessageActionPatch,
+ isReversibleMessageAction,
+ recordHasChanges,
+ snapshotMessageState,
+ planUndoRecord,
+ type MessageActionTarget,
+} from "./definitions";
+import { MAX_UNDO_AGE_MS, signUndoTokenForEnv, verifyUndoTokenForEnv } from "./token";
+import type {
+ MessageActionInput,
+ MessageActionRecord,
+ MessageActionResponse,
+ MessageActionSkipped,
+ MessageStateField,
+ MessageStateSnapshot,
+ UndoMessageActionResponse,
+} from "./types";
+
+const MAX_ACTION_MESSAGES = 5000;
+const MESSAGE_ID_CHUNK = 90;
+const MESSAGE_QUERY_CONCURRENCY = 5;
+const D1_BOUND_PARAMETER_BUDGET = 90;
+
+export class MessageActionError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ this.name = "MessageActionError";
+ }
+}
+
+type LoadedTarget = MessageActionTarget & { mailboxId: string | null };
+
+type PlannedUpdate = {
+ id: string;
+ /** Every field the operation writes; used for both the CAS and the update. */
+ fields: MessageStateField[];
+ condition: MessageStateSnapshot;
+ values: Partial;
+};
+
+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