Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): resolve TRASH label by linkId for multi-inbox (#6349)

KevinLau63ab76d39cb1
diff --git a/apps/web/src/features/block-email/component/TopBar.tsx b/apps/web/src/features/block-email/component/TopBar.tsx
index f33d4fe518..40fa39c973 100644
--- a/apps/web/src/features/block-email/component/TopBar.tsx
+++ b/apps/web/src/features/block-email/component/TopBar.tsx
@@ -154,7 +154,7 @@ export function TopBar(props: {
return soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
})();
- const handle = trashEmails([thread.db_id]);
+ const handle = trashEmails([{ id: thread.db_id, linkId: thread.link_id }]);
if (soup && nextRow) {
soup.selection.clear();
diff --git a/apps/web/src/features/next-soup/actions/make-delete-action.ts b/apps/web/src/features/next-soup/actions/make-delete-action.ts
index aa8ad2b360..c8d02af08e 100644
--- a/apps/web/src/features/next-soup/actions/make-delete-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-delete-action.ts
@@ -2,7 +2,11 @@ import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntity
import { globalSplitManager } from '@app/signal/splitLayout';
import { globalRemoveFromSplitHistory } from '@components/app/split-layout/layoutUtils';
import { toast } from '@core/component/Toast/Toast';
-import { createBulkDeleteDssItemsMutation, type EntityData } from '@entity';
+import {
+ createBulkDeleteDssItemsMutation,
+ type EntityData,
+ isEmailEntity,
+} from '@entity';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
import { restoreSoupFocus, trashEmails } from '../utils';
import type { EntityActionListState } from './entity-action-context';
@@ -103,7 +107,7 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {
// Three lanes: emails trash immediately (with Undo), reminders delete
// immediately (no Undo to give), everything else confirms first.
- const emailEntities = entities.filter((e) => e.type === 'email');
+ const emailEntities = entities.filter(isEmailEntity);
const reminderEntities = entities.filter((e) => e.type === 'reminder');
const nonEmailEntities = entities.filter(
(e) => e.type !== 'email' && e.type !== 'reminder'
@@ -116,7 +120,9 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {
};
const trashEmailEntities = () => {
- const handle = trashEmails(emailEntities.map((e) => e.id));
+ const handle = trashEmails(
+ emailEntities.map((e) => ({ id: e.id, linkId: e.linkId }))
+ );
const splitManager = globalSplitManager();
if (splitManager) {
diff --git a/apps/web/src/features/next-soup/trash-emails.test.ts b/apps/web/src/features/next-soup/trash-emails.test.ts
new file mode 100644
index 0000000000..ad6a40bd38
--- /dev/null
+++ b/apps/web/src/features/next-soup/trash-emails.test.ts
@@ -0,0 +1,248 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// updateThreadLabel returns a Result (an HTTP failure resolves to Err rather
+// than rejecting), so the mock mirrors that shape; trashEmails wraps it in
+// throwOnErr.
+type ResultLike = {
+ isErr: () => boolean;
+ value?: undefined;
+ error?: { code: string; message: string }[];
+};
+const okResult: ResultLike = { isErr: () => false, value: undefined };
+const errResult: ResultLike = {
+ isErr: () => true,
+ error: [{ code: 'ERR', message: 'boom' }],
+};
+
+const operationMocks = vi.hoisted(() => ({
+ cancelQueries: vi.fn(async () => {}),
+ fetchAndCacheThread: vi.fn(),
+ fetchQuery: vi.fn(),
+ getQueriesData: vi.fn(() => []),
+ getQueryData: vi.fn(),
+ invalidateQueries: vi.fn(async () => {}),
+ invalidateSoupEntity: vi.fn(async () => {}),
+ setQueryData: vi.fn(),
+ updateThreadLabel: vi.fn(
+ async (_args: {
+ thread_id: string;
+ label_id: string;
+ value: boolean;
+ }): Promise<ResultLike> => ({ isErr: () => false, value: undefined })
+ ),
+}));
+
+// utils.ts transitively imports websocket clients that would otherwise open
+// real sockets at module scope under jsdom.
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: {
+ alert: vi.fn(),
+ dismiss: vi.fn(),
+ failure: vi.fn(),
+ success: vi.fn(),
+ },
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ cancelQueries: operationMocks.cancelQueries,
+ fetchQuery: operationMocks.fetchQuery,
+ getQueriesData: operationMocks.getQueriesData,
+ getQueryData: operationMocks.getQueryData,
+ invalidateQueries: operationMocks.invalidateQueries,
+ setQueryData: operationMocks.setQueryData,
+ },
+}));
+vi.mock('@queries/email/thread', () => ({
+ fetchAndCacheThread: operationMocks.fetchAndCacheThread,
+}));
+vi.mock('@queries/notification/entity-mutations', () => ({
+ updateNotificationsForEntities: vi.fn(async () => []),
+}));
+vi.mock('@queries/notification/user-notifications', () => ({
+ bulkMarkNotificationsAsDone: vi.fn(async () => {}),
+ bulkMarkNotificationsAsUndone: vi.fn(async () => {}),
+ restoreUserNotifications: vi.fn(),
+ snapshotUserNotifications: vi.fn(() => []),
+}));
+vi.mock('@queries/reminders/reminders', () => ({
+ invalidateRemindersById: vi.fn(),
+ setReminderCompleted: vi.fn(async () => {}),
+}));
+vi.mock('@queries/soup/cache', () => ({
+ getSoupEntityById: vi.fn(),
+ invalidateSoupEntity: operationMocks.invalidateSoupEntity,
+ optimisticUpdateSoupEntity: vi.fn(() => ({ rollback: vi.fn() })),
+ removeSoupEntities: vi.fn(() => ({ rollback: vi.fn() })),
+ removeSoupEntitiesFromDoneFilteredQueries: vi.fn(() => ({
+ rollback: vi.fn(),
+ })),
+}));
+vi.mock('@service-email/client', () => ({
+ emailClient: {
+ flagArchived: vi.fn(async () => {}),
+ getUserLabels: vi.fn(async () => ({ labels: [] })),
+ updateThreadLabel: operationMocks.updateThreadLabel,
+ },
+}));
+
+import { trashEmails } from './utils';
+
+const trashLabels = [
+ {
+ id: 'trash-a',
+ linkId: 'link-a',
+ providerLabelId: 'TRASH',
+ },
+ {
+ id: 'trash-b',
+ linkId: 'link-b',
+ providerLabelId: 'TRASH',
+ },
+];
+
+afterEach(() => {
+ vi.clearAllMocks();
+ operationMocks.fetchQuery.mockResolvedValue({ labels: trashLabels });
+ operationMocks.getQueriesData.mockReturnValue([]);
+ operationMocks.getQueryData.mockReturnValue(undefined);
+ operationMocks.updateThreadLabel.mockImplementation(async () => okResult);
+ operationMocks.fetchAndCacheThread.mockReset();
+});
+
+describe('trashEmails', () => {
+ it('uses and undoes the TRASH label for each inbox independently', async () => {
+ operationMocks.fetchQuery.mockResolvedValue({ labels: trashLabels });
+
+ const handle = trashEmails([
+ { id: 'thread-a', linkId: 'link-a' },
+ { id: 'thread-b', linkId: 'link-b' },
+ ]);
+
+ await handle.done;
+
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledTimes(2);
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-a',
+ label_id: 'trash-a',
+ value: true,
+ });
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-b',
+ label_id: 'trash-b',
+ value: true,
+ });
+ expect(operationMocks.fetchAndCacheThread).not.toHaveBeenCalled();
+
+ await handle.undo();
+
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledTimes(4);
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-a',
+ label_id: 'trash-a',
+ value: false,
+ });
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-b',
+ label_id: 'trash-b',
+ value: false,
+ });
+ });
+
+ it('fetches the thread through queries when multi-inbox linkId is missing', async () => {
+ operationMocks.fetchQuery.mockResolvedValue({ labels: trashLabels });
+ operationMocks.fetchAndCacheThread.mockResolvedValueOnce({
+ isErr: () => false,
+ value: { thread: { link_id: 'link-b' } },
+ });
+
+ const handle = trashEmails([{ id: 'thread-b' }]);
+ await handle.done;
+
+ expect(operationMocks.fetchAndCacheThread).toHaveBeenCalledWith('thread-b');
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-b',
+ label_id: 'trash-b',
+ value: true,
+ });
+ });
+
+ it('falls back to the sole TRASH label only when the inbox is unknown', async () => {
+ operationMocks.fetchQuery.mockResolvedValue({ labels: [trashLabels[0]] });
+
+ const handle = trashEmails([{ id: 'thread-x' }]);
+ await handle.done;
+
+ // A single inbox needs no thread fetch to disambiguate.
+ expect(operationMocks.fetchAndCacheThread).not.toHaveBeenCalled();
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-x',
+ label_id: 'trash-a',
+ value: true,
+ });
+ });
+
+ it('fails without trashing when a known inbox has no matching label', async () => {
+ operationMocks.fetchQuery.mockResolvedValue({ labels: trashLabels });
+
+ const handle = trashEmails([{ id: 'thread-c', linkId: 'link-c' }]);
+
+ await expect(handle.done).rejects.toThrow();
+ // The mismatch is caught before any label is applied, so nothing is trashed
+ // into the wrong inbox.
+ expect(operationMocks.updateThreadLabel).not.toHaveBeenCalled();
+ });
+
+ it('surfaces an API failure and rejects done', async () => {
+ operationMocks.fetchQuery.mockResolvedValue({ labels: trashLabels });
+ operationMocks.updateThreadLabel.mockImplementation(async () => errResult);
+
+ const handle = trashEmails([{ id: 'thread-a', linkId: 'link-a' }]);
+
+ await expect(handle.done).rejects.toThrow();
+ // A failed trash must not silently look like a success (throwOnErr).
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-a',
+ label_id: 'trash-a',
+ value: true,
+ });
+ });
+
+ it('reverts threads that trashed when a sibling fails', async () => {
+ operationMocks.fetchQuery.mockResolvedValue({ labels: trashLabels });
+ operationMocks.updateThreadLabel.mockImplementation(async (args) =>
+ args.thread_id === 'thread-b' && args.value === true
+ ? errResult
+ : okResult
+ );
+
+ const handle = trashEmails([
+ { id: 'thread-a', linkId: 'link-a' },
+ { id: 'thread-b', linkId: 'link-b' },
+ ]);
+
+ await expect(handle.done).rejects.toThrow();
+
+ // thread-a trashed, thread-b failed -> thread-a is reverted so the server
+ // matches the rolled-back UI, and undo has nothing left to restore.
+ expect(operationMocks.updateThreadLabel).toHaveBeenCalledWith({
+ thread_id: 'thread-a',
+ label_id: 'trash-a',
+ value: false,
+ });
+
+ await handle.undo();
+ expect(operationMocks.updateThreadLabel).not.toHaveBeenCalledWith(
+ expect.objectContaining({ value: false, thread_id: 'thread-b' })
+ );
+ });
+});
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index e3b8494ef8..cacb594055 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -72,6 +72,7 @@ import {
} from '@notifications';
import { queryClient } from '@queries/client';
import { emailKeys } from '@queries/email/keys';
+import { fetchAndCacheThread } from '@queries/email/thread';
import {
type NotificationEntityRef,
updateNotificationsForEntities,
@@ -1086,13 +1087,21 @@ type TrashEmailsHandle = {
undo: () => Promise<void>;
};
+export type TrashEmailTarget = { id: string; linkId?: string };
+
+type TrashLabel = { id: string; linkId?: string };
+
/**
- * Optimistically removes one or more email threads from soup + email caches,
- * then fires the TRASH label API calls in the background. Takes a single
- * snapshot before all removals so undo restores the complete pre-trash state.
+ * Trash one or more email threads.
+ *
+ * Optimistically removes them from the soup and from all email queries,
+ * then resolves the TRASH label and calls the API. If anything fails, rolls
+ * back the optimistic update.
+ *
* Returns synchronously so the caller can show the undo toast immediately.
*/
-export function trashEmails(ids: string[]): TrashEmailsHandle {
+export function trashEmails(targets: TrashEmailTarget[]): TrashEmailsHandle {
+ const ids = targets.map((t) => t.id);
queryClient.cancelQueries({ queryKey: queryKeys.all.email });
const previousEmail = queryClient.getQueriesData<{
@@ -1123,8 +1132,74 @@ export function trashEmails(ids: string[]): TrashEmailsHandle {
}
};
- // Resolved lazily by the API calls; used by undo
- let trashLabelId: string | undefined;
+ // Map each thread id to the TRASH label used to trash it, so undo can remove
+ // the same label. Populated only once every thread has trashed successfully.
+ const threadTrashLabelIds = new Map<string, string>();
+
+ // Seed known linkIds from the explicit targets and the cached email lists.
+ const threadLinkIds = new Map<string, string>();
+ for (const target of targets) {
+ if (target.linkId) {
+ threadLinkIds.set(target.id, target.linkId);
+ }
+ }
+ for (const [, data] of previousEmail) {
+ if (!data?.pages) continue;
+ for (const page of data.pages) {
+ if (!page?.items) continue;
+ for (const item of page.items) {
+ if (
+ item?.id &&
+ idSet.has(item.id) &&
+ !threadLinkIds.has(item.id) &&
+ 'linkId' in item &&
+ item.linkId
+ ) {
+ threadLinkIds.set(item.id, item.linkId);
+ }
+ }
+ }
+ }
+
+ // Resolve the TRASH label belonging to a thread's own inbox. The labels
+ // endpoint returns every inbox's labels, so a multi-inbox user must trash
+ // with the label whose linkId matches the thread. The single-label fallback
+ // applies only when the inbox is unknown — a known inbox with no matching
+ // label fails rather than trashing into the wrong one.
+ const resolveTrashLabelId = async (
+ id: string,
+ trashLabels: TrashLabel[]
+ ): Promise<string> => {
+ let linkId = threadLinkIds.get(id);
+ if (!linkId) {
+ const threadData = queryClient.getQueryData<{
+ link_id?: string;
+ pages?: Array<{ link_id?: string }>;
+ }>(emailKeys.threadMessages(id).queryKey);
+ linkId = threadData?.link_id ?? threadData?.pages?.[0]?.link_id;
+ }
+ if (!linkId && trashLabels.length > 1) {
+ const fetched = await fetchAndCacheThread(id);
+ if (!fetched.isErr()) {
+ linkId = fetched.value.thread.link_id;
+ }
+ }
+
+ const matchedLabelId = linkId
+ ? trashLabels.find((label) => label.linkId === linkId)?.id
+ : undefined;
+ const labelId =
+ matchedLabelId ??
+ (linkId
+ ? undefined
+ : trashLabels.length === 1
+ ? trashLabels[0]?.id
+ : undefined);
+ if (!labelId) {
+ throw new Error('TRASH label not found');
+ }
+ return labelId;
+ };
const done = (async () => {
try {
@@ -1134,24 +1209,59 @@ export function trashEmails(ids: string[]): TrashEmailsHandle {
throwOnErr(async () => await emailClient.getUserLabels()),
staleTime: 5 * 60 * 1000,
});
- const trashLabel = labelsData?.labels.find(
- (l) => l.providerLabelId === 'TRASH'
- );
- const labelId = trashLabel?.id;
- if (!labelId) {
+ const trashLabels =
+ labelsData?.labels.filter((l) => l.providerLabelId === 'TRASH') ?? [];
+ if (trashLabels.length === 0) {
throw new Error('TRASH label not found');
}
- trashLabelId = labelId;
-
- await Promise.all(
- ids.map((id) =>
- emailClient.updateThreadLabel({
- thread_id: id,
- label_id: labelId,
- value: true,
- })
+
+ // Resolve every thread's label before trashing any of them, so a lookup
+ // failure can't leave part of the batch trashed on the server while the
+ // rest is rolled back locally.
+ const labelIds = await Promise.all(
+ ids.map((id) => resolveTrashLabelId(id, trashLabels))
+ );
+
+ // updateThreadLabel resolves an Err on HTTP failure rather than
+ // rejecting, so throwOnErr turns a failed trash into a real rejection.
+ // Settle every call so a partial failure can be compensated instead of
+ // leaving the server disagreeing with the rolled-back UI.
+ const outcomes = await Promise.allSettled(
+ ids.map((id, i) =>
+ throwOnErr(() =>
+ emailClient.updateThreadLabel({
+ thread_id: id,
+ label_id: labelIds[i]!,
+ value: true,
+ })
+ )
)
);
+
+ const failure = outcomes.find((o) => o.status === 'rejected');
+ if (failure) {
+ // Revert the threads that did trash so the server matches the rollback
+ // below; best effort, so a failed revert can't mask the original error.
+ await Promise.allSettled(
+ ids.flatMap((id, i) =>
+ outcomes[i]?.status === 'fulfilled'
+ ? [
+ throwOnErr(() =>
+ emailClient.updateThreadLabel({
+ thread_id: id,
+ label_id: labelIds[i]!,
+ value: false,
+ })
+ ),
+ ]
+ : []
+ )
+ );
+ throw (failure as PromiseRejectedResult).reason;
+ }
+
+ // Every thread trashed — remember the labels so undo can remove them.
+ ids.forEach((id, i) => threadTrashLabelIds.set(id, labelIds[i]!));
} catch (err) {
rollback();
throw err;
@@ -1166,8 +1276,9 @@ export function trashEmails(ids: string[]): TrashEmailsHandle {
return {
done,
undo: async () => {
- // Wait for the trash calls to finish so we know the label ID.
- // If the trash call itself failed, rollback already happened — nothing to undo.
+ // Wait for the trash calls to finish so we know the label IDs. On any
+ // failure `done` has already rolled back and reverted the server, so
+ // there is nothing left to undo.
try {
await done;
} catch {
@@ -1178,13 +1289,17 @@ export function trashEmails(ids: string[]): TrashEmailsHandle {
try {
await Promise.all(
- ids.map((id) =>
- emailClient.updateThreadLabel({
- thread_id: id,
- label_id: trashLabelId!,
- value: false,
- })
- )
+ ids.map((id) => {
+ const labelId = threadTrashLabelIds.get(id);
+ if (!labelId) return Promise.resolve();
+ return throwOnErr(() =>
+ emailClient.updateThreadLabel({
+ thread_id: id,
+ label_id: labelId,
+ value: false,
+ })
+ );
+ })
);
} finally {
// Only invalidate email queries — skip soup invalidation since