Skip to content

Email for professionals and teams

Fix conversation unread state and counts, and report skipped permanent deletes (#135)

Can K.68fb384c86a1
diff --git a/public/locales/tr.json b/public/locales/tr.json
index 577ad43..002dffd 100644
--- a/public/locales/tr.json
+++ b/public/locales/tr.json
@@ -116,6 +116,7 @@
"source.copy": "Panoya kopyala",
"actions.error.update": "İleti güncellenemedi",
"actions.error.delete": "İleti silinemedi",
+ "actions.error.deleteSkipped": "Bazı iletiler artık Çöp Kutusu veya Spam içinde olmadığı için silinemedi.",
"actions.error.trashRule": "Çöp kutusu kuralı oluşturulamadı",
"actions.moveToTrash": "Çöp kutusuna taşı",
"actions.moveToTrashHint": "Çöp kutusuna taşı (#)",
diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.ts
index d61cab2..708fd03 100644
--- a/src/app/api/messages/route.ts
+++ b/src/app/api/messages/route.ts
@@ -105,6 +105,9 @@ export async function GET(request: Request) {
// Which stored messages each visible row stands for, so acting on a
// conversation row acts on the whole conversation within this folder.
const threadMessageIds = new Map<string, string[]>();
+ // Unread messages per conversation within this folder; the row's unread state
+ // has to match what marking it read will actually change.
+ const scopedThreadCounts = new Map<string, { total: number; unread: number }>();
if (groupByThread) {
const page = await loadConversationPage({ db, where, offset, limit });
total = page.total;
@@ -116,13 +119,17 @@ export async function GET(request: Request) {
const keys = rows.map((row) => row.threadId ?? row.id);
if (keys.length > 0) {
const members = await db
- .select({ id: messages.id, key: threadKey })
+ .select({ id: messages.id, key: threadKey, read: messages.read })
.from(messages)
.where(and(where, inArray(threadKey, keys)));
for (const member of members) {
const list = threadMessageIds.get(member.key) ?? [];
list.push(member.id);
threadMessageIds.set(member.key, list);
+ const counts = scopedThreadCounts.get(member.key) ?? { total: 0, unread: 0 };
+ counts.total += 1;
+ if (!member.read) counts.unread += 1;
+ scopedThreadCounts.set(member.key, counts);
}
}
} else {
@@ -195,6 +202,8 @@ export async function GET(request: Request) {
// reading pane loads them from /api/messages/[id]/thread, so they are
// neither selected nor sent here.
const enrichedRows = rows.map(({ rawR2Key: _rawR2Key, ...message }) => {
+ const threadStats = message.threadId ? threadCounts.get(message.threadId) : undefined;
+ const folderUnread = scopedThreadCounts.get(message.threadId ?? message.id)?.unread;
const contactMap = contactMapsByUserId.get(message.userId);
const accountName = message.mailboxId ? mailboxNameMap.get(message.mailboxId) : null;
return {
@@ -206,8 +215,8 @@ export async function GET(request: Request) {
contactMap?.get(normalizeEmailAddress(message.fromAddr)) ??
null,
toContactName: contactMap?.get(normalizeEmailAddress(getFirstEmailAddressEntry(message.toAddr))) ?? null,
- threadCount: (message.threadId && threadCounts.get(message.threadId)?.total) || 1,
- threadUnread: (message.threadId && threadCounts.get(message.threadId)?.unread) || 0,
+ threadCount: threadStats?.total || 1,
+ threadUnread: (groupByThread ? folderUnread : threadStats?.unread) || 0,
...(groupByThread
? { threadMessageIds: threadMessageIds.get(message.threadId ?? message.id) ?? [message.id] }
: {}),
diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsx
index 1276327..0dacca7 100644
--- a/src/components/message-actions/message-actions.tsx
+++ b/src/components/message-actions/message-actions.tsx
@@ -15,7 +15,7 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { MessageActionsProps, ReplyMode } from "./types";
-import { getPermanentDeleteConfirmText, supportsPermanentDelete } from "@/lib/messages/permanent-delete-utils";
+import { getPermanentDeleteConfirmText, PartialDeleteError, supportsPermanentDelete } from "@/lib/messages/permanent-delete-utils";
import {
confirmTrashWithoutUnsubscribe,
blockMessageContact,
@@ -92,8 +92,8 @@ export function MessageActions({
await runSingleMessageAction(messageId, "delete");
router.push(getMessageBackHref(direction, status));
router.refresh();
- } catch {
- setError(t("actions.error.delete"));
+ } catch (deleteError) {
+ setError(deleteError instanceof PartialDeleteError ? t("actions.error.deleteSkipped") : t("actions.error.delete"));
setPendingAction(null);
}
}, [messageId, direction, status, router, t]);
diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts
index 0b7b878..c18854b 100644
--- a/src/components/message-actions/utils.ts
+++ b/src/components/message-actions/utils.ts
@@ -1,5 +1,6 @@
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import { authFetch } from "@/lib/auth/client";
+import { throwIfDeleteSkipped } from "@/lib/messages/permanent-delete-utils";
import { markMessagesReadInCaches } from "@/hooks/utils";
import { getEmailAddress, normalizeEmailAddress, splitEmailAddressList } from "@/lib/email/address";
import { getLatestEmailContent } from "@/lib/email/reply-content-utils";
@@ -51,6 +52,7 @@ export async function runSingleMessageAction(
throw new Error("Unable to update message");
}
+ await throwIfDeleteSkipped(response, action);
if (action === "read" || action === "unread") markMessagesReadInCaches([messageId], action === "read");
window.dispatchEvent(new Event("mailflare:messages-changed"));
}
diff --git a/src/components/messages/bulk-message-selection-pane.tsx b/src/components/messages/bulk-message-selection-pane.tsx
index ca7c9c7..f181e58 100644
--- a/src/components/messages/bulk-message-selection-pane.tsx
+++ b/src/components/messages/bulk-message-selection-pane.tsx
@@ -6,6 +6,7 @@ import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import { useLanguage } from "@/components/language-provider";
import { BulkMessageToolbar } from "./bulk-message-toolbar";
import type { BulkMessageSelectionPaneProps } from "./types";
+import { PartialDeleteError } from "@/lib/messages/permanent-delete-utils";
import { runBulkMessageAction } from "./utils";
export function BulkMessageSelectionPane({
@@ -15,12 +16,14 @@ export function BulkMessageSelectionPane({
}: BulkMessageSelectionPaneProps) {
const { t } = useLanguage();
const [pending, setPending] = useState(false);
+ const [error, setError] = useState<string | null>(null);
const hasUnreadSelection = selectedMessages.some((message) => !message.read);
async function runAction(action: BulkMessageAction, folderId?: string) {
if (selectedMessages.length === 0) return;
setPending(true);
+ setError(null);
try {
await runBulkMessageAction(
selectedMessages.map((message) => message.id),
@@ -29,6 +32,8 @@ export function BulkMessageSelectionPane({
folderId,
);
onClearSelection();
+ } catch (actionError) {
+ setError(actionError instanceof PartialDeleteError ? t("actions.error.deleteSkipped") : t("actions.error.update"));
} finally {
setPending(false);
}
@@ -57,6 +62,7 @@ export function BulkMessageSelectionPane({
hideSelectedCount
/>
</div>
+ {error && <p role="alert" className="mt-3 text-sm font-medium text-red-700">{error}</p>}
</div>
</div>
);
diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx
index 18bfe21..e17305f 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -32,6 +32,7 @@ import {
getMessageParty,
getMessagePartyClassName,
getMessagePreview,
+ getUnreadFlipCount,
isMessageListRowUnread,
formatEmailPageTitle,
getMailboxAddress,
@@ -43,6 +44,7 @@ import {
getEmptyFolderLabel,
getPermanentDeleteFolderLabel,
getPermanentDeleteConfirmText,
+ PartialDeleteError,
supportsPermanentDelete,
} from "@/lib/messages/permanent-delete-utils";
import clsx from "clsx";
@@ -76,10 +78,14 @@ function MessageListRow({
const href = `${config.hrefPrefix}/${message.id}`;
const navigation = useMessageNavigation(href, rowMessage);
+ const affectsInboxCount = config.folder === "inbox" && !config.folderId;
+
async function runRowAction(action: RowMessageAction) {
const previousRead = read;
const previousThreadUnread = threadUnread;
- const unreadDelta = action === "read" ? -1 : action === "unread" ? 1 : 0;
+ const unreadDelta = !affectsInboxCount || (action !== "read" && action !== "unread")
+ ? 0
+ : getUnreadFlipCount(rowMessage, action === "read") * (action === "read" ? -1 : 1);
if (action === "read") setRead(true);
if (action === "unread") setRead(false);
// Grouped rows derive their unread styling from the thread count, so it must change with the row.
@@ -108,11 +114,11 @@ function MessageListRow({
const previousThreadUnread = threadUnread;
setRead(true);
if (previousThreadUnread !== undefined) setThreadUnread(Math.max(0, previousThreadUnread - 1));
- if (message.direction === "inbound") dispatchMessageCountsDelta({ inboxUnreadDelta: -1 });
+ if (affectsInboxCount && message.direction === "inbound") dispatchMessageCountsDelta({ inboxUnreadDelta: -1 });
void runBulkMessageAction([message.id], "read", false).catch(() => {
setRead(false);
setThreadUnread(previousThreadUnread);
- if (message.direction === "inbound") dispatchMessageCountsDelta({ inboxUnreadDelta: 1 });
+ if (affectsInboxCount && message.direction === "inbound") dispatchMessageCountsDelta({ inboxUnreadDelta: 1 });
});
}
navigation.onNavigate(event, !read);
@@ -434,8 +440,8 @@ export function MessageFolderPage({
setActionError(null);
try {
await runSelectedAction(action, folderId);
- } catch {
- setActionError(t("actions.error.update"));
+ } catch (error) {
+ setActionError(error instanceof PartialDeleteError ? t("actions.error.deleteSkipped") : t("actions.error.update"));
}
}
@@ -449,17 +455,18 @@ export function MessageFolderPage({
setPendingBulkAction(true);
const previousMessages = messages;
const readValue = action === "read" ? true : action === "unread" ? false : null;
- const changedMessages = readValue === null
- ? []
- : messages.filter((message) => selectedIds.includes(message.id) && message.read !== readValue);
+ const inboxUnreadDelta = readValue === null || config.folder !== "inbox" || config.folderId
+ ? 0
+ : messages
+ .filter((message) => selectedIds.includes(message.id))
+ .reduce((total, message) => total + getUnreadFlipCount(message, readValue), 0) * (readValue ? -1 : 1);
if (readValue !== null) {
updateMessages((current) => current.map((message) =>
- selectedIds.includes(message.id) ? { ...message, read: readValue } : message,
+ selectedIds.includes(message.id)
+ ? { ...message, read: readValue, ...(message.threadMessageIds ? { threadUnread: readValue ? 0 : message.threadMessageIds.length } : {}) }
+ : message,
));
setSelectedMessages((current) => current.map((message) => ({ ...message, read: readValue })));
- const inboxUnreadDelta = changedMessages
- .filter((message) => message.direction === "inbound")
- .reduce((total, message) => total + (readValue ? (message.read ? 0 : -1) : (message.read ? 1 : 0)), 0);
if (inboxUnreadDelta) dispatchMessageCountsDelta({ inboxUnreadDelta });
}
try {
@@ -468,10 +475,7 @@ export function MessageFolderPage({
} catch (error) {
if (readValue !== null) {
updateMessages(previousMessages);
- const inboxUnreadDelta = changedMessages
- .filter((message) => message.direction === "inbound")
- .reduce((total, message) => total + (readValue ? (message.read ? 0 : 1) : (message.read ? -1 : 0)), 0);
- if (inboxUnreadDelta) dispatchMessageCountsDelta({ inboxUnreadDelta });
+ if (inboxUnreadDelta) dispatchMessageCountsDelta({ inboxUnreadDelta: -inboxUnreadDelta });
}
throw error;
} finally {
@@ -594,7 +598,7 @@ export function MessageFolderPage({
onMessageAction={(messageId, action) => {
setActionError(null);
return runBulkMessageAction(expandSelectedIds([messageId]), action, action !== "read" && action !== "unread").catch((error) => {
- setActionError(t("actions.error.update"));
+ setActionError(error instanceof PartialDeleteError ? t("actions.error.deleteSkipped") : t("actions.error.update"));
throw error;
});
}}
diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts
index 8d37187..853cfac 100644
--- a/src/components/messages/utils.ts
+++ b/src/components/messages/utils.ts
@@ -9,6 +9,7 @@ import type { MessageFolderConfig } from "./types";
import type { PageRange } from "./types";
import { defaultTranslator, type Translator } from "@/lib/i18n/utils";
import type { PermanentDeleteFolder } from "@/app/api/messages/bulk/types";
+import { throwIfDeleteSkipped } from "@/lib/messages/permanent-delete-utils";
import type { EmptyFolderResponse } from "@/app/api/messages/empty/types";
export function getMessageParty(
@@ -44,6 +45,16 @@ export function isMessageListRowUnread(message: Message): boolean {
return message.direction === "inbound" && !message.read;
}
+/** How many unread messages a read or unread action on this row would flip. */
+export function getUnreadFlipCount(message: Message, readValue: boolean): number {
+ if (message.threadMessageIds) {
+ const unread = Math.min(message.threadUnread ?? 0, message.threadMessageIds.length);
+ return readValue ? unread : message.threadMessageIds.length - unread;
+ }
+ if (message.direction !== "inbound") return 0;
+ return message.read === readValue ? 0 : 1;
+}
+
export function getMessagePreview(message: Message, folder: MessageFolderConfig["folder"], t: Translator = defaultTranslator) {
if (folder === "drafts") return message.snippet || message.toAddr || t("list.noContent");
return message.snippet || t("thread.noPreview");
@@ -92,6 +103,7 @@ export async function runBulkMessageAction(messageIds: string[], action: string,
});
if (!response.ok) throw new Error(defaultTranslator("error.updateSelected"));
+ await throwIfDeleteSkipped(response, action);
if (action === "read" || action === "unread") markMessagesReadInCaches(messageIds, action === "read");
if (notify) window.dispatchEvent(new Event("mailflare:messages-changed"));
}
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 1f474b3..f1415d0 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -119,6 +119,7 @@
"source.copy": "Copy to clipboard",
"actions.error.update": "Could not update message",
"actions.error.delete": "Could not delete message",
+ "actions.error.deleteSkipped": "Some messages could not be deleted because they are no longer in Trash or Spam.",
"actions.error.trashRule": "Could not create trash rule",
"actions.moveToTrash": "Move to trash",
"actions.moveToTrashHint": "Move to trash (#)",
diff --git a/src/lib/messages/permanent-delete-utils.ts b/src/lib/messages/permanent-delete-utils.ts
index e50a4c6..aec0035 100644
--- a/src/lib/messages/permanent-delete-utils.ts
+++ b/src/lib/messages/permanent-delete-utils.ts
@@ -25,3 +25,18 @@ export function getEmptyFolderConfirmText(folder: PermanentDeleteFolder, total?:
if (total === 1) return t("empty.confirm.single", vars);
return total && total > 1 ? t("empty.confirm.multiple", vars) : t("empty.confirm.all", vars);
}
+
+/** Some of the requested messages were not in Trash or Spam any more, so the server kept them. */
+export class PartialDeleteError extends Error {
+ constructor(readonly skipped: number) {
+ super("Some messages could not be deleted");
+ }
+}
+
+export async function throwIfDeleteSkipped(response: Response, action: string): Promise<void> {
+ if (action !== "delete") return;
+ const result = (await response.json().catch(() => null)) as { skipped?: number } | null;
+ if (!result?.skipped) return;
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
+ throw new PartialDeleteError(result.skipped);
+}
diff --git a/tests/message-list-unread.test.mjs b/tests/message-list-unread.test.mjs
new file mode 100644
index 0000000..a2ffe0d
--- /dev/null
+++ b/tests/message-list-unread.test.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const bundleDirectory = mkdtempSync(join(root, "node_modules", "mailflare-unread-bundle-"));
+await build({
+ stdin: {
+ contents: `
+ export { getUnreadFlipCount } from "./src/components/messages/utils.ts";
+ export { PartialDeleteError, throwIfDeleteSkipped } from "./src/lib/messages/permanent-delete-utils.ts";
+ `,
+ resolveDir: root,
+ sourcefile: "unread-test-entry.ts",
+ },
+ outfile: join(bundleDirectory, "entry.mjs"),
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node24",
+ tsconfig: join(root, "tsconfig.json"),
+ packages: "external",
+ alias: { "cloudflare:workers": "./server/runtime/cloudflare-workers.ts" },
+ logLevel: "silent",
+});
+const { getUnreadFlipCount, PartialDeleteError, throwIfDeleteSkipped } = await import(pathToFileURL(join(bundleDirectory, "entry.mjs")).href);
+rmSync(bundleDirectory, { recursive: true, force: true });
+
+const single = (read, direction = "inbound") => ({ direction, read });
+const grouped = (threadUnread, size) => ({ direction: "inbound", read: threadUnread === 0, threadUnread, threadMessageIds: Array.from({ length: size }, (_, index) => `m${index}`) });
+
+test("a single unread inbound message flips once", () => {
+ assert.equal(getUnreadFlipCount(single(false), true), 1);
+ assert.equal(getUnreadFlipCount(single(true), false), 1);
+});
+
+test("a message that already has the requested state flips nothing", () => {
+ assert.equal(getUnreadFlipCount(single(true), true), 0);
+ assert.equal(getUnreadFlipCount(single(false), false), 0);
+});
+
+test("outbound messages never count towards unread", () => {
+ assert.equal(getUnreadFlipCount(single(false, "outbound"), true), 0);
+ assert.equal(getUnreadFlipCount(single(true, "outbound"), false), 0);
+});
+
+test("a conversation row flips every unread message when marked read", () => {
+ assert.equal(getUnreadFlipCount(grouped(2, 5), true), 2);
+ assert.equal(getUnreadFlipCount(grouped(0, 5), true), 0);
+});
+
+test("a conversation row flips every read message when marked unread", () => {
+ assert.equal(getUnreadFlipCount(grouped(0, 4), false), 4);
+ assert.equal(getUnreadFlipCount(grouped(1, 4), false), 3);
+ assert.equal(getUnreadFlipCount(grouped(4, 4), false), 0);
+});
+
+test("a skipped permanent delete is reported after the list is told to refresh", async () => {
+ const events = [];
+ globalThis.window = { dispatchEvent: (event) => events.push(event.type) };
+ try {
+ await throwIfDeleteSkipped(Response.json({ ok: true, deleted: 1, skipped: 2 }), "read");
+ await throwIfDeleteSkipped(Response.json({ ok: true, deleted: 3, skipped: 0 }), "delete");
+ assert.deepEqual(events, []);
+ await assert.rejects(
+ throwIfDeleteSkipped(Response.json({ ok: true, deleted: 1, skipped: 2 }), "delete"),
+ (error) => error instanceof PartialDeleteError && error.skipped === 2,
+ );
+ assert.deepEqual(events, ["mailflare:messages-changed"]);
+ } finally {
+ delete globalThis.window;
+ }
+});