Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): mark thread read/unread from thread view, cmd-K, and soup (#5059)
Evan Hutnik0993e23929b9
diff --git a/apps/web/src/features/block-email/component/Email.tsx b/apps/web/src/features/block-email/component/Email.tsxindex 63b6942dec..def927b918 100644--- a/apps/web/src/features/block-email/component/Email.tsx+++ b/apps/web/src/features/block-email/component/Email.tsx@@ -512,6 +512,9 @@ function EmailContent(props: EmailViewProps) {markDone: context.archiveThread,markNotDone: context.markThreadNotDone,isThreadDone: context.isThreadDone,+ markUnread: context.markThreadUnread,+ markRead: context.markThreadRead,+ isThreadMarkedUnread: context.isThreadMarkedUnread,markSenderSignal: context.markSenderSignal,markSenderNoise: context.markSenderNoise,navigateToPreviousMessage,diff --git a/apps/web/src/features/block-email/component/EmailContext.tsx b/apps/web/src/features/block-email/component/EmailContext.tsxindex 2933a9ecad..399edba49f 100644--- a/apps/web/src/features/block-email/component/EmailContext.tsx+++ b/apps/web/src/features/block-email/component/EmailContext.tsx@@ -38,6 +38,8 @@ import {markSenderNoiseWithToast,markSenderSignalWithToast,trackExternalThreadArchive,+ useMarkThreadAsSeenMutation,+ useMarkThreadAsUnreadMutation,useThreadQuery,useUndoableArchiveThreadMutation,} from '@queries/email/thread';@@ -156,6 +158,13 @@ type EmailContextValues = {isThreadDone: Accessor<boolean>;/** Unarchives a done thread and restores its notifications. */markThreadNotDone: () => boolean;+ /** True when the user marked the open thread unread. Resets to false per+ * thread — viewing marks it read, so the toggle starts at Mark Unread. */+ isThreadMarkedUnread: Accessor<boolean>;+ /** Marks the open thread unread; the toggle then offers Mark Read. */+ markThreadUnread: () => boolean;+ /** Re-marks the thread read after a mark-unread. */+ markThreadRead: () => boolean;getMarkDoneNavigationTargetId: () => string | undefined;blockSender: () => boolean;markSenderSignal: () => boolean;@@ -626,6 +635,79 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {return true;};+ const markSeenMutation = useMarkThreadAsSeenMutation();+ const markUnreadMutation = useMarkThreadAsUnreadMutation();++ // Viewing a thread marks it read (EmailDebouncedReadMarker), so each thread+ // starts with the toggle offering Mark Unread.+ const [threadMarkedUnread, setThreadMarkedUnread] = createSignal(false);+ createEffect(() => {+ void props.threadID;+ setThreadMarkedUnread(false);+ });++ const markThreadUnread = () => {+ const thread = threadQuery.data;+ if (!thread?.db_id) return false;+ if (threadMarkedUnread()) return false;+ // A toggle mid-flight would race the pending request; ignore it.+ if (markUnreadMutation.isPending || markSeenMutation.isPending) {+ return false;+ }++ const threadId = thread.db_id;+ setThreadMarkedUnread(true);+ markUnreadMutation.mutate(+ { threadId, linkId: thread.link_id },+ {+ onSuccess: () => {+ toast.success('Marked as unread', {+ duration: 3_000,+ stack: true,+ hideOnMobile: true,+ });+ },+ onError: () => {+ setThreadMarkedUnread(false);+ toast.failure('Failed to mark as unread');+ void refetchSoupEntity(threadId, 'emailThread');+ },+ }+ );+ return true;+ };++ const markThreadRead = () => {+ const thread = threadQuery.data;+ if (!thread?.db_id) return false;+ if (!threadMarkedUnread()) return false;+ // A toggle mid-flight would race the pending request; ignore it.+ if (markUnreadMutation.isPending || markSeenMutation.isPending) {+ return false;+ }++ const threadId = thread.db_id;+ setThreadMarkedUnread(false);+ markSeenMutation.mutate(+ { threadId, linkId: toHeaderLinkId(thread.link_id) },+ {+ onSuccess: () => {+ toast.success('Marked as read', {+ duration: 3_000,+ stack: true,+ hideOnMobile: true,+ });+ },+ onError: () => {+ setThreadMarkedUnread(true);+ toast.failure('Failed to mark as read');+ void refetchSoupEntity(threadId, 'emailThread');+ },+ }+ );+ return true;+ };+const currentUserEmail = useEmail();const blockSender = () => {@@ -797,6 +879,9 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {archiveThread,isThreadDone,markThreadNotDone,+ isThreadMarkedUnread: threadMarkedUnread,+ markThreadUnread,+ markThreadRead,getMarkDoneNavigationTargetId,blockSender,markSenderSignal,diff --git a/apps/web/src/features/block-email/component/TopBar.tsx b/apps/web/src/features/block-email/component/TopBar.tsxindex 607a16c665..046dffb7b2 100644--- a/apps/web/src/features/block-email/component/TopBar.tsx+++ b/apps/web/src/features/block-email/component/TopBar.tsx@@ -36,6 +36,8 @@ import { isMobile } from '@core/mobile/isMobile';import IconShared from '@icon/wide-share.svg';import { AnimatedTaskIcon } from '@icon/wide-task';import CheckIcon from '@phosphor/check.svg';+import EnvelopeSimpleIcon from '@phosphor/envelope-simple.svg';+import EnvelopeSimpleOpenIcon from '@phosphor/envelope-simple-open.svg';import ProhibitIcon from '@phosphor/prohibit.svg';import TrashIcon from '@phosphor/trash.svg';import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';@@ -104,6 +106,14 @@ export function TopBar(props: {emailCtx.archiveThread();};+ const toggleMarkUnread = () => {+ if (emailCtx.isThreadMarkedUnread()) {+ emailCtx.markThreadRead();+ } else {+ emailCtx.markThreadUnread();+ }+ };+const trashThread = () => {const thread = emailCtx.thread();if (!thread?.db_id) return;@@ -250,6 +260,35 @@ export function TopBar(props: {A done thread shows a bold accent check and unarchives on click. */}<Show when={!isMobile()}><SplitHeaderRight>+ {/* Read-state toggle. Viewing the thread marks it read, so it+ starts as Mark as unread; marking unread flips it to a bold+ accent closed envelope that re-marks the thread read. */}+ <Show when={isOwnThread()}>+ <Button+ class="p-1 rounded-lg"+ label={+ emailCtx.isThreadMarkedUnread()+ ? 'Mark as read'+ : 'Mark as unread'+ }+ hotkey={+ emailCtx.isThreadMarkedUnread()+ ? TOKENS.entity.action.markRead+ : TOKENS.entity.action.markUnread+ }+ onClick={toggleMarkUnread}+ // Keep focus (and the hotkey scope cmd-K reads) in the thread+ // content: focusing the header would hide its commands.+ onMouseDown={(e) => e.preventDefault()}+ >+ <Show+ when={emailCtx.isThreadMarkedUnread()}+ fallback={<EnvelopeSimpleOpenIcon class="size-4" />}+ >+ <EnvelopeSimpleIcon class="size-4 text-accent" />+ </Show>+ </Button>+ </Show><Show when={isOwnThread()}><Buttonclass="p-1 rounded-lg"@@ -260,6 +299,8 @@ export function TopBar(props: {: TOKENS.entity.action.markDone}onClick={toggleMarkDone}+ // Same focus-preservation as the read-state toggle above.+ onMouseDown={(e) => e.preventDefault()}><Show when={isDone()} fallback={<CheckIcon class="size-4" />}><CheckBoldIcon class="size-4 text-accent" />diff --git a/apps/web/src/features/block-email/util/emailHotkeys.ts b/apps/web/src/features/block-email/util/emailHotkeys.tsindex 11fa617b1d..baf814ea3c 100644--- a/apps/web/src/features/block-email/util/emailHotkeys.ts+++ b/apps/web/src/features/block-email/util/emailHotkeys.ts@@ -10,6 +10,10 @@ interface EmailHotkeyHandlers {markNotDone: () => boolean;/** Gates which of Mark done / Mark as not done is active. */isThreadDone: () => boolean;+ markUnread: () => boolean;+ markRead: () => boolean;+ /** Gates which of Mark as unread / Mark as read is active. */+ isThreadMarkedUnread: () => boolean;markSenderSignal: () => boolean;markSenderNoise: () => boolean;navigateToPreviousMessage: () => boolean;@@ -66,6 +70,24 @@ export function registerEmailHotkeys(displayPriority: 10,condition: () => handlers.isThreadDone(),});+ registerHotkey({+ hotkey: 'u',+ scopeId,+ description: 'Mark as unread',+ keyDownHandler: handlers.markUnread,+ hotkeyToken: TOKENS.entity.action.markUnread,+ displayPriority: 9,+ condition: () => !handlers.isThreadMarkedUnread(),+ });+ registerHotkey({+ hotkey: 'shift+u',+ scopeId,+ description: 'Mark as read',+ keyDownHandler: handlers.markRead,+ hotkeyToken: TOKENS.entity.action.markRead,+ displayPriority: 9,+ condition: () => handlers.isThreadMarkedUnread(),+ });registerHotkey({scopeId: scopeId,description: 'Block sender',diff --git a/apps/web/src/features/next-soup/actions/index.ts b/apps/web/src/features/next-soup/actions/index.tsindex f669745e04..f08c066f9d 100644--- a/apps/web/src/features/next-soup/actions/index.ts+++ b/apps/web/src/features/next-soup/actions/index.ts@@ -10,6 +10,10 @@ export { makeMarkDoneAction } from './make-mark-done-action';export { makeMarkNotDoneAction } from './make-mark-not-done-action';export { makeMarkSenderSignalAction } from './make-mark-sender-important-action';export { makeMarkSenderNoiseAction } from './make-mark-sender-noise-action';+export {+ makeMarkReadAction,+ makeMarkUnreadAction,+} from './make-mark-unread-action';export { makeMoveToProjectAction } from './make-move-to-project-action';export { makeRemoveFromProjectAction } from './make-remove-from-project-action';export { makeRenameAction } from './make-rename-action';diff --git a/apps/web/src/features/next-soup/actions/make-mark-unread-action.ts b/apps/web/src/features/next-soup/actions/make-mark-unread-action.tsnew file mode 100644index 0000000000..19e7c797d1--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-mark-unread-action.ts@@ -0,0 +1,107 @@+import { toast } from '@core/component/Toast/Toast';+import type { EntityData } from '@entity';+import { useNonPrimaryEmailLinkIdHeader } from '@queries/email/link';+import {+ useMarkThreadAsSeenMutation,+ useMarkThreadAsUnreadMutation,+} from '@queries/email/thread';+import { refetchSoupEntity } from '@queries/soup/cache';+import type { SoupState } from '../create-soup-state';++/**+ * Marks read email threads as unread. Rows stay in place — only the soup+ * row's read indicator flips (optimistically via the mutation's onMutate).+ */+export const makeMarkUnreadAction = () => {+ const markUnreadMutation = useMarkThreadAsUnreadMutation();++ const canExecute = (entity: EntityData): boolean =>+ entity.type === 'email' && entity.isRead === true;++ const execute = async (entities: EntityData[]) => {+ const targets = entities.filter(canExecute);+ if (targets.length === 0) return;++ const results = await Promise.allSettled(+ targets.map((entity) =>+ markUnreadMutation.mutateAsync({+ threadId: entity.id,+ linkId: entity.type === 'email' ? entity.linkId : undefined,+ })+ )+ );++ const failed = targets.filter((_, i) => results[i]?.status === 'rejected');+ if (failed.length > 0) {+ toast.failure('Failed to mark as unread');+ // Restore the optimistically-flipped rows to the server's state.+ failed.forEach((entity) => refetchSoupEntity(entity.id, 'emailThread'));+ return;+ }++ toast.success(+ targets.length > 1+ ? `Marked ${targets.length} items as unread`+ : 'Marked as unread',+ { duration: 3_000, stack: true, hideOnMobile: true }+ );+ };++ /** Signature parity with the mark-done actions — no navigation or+ * collapse: the rows stay in place. */+ const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {+ await execute(entities);+ };++ return { canExecute, execute, executeWithSoup };+};++/**+ * Marks unread email threads as read via the seen endpoint (same call the+ * thread view fires on open).+ */+export const makeMarkReadAction = () => {+ const markSeenMutation = useMarkThreadAsSeenMutation();+ const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();++ const canExecute = (entity: EntityData): boolean =>+ entity.type === 'email' && entity.isRead === false;++ const execute = async (entities: EntityData[]) => {+ const targets = entities.filter(canExecute);+ if (targets.length === 0) return;++ const results = await Promise.allSettled(+ targets.map((entity) =>+ markSeenMutation.mutateAsync({+ threadId: entity.id,+ linkId: toHeaderLinkId(+ entity.type === 'email' ? entity.linkId : undefined+ ),+ })+ )+ );++ const failed = targets.filter((_, i) => results[i]?.status === 'rejected');+ if (failed.length > 0) {+ toast.failure('Failed to mark as read');+ failed.forEach((entity) => refetchSoupEntity(entity.id, 'emailThread'));+ return;+ }++ toast.success(+ targets.length > 1+ ? `Marked ${targets.length} items as read`+ : 'Marked as read',+ { duration: 3_000, stack: true, hideOnMobile: true }+ );+ };++ /** Signature parity with the mark-done actions — no navigation or+ * collapse: the rows stay in place. */+ const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {+ await execute(entities);+ };++ return { canExecute, execute, executeWithSoup };+};diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.tsindex 99c3430ded..3543ddd825 100644--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts@@ -25,6 +25,8 @@ import {makeFavoriteAction,makeMarkDoneAction,makeMarkNotDoneAction,+ makeMarkReadAction,+ makeMarkUnreadAction,makeMoveToProjectAction,makeRenameAction,makeSetCompanyPropertyAction,@@ -61,6 +63,9 @@ export const useEntityActionHotkeys = (notificationSource: () => notificationSource,});+ const markRead = makeMarkReadAction();+ const markUnread = makeMarkUnreadAction();+const deleteAction = makeDeleteAction({userId: () => userId(),});@@ -211,6 +216,56 @@ export const useEntityActionHotkeys = (tags: [HotkeyTags.SelectionModification],}).withGroup(group);+ // Mark unread - 'u', read email threads only; rows stay in place+ registerHotkey({+ hotkey: ['u'],+ hotkeyToken: TOKENS.entity.action.markUnread,+ scopeId,+ description: 'Mark unread',+ keyDownHandler: () => {+ const entities = getEntitiesForAction();+ if (entities.length === 0) return false;+ if (!entities.every(markUnread.canExecute)) return false;++ markUnread.executeWithSoup(entities, soup);+ return true;+ },+ condition: () => {+ if (condition && !condition()) return false;+ const entities = getEntitiesForAction();+ return entities.length > 0 && entities.every(markUnread.canExecute);+ },+ displayPriority: 9,+ tags: [HotkeyTags.SelectionModification],+ }).withGroup(group);++ // Mark read - 'shift+u', email selections with at least one unread thread+ registerHotkey({+ hotkey: ['shift+u'],+ hotkeyToken: TOKENS.entity.action.markRead,+ scopeId,+ description: 'Mark read',+ keyDownHandler: () => {+ const entities = getEntitiesForAction();+ if (entities.length === 0) return false;+ if (!entities.some(markRead.canExecute)) return false;++ markRead.executeWithSoup(entities, soup);+ return true;+ },+ condition: () => {+ if (condition && !condition()) return false;+ const entities = getEntitiesForAction();+ return (+ entities.length > 0 &&+ entities.every((e) => e.type === 'email') &&+ entities.some(markRead.canExecute)+ );+ },+ displayPriority: 9,+ tags: [HotkeyTags.SelectionModification],+ }).withGroup(group);+// Delete - 'delete', 'backspace'registerHotkey({hotkey: ['delete', 'backspace'],diff --git a/apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.ts b/apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.tsindex d9fa58e056..f760697f9f 100644--- a/apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.ts+++ b/apps/web/src/features/next-soup/soup-view/create-soup-entity-actions.ts@@ -25,8 +25,10 @@ import {makeHideCompanyAction,makeMarkDoneAction,makeMarkNotDoneAction,+ makeMarkReadAction,makeMarkSenderNoiseAction,makeMarkSenderSignalAction,+ makeMarkUnreadAction,makeMoveToProjectAction,makeRemoveFromProjectAction,makeRenameAction,@@ -97,6 +99,9 @@ export function createSoupEntityActions(): {notificationSource: () => notificationSource,});+ const markRead = makeMarkReadAction();+ const markUnread = makeMarkUnreadAction();+const deleteAction = makeDeleteAction({userId: () => userId(),});@@ -162,6 +167,28 @@ export function createSoupEntityActions(): {}}+ // Read-state toggle for email selections: a fully-read selection gets+ // Mark Unread; anything with an unread thread gets Mark Read (which+ // skips the already-read ones).+ if (canExecuteAll(markUnread.canExecute)) {+ topItems.push({+ id: 'mark-unread',+ label: 'Mark Unread',+ hotkeyToken: TOKENS.entity.action.markUnread,+ onClick: handle(markUnread.executeWithSoup),+ });+ } else if (+ entities.every((e) => e.type === 'email') &&+ entities.some(markRead.canExecute)+ ) {+ topItems.push({+ id: 'mark-read',+ label: 'Mark Read',+ hotkeyToken: TOKENS.entity.action.markRead,+ onClick: handle(markRead.executeWithSoup),+ });+ }+const canOpenInSplit = () => {if (isMobile()) return false;if (entities.length !== 1) return false;diff --git a/apps/web/src/features/settings/Shortcuts.tsx b/apps/web/src/features/settings/Shortcuts.tsxindex 0d20b7107d..84393b1667 100644--- a/apps/web/src/features/settings/Shortcuts.tsx+++ b/apps/web/src/features/settings/Shortcuts.tsx@@ -984,6 +984,12 @@ const shortcutSections: ShortcutSection[] = [{ keys: ['f'], codes: ['KeyF'], description: 'Open filter menu' },{ keys: ['x'], codes: ['KeyX'], description: 'Select items' },{ keys: ['e'], codes: ['KeyE'], description: 'Mark done' },+ { keys: ['u'], codes: ['KeyU'], description: 'Mark unread' },+ {+ keys: ['shift+u'],+ codes: ['ShiftLeft', 'KeyU'],+ description: 'Mark read',+ },],},];diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.tsindex 6bc64cc512..95b43eea24 100644--- a/apps/web/src/lib/core/hotkey/tokens.ts+++ b/apps/web/src/lib/core/hotkey/tokens.ts@@ -47,6 +47,8 @@ export const TOKENS = {action: {markDone: 'entity.action.markDone',markNotDone: 'entity.action.markNotDone',+ markRead: 'entity.action.markRead',+ markUnread: 'entity.action.markUnread',delete: 'entity.action.delete',rename: 'entity.action.rename',moveToFolder: 'entity.action.moveToFolder',diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex 844f67f6c5..d4c5c27462 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -200,6 +200,75 @@ export function useMarkThreadAsSeenMutation(}));}+type MarkThreadAsUnreadParams = {+ threadId: string;+ /** The inbox (email_links row) the thread belongs to; selects that inbox's+ * UNREAD label for multi-inbox users. */+ linkId?: string;+};++/**+ * Resolve an inbox's UNREAD system label from the cached labels list (the+ * endpoint returns every inbox's labels; mirrors trashEmails' TRASH lookup).+ */+async function fetchUnreadLabelId(linkId?: string): Promise<string> {+ const labelsData = await queryClient.fetchQuery({+ queryKey: emailKeys.labels.queryKey,+ queryFn: async () =>+ throwOnErr(async () => await emailClient.getUserLabels()),+ staleTime: 5 * 60 * 1000,+ });+ const labels = labelsData?.labels ?? [];+ const unreadLabel =+ (linkId+ ? labels.find(+ (l) => l.providerLabelId === 'UNREAD' && l.linkId === linkId+ )+ : undefined) ?? labels.find((l) => l.providerLabelId === 'UNREAD');+ if (!unreadLabel) {+ throw new Error('UNREAD label not found');+ }+ return unreadLabel.id;+}++/**+ * Optimistically flip the soup row to unread. The thread messages cache is+ * intentionally left alone for the same Suspense/scroll-reset reason as+ * threadSeenOnMutate.+ */+function threadUnreadOnMutate(params: MarkThreadAsUnreadParams): void {+ optimisticUpdateSoupEntity({+ tag: 'emailThread',+ data: { id: params.threadId, isRead: false },+ frecency_score: 0,+ });+}++/**+ * Mutation to mark a thread as unread: adds the UNREAD label to all its+ * messages — the backend also flips the thread-level flag and syncs Gmail.+ */+export function useMarkThreadAsUnreadMutation(+ callbacks?: MutationCallbacks<void, Error, MarkThreadAsUnreadParams>+) {+ return useMutation(() => ({+ mutationFn: async (params: MarkThreadAsUnreadParams) => {+ const labelId = await fetchUnreadLabelId(params.linkId);+ await throwOnErr(() =>+ emailClient.updateThreadLabel({+ thread_id: params.threadId,+ label_id: labelId,+ value: true,+ })+ );+ },+ ...withCallbacks<void, Error, MarkThreadAsUnreadParams>(+ { onMutate: threadUnreadOnMutate },+ callbacks+ ),+ }));+}+type ArchiveThreadParams = {threadId: string;archive: boolean;diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex e707cc7334..f13c3bfb21 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -264,7 +264,6 @@ impl EmailService for CountingEmailService {async fn update_thread_labels(&self,- _access_token: &str,_link: &Link,_thread_id: Uuid,_label_id: Uuid,diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rsindex bd3bc18502..4ae92ca1f0 100644--- a/crates/email/src/domain/ports.rs+++ b/crates/email/src/domain/ports.rs@@ -252,6 +252,14 @@ pub trait EmailRepo: Send + Sync + 'static {is_read: bool,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Update the denormalized thread-level read status, verified by link_id.+ fn update_thread_read_status(+ &self,+ thread_id: Uuid,+ link_id: Uuid,+ is_read: bool,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// Update the starred status for a batch of messages, verified by link_id.fn update_message_starred_status_batch(&self,@@ -442,10 +450,10 @@ pub trait EmailService: Send + Sync + 'static {link: &Link,) -> impl Future<Output = Result<Vec<LinkLabel>, EmailErr>> + Send;- /// Add or remove a label from all messages in a thread.+ /// Add or remove a label from all messages in a thread. Provider sync+ /// happens asynchronously via the gmail_ops queue.fn update_thread_labels(&self,- access_token: &str,link: &Link,thread_id: Uuid,label_id: Uuid,@@ -639,7 +647,6 @@ impl EmailService for NoOpEmailService {async fn update_thread_labels(&self,- _access_token: &str,_link: &Link,_thread_id: Uuid,_label_id: Uuid,diff --git a/crates/email/src/domain/service/mod.rs b/crates/email/src/domain/service/mod.rsindex d2329d2217..e73e6a7a32 100644--- a/crates/email/src/domain/service/mod.rs+++ b/crates/email/src/domain/service/mod.rs@@ -263,13 +263,12 @@ whereasync fn update_thread_labels(&self,- access_token: &str,link: &Link,thread_id: Uuid,label_id: Uuid,add: bool,) -> Result<UpdateThreadLabelsResult, EmailErr> {- self.update_thread_labels_impl(access_token, link, thread_id, label_id, add)+ self.update_thread_labels_impl(link, thread_id, label_id, add).await}diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rsindex 434f298a8d..0c486c8b5c 100644--- a/crates/email/src/domain/service/thread_labels.rs+++ b/crates/email/src/domain/service/thread_labels.rs@@ -21,10 +21,9 @@ whereanyhow::Error: From<T::Err>,anyhow::Error: From<E::Err>,{- #[tracing::instrument(err, skip(self, _access_token, link))]+ #[tracing::instrument(err, skip(self, link))]pub(crate) async fn update_thread_labels_impl(&self,- _access_token: &str,link: &Link,thread_id: Uuid,label_id: Uuid,@@ -55,44 +54,86 @@ wherelet all_ids: Vec<Uuid> = messages.iter().map(|m| m.db_id).collect();- // Optimistic DB update: update all messages first- let db_result = if add {- self.email_repo- .insert_message_labels_batch(&all_ids, &provider_label_id, link.id)- .await- } else {- self.email_repo- .delete_message_labels_batch(&all_ids, &provider_label_id, link.id)- .await+ // Snapshot which messages actually gain/lose the label, so an+ // enqueue-failure revert restores only what this call changed — the+ // batch writes are idempotent, and blindly inverting every message+ // would strip pre-existing state. Best effort: if the snapshot read+ // fails, fall back to treating all messages as changed.+ let changed_ids: Vec<Uuid> = match self.email_repo.labels_by_message_ids(&all_ids).await {+ Ok(labels_by_id) => all_ids+ .iter()+ .filter(|id| {+ let has_label = labels_by_id.get(id).is_some_and(|labels| {+ labels+ .iter()+ .any(|l| l.provider_label_id == provider_label_id)+ });+ has_label != add+ })+ .copied()+ .collect(),+ Err(e) => {+ let err = anyhow::Error::from(e);+ tracing::warn!(error=?err, "failed to snapshot message labels; revert would cover all messages");+ all_ids.clone()+ }};- if let Err(e) = db_result {- let err = anyhow::Error::from(e);- tracing::error!(error=?err, "failed to update message labels in database");- return Err(EmailErr::RepoErr(err));- }+ // Optimistic DB update: update all messages first+ self.apply_label_db_changes(link, thread_id, &all_ids, &provider_label_id, add)+ .await?;++ // Enqueue Gmail API calls via the gmail_ops worker (provider messages+ // only). Enqueue failure means Gmail would never learn about this+ // change (there is no worker to retry a message that was never+ // queued), so revert the optimistic DB writes and fail — mirroring+ // the worker's revert on permanent Gmail errors.+ let provider_messages: Vec<(Uuid, String)> = messages+ .iter()+ .filter_map(|msg| {+ msg.provider_id+ .as_ref()+ .filter(|pid| !pid.is_empty())+ .map(|pid| (msg.db_id, pid.clone()))+ })+ .collect();++ if !provider_messages.is_empty() {+ let (labels_to_add, labels_to_remove) = if add {+ (vec![provider_label_id.clone()], vec![])+ } else {+ (vec![], vec![provider_label_id.clone()])+ };- // Side effects for system labels- if provider_label_id == system_labels::UNREAD {if let Err(e) = self- .email_repo- .update_message_read_status_batch(&all_ids, link.id, !add)+ .enqueuer+ .enqueue_gmail_ops_modify_labels_batch(+ link.id,+ provider_messages,+ labels_to_add,+ labels_to_remove,+ ).await{let err = anyhow::Error::from(e);- tracing::error!(error=?err, "failed to update message read status");+ tracing::error!(error=?err, "failed to enqueue gmail ops label sync, reverting database changes");+ self.revert_label_db_changes(+ link,+ thread_id,+ &all_ids,+ &changed_ids,+ &provider_label_id,+ add,+ )+ .await;+ return Err(EmailErr::EnqueueErr(err));}- } else if provider_label_id == system_labels::STARRED- && let Err(e) = self- .email_repo- .update_message_starred_status_batch(&all_ids, link.id, add)- .await- {- let err = anyhow::Error::from(e);- tracing::error!(error=?err, "failed to update message starred status");}- // When trashing a thread, cancel any pending scheduled sends for drafts+ // When trashing a thread, cancel any pending scheduled sends for+ // drafts. After the enqueue, so an enqueue failure can't strand+ // cancelled sends (macro drafts have no provider id and are never in+ // the enqueue payload).let mut cancelled_send_ids: Vec<Uuid> = Vec::new();if add && provider_label_id == system_labels::TRASH {let draft_message_ids: Vec<_> = messages@@ -117,43 +158,145 @@ where}// Publish semantic macro.email events now that the optimistic DB- // writes are committed. The provider echo of this change finds no- // label diff during inbox sync, so each change publishes only once.+ // writes are committed and the provider sync is queued. The provider+ // echo of this change finds no label diff during inbox sync, so each+ // change publishes only once.self.publish_thread_label_events(link, thread_id, &label, add, &cancelled_send_ids);- // Enqueue Gmail API calls via the gmail_ops worker (provider messages only)- let provider_messages: Vec<(Uuid, String)> = messages- .iter()- .filter_map(|msg| {- msg.provider_id- .as_ref()- .filter(|pid| !pid.is_empty())- .map(|pid| (msg.db_id, pid.clone()))- })- .collect();+ Ok(UpdateThreadLabelsResult {+ successful_ids: all_ids,+ failed_ids: vec![],+ })+ }- if !provider_messages.is_empty() {- let (labels_to_add, labels_to_remove) = if add {- (vec![provider_label_id.clone()], vec![])+ /// Best-effort revert of the optimistic label write after the Gmail sync+ /// could not be enqueued. Only `changed_ids` — the messages that actually+ /// gained/lost the label — are inverted, so messages that already held+ /// the requested state keep it; the denormalized thread read flag is+ /// restored to its derived pre-op value. Every step logs and continues on+ /// failure: the caller surfaces the enqueue error regardless.+ async fn revert_label_db_changes(+ &self,+ link: &Link,+ thread_id: Uuid,+ all_ids: &[Uuid],+ changed_ids: &[Uuid],+ provider_label_id: &str,+ add: bool,+ ) {+ if !changed_ids.is_empty() {+ let db_result = if add {+ self.email_repo+ .delete_message_labels_batch(changed_ids, provider_label_id, link.id)+ .await} else {- (vec![], vec![provider_label_id.clone()])+ self.email_repo+ .insert_message_labels_batch(changed_ids, provider_label_id, link.id)+ .await};+ if let Err(e) = db_result {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to revert message labels after enqueue failure");+ }+ }- self.enqueuer- .enqueue_gmail_ops_modify_labels_batch(- link.id,- provider_messages,- labels_to_add,- labels_to_remove,- )+ if provider_label_id == system_labels::UNREAD {+ // Restore is_read on the flipped messages: they were read before+ // an UNREAD add (`add` == true) and unread before a removal.+ if !changed_ids.is_empty()+ && let Err(e) = self+ .email_repo+ .update_message_read_status_batch(changed_ids, link.id, add)+ .await+ {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to revert message read status after enqueue failure");+ }+ // Pre-op unread set: everything outside `changed_ids` for an add,+ // `changed_ids` itself for a removal — the thread was read iff+ // that set was empty.+ let original_is_read = if add {+ changed_ids.len() == all_ids.len()+ } else {+ changed_ids.is_empty()+ };+ if let Err(e) = self+ .email_repo+ .update_thread_read_status(thread_id, link.id, original_is_read)+ .await+ {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to revert thread read status after enqueue failure");+ }+ } else if provider_label_id == system_labels::STARRED+ && !changed_ids.is_empty()+ && let Err(e) = self+ .email_repo+ .update_message_starred_status_batch(changed_ids, link.id, !add).await- .map_err(|e| EmailErr::EnqueueErr(anyhow::Error::from(e)))?;+ {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to revert message starred status after enqueue failure");}+ }- Ok(UpdateThreadLabelsResult {- successful_ids: all_ids,- failed_ids: vec![],- })+ /// Apply a thread label change to the DB: the label rows plus the+ /// denormalized read/starred state for system labels. The label write is+ /// a hard error; the denormalized side effects are logged and skipped.+ async fn apply_label_db_changes(+ &self,+ link: &Link,+ thread_id: Uuid,+ message_ids: &[Uuid],+ provider_label_id: &str,+ add: bool,+ ) -> Result<(), EmailErr> {+ let db_result = if add {+ self.email_repo+ .insert_message_labels_batch(message_ids, provider_label_id, link.id)+ .await+ } else {+ self.email_repo+ .delete_message_labels_batch(message_ids, provider_label_id, link.id)+ .await+ };++ if let Err(e) = db_result {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to update message labels in database");+ return Err(EmailErr::RepoErr(err));+ }++ // Side effects for system labels+ if provider_label_id == system_labels::UNREAD {+ if let Err(e) = self+ .email_repo+ .update_message_read_status_batch(message_ids, link.id, !add)+ .await+ {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to update message read status");+ }+ // Keep the denormalized thread flag in sync — soup previews read it.+ if let Err(e) = self+ .email_repo+ .update_thread_read_status(thread_id, link.id, !add)+ .await+ {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to update thread read status");+ }+ } else if provider_label_id == system_labels::STARRED+ && let Err(e) = self+ .email_repo+ .update_message_starred_status_batch(message_ids, link.id, add)+ .await+ {+ let err = anyhow::Error::from(e);+ tracing::error!(error=?err, "failed to update message starred status");+ }++ Ok(())}/// Map a user-initiated thread label change onto the semanticdiff --git a/crates/email/src/inbound/axum/thread_labels_router.rs b/crates/email/src/inbound/axum/thread_labels_router.rsindex 11a48d9811..bb3534bc24 100644--- a/crates/email/src/inbound/axum/thread_labels_router.rs+++ b/crates/email/src/inbound/axum/thread_labels_router.rs@@ -13,12 +13,9 @@ use model_error_response::ErrorResponse;use thiserror::Error;use uuid::Uuid;-use crate::domain::{- models::EmailErr,- ports::{EmailService, GmailTokenProvider},-};+use crate::domain::{models::EmailErr, ports::EmailService};-use super::{axum_impls::GmailTokenState, previews_router::EmailRouterState};+use super::previews_router::EmailRouterState;/// Request body for updating a thread's labels.#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]@@ -83,19 +80,17 @@ impl From<EmailErr> for UpdateThreadLabelError {}/// Create the thread labels router with a `PATCH /{id}/labels` handler.-pub fn thread_labels_router<S, T, G, Auth>() -> Router<S>+pub fn thread_labels_router<S, T, Auth>() -> Router<S>whereS: Send + Sync + Clone + 'static,T: EmailService,- G: GmailTokenProvider,Auth: MacroAuthorizationService,EmailRouterState<T>: axum::extract::FromRef<S>,- GmailTokenState<G>: axum::extract::FromRef<S>,MacroAuthorizationState<Auth>: axum::extract::FromRef<S>,{Router::new().route("/{id}/labels",- patch(update_thread_labels_handler::<T, G, Auth>),+ patch(update_thread_labels_handler::<T, Auth>),)}@@ -117,31 +112,25 @@ where(status = 500, body = ErrorResponse),))]-#[tracing::instrument(err, skip(state, token_state, macro_user, body))]-pub async fn update_thread_labels_handler<- T: EmailService,- G: GmailTokenProvider,- Auth: MacroAuthorizationService,->(+#[tracing::instrument(err, skip(state, macro_user, body))]+pub async fn update_thread_labels_handler<T: EmailService, Auth: MacroAuthorizationService>(State(state): State<EmailRouterState<T>>,- State(token_state): State<GmailTokenState<G>>,Cached(macro_user): Cached<MacroAuthorizationExtractor<Auth>>,Path(thread_id): Path<Uuid>,Json(body): Json<UpdateThreadLabelRequest>,) -> Result<Json<UpdateThreadLabelsResponse>, UpdateThreadLabelError> {// Resolve the inbox from the thread (scoped to the caller's own and delegated- // inboxes), then use that inbox's own Gmail token.+ // inboxes). No Gmail token is needed here — provider sync goes through the+ // gmail_ops queue, which authenticates itself.let link = state.inner.get_owned_link_for_thread(macro_user.macro_user_id, thread_id).await?.ok_or_else(|| UpdateThreadLabelError::NotFound("Thread not found".to_string()))?;- let access_token = token_state.inner.fetch_gmail_access_token(&link).await?;-let result = state.inner- .update_thread_labels(&access_token, &link, thread_id, body.label_id, body.value)+ .update_thread_labels(&link, thread_id, body.label_id, body.value).await?;Ok(Json(UpdateThreadLabelsResponse {diff --git a/crates/email/src/inbound/toolset/update_thread_labels.rs b/crates/email/src/inbound/toolset/update_thread_labels.rsindex 33688a607a..10852b82dd 100644--- a/crates/email/src/inbound/toolset/update_thread_labels.rs+++ b/crates/email/src/inbound/toolset/update_thread_labels.rs@@ -102,13 +102,9 @@ whereinternal_error: anyhow::anyhow!("no owned link for thread"),})?;- // No Gmail token needed here. Label changes are written to the DB and the- // Gmail API calls are enqueued to the gmail_ops worker, which fetches its- // own token. The AI tool context has a no-op token provider, so fetching- // one here would always fail.let result = service_context.service- .update_thread_labels("", &link, self.thread_id, self.label_id, self.add)+ .update_thread_labels(&link, self.thread_id, self.label_id, self.add).await.map_err(|e| ToolCallError {description: format!("Failed to update thread labels: {e}"),diff --git a/crates/email/src/outbound/email_pg_repo/mod.rs b/crates/email/src/outbound/email_pg_repo/mod.rsindex 3c83b6460e..541dedd620 100644--- a/crates/email/src/outbound/email_pg_repo/mod.rs+++ b/crates/email/src/outbound/email_pg_repo/mod.rs@@ -289,6 +289,15 @@ impl EmailRepo for EmailPgRepo {label::update_message_read_status_batch(&self.pool, message_ids, link_id, is_read).await}+ async fn update_thread_read_status(+ &self,+ thread_id: Uuid,+ link_id: Uuid,+ is_read: bool,+ ) -> Result<(), Self::Err> {+ thread::update_thread_read_status(&self.pool, thread_id, link_id, is_read).await+ }+async fn update_message_starred_status_batch(&self,message_ids: &[Uuid],diff --git a/crates/email/src/outbound/email_pg_repo/test/thread_labels.rs b/crates/email/src/outbound/email_pg_repo/test/thread_labels.rsindex cd837bd9fa..aecf4bfdfa 100644--- a/crates/email/src/outbound/email_pg_repo/test/thread_labels.rs+++ b/crates/email/src/outbound/email_pg_repo/test/thread_labels.rs@@ -349,6 +349,63 @@ async fn test_update_message_read_status_batch_empty(pool: Pool<Postgres>) -> anOk(())}+// ── update_thread_read_status ───────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))+)]+#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]+async fn test_update_thread_read_status_mark_read(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ // Thread starts as unread (is_read=false in fixture)+ repo.update_thread_read_status(thread1, link_id, true)+ .await?;++ let is_read: bool = sqlx::query_scalar("SELECT is_read FROM email_threads WHERE id = $1")+ .bind(thread1)+ .fetch_one(&pool)+ .await?;+ assert!(is_read, "Thread should be marked as read");++ repo.update_thread_read_status(thread1, link_id, false)+ .await?;++ let is_read: bool = sqlx::query_scalar("SELECT is_read FROM email_threads WHERE id = $1")+ .bind(thread1)+ .fetch_one(&pool)+ .await?;+ assert!(!is_read, "Thread should be marked as unread");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))+)]+#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]+async fn test_update_thread_read_status_wrong_link(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());+ let wrong_link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-bbbbbbbbbbbb")?;+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ // Should not update — thread belongs to a different link+ repo.update_thread_read_status(thread1, wrong_link_id, true)+ .await?;++ let is_read: bool = sqlx::query_scalar("SELECT is_read FROM email_threads WHERE id = $1")+ .bind(thread1)+ .fetch_one(&pool)+ .await?;+ assert!(!is_read, "Thread should remain unread (wrong link_id)");++ Ok(())+}+// ── update_message_starred_status_batch ─────────────────────────────#[sqlx::test(diff --git a/crates/email/src/outbound/email_pg_repo/thread.rs b/crates/email/src/outbound/email_pg_repo/thread.rsindex 2c3bbf10e9..84b4342ad2 100644--- a/crates/email/src/outbound/email_pg_repo/thread.rs+++ b/crates/email/src/outbound/email_pg_repo/thread.rs@@ -554,6 +554,34 @@ async fn update_db_thread_metadata(Ok(())}+/// Update the denormalized thread-level read status, verified by link_id.+#[tracing::instrument(err, skip(pool))]+pub(super) async fn update_thread_read_status(+ pool: &PgPool,+ thread_id: Uuid,+ link_id: Uuid,+ is_read: bool,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"+ UPDATE email_threads+ SET+ is_read = $1,+ updated_at = NOW()+ WHERE+ id = $2 AND+ link_id = $3+ "#,+ is_read,+ thread_id,+ link_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}+/// Update the project assignment for a thread. Returns `false` if the thread was not found.#[tracing::instrument(err, skip(pool))]pub(super) async fn update_thread_project(diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rsindex 4380e81737..6524cbfd95 100644--- a/crates/soup/src/inbound/axum_router/tests.rs+++ b/crates/soup/src/inbound/axum_router/tests.rs@@ -310,7 +310,6 @@ impl EmailService for MockEmail {async fn update_thread_labels(&self,- _access_token: &str,_link: &email::domain::models::Link,_thread_id: uuid::Uuid,_label_id: uuid::Uuid,@@ -729,7 +728,6 @@ impl EmailService for MockEmailLinkResult {async fn update_thread_labels(&self,- _access_token: &str,_link: &email::domain::models::Link,_thread_id: uuid::Uuid,_label_id: uuid::Uuid,diff --git a/services/email_service/src/api/email/threads/mod.rs b/services/email_service/src/api/email/threads/mod.rsindex 20177c7107..c7a114ee01 100644--- a/services/email_service/src/api/email/threads/mod.rs+++ b/services/email_service/src/api/email/threads/mod.rs@@ -30,7 +30,6 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {let hex_thread_labels_routes = email::inbound::axum::thread_labels_router::thread_labels_router::<ApiContext,crate::api::context::EmailSvc,- email::outbound::GmailTokenProviderImpl,crate::api::context::AuthorizationService,>();