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: mark not done (#4997)
Peter Chinman1b1b24bd4e25
diff --git a/apps/web/src/features/block-email/component/BottomReplyButtons.tsx b/apps/web/src/features/block-email/component/BottomReplyButtons.tsxindex 03f51e1286..3309b32812 100644--- a/apps/web/src/features/block-email/component/BottomReplyButtons.tsx+++ b/apps/web/src/features/block-email/component/BottomReplyButtons.tsx@@ -6,6 +6,7 @@ import { isMobile } from '@core/mobile/isMobile';import ArrowBendUpLeft from '@phosphor/arrow-bend-up-left.svg';import ArrowBendUpRight from '@phosphor/arrow-bend-up-right.svg';import CheckIcon from '@phosphor/check.svg';+import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';import type { ApiMessage } from '@service-email/generated/schemas';import { createCallback } from '@solid-primitives/rootless';import { Button, cn } from '@ui';@@ -29,7 +30,7 @@ function ReplyActionButton(props: {// Button's own Layer would reset it.)depth={isMobile() ? 3 : undefined}variant="base"- aria-label={props.ariaLabel ?? props.label}+ aria-label={props.ariaLabel}class={cn(// Island pills when floating in the mobile accessory region.'mobile:island mobile:h-8 mobile:rounded-full mobile:border-0'@@ -67,8 +68,14 @@ export function BottomReplyButtons(props: { lastMessage: ApiMessage }) {return email ? inboxIconProps(email) : { email: '' };};- const markDone = () => {- ctx.archiveThread();+ const isDone = () => ctx.isThreadDone();++ const toggleMarkDone = () => {+ if (isDone()) {+ ctx.markThreadNotDone();+ } else {+ ctx.archiveThread();+ }};return (@@ -109,9 +116,16 @@ export function BottomReplyButtons(props: { lastMessage: ApiMessage }) {</div><ReplyActionButton- icon={CheckIcon}- ariaLabel="Mark done"- onClick={markDone}+ icon={(iconProps) => (+ <Show+ when={isDone()}+ fallback={<CheckIcon class={iconProps.class} />}+ >+ <CheckBoldIcon class={cn(iconProps.class, 'text-accent')} />+ </Show>+ )}+ ariaLabel={isDone() ? 'Mark as not done' : 'Mark done'}+ onClick={toggleMarkDone}/></div></div>diff --git a/apps/web/src/features/block-email/component/Email.tsx b/apps/web/src/features/block-email/component/Email.tsxindex b76c12581b..63b6942dec 100644--- a/apps/web/src/features/block-email/component/Email.tsx+++ b/apps/web/src/features/block-email/component/Email.tsx@@ -510,7 +510,8 @@ function EmailContent(props: EmailViewProps) {forwardFocusedMessage: () => openHotkeyTarget('forward'),blockSender: context.blockSender,markDone: context.archiveThread,- markNotDone: context.markNotDone,+ markNotDone: context.markThreadNotDone,+ isThreadDone: context.isThreadDone,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 bda62b88e2..2933a9ecad 100644--- a/apps/web/src/features/block-email/component/EmailContext.tsx+++ b/apps/web/src/features/block-email/component/EmailContext.tsx@@ -1,4 +1,7 @@-import { makeMarkDoneAction } from '@app/features/next-soup/actions';+import {+ makeMarkDoneAction,+ makeMarkNotDoneAction,+} from '@app/features/next-soup/actions';import { useMaybeSoup } from '@app/features/next-soup/soup-context';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import { URL_PARAMS } from '@block-email/constants';@@ -21,7 +24,11 @@ import {type WithCustomUserInput,} from '@core/user';import { whenSettled } from '@core/util/whenSettled';-import { createEffectOnEntityTypeNotification } from '@notifications';+import {+ compositeEntity,+ createEffectOnEntityTypeNotification,+ setDoneOverride,+} from '@notifications';import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';import { queryClient } from '@queries/client';import { emailKeys } from '@queries/email/keys';@@ -34,7 +41,16 @@ import {useThreadQuery,useUndoableArchiveThreadMutation,} from '@queries/email/thread';-import { getSoupEntityById } from '@queries/soup/cache';+import {+ bulkMarkNotificationsAsDone,+ bulkMarkNotificationsAsUndone,+ fetchDoneNotificationIdsByEventItemIds,+} from '@queries/notification/user-notifications';+import {+ getSoupEntityById,+ invalidateAllSoup,+ refetchSoupEntity,+} from '@queries/soup/cache';import { mapApiSoupItemToEntity } from '@queries/soup/transform-utils';import type { UndoHandle } from '@queries/undo';import type {@@ -136,7 +152,10 @@ type EmailContextValues = {};archiveThread: (opts?: ArchiveThreadOptions) => boolean;- markNotDone: () => boolean;+ /** True when the thread is archived, i.e. currently marked done. */+ isThreadDone: Accessor<boolean>;+ /** Unarchives a done thread and restores its notifications. */+ markThreadNotDone: () => boolean;getMarkDoneNavigationTargetId: () => string | undefined;blockSender: () => boolean;markSenderSignal: () => boolean;@@ -366,8 +385,16 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {userId,});- // Only the direct-archive fallback goes through this mutation with- // archive=true (the mark-done action paths toast on their own).+ const markNotDoneAction = makeMarkNotDoneAction({+ notificationSource: () => notificationSource,+ });++ // Notification ids the mark-not-done fallback restored, per thread, so the+ // undo/redo hooks below can re-mark them when the archive flip is replayed.+ const restoredNotificationIds = new Map<string, string[]>();++ // Only the direct archive/unarchive fallbacks go through this mutation+ // (the mark-done / mark-not-done action paths toast on their own).const archiveMutation = useUndoableArchiveThreadMutation({onPushed: (handle, params) => {const message = params.archive ? 'Marked as done' : 'Marked as not done';@@ -394,11 +421,33 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {showToast();+ // Undo/redo replay only the /archived flip; mirror the fallback's+ // notification and soup-list side effects for the resulting state.+ const syncSideEffects = (nowArchived: boolean) => {+ const ids = restoredNotificationIds.get(params.threadId) ?? [];+ if (ids.length > 0) {+ setDoneOverride(ids, nowArchived);+ void (+ nowArchived+ ? bulkMarkNotificationsAsDone(ids)+ : bulkMarkNotificationsAsUndone(ids)+ ).catch(() => setDoneOverride(ids, undefined));+ }+ if (!nowArchived) {+ void refetchSoupEntity(params.threadId, 'emailThread');+ }+ invalidateAllSoup();+ };+return {onUndone: () => {if (toastId !== undefined) toast.dismiss(toastId);+ syncSideEffects(!params.archive);+ },+ onRedone: () => {+ showToast();+ syncSideEffects(params.archive);},- onRedone: showToast,};},onError: (params) => {@@ -426,6 +475,97 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {return candidates.find((row) => row && row.id !== focusedId)?.id;};+ const isThreadDone = () => {+ const thread = threadQuery.data;+ return thread ? !thread.inbox_visible : false;+ };++ // Resolve a thread's soup representation for the mark-done / mark-not-done+ // paths: the live list row when it's rendered, else the normalized+ // soup-cache entity. Shared by markThreadNotDone and archiveThread.+ const resolveThreadSoupLookup = (threadId: string) => {+ const selectedRow = soup?.items.get(threadId);+ const cachedItem = selectedRow ? undefined : getSoupEntityById(threadId);+ return { selectedRow, cachedItem };+ };++ const markThreadNotDone = () => {+ const thread = threadQuery.data;+ if (!thread?.db_id) return false;++ if (thread.inbox_visible) return false;++ // Mark-not-done issues the /archived request itself (plus notification+ // and soup-cache restore), so the path below skips archiveMutation and+ // only mirrors its thread-cache handling via trackExternalThreadArchive.+ const { selectedRow, cachedItem } = resolveThreadSoupLookup(thread.db_id);++ const entity =+ selectedRow?.original ??+ (cachedItem && cachedItem.tag !== 'channelThread'+ ? mapApiSoupItemToEntity(cachedItem)+ : undefined);++ if (entity && markNotDoneAction.canExecute(entity)) {+ void trackExternalThreadArchive(+ thread.db_id,+ markNotDoneAction.execute([entity]),+ false+ );+ } else {+ // No soup entity to drive the action from — the mark-done removal+ // evicted it from the soup caches (or its done state hasn't caught up+ // with the thread's): unarchive directly, then refetch the thread's+ // soup item to reinsert its rows and refetch the lists.+ const threadId = thread.db_id;+ // Snapshot the thread's notification ids now — the entity path restores+ // them via executeMarkEntitiesUndone, so mirror that here or they stay+ // done after the unarchive.+ const notificationIds = (+ notificationSource.notificationsByEntity()[+ compositeEntity({ type: 'email_thread', id: threadId })+ ] ?? []+ ).map((n) => n.id);+ archiveMutation.mutate(+ {+ threadId,+ archive: false,+ linkId: toHeaderLinkId(thread.link_id),+ },+ {+ onSuccess: async () => {+ // The live notification stream only carries not-done+ // notifications, so the thread's done ids may have aged out of+ // the local cache — merge the server's view (best effort: the+ // unarchive itself already succeeded).+ const serverIds = await fetchDoneNotificationIdsByEventItemIds([+ threadId,+ ]).catch(() => []);+ const allIds = [...new Set([...notificationIds, ...serverIds])];+ // Record for the undo/redo hooks, which re-mark these when the+ // archive flip is replayed.+ restoredNotificationIds.set(threadId, allIds);+ if (allIds.length > 0) {+ setDoneOverride(allIds, false);+ try {+ await bulkMarkNotificationsAsUndone(allIds);+ } catch {+ // The unarchive itself succeeded, so keep that outcome and+ // let the override fall back to the server's done state.+ setDoneOverride(allIds, undefined);+ toast.failure('Failed to mark as not done');+ }+ }+ void refetchSoupEntity(threadId, 'emailThread');+ invalidateAllSoup();+ },+ }+ );+ }++ return true;+ };+const archiveThread = (opts?: ArchiveThreadOptions) => {const thread = threadQuery.data;// `=== true` because callers may pass this straight to an event handler.@@ -437,24 +577,12 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {if (!thread?.db_id) return false;- // Unarchiving ('e' on an already-done thread) is a plain toggle back to- // the inbox; the mark-done action doesn't apply.- if (!thread.inbox_visible) {- archiveMutation.mutate({- threadId: thread.db_id,- archive: false,- linkId: toHeaderLinkId(thread.link_id),- });- return true;- }+ if (!thread.inbox_visible) return false;// Mark done issues the /archived request itself (with undo support), so// the paths below skip archiveMutation and only mirror its thread-cache// handling via trackExternalThreadArchive.- const selectedRow = soup?.items.get(thread.db_id);- const cachedItem = selectedRow- ? undefined- : getSoupEntityById(thread.db_id);+ const { selectedRow, cachedItem } = resolveThreadSoupLookup(thread.db_id);if (soup && selectedRow) {void trackExternalThreadArchive(@@ -498,18 +626,6 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {return true;};- const markNotDone = () => {- const thread = threadQuery.data;- if (!thread?.db_id || thread.inbox_visible) return false;-- archiveMutation.mutate({- threadId: thread.db_id,- archive: false,- linkId: toHeaderLinkId(thread.link_id),- });- return true;- };-const currentUserEmail = useEmail();const blockSender = () => {@@ -679,7 +795,8 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {recipientOptions: createMemo(getRecipientOptions),onRecipientsChange,archiveThread,- markNotDone,+ isThreadDone,+ markThreadNotDone,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 aae8875c8e..607a16c665 100644--- a/apps/web/src/features/block-email/component/TopBar.tsx+++ b/apps/web/src/features/block-email/component/TopBar.tsx@@ -38,6 +38,7 @@ import { AnimatedTaskIcon } from '@icon/wide-task';import CheckIcon from '@phosphor/check.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';import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';import { useEmailLinksQuery } from '@queries/email/link';import { Button } from '@ui';@@ -86,15 +87,21 @@ export function TopBar(props: {return links.some((link) => link.id === thread.link_id);};- const markDone = () => {+ const isDone = () => emailCtx.isThreadDone();++ const toggleMarkDone = () => {+ if (isDone()) {+ emailCtx.markThreadNotDone();+ return;+ }// Prefer the active Mark done command so it drives soup navigation and- // notifications; fall back to archiving the thread directly.+ // notifications; fall back to archiving the thread directly. A command+ // can be found but still decline (condition/handler returns false, e.g.+ // the triage registration when not opened from inbox/mail), so gate on+ // it actually capturing.const command = getActiveCommandByToken(TOKENS.entity.action.markDone);- if (command) {- runCommand(command);- } else {- emailCtx.archiveThread();- }+ if (command && runCommand(command).commandCaptured) return;+ emailCtx.archiveThread();};const trashThread = () => {@@ -165,12 +172,6 @@ export function TopBar(props: {action: () => props.onCreateTask?.(),condition: () => !!props.onCreateTask && !!emailCtx.thread()?.db_id,},- {- label: 'Mark done',- icon: CheckIcon,- action: markDone,- condition: isOwnThread,- },{label: 'Delete',icon: TrashIcon,@@ -245,17 +246,24 @@ export function TopBar(props: {</SplitTitleFileMenu>{/* Desktop-only Mark done button, sitting just left of the Previous item- caret. On mobile this action lives in the bottom reply bar instead. */}+ caret. On mobile this action lives in the bottom reply bar instead.+ A done thread shows a bold accent check and unarchives on click. */}<Show when={!isMobile()}><SplitHeaderRight><Show when={isOwnThread()}><Buttonclass="p-1 rounded-lg"- label="Mark done"- hotkey={TOKENS.entity.action.markDone}- onClick={markDone}+ label={isDone() ? 'Mark as not done' : 'Mark done'}+ hotkey={+ isDone()+ ? TOKENS.entity.action.markNotDone+ : TOKENS.entity.action.markDone+ }+ onClick={toggleMarkDone}>- <CheckIcon class="size-4" />+ <Show when={isDone()} fallback={<CheckIcon class="size-4" />}>+ <CheckBoldIcon class="size-4 text-accent" />+ </Show></Button></Show></SplitHeaderRight>diff --git a/apps/web/src/features/block-email/util/emailHotkeys.ts b/apps/web/src/features/block-email/util/emailHotkeys.tsindex 8592f487e0..11fa617b1d 100644--- a/apps/web/src/features/block-email/util/emailHotkeys.ts+++ b/apps/web/src/features/block-email/util/emailHotkeys.ts@@ -8,6 +8,8 @@ interface EmailHotkeyHandlers {blockSender: () => boolean;markDone: () => boolean;markNotDone: () => boolean;+ /** Gates which of Mark done / Mark as not done is active. */+ isThreadDone: () => boolean;markSenderSignal: () => boolean;markSenderNoise: () => boolean;navigateToPreviousMessage: () => boolean;@@ -53,14 +55,16 @@ export function registerEmailHotkeys(keyDownHandler: handlers.markDone,hotkeyToken: TOKENS.entity.action.markDone,displayPriority: 10,+ condition: () => !handlers.isThreadDone(),});registerHotkey({hotkey: 'shift+e',scopeId,- description: 'Mark not done',+ description: 'Mark as not done',keyDownHandler: handlers.markNotDone,hotkeyToken: TOKENS.entity.action.markNotDone,displayPriority: 10,+ condition: () => handlers.isThreadDone(),});registerHotkey({scopeId: scopeId,diff --git a/apps/web/src/features/entity/index.ts b/apps/web/src/features/entity/index.tsindex 688f974336..325e8d138a 100644--- a/apps/web/src/features/entity/index.ts+++ b/apps/web/src/features/entity/index.ts@@ -35,7 +35,7 @@ export {} from './queries/dss';export { createEmailsInfiniteQuery } from './queries/email';export { createUpdateFileTypeMutation } from './queries/file-type';-export { queryKeys } from './queries/key';+export { emailQueryKeyExcludesDone, queryKeys } from './queries/key';export {createBulkRenameDssEntityMutation,createRenameDssEntityMutation,diff --git a/apps/web/src/features/entity/queries/key.ts b/apps/web/src/features/entity/queries/key.tsindex 05c77796a4..f25fbfb7ea 100644--- a/apps/web/src/features/entity/queries/key.ts+++ b/apps/web/src/features/entity/queries/key.ts@@ -30,6 +30,33 @@ type SearchKeyOptions = {infinite: true;} & SearchArgs;+/**+ * Email preview views that are inbox-scoped server-side and so exclude+ * archived (done) threads. Exhaustive over PreviewViewStandardLabel: adding+ * a view label won't compile until it's classified here.+ */+const EMAIL_VIEW_EXCLUDES_DONE: Record<PreviewViewStandardLabel, boolean> = {+ inbox: true,+ important: true,+ other: true,+ all: false,+ starred: false,+ sent: false,+ drafts: false,+};++/**+ * Whether an email list query key (built by `queryKeys.email`) belongs to a+ * view that excludes done threads. Owned here because this module owns the+ * key shape: the options object is the key's final element.+ */+export function emailQueryKeyExcludesDone(key: readonly unknown[]): boolean {+ const options = key.at(-1);+ if (typeof options !== 'object' || options === null) return false;+ const view = (options as Partial<EmailKeyOptions>).view;+ return view !== undefined && EMAIL_VIEW_EXCLUDES_DONE[view] === true;+}+export const queryKeys = {all: {...BASE_ENTITY,diff --git a/apps/web/src/features/next-soup/actions/index.ts b/apps/web/src/features/next-soup/actions/index.tsindex bb266011bf..f669745e04 100644--- a/apps/web/src/features/next-soup/actions/index.ts+++ b/apps/web/src/features/next-soup/actions/index.ts@@ -7,6 +7,7 @@ export { makeDeleteAction } from './make-delete-action';export { makeFavoriteAction } from './make-favorite-action';export { makeHideCompanyAction } from './make-hide-company-action';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 { makeMoveToProjectAction } from './make-move-to-project-action';diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.tsindex 59b383573c..48925473a5 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts@@ -36,6 +36,12 @@ export const canExecuteMarkDoneOnView = (view: ListView, tabId: string) => {return VALID_MARK_DONE_LIST_VIEWS.includes(`${view}-${tabId}`);};+/** Already-done emails are skipped by mark-done (they appear alongside+ * not-done rows in views that show done content, e.g. mail "All"). done+ * state is email-specific; other entity types are never filtered. */+const isMarkDoneTarget = (e: EntityData) =>+ !(e.type === 'email' && e.done === true);+type MakeMarkDoneOptions = {userId?: () => string | undefined;notificationSource: () => NotificationSource;@@ -208,13 +214,18 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {restoreFocus?: () => void,opts?: MarkDoneExecuteOpts) => {+ // Skip already-done emails so a mixed selection (e.g. done + not-done rows+ // in mail "All") doesn't re-archive the done ones or overcount the toast.+ const targets = entities.filter(isMarkDoneTarget);+ if (targets.length === 0) return;+const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({- entities,+ entities: targets,notificationSource: notificationSource(),scopeChannelNotificationsToEntity: scopeChannelNotificationsToEntity(),});await mutation.mutateAsync({- entities,+ entities: targets,emailIds,notificationIds,restoreFocus,@@ -230,8 +241,14 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {onNavigate?: (entity: EntityData) => void,opts?: MarkDoneExecuteWithSoupOpts) => {+ // Apply execute's already-done filter up front so navigation, selection+ // clearing, collapse, and the undo target all reflect what's actually+ // marked (and nothing happens when nothing will be).+ const targets = entities.filter(isMarkDoneTarget);+ if (targets.length === 0) return;+const focusedIdBeforeMarkDone = soup.focus.id();- const markedEntityIds = new Set(entities.map((entity) => entity.id));+ const markedEntityIds = new Set(targets.map((entity) => entity.id));const adjacentRow = (direction: 1 | -1) => {let previousCandidateIndex: number | undefined;@@ -265,7 +282,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {if (soup.collapseEntity.shouldCollapse()) {const collapse = soup.collapseEntity.callback();if (collapse) {- await Promise.all(entities.map((entity) => collapse(entity.id)));+ await Promise.all(targets.map((entity) => collapse(entity.id)));}}@@ -282,14 +299,14 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {// When marking done navigated the view to the next item, undo navigates// back to the marked entity through the same callback.- const firstEntity = entities[0];+ const firstEntity = targets[0];const navigateBack =opts?.navigateBack ??(nextRow && onNavigate && firstEntity? () => onNavigate(firstEntity): undefined);- await execute(entities, restoreFocus, { ...opts, navigateBack });+ await execute(targets, restoreFocus, { ...opts, navigateBack });};return { canExecute, execute, executeWithSoup };diff --git a/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.tsnew file mode 100644index 0000000000..47382f103c--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-mark-not-done-action.ts@@ -0,0 +1,86 @@+import {+ applyEntitiesNotDoneOptimistic,+ executeMarkEntitiesUndone,+ resolveMarkEntitiesDoneVariables,+} from '@app/features/next-soup/utils';+import { toast } from '@core/component/Toast/Toast';+import type { EntityData } from '@entity';+import type { NotificationSource } from '@notifications';+import { fetchDoneNotificationIdsByEventItemIds } from '@queries/notification/user-notifications';+import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';+import type { SoupState } from '../create-soup-state';++type MakeMarkNotDoneOptions = {+ notificationSource: () => NotificationSource;+};++/**+ * Reverses a mark-done: unarchives email threads and restores their+ * notifications. Only done emails qualify — other entity types' done state+ * lives on their notifications, and their rows never render as done in the+ * mark-done-capable views.+ */+export const makeMarkNotDoneAction = (options: MakeMarkNotDoneOptions) => {+ const canExecute = (entity: EntityData): boolean =>+ entity.type === 'email' && entity.done === true;++ const execute = async (entities: EntityData[]) => {+ const targets = entities.filter(canExecute);+ if (targets.length === 0) return;++ const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({+ entities: targets,+ notificationSource: options.notificationSource(),+ });++ const optimistic = applyEntitiesNotDoneOptimistic({+ emailIds,+ notificationIds,+ });++ try {+ // The live notification stream only carries not-done notifications, so+ // a done thread's ids may have aged out of the local cache — resolve+ // them from the server and merge before restoring.+ const serverNotificationIds =+ await fetchDoneNotificationIdsByEventItemIds(emailIds);+ await executeMarkEntitiesUndone({+ emailIds,+ notificationIds: [+ ...new Set([...notificationIds, ...serverNotificationIds]),+ ],+ });+ // Match the mark-done action's success feedback (and the direct+ // unarchive fallback's toast in EmailContext).+ toast.success(+ targets.length > 1+ ? `Marked ${targets.length} items as not done`+ : 'Marked as not done',+ { duration: 3_000, stack: true, hideOnMobile: true }+ );+ // Restore the rows deterministically: refetch each thread's soup item+ // and upsert it into the caches (flat, grouped parents, and expanded+ // group queries), then refetch the lists so done-filtered views+ // reconcile membership and ordering.+ await Promise.all(+ emailIds.map((id) => refetchSoupEntity(id, 'emailThread'))+ );+ invalidateAllSoup();+ } catch (err) {+ optimistic.rollback();+ toast.failure('Failed to mark as not done');+ // Rethrow (matching makeMarkDoneAction's mutateAsync) so wrappers like+ // trackExternalThreadArchive can restore their own caches; UI feedback+ // is already handled above.+ throw err;+ }+ };++ /** Signature parity with makeMarkDoneAction's executeWithSoup — 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 2b3240d0d0..99c3430ded 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@@ -24,6 +24,7 @@ import {makeDeleteAction,makeFavoriteAction,makeMarkDoneAction,+ makeMarkNotDoneAction,makeMoveToProjectAction,makeRenameAction,makeSetCompanyPropertyAction,@@ -56,6 +57,10 @@ export const useEntityActionHotkeys = (hotkeyGroup: group,});+ const markNotDone = makeMarkNotDoneAction({+ notificationSource: () => notificationSource,+ });+const deleteAction = makeDeleteAction({userId: () => userId(),});@@ -172,6 +177,40 @@ export const useEntityActionHotkeys = (tags: [HotkeyTags.SelectionModification],}).withGroup(group);+ // Mark as not done - 'shift+e', reverses mark done on archived emails+ registerHotkey({+ hotkey: ['shift+e'],+ hotkeyToken: TOKENS.entity.action.markNotDone,+ scopeId,+ description: 'Mark as not done',+ keyDownHandler: () => {+ const entities = getEntitiesForAction();+ if (entities.length === 0) return false;+ if (!entities.every(markNotDone.canExecute)) return false;++ markNotDone.executeWithSoup(entities, soup);+ return true;+ },+ condition: () => {+ if (condition && !condition()) return false;++ const contentId = splitHandle?.content().id;++ const soupViewTab = options.activeSoupViewTab?.();++ if (+ !isListViewID(contentId) ||+ (soupViewTab && !canExecuteMarkDoneOnView(contentId, soupViewTab))+ )+ return false;++ const entities = getEntitiesForAction();+ return entities.length > 0 && entities.every(markNotDone.canExecute);+ },+ displayPriority: 10,+ 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 fe955de6fd..d9fa58e056 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@@ -24,6 +24,7 @@ import {makeFavoriteAction,makeHideCompanyAction,makeMarkDoneAction,+ makeMarkNotDoneAction,makeMarkSenderNoiseAction,makeMarkSenderSignalAction,makeMoveToProjectAction,@@ -92,6 +93,10 @@ export function createSoupEntityActions(): {notificationSource: () => notificationSource,});+ const markNotDone = makeMarkNotDoneAction({+ notificationSource: () => notificationSource,+ });+const deleteAction = makeDeleteAction({userId: () => userId(),});@@ -136,15 +141,25 @@ export function createSoupEntityActions(): {if (activeTab &&isListViewID(activeListView) &&- canExecuteMarkDoneOnView(activeListView, activeTab) &&- canExecuteAll(markDone.canExecute)+ canExecuteMarkDoneOnView(activeListView, activeTab)) {- topItems.push({- id: 'mark-done',- label: 'Mark Done',- hotkeyToken: TOKENS.entity.action.markDone,- onClick: handle(markDone.executeWithSoup),- });+ // A fully-done selection (e.g. archived threads in mail "All") gets the+ // reverse action; anything else gets Mark Done.+ if (canExecuteAll(markNotDone.canExecute)) {+ topItems.push({+ id: 'mark-not-done',+ label: 'Mark Not Done',+ hotkeyToken: TOKENS.entity.action.markNotDone,+ onClick: handle(markNotDone.executeWithSoup),+ });+ } else if (canExecuteAll(markDone.canExecute)) {+ topItems.push({+ id: 'mark-done',+ label: 'Mark Done',+ hotkeyToken: TOKENS.entity.action.markDone,+ onClick: handle(markDone.executeWithSoup),+ });+ }}const canOpenInSplit = () => {diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.tsindex a9e1260233..f5c0ba9b47 100644--- a/apps/web/src/features/next-soup/utils.ts+++ b/apps/web/src/features/next-soup/utils.ts@@ -28,6 +28,7 @@ import { openExternalUrl } from '@core/util/url';import {type ChannelClickTarget,type EntityData,+ emailQueryKeyExcludesDone,getSnippetHit,isEmailEntity,isGithubPrEntity,@@ -63,6 +64,7 @@ import {invalidateSoupEntity,optimisticUpdateSoupEntity,removeSoupEntities,+ removeSoupEntitiesFromDoneFilteredQueries,} from '@queries/soup/cache';import { emailClient } from '@service-email/client';import { isAfter } from 'date-fns';@@ -960,9 +962,10 @@ export function resolveMarkEntitiesDoneVariables(args: {}/**- * Applies the optimistic UI state for marking entities as done — removes- * emails from the soup + email caches and flips the notification `done`- * override. Returns a context the mutation uses for rollback / reapply.+ * Applies the optimistic UI state for marking entities as done — removes the+ * entities from done-filtered soup/email caches, flips surviving email rows+ * to the done state, and sets the notification `done` override. Returns a+ * context the mutation uses for rollback / reapply.*/export function applyEntitiesDoneOptimistic(args: {entityIds: string[];@@ -989,6 +992,8 @@ export function applyEntitiesDoneOptimistic(args: {queryKey: queryKeys.all.email,})) {if (!data) continue;+ // Views that show done threads keep their rows.+ if (!emailQueryKeyExcludesDone(key)) continue;const bucket = removedEmails.get(key) ?? new Map<string, EntityData>();let mutated = false;const pages = data.pages.map((page) => {@@ -1038,26 +1043,45 @@ export function applyEntitiesDoneOptimistic(args: {};let soupTxn: ReturnType<typeof removeSoupEntities> | null = null;+ let emailRowTxns: { rollback: () => void }[] = [];const reapply = () => {- // Remove every marked entity from the soup feed cache so the hide is- // authoritative for all types; undo restores them via this transaction's- // rollback.- soupTxn = entityIds.length > 0 ? removeSoupEntities(entityIdSet) : null;+ // Remove the marked entities from done-filtered soup queries (inbox,+ // mail Important/Noise); views that show done content (e.g. mail All)+ // keep their rows. Undo restores them via this transaction's rollback.+ soupTxn =+ entityIds.length > 0+ ? removeSoupEntitiesFromDoneFilteredQueries(entityIdSet)+ : null;+ // Rows that remain visible flip to the done state.+ emailRowTxns = emailIds.map((id) =>+ optimisticUpdateSoupEntity({+ tag: 'emailThread',+ data: { id, inboxVisible: false },+ frecency_score: getSoupEntityById(id)?.frecency_score ?? 0,+ })+ );filterEmailCache();setDoneOverride(notificationIds, true);};- const rollback = () => {+ const rollbackSoup = () => {+ for (const txn of [...emailRowTxns].reverse()) {+ txn.rollback();+ }+ emailRowTxns = [];soupTxn?.rollback();soupTxn = null;+ };++ const rollback = () => {+ rollbackSoup();restoreEmailCache();setDoneOverride(notificationIds, undefined);};const applyUndone = () => {- soupTxn?.rollback();- soupTxn = null;+ rollbackSoup();restoreEmailCache();restoreUserNotifications(notificationSnapshots);// Force `done=false` — cache may have reconciled to `done=true` from the@@ -1070,6 +1094,37 @@ export function applyEntitiesDoneOptimistic(args: {return { rollback, reapply, applyUndone };}+/**+ * Optimistic UI for marking entities as not done — flips email rows back to+ * inbox-visible and forces the notification `done` override off. Rows are+ * patched in place; done-filtered views regain the entities when the caller+ * invalidates after the server confirms.+ */+export function applyEntitiesNotDoneOptimistic(args: {+ emailIds: string[];+ notificationIds: string[];+}): { rollback: () => void } {+ const { emailIds, notificationIds } = args;++ const emailRowTxns = emailIds.map((id) =>+ optimisticUpdateSoupEntity({+ tag: 'emailThread',+ data: { id, inboxVisible: true },+ frecency_score: getSoupEntityById(id)?.frecency_score ?? 0,+ })+ );+ setDoneOverride(notificationIds, false);++ return {+ rollback: () => {+ for (const txn of [...emailRowTxns].reverse()) {+ txn.rollback();+ }+ setDoneOverride(notificationIds, undefined);+ },+ };+}+/*** Fires the archive + bulk-done APIs for the given ids. Throws on any* failure; caller is responsible for rollback via the context returned bydiff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.tsindex 8ba4af5f68..844f67f6c5 100644--- a/apps/web/src/lib/queries/email/thread.ts+++ b/apps/web/src/lib/queries/email/thread.ts@@ -236,19 +236,21 @@ async function threadArchiveOnMutate(params: ArchiveThreadParams) {}/**- * Cache bookkeeping for an archive performed by another mutation (e.g. the- * mark-done action, which issues its own /archived request): optimistically- * flips `inbox_visible`, rolls back if the request fails, and invalidates the- * thread + preview queries once it settles. Mirrors useArchiveThreadMutation- * without firing a second request.+ * Cache bookkeeping for an archive/unarchive performed by another mutation+ * (e.g. the mark-done and mark-not-done actions, which issue their own+ * /archived requests): optimistically flips `inbox_visible`, rolls back if+ * the request fails, and invalidates the thread + preview queries once it+ * settles. Mirrors useUndoableArchiveThreadMutation's cache handling without+ * firing a second request or pushing an undo entry.*/export async function trackExternalThreadArchive(threadId: string,- archived: Promise<unknown>+ archived: Promise<unknown>,+ archive = true): Promise<void> {const { previousData } = await threadArchiveOnMutate({threadId,- archive: true,+ archive,});try {await archived;@@ -267,54 +269,6 @@ export async function trackExternalThreadArchive(}}-/**- * Mutation to archive or unarchive a thread.- * Uses optimistic updates to immediately reflect the change in UI.- */-export function useArchiveThreadMutation(- callbacks?: MutationCallbacks<- void,- Error,- ArchiveThreadParams,- ArchiveThreadContext- >-) {- return useMutation(() => ({- mutationFn: async (params: ArchiveThreadParams) => {- await throwOnErr(- async () =>- await emailClient.flagArchived(- {- id: params.threadId,- value: params.archive,- },- params.linkId- )- );- },- ...withCallbacks<void, Error, ArchiveThreadParams, ArchiveThreadContext>(- {- onMutate: async (params) => await threadArchiveOnMutate(params),- onError: (_err, params, context) => {- if (context?.previousData) {- queryClient.setQueryData(- emailKeys.threadMessages(params.threadId).queryKey,- context.previousData- );- }- },- onSettled: (_data, _error, params) => {- queryClient.invalidateQueries({- queryKey: emailKeys.threadMessages(params.threadId).queryKey,- });- queryClient.invalidateQueries({ queryKey: emailKeys.previews._def });- },- },- callbacks- ),- }));-}-/*** One archive/unarchive cycle for undo/redo replays: optimistic flip, API* call, rollback on failure, invalidate on settle. Mirrors what@@ -347,10 +301,10 @@ async function replayThreadArchive(params: ArchiveThreadParams): Promise<void> {}/**- * Undoable variant of `useArchiveThreadMutation`: each successful archive or- * unarchive is pushed onto the mutation undo stack, and undo/redo replays the- * opposite call with the same optimistic cache handling.- * Must be used inside a MutationUndoProvider.+ * Mutation to archive or unarchive a thread, with optimistic `inbox_visible`+ * handling. Each successful archive or unarchive is pushed onto the mutation+ * undo stack, and undo/redo replays the opposite call with the same+ * optimistic cache handling. Must be used inside a MutationUndoProvider.*/export function useUndoableArchiveThreadMutation(options: {/** Bind side effects (e.g. an undo toast) to the pushed undo entry. */diff --git a/apps/web/src/lib/queries/notification/user-notifications.ts b/apps/web/src/lib/queries/notification/user-notifications.tsindex cdfebbabb4..f6b31b4f90 100644--- a/apps/web/src/lib/queries/notification/user-notifications.ts+++ b/apps/web/src/lib/queries/notification/user-notifications.ts@@ -313,6 +313,36 @@ export async function bulkMarkNotificationsAsUndone();}+/**+ * Fetch the ids of the given event items' DONE notifications from the server.+ * The live user-notifications stream only carries not-done notifications, so+ * a done thread's ids age out of the local cache — mark-not-done resolves+ * them server-side to restore reliably. Throws on failure.+ */+export async function fetchDoneNotificationIdsByEventItemIds(+ eventItemIds: string[]+): Promise<string[]> {+ if (eventItemIds.length === 0) return [];+ const ids: string[] = [];+ let cursor: string | undefined;+ do {+ const response = await throwOnErr(+ async () =>+ await notificationServiceClient.bulkGetUserNotificationsByEventItemId({+ eventItemIds,+ // Server max page size; bulk selections can span many threads, so+ // follow the cursor through every page rather than capping.+ limit: 500,+ done: true,+ cursor,+ })+ );+ ids.push(...response.items.map((n) => n.id));+ cursor = response.next_cursor ?? undefined;+ } while (cursor);+ return ids;+}+export function invalidateEntityNotifications(eventItemId: string) {return queryClient.invalidateQueries({queryKey: [...notificationKeys.entity._def, eventItemId],diff --git a/apps/web/src/lib/queries/soup/normalized-cache/index.ts b/apps/web/src/lib/queries/soup/normalized-cache/index.tsindex 498e3a2fcc..a8ac18bc6f 100644--- a/apps/web/src/lib/queries/soup/normalized-cache/index.ts+++ b/apps/web/src/lib/queries/soup/normalized-cache/index.ts@@ -12,6 +12,7 @@ export {refetchSoupEntity,removeSearchEntities,removeSoupEntities,+ removeSoupEntitiesFromDoneFilteredQueries,removeSoupEntitiesFromQueriesReferencing,} from './operations';export type {diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.tsindex be2963deb7..f277ed97d6 100644--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts@@ -51,6 +51,7 @@ import {optimisticUpdateSoupItemUpdatedAt,removeSearchEntities,removeSoupEntities,+ removeSoupEntitiesFromDoneFilteredQueries,} from './operations';// -- Fixtures --@@ -333,6 +334,58 @@ describe('removeSoupEntities', () => {});});+describe('removeSoupEntitiesFromDoneFilteredQueries', () => {+ const emailItem = (id: string): SoupApiItem =>+ ({+ tag: 'emailThread',+ data: { id, inboxVisible: true },+ frecency_score: 1,+ }) as unknown as SoupApiItem;++ // Query keys carry the compiled filter body; done-excluding views embed+ // `emailView: 'inbox'` or a compiled `*Done: false` literal.+ const inboxViewKey = [...soupKeys.items._def, { emailView: 'inbox' }];+ const doneFilterKey = [+ ...soupKeys.items._def,+ { ef: [{ l: { NotificationDone: false } }] },+ ];+ const ndFilterKey = [...soupKeys.items._def, { df: [{ l: { nd: false } }] }];+ const allViewKey = [...soupKeys.items._def, { emailView: 'all' }];++ const itemsAt = (key: unknown[]) =>+ testQueryClient+ .getQueryData<InfiniteData<SoupPage, unknown>>(key)!+ .pages[0].items.map(getSoupItemId);++ it('removes from done-filtered queries and keeps done-inclusive ones', () => {+ const data = () => mockSoupCache([[emailItem('e-1'), mockChatItem('c-1')]]);+ testQueryClient.setQueryData(inboxViewKey, data());+ testQueryClient.setQueryData(doneFilterKey, data());+ testQueryClient.setQueryData(ndFilterKey, data());+ testQueryClient.setQueryData(allViewKey, data());++ removeSoupEntitiesFromDoneFilteredQueries(new Set(['e-1']));++ expect(itemsAt(inboxViewKey)).toEqual(['c-1']);+ expect(itemsAt(doneFilterKey)).toEqual(['c-1']);+ expect(itemsAt(ndFilterKey)).toEqual(['c-1']);+ expect(itemsAt(allViewKey)).toEqual(['e-1', 'c-1']);+ });++ it('rollback restores removed rows', () => {+ testQueryClient.setQueryData(+ inboxViewKey,+ mockSoupCache([[emailItem('e-1'), mockChatItem('c-1')]])+ );++ const tx = removeSoupEntitiesFromDoneFilteredQueries(new Set(['e-1']));+ expect(itemsAt(inboxViewKey)).toEqual(['c-1']);++ tx.rollback();+ expect(itemsAt(inboxViewKey)).toEqual(['e-1', 'c-1']);+ });+});+describe('removeSearchEntities', () => {it('filters matching IDs from search results', () => {seedSearchQuery(diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.tsindex 07ebc1a709..8c53d2965b 100644--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts@@ -162,6 +162,12 @@ export function invalidateAllSoup(): void {queryClient.invalidateQueries({queryKey: soupKeys.astItems._def,});+ // Expanded single-group caches back grouped views' rows (mail/inbox group+ // by date); leaving them stale keeps removed rows hidden even after their+ // parent queries refetch.+ queryClient.invalidateQueries({+ queryKey: soupKeys.groupedGroup._def,+ });}export function hasSoupEntity(entityId: string): boolean {@@ -336,11 +342,46 @@ export function removeSoupEntitiesFromQueriesReferencing(): SoupTransaction {if (referenceIds.length === 0) return { rollback: () => {} };- const referencesIds = (key: QueryKey) => {+ return removeSoupEntitiesWhere(entityIds, (key: QueryKey) => {const serialized = JSON.stringify(key);return referenceIds.some((id) => serialized.includes(id));- };+ });+}+/**+ * Serialized-key test for soup queries that exclude done content. The markers+ * a compiled soup query key can carry: `emailView: 'inbox'` (server-side+ * inbox scoping of email views, e.g. mail Important/Noise) and compiled+ * done-filter literals — `NotificationDone` (emails/channels) or `nd`+ * (documents/chats/folders/foreign entities) with a `false` value, produced+ * by the `*Done: false` filter presets.+ */+function soupQueryExcludesDone(key: QueryKey): boolean {+ const serialized = JSON.stringify(key);+ return (+ serialized.includes('"emailView":"inbox"') ||+ serialized.includes('"NotificationDone":false') ||+ serialized.includes('"nd":false')+ );+}++/**+ * Remove entities from soup queries that filter out done content, leaving+ * them in place everywhere else (e.g. mail "All", which shows done threads).+ * Use with an entity-level done patch so the remaining rows reflect the new+ * state.+ */+export function removeSoupEntitiesFromDoneFilteredQueries(+ entityIds: Set<string>+): SoupTransaction {+ return removeSoupEntitiesWhere(entityIds, soupQueryExcludesDone);+}++/** Remove entities from the soup queries whose key matches the predicate. */+function removeSoupEntitiesWhere(+ entityIds: Set<string>,+ referencesIds: (key: QueryKey) => boolean+): SoupTransaction {// Scoped equivalent of cancelSoupQueries (same data !== undefined guard)const cancelPredicate = (query: Query) =>query.state.data !== undefined && referencesIds(query.queryKey);diff --git a/apps/web/src/lib/service-clients/service-notification/client.ts b/apps/web/src/lib/service-clients/service-notification/client.tsindex 39e0cdfa3c..4b23f8e30e 100644--- a/apps/web/src/lib/service-clients/service-notification/client.ts+++ b/apps/web/src/lib/service-clients/service-notification/client.ts@@ -104,12 +104,12 @@ export const notificationServiceClient = {).map((result) => result);},async bulkGetUserNotificationsByEventItemId(- args: NotificationParams & BulkGetByEventItemIdsRequest+ args: UserNotificationParams & BulkGetByEventItemIdsRequest) {- const { limit, cursor } = args;+ const { limit, cursor, done } = args;return (await notificationFetch<GetAllUserNotificationsResponse>(- `/user_notifications/item/bulk?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}`,+ `/user_notifications/item/bulk?limit=${limit}${cursor ? `&cursor=${cursor}` : ''}${done !== undefined ? `&done=${done}` : ''}`,{method: 'POST',headers: { 'Content-Type': 'application/json' },