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 done on reply send (#4521)
Evan Hutnik7ffdb4365eec
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.tsindex 39c7a193c2..05da9f5c21 100644--- a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts@@ -13,7 +13,7 @@ import type { HotkeyGroup } from '@core/hotkey/types';import type { EntityData } from '@entity';import type { NotificationSource } from '@notifications';import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';-import { useUndoableMutation } from '@queries/undo';+import { type UndoHandle, useUndoableMutation } from '@queries/undo';import type { SoupState } from '../create-soup-state';// Valid list views where the mark done should be allowed to run@@ -43,8 +43,16 @@ type MarkDoneVariables = {emailIds: string[];notificationIds: string[];restoreFocus?: () => void;+ /** Suppress the "Marked as done" toast, e.g. for send-triggered mark done+ * where it would replace the "Email sent" toast. */+ silent?: boolean;+ /** Receives the undo handle once the mark-done is pushed onto the undo+ * stack, so callers (e.g. undo-send) can reverse it programmatically. */+ onUndoHandle?: (handle: UndoHandle) => void;};+type MarkDoneExecuteOpts = Pick<MarkDoneVariables, 'silent' | 'onUndoHandle'>;+/** Must be invoked inside a component tree that provides MutationUndoProvider. */export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {const { notificationSource, hotkeyGroup } = options;@@ -99,6 +107,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {},undoLabel: 'Mark Done',onPushed: (handle, variables) => {+ variables.onUndoHandle?.(handle);const firstEntityId = variables.entities[0]?.id;const count = variables.entities.length;const message =@@ -106,6 +115,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {let toastId: number | undefined;const showToast = () => {+ if (variables.silent) return;toastId = toast.success(message, {actions: [{@@ -154,7 +164,11 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {return false;};- const execute = async (entities: EntityData[], restoreFocus?: () => void) => {+ const execute = async (+ entities: EntityData[],+ restoreFocus?: () => void,+ opts?: MarkDoneExecuteOpts+ ) => {const { emailIds, notificationIds } = resolveMarkEntitiesDoneVariables({entities,notificationSource: notificationSource(),@@ -164,13 +178,16 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {emailIds,notificationIds,restoreFocus,+ silent: opts?.silent,+ onUndoHandle: opts?.onUndoHandle,});};const executeWithSoup = async (entities: EntityData[],soup: SoupState,- onNavigate?: (entity: EntityData) => void+ onNavigate?: (entity: EntityData) => void,+ opts?: MarkDoneExecuteOpts) => {const currentIndex = soup.focus.index();const focusedIdBeforeMarkDone = soup.focus.id();@@ -195,7 +212,7 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {onNavigate?.(nextRow.original);}- await execute(entities, restoreFocus);+ await execute(entities, restoreFocus, opts);};return { canExecute, execute, executeWithSoup };diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex d30c76d5fa..3e42a9b6a7 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -81,7 +81,8 @@ import {useSendMessageMutation,useUnscheduleMessageMutation,} from '@queries/email/thread';-import { invalidateSoupEntity } from '@queries/soup/cache';+import { invalidateSoupEntity, refetchSoupEntity } from '@queries/soup/cache';+import type { UndoHandle } from '@queries/undo';import { emailClient } from '@service-email/client';import type {ApiDraftOutputDbId,@@ -400,7 +401,10 @@ export function BaseInput(props: {preloadedBody?: string;preloadedHtml?: string;sideEffectOnSend?: (newMessageId: ApiDraftOutputDbId | null) => void;- onMarkDone?: () => void;+ onMarkDone?: (opts?: {+ silent?: boolean;+ onUndoHandle?: (handle: UndoHandle) => void;+ }) => void;setShowReply?: Setter<boolean>;markdownDomRef?: (ref: HTMLDivElement) => void | HTMLDivElement;}) {@@ -546,6 +550,10 @@ export function BaseInput(props: {let pendingMentions: { documentId: string }[] = [];const [shouldMarkDoneOnSuccess, setShouldMarkDoneOnSuccess] =createSignal(false);+ // Undo entry for the mark-done triggered by the latest send, so undo-send+ // can reverse it. Cleared on each send: undo-send must only un-mark-done+ // when this send did the marking.+ let markDoneUndoHandle: UndoHandle | undefined;const undoSend = async (draftId: string) => {try {@@ -600,6 +608,20 @@ export function BaseInput(props: {props.setShowReply?.(true);}+ // Reverse the mark-done this send triggered (restores the soup rows,+ // notification state, and unarchives), then refresh the thread's soup+ // item the same way a send does so inbox views show the restored draft.+ const doneHandle = markDoneUndoHandle;+ markDoneUndoHandle = undefined;+ if (doneHandle) {+ await doneHandle.undo({+ onError: () => toast.failure('Failed to restore thread to inbox'),+ });+ }+ if (threadId) {+ void refetchSoupEntity(threadId, 'emailThread');+ }+toast.success('Send cancelled');invalidateSoupEntity(draftId);} catch {@@ -638,7 +660,14 @@ export function BaseInput(props: {refetchThreadMessages();props.sideEffectOnSend?.(message.db_id ?? null);if (shouldMarkDoneOnSuccess()) {- props.onMarkDone?.();+ // Silent: the "Email sent" toast is already up and the mark-done+ // toast would replace it.+ props.onMarkDone?.({+ silent: true,+ onUndoHandle: (handle) => {+ markDoneUndoHandle = handle;+ },+ });setShouldMarkDoneOnSuccess(false);}},@@ -1060,7 +1089,12 @@ export function BaseInput(props: {}pendingMentions = prepared.mentions;- setShouldMarkDoneOnSuccess(markDone);+ // Sending a reply marks the thread done. Gated on inbox_visible because+ // onMarkDone (archiveThread) toggles: an already-archived thread (e.g.+ // replying from search or the sent view) would be unarchived.+ const willMarkDone = markDone || (currentThread?.inbox_visible ?? false);+ setShouldMarkDoneOnSuccess(willMarkDone);+ markDoneUndoHandle = undefined;const processedMacroBody = prepareMacroBody(bodyMacro());@@ -1085,6 +1119,7 @@ export function BaseInput(props: {include_signature: includeSignature() ? undefined : false,},linkId: toHeaderLinkId(linkId),+ skipSoupRefetch: willMarkDone,});// Block any save scheduled by reset side effects (form().reset() callDirty,diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsxindex 6a908997bd..7d378d938b 100644--- a/js/app/packages/block-email/component/EmailContext.tsx+++ b/js/app/packages/block-email/component/EmailContext.tsx@@ -31,6 +31,9 @@ import {useArchiveThreadMutation,useThreadQuery,} from '@queries/email/thread';+import { getSoupEntityById } from '@queries/soup/cache';+import { mapApiSoupItemToEntity } from '@queries/soup/transform-utils';+import type { UndoHandle } from '@queries/undo';import type {ApiMessage,ApiThread,@@ -107,7 +110,10 @@ type EmailContextValues = {refetch: () => void;};- archiveThread: () => boolean;+ archiveThread: (opts?: {+ silent?: boolean;+ onUndoHandle?: (handle: UndoHandle) => void;+ }) => boolean;blockSender: () => boolean;markSenderSignal: () => boolean;markSenderNoise: () => boolean;@@ -336,8 +342,14 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();- const archiveThread = () => {+ const archiveThread = (opts?: {+ silent?: boolean;+ onUndoHandle?: (handle: UndoHandle) => void;+ }) => {const thread = threadQuery.data;+ // `=== true` because callers may pass this straight to an event handler.+ const silent = opts?.silent === true;+ const markDoneOpts = { silent, onUndoHandle: opts?.onUndoHandle };if (!thread?.db_id) return false;@@ -351,30 +363,34 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {const selectedRow = soup?.items.get(thread.db_id);- if (selectedRow) {- if (soup) {- markAsDoneAction.executeWithSoup(- [selectedRow.original],- soup,- (nextEntity) => {- const splitHandle = splitPanel?.handle;- if (!splitHandle) return;- void openEntityInSplitFromUnifiedList(nextEntity, {- splitHandle,- mergeHistory: true,- referredFrom: splitHandle.referredFrom(),- });- }+ if (soup && selectedRow) {+ markAsDoneAction.executeWithSoup(+ [selectedRow.original],+ soup,+ (nextEntity) => {+ const splitHandle = splitPanel?.handle;+ if (!splitHandle) return;+ void openEntityInSplitFromUnifiedList(nextEntity, {+ splitHandle,+ mergeHistory: true,+ referredFrom: splitHandle.referredFrom(),+ });+ },+ markDoneOpts+ );+ } else {+ // Not rendered inside a soup list (e.g. thread opened in a split): no+ // row to drive the action from, so mark done via the cached soup entity+ // so soup views drop the thread and its notifications settle. The+ // archive itself already ran above.+ const cachedItem = getSoupEntityById(thread.db_id);+ if (cachedItem && cachedItem.tag !== 'channelThread') {+ void markAsDoneAction.execute(+ [mapApiSoupItemToEntity(cachedItem)],+ undefined,+ markDoneOpts);- } else {- markAsDoneAction.execute([selectedRow.original]);}- } else {- archiveMutation.mutate({- threadId: thread.db_id,- archive: thread.inbox_visible,- linkId: toHeaderLinkId(thread.link_id),- });}return true;diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.tsindex 4eeca53807..cdcfcdd34d 100644--- a/js/app/packages/queries/email/thread.ts+++ b/js/app/packages/queries/email/thread.ts@@ -20,7 +20,7 @@ import {import { err, ok } from 'neverthrow';import type { Accessor } from 'solid-js';import { queryClient } from '../client';-import { optimisticUpdateSoupEntity } from '../soup/cache';+import { optimisticUpdateSoupEntity, refetchSoupEntity } from '../soup/cache';import { invalidateAllSoup } from '../soup/normalized-cache';import { type MutationCallbacks, withCallbacks } from '../utils';import { emailKeys } from './keys';@@ -285,6 +285,10 @@ type SendMessageParams = {message: ApiDraftInput;/** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */linkId?: string;+ /** Skip the post-send soup refresh, e.g. when the thread is about to be+ * marked done and removed from soup views — the refetch would race the+ * removal and re-insert the row. */+ skipSoupRefetch?: boolean;};/**@@ -303,13 +307,18 @@ export function useSendMessageMutation(),...withCallbacks<SendMessageResponse, Error, SendMessageParams>({- onSuccess: (data) => {+ onSuccess: (data, vars) => {analytics.track('email_message_sent');const threadID = data.message.thread_db_id;if (threadID) {queryClient.invalidateQueries({queryKey: emailKeys.threadMessages(threadID).queryKey,});+ // Refresh the thread's soup item so inbox views stop showing it+ // as a draft once the message is sent.+ if (!vars.skipSoupRefetch) {+ refetchSoupEntity(threadID, 'emailThread');+ }}queryClient.invalidateQueries({queryKey: emailKeys.previews._def,diff --git a/js/app/packages/queries/undo.ts b/js/app/packages/queries/undo.tsindex a87c74f828..8cb72e54d6 100644--- a/js/app/packages/queries/undo.ts+++ b/js/app/packages/queries/undo.ts@@ -48,7 +48,7 @@ type UndoEntry = {type UndoEntryInput = Omit<UndoEntry, 'id'>;-type UndoHandle = {+export type UndoHandle = {id: string;/** Undo this specific entry, even if it is not at the top of the stack. */undo: (callbacks?: UndoCallbacks) => Promise<void>;