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): Undo send functionality (#1580)
Evan Hutnik02f1475d5ef5
diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex 77e1d74682..d1e9120090 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -58,7 +58,9 @@ export function resolveComponent(registerComponent('unified-list', () => <SoupView />);registerComponent('loading', () => <LoadingBlock />);registerComponent('channel-compose', () => <ChannelCompose />);-registerComponent('email-compose', () => <EmailCompose />);+registerComponent('email-compose', (params) => (+ <EmailCompose draftID={params?.draftID} />+));registerComponent('task-compose', () => <ComposeTask />);registerComponent('import-linear',diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex 2de4193b90..4d88133479 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -39,8 +39,12 @@ import {$appendWatermarkNodeToLast,$removeAllWatermarkNodes,} from '@lexical-core';+import { $generateHtmlFromNodes } from '@lexical/html';+import { setEditorStateFromHtml } from '@core/component/LexicalMarkdown/utils';import { logger } from '@observability';import { useEmailLinksQuery } from '@queries/email/link';+import { invalidateSoupEntity } from '@queries/soup/cache';+import { emailClient } from '@service-email/client';import {useScheduleMessageMutation,useSendMessageMutation,@@ -300,6 +304,13 @@ function TruncatedRecipientList(props: {);}+type UndoReplySnapshot = {+ draftId: string;+ bodyHtml: string;+ attachments: DraftFormAttachment[];+};+let undoReplySnapshot: UndoReplySnapshot | null = null;+export function BaseInput(props: {replyingTo: Accessor<MessageWithBodyReplyless | undefined>;// TODO: Remove `newMessage` props. It's not used...@@ -368,15 +379,103 @@ export function BaseInput(props: {const [showBcc, setShowBcc] = createSignal<boolean>();const [savedDraftId, setSavedDraftId] = createSignal<MessageToSendDbId | undefined- >(props.draft?.db_id ?? undefined);+ >(props.draft?.db_id ?? undoReplySnapshot?.draftId ?? undefined);++ // Consume undo-send snapshot if one exists (inline reply remount case).+ // Use bodyHtml as initialHtml for the editor, restore attachments on mount.+ const restoredSnapshot = undoReplySnapshot;+ if (restoredSnapshot) {+ undoReplySnapshot = null;+ onMount(() => {+ for (const attachment of restoredSnapshot.attachments) {+ form().attachments.add(attachment);+ }+ });+ }let pendingMentions: { documentId: string }[] = [];const [shouldMarkDoneOnSuccess, setShouldMarkDoneOnSuccess] =createSignal(false);+ const undoSend = async (draftId: string) => {+ try {+ await emailClient.unscheduleMessage({ draftID: draftId });+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });++ // Remove the sent message from the thread cache so it disappears from the list.+ const threadId = ctx.thread()?.db_id;+ if (threadId) {+ queryClient.setQueryData(+ emailKeys.threadMessages(threadId).queryKey,+ (old: any) => {+ if (!old?.pages) return old;+ return {+ ...old,+ pages: old.pages.map((page: any) => ({+ ...page,+ messages: page.messages.filter((m: any) => m.db_id !== draftId),+ })),+ };+ }+ );+ // Mark stale so next navigation fetches fresh data+ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(threadId).queryKey,+ refetchType: 'none',+ });+ }++ if (props.setShowReply) {+ // Inline reply: component was unmounted by clearDraftState.+ // Re-show the reply box — the new BaseInput instance will+ // pick up undoReplySnapshot on mount and restore from it.+ props.setShowReply(true);+ } else {+ // Bottom reply: component is still mounted. Restore compose box+ // after reactive updates from setQueryData have settled+ // (form may have re-keyed).+ const snapshot = undoReplySnapshot;+ if (snapshot) {+ setTimeout(() => {+ setSavedDraftId(draftId);+ const currentEditor = editor();+ if (currentEditor && snapshot.bodyHtml) {+ setEditorStateFromHtml(currentEditor, snapshot.bodyHtml);+ }+ for (const attachment of snapshot.attachments) {+ form().attachments.add(attachment);+ }+ undoReplySnapshot = null;+ }, 0);+ }+ }++ toast.success('Send cancelled');+ invalidateSoupEntity(draftId);+ } catch {+ toast.failure('Failed to undo send');+ }+ };+const sendMutation = useSendMessageMutation({onSuccess: async ({ message }) => {- toast.success('Email sent');+ const draftId = message.db_id;+ const toastId = toast.success(+ 'Email sent',+ undefined,+ draftId+ ? {+ text: 'Undo',+ onClick: () => {+ if (toastId != null) toast.dismiss(toastId);+ void undoSend(draftId);+ },+ }+ : undefined,+ 10_000+ );pendingMentions.forEach((mention) => {trackMention(blockId, 'document', mention.documentId);});@@ -710,6 +809,21 @@ export function BaseInput(props: {const currentEditor = editor();+ // Snapshot editor state before watermark so undo-send can restore it+ if (currentEditor) {+ const snapshotHtml = currentEditor.read(() =>+ $generateHtmlFromNodes(currentEditor)+ );+ const snapshotDraftId = savedDraftId();+ if (snapshotDraftId) {+ undoReplySnapshot = {+ draftId: snapshotDraftId,+ bodyHtml: snapshotHtml,+ attachments: [...form().attachments.list()],+ };+ }+ }+// We handle cleaning up the signature after we've sent the request because// otherwise the `bodyMacro` signal would update after the clean up call and// not contain the signature in the request data@@ -809,6 +923,7 @@ export function BaseInput(props: {refetchThreadMessages();}resetState();+ form().setReplyAppended(false);clearDraftState();};@@ -1257,7 +1372,7 @@ export function BaseInput(props: {class={`cursor-text text-sm break-words text-ink ${isDragging() && 'blur'}`}editable={() => !sendMutation.isPending}initialValue={props.preloadedBody}- initialHtml={props.preloadedHtml}+ initialHtml={restoredSnapshot?.bodyHtml ?? props.preloadedHtml}placeholder="Reply — @mention to share or cc people"watermark={!hasPaidAccess() ? <MacroSignatureButton /> : undefined}onChange={handleChange}diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex ad22dba283..46cccab551 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -72,9 +72,25 @@ import { stickyGate } from '@core/util/debounce';import { invalidateSoupEntity } from '@queries/soup/cache';import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';import { isMobile } from '@core/mobile/isMobile';+import { $generateHtmlFromNodes } from '@lexical/html';+import type { EmailFormRecipients } from '@block-email/component/createEmailFormState';+import { unwrap } from 'solid-js/store';+import { emailClient } from '@service-email/client';+import { queryClient } from '@queries/client';+import { emailKeys } from '@queries/email/keys';const DRAFT_DEBOUNCE_MS = 1000;+type UndoComposeSnapshot = {+ draftId: string;+ recipients: EmailFormRecipients;+ subject: string;+ bodyHtml: string;+ attachments: DraftFormAttachment[];+};++let undoComposeSnapshot: UndoComposeSnapshot | null = null;+type EmailComposeErrors =| 'no_recipient'| 'no_message'@@ -182,6 +198,20 @@ export function EmailCompose(props: EmailComposeProps) {props.draftID);+ // Restore form state from undo-send snapshot if available+ const restoredSnapshot =+ undoComposeSnapshot?.draftId === props.draftID ? undoComposeSnapshot : null;+ if (restoredSnapshot) {+ form.setRecipients('to', restoredSnapshot.recipients.to);+ form.setRecipients('cc', restoredSnapshot.recipients.cc);+ form.setRecipients('bcc', restoredSnapshot.recipients.bcc);+ form.setSubject(restoredSnapshot.subject);+ for (const attachment of restoredSnapshot.attachments) {+ form.attachments.add(attachment);+ }+ undoComposeSnapshot = null;+ }+const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();const saveDraftMutation = useSaveDraftMutation();const deleteDraftMutation = useDeleteDraftMutation();@@ -468,9 +498,43 @@ export function EmailCompose(props: EmailComposeProps) {const [validationError, setValidationError] =createSignal<EmailComposeError | null>(null);+ const undoSend = async (draftId: string) => {+ try {+ await emailClient.unscheduleMessage({ draftID: draftId });+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ replaceSplit({+ content: {+ type: 'component',+ id: 'email-compose',+ params: { draftID: draftId },+ },+ });+ toast.success('Send cancelled');+ invalidateSoupEntity(draftId);+ } catch {+ toast.failure('Failed to undo send');+ }+ };+const sendMutation = useSendMessageMutation({onSuccess: (data) => {- toast.success('Email sent');+ const draftId = data.message.db_id;+ const toastId = toast.success(+ 'Email sent',+ undefined,+ draftId+ ? {+ text: 'Undo',+ onClick: () => {+ if (toastId != null) toast.dismiss(toastId);+ void undoSend(draftId);+ },+ }+ : undefined,+ 10_000+ );if (data.message.thread_db_id) {replaceSplit({content: { type: 'email', id: data.message.thread_db_id },@@ -502,6 +566,23 @@ export function EmailCompose(props: EmailComposeProps) {const currentEditor = editor();+ // Snapshot editor state before watermark so undo-send can restore it+ if (currentEditor) {+ const snapshotHtml = currentEditor.read(() =>+ $generateHtmlFromNodes(currentEditor)+ );+ const draftId = currentDraftID();+ if (draftId) {+ undoComposeSnapshot = {+ draftId,+ recipients: structuredClone(unwrap(form.recipients())),+ subject: form.subject(),+ bodyHtml: snapshotHtml,+ attachments: [...form.attachments.list()],+ };+ }+ }+// We handle cleaning up the signature after we've sent the request because// otherwise the `bodyMacro` signal would update after the clean up call and// not contain the signature in the request data@@ -649,6 +730,10 @@ export function EmailCompose(props: EmailComposeProps) {};const initialHtml = () => {+ if (restoredSnapshot) {+ return restoredSnapshot.bodyHtml;+ }+const draft = form.draft;if (!draft || !draft.body_html_sanitized) return;diff --git a/js/app/packages/core/component/Toast/Toast.tsx b/js/app/packages/core/component/Toast/Toast.tsxindex 102565468e..d232117203 100644--- a/js/app/packages/core/component/Toast/Toast.tsx+++ b/js/app/packages/core/component/Toast/Toast.tsx@@ -109,12 +109,16 @@ function success(subtext?: string,action?: { text: string; onClick: () => void },duration?: number-) {+): number | undefined {if (!wasRecentlyShown(message, ToastType.SUCCESS)) {- createToast(message, ToastType.SUCCESS, subtext, action, duration);+ return createToast(message, ToastType.SUCCESS, subtext, action, duration);}}+function dismiss(toastId: number) {+ toaster.dismiss(toastId);+}+// Tell users that an action has failed, because of usfunction failure(message: string, subtext?: string, duration?: number) {if (!wasRecentlyShown(message, ToastType.FAILURE)) {@@ -352,4 +356,5 @@ export const toast = {alert,promise,embed,+ dismiss,};diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rsindex e0f91c91ee..881e0ab540 100644--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs@@ -27,26 +27,28 @@ pub async fn process_message(error = ?e,message_id = %data.message_id,link_id = %data.link_id,- "Failed to process scheduled message - clearing processing flag"+ "Failed to process scheduled message"+ );+ }++ if let Err(clear_err) =+ email_db_client::messages::scheduled::upsert::clear_scheduled_message_processing(+ &ctx.db,+ data.link_id,+ data.message_id,+ )+ .await+ {+ tracing::error!(+ error = ?clear_err,+ message_id = %data.message_id,+ link_id = %data.link_id,+ "Failed to clear processing flag");- if let Err(clear_err) =- email_db_client::messages::scheduled::upsert::clear_scheduled_message_processing(- &ctx.db,- data.link_id,- data.message_id,- )- .await- {- tracing::error!(- error = ?clear_err,- message_id = %data.message_id,- link_id = %data.link_id,- "Failed to clear processing flag"- );- }- return result;}+ result?;+cleanup_message(&ctx.sqs_worker, message).await?;Ok(())diff --git a/rust/cloud-storage/macro_db_client/migrations/20260218233040_email_replying_to_null.sql b/rust/cloud-storage/macro_db_client/migrations/20260218233040_email_replying_to_null.sqlnew file mode 100644index 0000000000..f07932f65a--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260218233040_email_replying_to_null.sql@@ -0,0 +1,8 @@+ALTER TABLE email_messages+DROP CONSTRAINT email_messages_replying_to_id_fkey;++ALTER TABLE email_messages+ ADD CONSTRAINT email_messages_replying_to_id_fkey+ FOREIGN KEY (replying_to_id)+ REFERENCES email_messages(id)+ ON DELETE SET NULL;\ No newline at end of file