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): schedule sending emails (#1119)
dev-rb36aae684fa06
diff --git a/js/app/packages/app/index.css b/js/app/packages/app/index.cssindex 7d7a393a1c..8385908d80 100644--- a/js/app/packages/app/index.css+++ b/js/app/packages/app/index.css@@ -947,3 +947,16 @@ input[type="number"]::-webkit-outer-spin-button {.portal-child-collapse > div {display: contents;}++input[type="time"]::-webkit-calendar-picker-indicator {+ --icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' viewBox='0 0 256 256'%3E%3C!-- Icon from Phosphor by Phosphor Icons - https://github.com/phosphor-icons/core/blob/main/LICENSE --%3E%3Cpath fill='currentColor' d='M128 24a104 104 0 1 0 104 104A104.11 104.11 0 0 0 128 24m0 192a88 88 0 1 1 88-88a88.1 88.1 0 0 1-88 88m64-88a8 8 0 0 1-8 8h-56a8 8 0 0 1-8-8V72a8 8 0 0 1 16 0v48h48a8 8 0 0 1 8 8'/%3E%3C/svg%3E");+ -webkit-mask: var(--icon) no-repeat;+ mask: var(--icon) no-repeat;+ -webkit-mask-size: 100% 100%;+ mask-size: 100% 100%;+ background-color: currentColor;+ color: inherit;+ width: 1em;+ height: 1em;+ background-image: none;+}diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex 0e55d04fae..c6d79be823 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -41,7 +41,11 @@ import {} from '@lexical-core';import { logger } from '@observability';import { useEmailLinksQuery } from '@queries/email/link';-import { useSendMessageMutation } from '@queries/email/thread';+import {+ useScheduleMessageMutation,+ useSendMessageMutation,+ useUnscheduleMessageMutation,+} from '@queries/email/thread';import type {MessageToSendDbId,MessageWithBodyReplyless,@@ -79,7 +83,10 @@ import {untrack,} from 'solid-js';import { createStore } from 'solid-js/store';-import { deleteEmailDraft, saveEmailDraft } from '../signal/emailDraft';+import {+ useDeleteDraftMutation,+ useSaveDraftMutation,+} from '@queries/email/draft';import { makeAttachmentPublic } from '../util/makeAttachmentPublic';import { getFirstName } from '../util/name';import {@@ -100,7 +107,12 @@ import {import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';import { plural } from '@core/util/string';+import { EmailDateSelector } from '@block-email/component/email-date-selector';import { isMobile } from '@core/mobile/isMobile';+import { queryClient } from '@queries/client';+import { emailKeys } from '@queries/email/keys';+import { stickyGate } from '@core/util/debounce';+import { ENABLE_EMAIL_SCHEDULED_SEND } from '@core/constant/featureFlags';false && fileFolderDrop;false && fileSelector;@@ -376,6 +388,8 @@ export function BaseInput(props: {});const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();+ const saveDraftMutation = useSaveDraftMutation();+ const deleteDraftMutation = useDeleteDraftMutation();function refetchThreadMessages() {ctx.query.refetch();@@ -459,7 +473,7 @@ export function BaseInput(props: {if (!draftToSave) {const draftId = savedDraftId();if (draftId) {- await deleteEmailDraft(draftId);+ await deleteDraftMutation.mutateAsync({ draftId });refetchThreadMessages();}setSavedDraftId(undefined);@@ -470,7 +484,7 @@ export function BaseInput(props: {if (!currentThread && !newMessage) {logger.error(new Error('Failed to save draft: thread not found'));- return false;+ return;}if (newMessage && currentThread) {@@ -479,39 +493,51 @@ export function BaseInput(props: {'Failed to save draft: new message and current thread cannot be provided together'));- return false;+ return;}let linkId: string | undefined = currentThread?.link_id;if (newMessage || !linkId) {if (emailLinksQuery.isPending) {- return false;+ return;}if (emailLinksQuery.isError) {logger.error(new Error('Failed to save email draft: could not load email links'));- return false;+ return;}const linksData = emailLinksQuery.data;if (!linksData || linksData.links.length === 0) {logger.error(new Error('Failed to save email draft: no links found'));- return false;+ return;}linkId = linksData.links[0].id;}- const draftResponse = await saveEmailDraft({- ...draftToSave,- db_id: savedDraftId(),- link_id: linkId!,- provider_thread_id: currentThread?.provider_id,- thread_db_id: currentThread?.db_id,+ const existingDraft = savedDraftId() !== undefined;++ // If there's an existing draft, we should send the sendTime so that the send time+ // stays up to date and is not removed+ const sendTime = existingDraft+ ? form().sendTime()?.toISOString()+ : undefined;++ const draftResponse = await saveDraftMutation.mutateAsync({+ draft: {+ ...draftToSave,+ db_id: savedDraftId(),+ link_id: linkId!,+ provider_thread_id: currentThread?.provider_id,+ thread_db_id: currentThread?.db_id,+ },+ sendTime,});- if (draftResponse) {+ const draftId = draftResponse.draft.db_id;+ if (draftId) {// If the email draft saved successfully, we want to upload the// attachments as well. We should grab only the attachments that// haven't been uploaded yet@@ -524,7 +550,7 @@ export function BaseInput(props: {if (attachments.length) {const uploaded = await uploadAttachmentMutation.mutateAsync({- draftID: draftResponse,+ draftID: draftId,attachments: attachments.map((a) => a.file),});@@ -537,8 +563,9 @@ export function BaseInput(props: {}}- setSavedDraftId(draftResponse);+ setSavedDraftId(draftId);refetchThreadMessages();+ return draftId;}}@@ -590,6 +617,23 @@ export function BaseInput(props: {useHotkeyDOMScope('compose-message');let composeContainerRef: HTMLDivElement | undefined;+ const scheduleMessageMutation = useScheduleMessageMutation({+ onSuccess: () => {+ toast.success('Email scheduled');++ const thread = ctx.thread();++ if (!thread?.db_id) return;++ queryClient.invalidateQueries({+ queryKey: emailKeys.threadMessages(thread.db_id).queryKey,+ });+ },+ onError: () => {+ toast.failure('Failed to schedule email');+ },+ });+const sendEmail = async (markDone = false) => {if (sendMutation.isPending || uploadAttachmentMutation.isPending) return;@@ -672,6 +716,28 @@ export function BaseInput(props: {const currentDraftID = savedDraftId();if (draftSaveTimer) window.clearTimeout(draftSaveTimer);+ const sendTime = form().sendTime()?.toISOString();++ if (sendTime) {+ // Just in case, always get a fresh save of the draft so we don't miss any information+ const draftID = await executeSaveDraft();++ if (!draftID) {+ console.error('No draft');+ toast.failure('Failed to schedule message', 'Draft required');+ cleanupWatermark();+ return;+ }++ scheduleMessageMutation.mutate({+ draftID,+ sendTime,+ });++ cleanupWatermark();+ return;+ }+sendMutation.mutate({message: {db_id: currentDraftID,@@ -714,7 +780,7 @@ export function BaseInput(props: {const deleteDraftAndReset = async () => {const draftId = savedDraftId();if (draftId) {- await deleteEmailDraft(draftId);+ await deleteDraftMutation.mutateAsync({ draftId });refetchThreadMessages();}resetState();@@ -888,6 +954,39 @@ export function BaseInput(props: {});};+ const unscheduleMessageMutation = useUnscheduleMessageMutation({+ onSuccess: () => {+ toast.success('Email unscheduled');+ },+ onError: () => {+ toast.failure('Failed to unschedule email');+ },+ });++ const handleSendTimeChange = (date: Date | null) => {+ const currentSendTime = form().sendTime();+ const currentDraft = savedDraftId();++ // If we unset the send time, we need to unschedule the message+ if (!date && currentSendTime && currentDraft) {+ unscheduleMessageMutation.mutate({+ draftID: currentDraft,+ });+ }++ form().setSendTime(date);+ scheduleDraftSave();+ };++ const isDraftSaving = () => saveDraftMutation.isPending;++ // Used to keep displaying draft status for some time+ const debouncedIsDraftSaving = stickyGate(isDraftSaving, 2000);++ // Used to keep displaying spinner for a short time before switching+ // to saved state+ const laggedIsDraftSaving = stickyGate(isDraftSaving, 250);+return (<divref={(el) => {@@ -896,7 +995,7 @@ export function BaseInput(props: {class="relative flex flex-col flex-1 bg-input border-t border-x border-edge-muted rounded-t-[5px] -mb-[7px] max-w-full">{/* Top Bar */}- <div class="flex items-start gap-2 p-2">+ <div class="relative flex items-start gap-2 p-2"><DropdownMenu><DropdownMenu.Trigger><div class="px-1">@@ -1038,6 +1137,17 @@ export function BaseInput(props: {</div></div></Show>+ <Show when={debouncedIsDraftSaving()}>+ <div class="absolute right-4 top-4 flex gap-1 items-center text-xs text-ink-muted">+ <Show+ when={laggedIsDraftSaving()}+ fallback={<span>Draft saved</span>}+ >+ <Spinner class="size-4 animate-spin" />+ <span>Saving draft</span>+ </Show>+ </div>+ </Show></div><divclass={`${props.isEditingExisting || props.newMessage ? 'flex' : 'hidden'} flex-row items-center`}@@ -1242,6 +1352,12 @@ export function BaseInput(props: {</div></KToggleButton></Tooltip>+ <Show when={ENABLE_EMAIL_SCHEDULED_SEND}>+ <EmailDateSelector+ sendTime={form().sendTime() ?? null}+ onSendTimeChange={handleSendTimeChange}+ />+ </Show><Show when={savedDraftId()}><Buttononclick={deleteDraftAndReset}diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex 850b2d0bec..6a844423ee 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -23,7 +23,11 @@ import {} from '@core/user';import Caution from '@icon/regular/warning.svg';import { useEmailLinksQuery } from '@queries/email/link';-import { useSendMessageMutation } from '@queries/email/thread';+import {+ useScheduleMessageMutation,+ useSendMessageMutation,+ useUnscheduleMessageMutation,+} from '@queries/email/thread';import {createMemo,createSignal,@@ -52,9 +56,9 @@ import {} from '@block-email/util/prepareEmailBody';import { convertEmailRecipientToContactInfo } from '@block-email/util/recipientConversion';import {- deleteEmailDraft,- saveEmailDraft,-} from '@block-email/signal/emailDraft';+ useDeleteDraftMutation,+ useSaveDraftMutation,+} from '@queries/email/draft';import {useRemoveDraftAttachmentMutation,useUploadDraftAttachmentsMutation,@@ -62,6 +66,9 @@ import {import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';import { useMaybeEmailContext } from '@block-email/component/EmailContext';import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';+import { stickyGate } from '@core/util/debounce';+import { queryClient } from '@queries/client';+import { queryKeys } from '@macro-entity';const DRAFT_DEBOUNCE_MS = 1000;@@ -160,6 +167,8 @@ export function EmailCompose(props: EmailComposeProps) {);const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();+ const saveDraftMutation = useSaveDraftMutation();+ const deleteDraftMutation = useDeleteDraftMutation();function collectDraft() {$removeAllWatermarkNodes(editor());@@ -196,7 +205,7 @@ export function EmailCompose(props: EmailComposeProps) {if (!draftToSave) {const draftID = currentDraftID();if (draftID) {- await deleteEmailDraft(draftID);+ await deleteDraftMutation.mutateAsync({ draftId: draftID });}setCurrentDraftID(undefined);return;@@ -207,16 +216,26 @@ export function EmailCompose(props: EmailComposeProps) {logger.error(new Error('Failed to save email draft: could not load email links'));- return false;+ return;}- const draftResponse = await saveEmailDraft({- ...draftToSave,- db_id: currentDraftID(),- link_id: linkID,+ const existingDraft = currentDraftID() !== undefined;++ // If there's an existing draft, we should send the sendTime so that the send time+ // stays up to date and is not removed+ const sendTime = existingDraft ? form.sendTime()?.toISOString() : undefined;++ const draftResponse = await saveDraftMutation.mutateAsync({+ draft: {+ ...draftToSave,+ db_id: currentDraftID(),+ link_id: linkID,+ },+ sendTime,});- if (draftResponse) {+ const draftId = draftResponse.draft.db_id;+ if (draftId) {// If the email draft saved successfully, we want to upload the// attachments as well. We should grab only the attachments that// haven't been uploaded yet@@ -229,7 +248,7 @@ export function EmailCompose(props: EmailComposeProps) {if (attachments.length) {const uploaded = await uploadAttachmentMutation.mutateAsync({- draftID: draftResponse,+ draftID: draftId,attachments: attachments.map((a) => a.file),});@@ -242,7 +261,9 @@ export function EmailCompose(props: EmailComposeProps) {}}- setCurrentDraftID(draftResponse);+ setCurrentDraftID(draftId);++ return draftId;}}@@ -432,7 +453,21 @@ export function EmailCompose(props: EmailComposeProps) {},});- const onSubmit = () => {+ const scheduleMessageMutation = useScheduleMessageMutation({+ onSuccess: () => {+ toast.success('Email scheduled');++ replaceSplit({+ content: { type: 'component', id: 'unified-list' },+ mergeHistory: true,+ });+ },+ onError: () => {+ toast.failure('Failed to schedule email');+ },+ });++ const onSubmit = async () => {setValidationError(null);const currentEditor = editor();@@ -491,6 +526,28 @@ export function EmailCompose(props: EmailComposeProps) {return;}+ const sendTime = form.sendTime()?.toISOString();++ if (sendTime) {+ // Just in case, always get a fresh save of the draft so we don't miss any information+ const draftID = await executeSaveDraft();++ if (!draftID) {+ console.error('No draft');+ toast.failure('Failed to schedule message', 'Draft required');+ cleanupWatermark();+ return;+ }++ scheduleMessageMutation.mutate({+ draftID,+ sendTime,+ });++ cleanupWatermark();+ return;+ }+sendMutation.mutate({message: {link_id: currentLink.id,@@ -508,12 +565,40 @@ export function EmailCompose(props: EmailComposeProps) {body_html: data.html,body_macro: data.raw,db_id: currentDraftID(),+ send_time: sendTime,},});cleanupWatermark();};+ const unscheduleMessageMutation = useUnscheduleMessageMutation({+ onSuccess: () => {+ toast.success('Email unscheduled');+ queryClient.invalidateQueries({+ queryKey: queryKeys.all.dss,+ });+ },+ onError: () => {+ toast.failure('Failed to unschedule email');+ },+ });++ const handleSendTimeChange = (date: Date | null) => {+ const currentSendTime = form.sendTime();+ const currentDraft = currentDraftID();++ // If we unset the send time, we need to unschedule the message+ if (!date && currentSendTime && currentDraft) {+ unscheduleMessageMutation.mutate({+ draftID: currentDraft,+ });+ }++ form.setSendTime(date);+ scheduleDraftSave();+ };+const resetState = () => {clearEmailBody(editor());setContent('');@@ -524,7 +609,7 @@ export function EmailCompose(props: EmailComposeProps) {const deleteDraftAndReset = async () => {const draftId = currentDraftID();if (draftId) {- await deleteEmailDraft(draftId);+ await deleteDraftMutation.mutateAsync({ draftId });}resetState();};@@ -544,6 +629,23 @@ export function EmailCompose(props: EmailComposeProps) {return decodedHtml;};+ const getRecipientOptions = () => {+ // If we're being displayed for a draft,+ // we should get the recipients from the draft+ const fromDraft = emailContext?.recipientOptions();++ return fromDraft ?? destinationOptions();+ };++ const isDraftSaving = () => saveDraftMutation.isPending;++ // Used to keep displaying draft status for some time+ const debouncedIsDraftSaving = stickyGate(isDraftSaving, 2000);++ // Used to keep displaying spinner for a short time before switching+ // to saved state+ const laggedIsDraftSaving = stickyGate(isDraftSaving, 250);+return (<><SplitHeaderLeft>@@ -628,6 +730,17 @@ export function EmailCompose(props: EmailComposeProps) {</Show></Suspense><div class="flex gap-2 ml-auto">+ <Show when={debouncedIsDraftSaving()}>+ <div class="flex gap-1 items-center text-sm text-ink-muted">+ <Show+ when={laggedIsDraftSaving()}+ fallback={<span>Draft saved</span>}+ >+ <CircleSpinner class="size-4 animate-spin" />+ <span>Saving draft</span>+ </Show>+ </div>+ </Show><Show when={!showCc()}><buttontype="button"@@ -657,9 +770,9 @@ export function EmailCompose(props: EmailComposeProps) {To</div><div class="flex-1">- <RecipientSelector<'user' | 'contact'>+ <RecipientSelectorinputRef={registerRef('directRecipientsSelector')}- options={destinationOptions}+ options={getRecipientOptions}selectedOptions={form.recipients().to}setSelectedOptions={(next) =>form.setRecipients('to', next)@@ -686,9 +799,9 @@ export function EmailCompose(props: EmailComposeProps) {Cc</div><div class="flex-1">- <RecipientSelector<'user' | 'contact'>+ <RecipientSelectorinputRef={registerRef('ccRecipientsSelector')}- options={destinationOptions}+ options={getRecipientOptions}selectedOptions={form.recipients().cc}setSelectedOptions={(next) =>form.setRecipients('cc', next)@@ -708,9 +821,9 @@ export function EmailCompose(props: EmailComposeProps) {Bcc</div><div class="flex-1">- <RecipientSelector<'user' | 'contact'>+ <RecipientSelectorinputRef={registerRef('bccRecipientsSelector')}- options={destinationOptions}+ options={getRecipientOptions}selectedOptions={form.recipients().bcc}setSelectedOptions={(next) =>form.setRecipients('bcc', next)@@ -769,7 +882,9 @@ export function EmailCompose(props: EmailComposeProps) {onAddAttachments={onAddAttachments}onRemoveAttachment={handleRemoveAttachment}attachments={form.attachments.list()}- onSubmit={onSubmit}+ sendTime={form.sendTime()}+ onSendTimeChange={handleSendTimeChange}+ onSubmit={() => void onSubmit()}isSubmitting={sendMutation.isPending}hasDraft={currentDraftID() != null}onDraftDeletePress={deleteDraftAndReset}diff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsxindex 54a32a3fb6..eef1c3dd74 100644--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx@@ -1,3 +1,4 @@+import ArrowUp from '@icon/bold/arrow-up-bold.svg';import { useSplitPanel } from '@app/component/split-layout/layoutUtils';import Trash from '@icon/regular/trash.svg';import { FormatRibbon } from '@block-channel/component/FormatRibbon';@@ -12,7 +13,6 @@ import { fileFolderDrop } from '@core/directive/fileFolderDrop';import { handleFileFolderDrop } from '@core/util/upload';import TextAa from '@icon/regular/text-aa.svg';import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';-import ArrowFatLineUp from '@phosphor-icons/core/fill/arrow-fat-line-up-fill.svg?component-solid';import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';import { useUserId } from '@core/context/user';import { defaultSelectionData } from 'core/component/LexicalMarkdown/plugins';@@ -35,6 +35,8 @@ import { toast } from '@core/component/Toast/Toast';import { plural } from '@core/util/string';import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';+import { EmailDateSelector } from '@block-email/component/email-date-selector';+import { ENABLE_EMAIL_SCHEDULED_SEND } from '@core/constant/featureFlags';false && fileFolderDrop;@@ -51,6 +53,8 @@ type ComposeEmailInputProps = {onAddAttachments?: (attachments: DraftFormAttachment[]) => void;onRemoveAttachment?: (attachment: DraftFormAttachment) => void;onContentChange?: (content: string) => void;+ sendTime?: Date | null;+ onSendTimeChange?: (date: Date | null) => void;};export function ComposeEmailInput(props: ComposeEmailInputProps) {@@ -304,6 +308,12 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {setShowFormatRibbon(!showFormatRibbon());}}/>+ <Show when={ENABLE_EMAIL_SCHEDULED_SEND}>+ <EmailDateSelector+ sendTime={props.sendTime}+ onSendTimeChange={props.onSendTimeChange}+ />+ </Show><Show when={props.hasDraft}><Buttononclick={props.onDraftDeletePress}@@ -314,26 +324,23 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {</Button></Show></div>- <button- type="button"++ <Buttondisabled={props.isSubmitting || props.disabled}onClick={() => {handleSend();}}- class="text-ink-muted focus:scale-110 hover:scale-110 transition ease-in-out delay-150 flex gap-2 justify-center items-center hover:bg-hover py-1 px-2 text-sm"+ class="text-ink-muted hover:scale-115 transition ease-in-out flex-col items-center rounded-full p-[0.25lh] hover:bg-transparent disabled:opacity-30"><Showwhen={!props.isSubmitting}- fallback={<Spinner class="w-5 h-5 animate-spin cursor-disabled" />}+ fallback={<Spinner class="size-6 animate-spin cursor-disabled" />}>- <span class="font-medium font-mono uppercase">Send</span>- <ArrowFatLineUp- width={20}- height={20}- class="text-accent-ink fill-accent rotate-90"- />+ <div class="group hover:bg-accent transition ease-in-out size-6 border border-accent rounded-full flex items-center justify-center p-0">+ <ArrowUp class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />+ </div></Show>- </button>+ </Button></div></div>);diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsxindex 97a814c90e..e8975a0eb7 100644--- a/js/app/packages/block-email/component/Email.tsx+++ b/js/app/packages/block-email/component/Email.tsx@@ -3,7 +3,6 @@ import {useEmailContext,} from '@block-email/component/EmailContext';import { CustomScrollbar } from '@core/component/CustomScrollbar';-import { FloatingInputLoader } from '@core/component/FloatingInputLoader';import { TOKENS } from '@core/hotkey/tokens';import { registerScopeSignalHotkey } from '@core/hotkey/utils';import {@@ -29,10 +28,11 @@ import { isScrollingToMessage } from '../signal/scrollState';import { registerEmailHotkeys } from '../util/emailHotkeys';import { scrollToMessage } from '../util/scrollToMessage';import { EmailFormContextProvider } from './EmailFormContext';-import { EmailInput } from './EmailInput';import { MessageList } from './MessageList';import { TopBar } from './TopBar';import { EmailCompose } from '@block-email/component/Compose';+import { EmailInput } from '@block-email/component/EmailInput';+import { FloatingInputLoader } from '@core/component/FloatingInputLoader';const TARGET_MESSAGE_HIGHLIGHT_MS = 800;const SCROLL_ANIMATION_MS = 1000;diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsxindex 2f373bd6a4..52cd7622ff 100644--- a/js/app/packages/block-email/component/EmailContext.tsx+++ b/js/app/packages/block-email/component/EmailContext.tsx@@ -1,6 +1,7 @@import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import { URL_PARAMS } from '@block-email/constants';+import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';import {getPermissions,hasPermissions,@@ -251,7 +252,12 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {const optionsMap = new Map<string, EmailRecipient>();for (const contact of contacts()) {- const mapped = recipientEntityMapper('user')(contact);+ const mapped = recipientEntityMapper('contact')({+ type: 'extracted',+ email: contact.email,+ id: contact.id,+ name: contact.name,+ });optionsMap.set(mapped.data.email, mapped);}@@ -276,11 +282,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {});for (const value of seen.values()) {- const mapped = recipientEntityMapper('contact')({- ...value,- type: 'extracted',- id: value.email,- });+ const mapped = convertContactInfoToEmailRecipient(value);optionsMap.set(mapped.data.email, mapped);}}diff --git a/js/app/packages/block-email/component/MessageActions.tsx b/js/app/packages/block-email/component/MessageActions.tsxindex a14f969a42..383a00f678 100644--- a/js/app/packages/block-email/component/MessageActions.tsx+++ b/js/app/packages/block-email/component/MessageActions.tsx@@ -7,6 +7,7 @@ import { Button } from '@ui/components/Button';import { type Setter, Show } from 'solid-js';import { getEmailFormRegistry } from './EmailFormContext';import type { ReplyType } from '@block-email/util/replyType';+import { createCallback } from '@solid-primitives/rootless';const EMAIL_MESSAGE_ACTIONS = ['reply', 'reply-all', 'forward'] as const;export type EmailMessageAction = (typeof EMAIL_MESSAGE_ACTIONS)[number];@@ -41,17 +42,15 @@ export function MessageActions(props: {};const onChangeReplyType = (type: ReplyType) => {- return () => {- if (!props.isLastMessage) {- props.setShowReply(true);- }+ return createCallback(() => {+ props.setShowReply(true);const form = formRegistry.getOrInit({type: 'replying_to',messageID: props.message.db_id ?? '',});form.setReplyType(type);form.setShouldFocusInput(true);- };+ });};return (diff --git a/js/app/packages/block-email/component/MessageList.tsx b/js/app/packages/block-email/component/MessageList.tsxindex c906424172..59d4ae5060 100644--- a/js/app/packages/block-email/component/MessageList.tsx+++ b/js/app/packages/block-email/component/MessageList.tsx@@ -101,10 +101,7 @@ export function MessageList(props: MessageListProps) {return (<MessageContainerisFirstMessage={normalizedIndex() === 0}- isLastMessage={- normalizedIndex() ===- (context.messages.list().length ?? 0) - 1- }+ isLastMessage={isLastMessage()}isFocused={isFocusedSelector(message().db_id ?? undefined)}isTarget={isTargetSelector(message().db_id ?? undefined)}message={message()}diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.tsindex 0b856511eb..3f20c17e99 100644--- a/js/app/packages/block-email/component/createEmailFormState.ts+++ b/js/app/packages/block-email/component/createEmailFormState.ts@@ -51,6 +51,7 @@ type EmailFormState = {withQuotedText: boolean;subject: string;markdownBody: string;+ sendTime?: Date;};const EMPTY_FORM_STATE: EmailFormState = {@@ -137,6 +138,9 @@ export function createEmailFormState(withQuotedText: draftContainsAppendedReply(),subject: initialSubject,markdownBody: '',+ sendTime: draft?.scheduled_send_time+ ? new Date(draft.scheduled_send_time)+ : undefined,} satisfies EmailFormState;};@@ -228,6 +232,11 @@ export function createEmailFormState(return rt;};+ const setSendTime = (date: Date | null) => {+ setState('sendTime', date ?? undefined);+ callDirty();+ };+const callDirty = () => {onDirtyCb()?.();};@@ -276,6 +285,8 @@ export function createEmailFormState(setReplyType,shouldFocusInput,setShouldFocusInput,+ sendTime: () => state.sendTime,+ setSendTime,reset,clear,setOnDirty: (cb?: () => void) => {diff --git a/js/app/packages/block-email/component/date-selector.tsx b/js/app/packages/block-email/component/date-selector.tsxnew file mode 100644index 0000000000..979f1a0e30--- /dev/null+++ b/js/app/packages/block-email/component/date-selector.tsx@@ -0,0 +1,442 @@+import { useDateSearch } from '@core/util/dateSearch/useDateSearch';+import { useSearchInputFocus } from '@core/component/Properties/utils';+import { DatePickerUI } from '@core/component/DatePicker/DatePickerUI';+import SearchIcon from '@icon/regular/magnifying-glass.svg';+import {+ createMemo,+ createSignal,+ type JSX,+ Show,+ type FlowComponent,+ type Component,+ createEffect,+ on,+} from 'solid-js';+import {+ Combobox,+ type ComboboxRootItemComponentProps,+} from '@kobalte/core/combobox';+import { cn } from '@ui/utils/classname';+import { format, setHours, setMinutes, startOfDay } from 'date-fns';++type DateSelectorMode = 'search' | 'calendar';++type DateSelectorOption =+ | {+ type: 'option';+ displayText: string;+ secondaryText?: string;+ date: Date;+ }+ | { type: 'select-custom' }+ | { type: 'custom'; date: Date };++type DateSelectorProps = {+ open?: boolean;+ onClose?: VoidFunction;+ selectedDate?: Date | null;+ onSelectDate?: (date: Date | null) => void;+ placeholder?: string;+ disablePriorToDate?: Date;+ withTime?: boolean;+ trigger?:+ | JSX.Element+ | ((props: { selectedDate: Date | null }) => JSX.Element);+};++export const DateSelector = (props: DateSelectorProps) => {+ const [selectedOption, setSelectedOption] =+ createSignal<DateSelectorOption | null>(+ props.selectedDate ? { type: 'custom', date: props.selectedDate } : null+ );++ createEffect(+ on(+ () => props.selectedDate,+ () => {+ const next = props.selectedDate+ ? { type: 'custom' as const, date: props.selectedDate }+ : null;+ const current = selectedOption();++ if (+ current?.type !== 'select-custom' &&+ current?.date.toString() === next?.date.toString()+ )+ return;++ setSelectedOption(next);+ }+ )+ );++ const [mode, setMode] = createSignal<DateSelectorMode>('search');++ const [searchQuery, setSearchQuery] = createSignal('');+ const [listboxRef, setListboxRef] = createSignal<HTMLElement | undefined>();+ const [searchInputRef, setSearchInputRef] = createSignal<+ HTMLInputElement | undefined+ >();++ const dateOptions = useDateSearch({+ query: searchQuery,+ baseDate: startOfDay(new Date()),+ });++ const dispatchKeyToListbox = (key: string) => {+ listboxRef()?.dispatchEvent(+ // We need to send `bubbles: true` because otherwise Kobalte ignores the event+ new KeyboardEvent('keydown', { bubbles: true, key: key })+ );+ };++ const handleKeyDown = (e: KeyboardEvent) => {+ switch (e.key) {+ case 'Delete':+ case 'Backspace': {+ if (searchQuery().trim()) {+ return;+ }+ e.preventDefault();+ onChange(null);++ break;+ }+ case 'j': {+ if (!e.ctrlKey) return;++ e.preventDefault();+ dispatchKeyToListbox('ArrowDown');+ break;+ }+ case 'k': {+ if (!e.ctrlKey) return;++ e.preventDefault();+ dispatchKeyToListbox('ArrowUp');+ break;+ }+ }+ };++ useSearchInputFocus(+ () => searchInputRef(),+ () => true+ );++ const onInputChange = (value: string) => {+ setSearchQuery(value);++ // Send the keydown event to the listbox so Kobalte's internal system can update the focus state+ // This makes it so it behaves the same as if you had manually pressed the down arrow to focus the item+ queueMicrotask(() => {+ dispatchKeyToListbox('ArrowDown');+ });+ };++ const resetState = () => {+ setSearchQuery('');+ setMode('search');+ };++ const onOpenChange = (open: boolean) => {+ if (!open) {+ resetState();+ props.onClose?.();+ }+ };++ const onChange = (option: DateSelectorOption | null) => {+ if (option?.type === 'select-custom') {+ setMode('calendar');+ return;+ }++ setSelectedOption(option);+ if (!option) {+ props.onSelectDate?.(null);+ return;+ }++ const dateValue = option.date;++ props.onSelectDate?.(dateValue);+ };++ const options = createMemo(() => {+ const list: DateSelectorOption[] = [];++ for (const option of dateOptions()) {+ list.push({+ type: 'option',+ displayText: option.displayText,+ secondaryText: option.secondaryText,+ date: option.date,+ });+ }++ list.push({+ type: 'select-custom',+ });++ return list;+ });++ const getOptionValue = (option: DateSelectorOption) => {+ if (option.type === 'select-custom') return '';+ return option.date.toString();+ };++ const getOptionTextValue = (option: DateSelectorOption) => {+ if (option.type === 'select-custom') return 'Custom date';++ return option.type === 'option' ? option.displayText : '';+ };++ const selectedDate = () => {+ const option = selectedOption();++ if (!option || option.type === 'select-custom') return null;++ return option.date;+ };++ const onTimeInputChange = (e: Event) => {+ if (!(e.currentTarget instanceof HTMLInputElement)) return;+ const value = e.currentTarget.value;++ if (!value || !value.trim().length) {+ const currentDate = selectedDate() ?? new Date();++ onChange({+ type: 'custom',+ date: startOfDay(currentDate),+ });+ return;+ }++ const split = value.split(':');+ if (!split.length || split.length !== 2) return;++ if (Number.isNaN(split[0]) || Number.isNaN(split[1])) return;++ let hours = Number(split[0]);+ let mins = Number(split[1]);++ let currentDate = selectedDate() ?? new Date();++ currentDate = setHours(currentDate, Number(hours));+ currentDate = setMinutes(currentDate, Number(mins));++ onChange({ type: 'custom', date: currentDate });+ };++ return (+ <Combobox<DateSelectorOption>+ open={props.open}+ multiple={false}+ value={selectedOption()}+ options={options()}+ optionValue={getOptionValue}+ optionTextValue={getOptionTextValue}+ optionLabel={() => ''}+ onOpenChange={onOpenChange}+ onChange={onChange}+ onInputChange={onInputChange}+ allowsEmptyCollection+ placement="bottom-start"+ placeholder={props.placeholder ?? 'Select date'}+ closeOnSelection={false}+ // Filtering is done by `useDateSearch`+ defaultFilter={() => true}+ itemComponent={DateSelectorItem}+ >+ <Show when={typeof props.trigger !== 'undefined'}>+ <Combobox.Control>+ <Combobox.Trigger+ class="flex group/date-selector-trigger"+ tabIndex={0}+ >+ {typeof props.trigger === 'function'+ ? props.trigger({ selectedDate: selectedDate() })+ : props.trigger}+ </Combobox.Trigger>+ </Combobox.Control>+ </Show>++ <Combobox.Portal>+ <Combobox.Content+ class="w-full max-w-sm bg-dialog text-ink border border-edge-muted"+ on:keydown={handleKeyDown}+ >+ <WithCustomDateMode+ selectedDate={selectedDate()}+ disablePriorToDate={props.disablePriorToDate}+ mode={mode()}+ onSelectDate={(date) => {+ onChange({ type: 'custom', date });+ setMode('search');+ }}+ >+ <div class="flex w-full items-center py-1 gap-2 px-2 border-b border-edge-muted">+ <SearchIcon class="h-4 w-4 text-ink-muted" />+ <Combobox.Input+ ref={setSearchInputRef}+ class="w-full caret-accent"+ autofocus+ />+ </div>++ <Show when={selectedOption()}>+ {(option) => (+ <CurrentValueDisplay+ selectedOption={option()}+ onClear={() => {+ onChange(null);+ }}+ />+ )}+ </Show>+ <Show when={dateOptions().length === 0}>+ <Show+ when={searchQuery().trim()}+ fallback={+ <div class="text-center py-2 text-ink-muted text-sm">+ Enter a date or duration+ </div>+ }+ >+ <div class="text-center py-2 text-ink-muted text-sm">+ No dates match "{searchQuery()}"+ </div>+ </Show>+ </Show>+ <Combobox.Listbox ref={setListboxRef} />+ <Show when={props.withTime}>+ <div class="px-2 py-1.5 border-t border-edge-muted">+ <label class="flex items-center justify-between text-sm">+ Time+ <input+ type="time"+ value={+ selectedDate()+ ? format(selectedDate()!, 'HH:mm')+ : undefined+ }+ onInput={onTimeInputChange}+ />+ </label>+ </div>+ </Show>+ <div class="px-2 py-1.5 border-t border-edge-muted">+ <div class="text-xs text-ink-muted">+ <span>Use queries like </span>+ <code class="bg-active px-1">3d</code>,{' '}+ <code class="bg-active px-1">1w</code>,{' '}+ <code class="bg-active px-1">feb 17</code>, or{' '}+ <code class="bg-active px-1">tomorrow</code>+ </div>+ </div>+ </WithCustomDateMode>+ </Combobox.Content>+ </Combobox.Portal>+ </Combobox>+ );+};++interface CurrentValueDisplayProps {+ selectedOption: DateSelectorOption;+ onClear: VoidFunction;+}++const CurrentValueDisplay = (props: CurrentValueDisplayProps) => {+ const currentDateDisplay = createMemo(() => {+ if (props.selectedOption.type === 'select-custom') return '';+ try {+ return format(props.selectedOption.date, "MMMM d, yyyy 'at' h:mm a");+ } catch {+ return 'Invalid date';+ }+ });++ return (+ <div class="px-3 py-2 border-b border-edge-muted pattern pattern-edge-muted pattern-dot-4">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-2">+ <span class="text-xs text-ink-muted">Current:</span>+ <span class="text-xs font-medium">{currentDateDisplay()}</span>+ </div>+ <button+ onClick={props.onClear}+ class="text-xs text-ink-muted hover:text-ink underline"+ >+ Clear+ </button>+ </div>+ </div>+ );+};++interface WithCustomDateModeProps {+ selectedDate: Date | null;+ mode: DateSelectorMode;+ onSelectDate: (date: Date) => void;+ disablePriorToDate?: Date;+}++const WithCustomDateMode: FlowComponent<WithCustomDateModeProps> = (props) => {+ return (+ <Show when={props.mode === 'calendar'} fallback={props.children}>+ <div class="border-b border-edge-muted text-sm flex justify-center">+ <DatePickerUI+ disablePriorToDate={props.disablePriorToDate}+ value={props.selectedDate ?? new Date()}+ onChange={props.onSelectDate}+ />+ </div>+ </Show>+ );+};++const DateSelectorItem: Component<+ ComboboxRootItemComponentProps<DateSelectorOption>+> = (props) => {+ const label = () => {+ const item = props.item.rawValue;++ if (item.type === 'option') return item.displayText;++ return 'Custom date';+ };++ const description = () => {+ const item = props.item.rawValue;++ if (item.type === 'option') return item.secondaryText;+ return 'Pick from calendar';+ };++ return (+ <Combobox.Item+ item={props.item}+ class={cn(+ 'flex flex-row w-full justify-between items-center gap-2 py-1.5 pr-2 pl-6 relative cursor-pointer data-[highlighted]:bg-hover',+ props.item.rawValue.type === 'select-custom' &&+ 'border-t border-edge-muted pl-2'+ )}+ >+ <Combobox.ItemIndicator class="absolute left-2 top-1/2 -translate-y-1/2 size-2 bg-accent aspect-square" />+ <div class="flex items-center gap-2 flex-1 min-w-0">+ <Combobox.ItemLabel class="text-sm font-medium truncate">+ {label()}+ </Combobox.ItemLabel>+ </div>++ <Show when={description()}>+ <Combobox.ItemDescription as="span" class="text-xs text-ink-muted">+ {description()}+ </Combobox.ItemDescription>+ </Show>+ </Combobox.Item>+ );+};diff --git a/js/app/packages/block-email/component/email-date-selector.tsx b/js/app/packages/block-email/component/email-date-selector.tsxnew file mode 100644index 0000000000..4e70410bf7--- /dev/null+++ b/js/app/packages/block-email/component/email-date-selector.tsx@@ -0,0 +1,64 @@+import ClockIcon from '@phosphor-icons/core/assets/regular/clock.svg';+import { DateSelector } from '@block-email/component/date-selector';+import { Tooltip } from '@core/component/Tooltip';+import { cn } from '@ui/utils/classname';+import { format } from 'date-fns/format';+import { Show, type VoidComponent } from 'solid-js';+import IconX from '@icon/regular/x.svg';++interface EmailDateSelectorProps {+ sendTime?: Date | null;+ onSendTimeChange?: (date: Date | null) => void;+}+export const EmailDateSelector: VoidComponent<EmailDateSelectorProps> = (+ props+) => {+ return (+ <DateSelector+ selectedDate={props.sendTime}+ onSelectDate={props.onSendTimeChange}+ disablePriorToDate={new Date()}+ trigger={(state) => {+ const formattedDate = () => {+ if (!state.selectedDate) return;+ return format(state.selectedDate, 'MMM d, yyyy h:mm a');+ };+ return (+ <Tooltip+ tooltip={+ state.selectedDate+ ? `Scheduled for ${formattedDate()}`+ : 'Schedule this email'+ }+ >+ <div+ class={cn(+ 'flex items-center p-1 gap-2 hover:bg-surface-4 group-data-[expanded]/date-selector-trigger:bg-surface-4',+ state.selectedDate &&+ 'bg-accent/20 text-accent-ink hover:bg-accent/15 group-data-[expanded]/date-selector-trigger:bg-accent/20'+ )}+ >+ <ClockIcon class="size-5" />+ <Show when={formattedDate()}>+ <span class="text-sm">{formattedDate()}</span>+ <Tooltip tooltip="Clear">+ <div+ role="button"+ tabIndex={0}+ class="hover:bg-accent/30"+ onPointerDown={(e) => {+ e.stopPropagation();+ }}+ onClick={() => props.onSendTimeChange?.(null)}+ >+ <IconX class="size-5" />+ </div>+ </Tooltip>+ </Show>+ </div>+ </Tooltip>+ );+ }}+ />+ );+};diff --git a/js/app/packages/block-email/signal/emailDraft.ts b/js/app/packages/block-email/signal/emailDraft.tsindex 6ab06422f9..86833bd986 100644--- a/js/app/packages/block-email/signal/emailDraft.ts+++ b/js/app/packages/block-email/signal/emailDraft.ts@@ -5,9 +5,13 @@ import type { MessageToSendDbId } from '@service-email/generated/schemas';import type { MessageToSend } from '@service-email/generated/schemas/messageToSend';export async function saveEmailDraft(- draft: MessageToSend+ draft: MessageToSend,+ sendTime?: string | null): Promise<MessageToSendDbId | false> {- const createRes = await emailClient.createDraft({ draft });+ const createRes = await emailClient.createDraft({+ draft,+ send_time: sendTime,+ });if (isErr(createRes)) {logger.error(new Error('Failed to save draft', { cause: createRes[0] }));return false;diff --git a/js/app/packages/core/component/DatePicker/DatePickerUI.tsx b/js/app/packages/core/component/DatePicker/DatePickerUI.tsxindex 60b7b63c0a..c913a16667 100644--- a/js/app/packages/core/component/DatePicker/DatePickerUI.tsx+++ b/js/app/packages/core/component/DatePicker/DatePickerUI.tsx@@ -1,10 +1,13 @@import CaretLeft from '@icon/regular/caret-left.svg';import CaretRight from '@icon/regular/caret-right.svg';import { createSignal, For, Show } from 'solid-js';+import { isBefore } from 'date-fns/isBefore';+import { startOfDay } from 'date-fns/startOfDay';export type DatePickerUIProps = {value: Date;onChange: (date: Date) => void;+ disablePriorToDate?: Date;};const MONTHS = [@@ -57,8 +60,12 @@ export function DatePickerUI(props: DatePickerUIProps) {}};+ const getDateForDay = (day: number) => {+ return new Date(displayYear(), displayMonth(), day);+ };+const handleDateClick = (day: number) => {- const newDate = new Date(displayYear(), displayMonth(), day);+ const newDate = getDateForDay(day);props.onChange(newDate);};@@ -125,6 +132,7 @@ export function DatePickerUI(props: DatePickerUIProps) {{/* Month/Year header */}<div class="flex items-center justify-between mb-3"><button+ type="button"class="p-1 hover:bg-active transition-colors"onClick={handlePrevMonth}>@@ -132,6 +140,7 @@ export function DatePickerUI(props: DatePickerUIProps) {</button><button+ type="button"class="font-semibold hover:bg-active px-2 py-1 transition-colors"onClick={() => setPickerMode('month')}>@@ -139,6 +148,7 @@ export function DatePickerUI(props: DatePickerUIProps) {</button><button+ type="button"class="p-1 hover:bg-active transition-colors"onClick={handleNextMonth}>@@ -161,13 +171,21 @@ export function DatePickerUI(props: DatePickerUIProps) {{(day) => (<Show when={day !== null} fallback={<div class="h-8" />}><button- class="h-8 w-8 hover:bg-active transition-colors"+ type="button"+ class="h-8 w-8 hover:bg-active transition-colors disabled:opacity-40"classList={{'bg-accent text-dialog hover:bg-accent-ink': isSelected(day!),'ring-1 ring-accent': isToday(day!),}}+ disabled={+ props.disablePriorToDate &&+ isBefore(+ getDateForDay(day!),+ startOfDay(props.disablePriorToDate)+ )+ }onClick={() => handleDateClick(day!)}>{day}@@ -182,6 +200,7 @@ export function DatePickerUI(props: DatePickerUIProps) {{/* Month picker */}<div class="mb-3"><button+ type="button"class="w-full font-semibold hover:bg-active px-2 py-1 transition-colors text-center"onClick={() => setPickerMode('year')}>@@ -193,6 +212,7 @@ export function DatePickerUI(props: DatePickerUIProps) {<For each={MONTHS}>{(month, index) => (<button+ type="button"class="px-3 py-2 hover:bg-active transition-colors"classList={{'bg-accent text-dialog hover:bg-accent-ink':@@ -218,6 +238,7 @@ export function DatePickerUI(props: DatePickerUIProps) {<For each={yearOptions()}>{(year) => (<button+ type="button"class="px-3 py-2 hover:bg-active transition-colors"classList={{'bg-accent text-dialog hover:bg-accent-ink':diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 267e29a7bb..b1923784fe 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -123,3 +123,5 @@ export const ENABLE_UNIFIED_LIST_AI_INPUT = true;// snapshot mention content inline for AI chatexport const ENABLE_SNAPSHOT_NODE = true;++export const ENABLE_EMAIL_SCHEDULED_SEND = false;diff --git a/js/app/packages/queries/email/draft.ts b/js/app/packages/queries/email/draft.tsnew file mode 100644index 0000000000..afb89ae5c5--- /dev/null+++ b/js/app/packages/queries/email/draft.ts@@ -0,0 +1,89 @@+import { toast } from '@core/component/Toast/Toast';+import { throwOnErr } from '@core/util/maybeResult';+import { emailClient } from '@service-email/client';+import type {+ CreateDraftResponse,+ MessageToSend,+} from '@service-email/generated/schemas';+import { useMutation } from '@tanstack/solid-query';+import { queryClient } from '../client';+import { type MutationCallbacks, withCallbacks } from '../utils';+import { emailKeys } from './keys';+import { queryKeys } from '@macro-entity';++type CreateDraftParams = {+ draft: MessageToSend;+ sendTime?: string | null;+};++/**+ * Mutation to save a new email draft.+ */+export function useSaveDraftMutation(+ callbacks?: MutationCallbacks<CreateDraftResponse, Error, CreateDraftParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: CreateDraftParams) => {+ return await throwOnErr(+ async () =>+ await emailClient.createDraft({+ draft: vars.draft,+ send_time: vars.sendTime,+ })+ );+ },+ ...withCallbacks<CreateDraftResponse, Error, CreateDraftParams>(+ {+ onError(error) {+ console.error('Failed to save draft', error);+ toast.failure('Failed to save draft');+ },+ onSuccess() {+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.all.dss,+ });+ },+ },+ callbacks+ ),+ }));+}++type DeleteDraftParams = {+ draftId: string;+};++/**+ * Mutation to delete an email draft.+ */+export function useDeleteDraftMutation(+ callbacks?: MutationCallbacks<void, Error, DeleteDraftParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: DeleteDraftParams) => {+ await throwOnErr(+ async () => await emailClient.deleteDraft({ id: vars.draftId })+ );+ },+ ...withCallbacks<void, Error, DeleteDraftParams>(+ {+ onError(error) {+ console.error('Failed to delete draft', error);+ toast.failure('Failed to delete draft');+ },+ onSuccess() {+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ queryClient.invalidateQueries({+ queryKey: queryKeys.all.dss,+ });+ },+ },+ callbacks+ ),+ }));+}diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.tsindex e35fb9f6fb..1c9c866d02 100644--- a/js/app/packages/queries/email/thread.ts+++ b/js/app/packages/queries/email/thread.ts@@ -6,6 +6,7 @@ import type {MessageToSend,SendMessageResponse,APIThread as Thread,+ UpsertScheduledResponse,} from '@service-email/generated/schemas';import type { SoupPage } from '@service-storage/generated/schemas';import {@@ -298,11 +299,11 @@ export function useSendMessageMutation(),...withCallbacks<SendMessageResponse, Error, SendMessageParams>({- onSuccess: (_data, params) => {- if (params.message.thread_db_id) {+ onSuccess: (data) => {+ const threadID = data.message.thread_db_id;+ if (threadID) {queryClient.invalidateQueries({- queryKey: emailKeys.threadMessages(params.message.thread_db_id)- .queryKey,+ queryKey: emailKeys.threadMessages(threadID).queryKey,});}queryClient.invalidateQueries({@@ -314,3 +315,67 @@ export function useSendMessageMutation(),}));}++type ScheduleMessageParams = { draftID: string; sendTime: string };++/**+ * Mutation to send an email message.+ */+export function useScheduleMessageMutation(+ callbacks?: MutationCallbacks<+ UpsertScheduledResponse,+ Error,+ ScheduleMessageParams+ >+) {+ return useMutation(() => ({+ mutationFn: async (vars: ScheduleMessageParams) =>+ await throwOnErr(+ async () =>+ await emailClient.scheduleMessage({+ draftID: vars.draftID,+ send_time: vars.sendTime,+ })+ ),+ ...withCallbacks<UpsertScheduledResponse, Error, ScheduleMessageParams>(+ {+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ },+ },+ callbacks+ ),+ }));+}++type UnscheduleMessageParams = { draftID: string };++/**+ * Mutation to send an email message.+ */+export function useUnscheduleMessageMutation(+ callbacks?: MutationCallbacks<void, Error, UnscheduleMessageParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: UnscheduleMessageParams) => {+ await throwOnErr(+ async () =>+ await emailClient.unscheduleMessage({+ draftID: vars.draftID,+ })+ );+ },+ ...withCallbacks<void, Error, UnscheduleMessageParams>(+ {+ onSuccess: () => {+ queryClient.invalidateQueries({+ queryKey: emailKeys.previews._def,+ });+ },+ },+ callbacks+ ),+ }));+}diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex a6d5a02e83..fbe920e2fc 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -26,6 +26,8 @@ import type {SendMessageResponse,UpdateLabelBatchRequest,UpdateLabelBatchResponse,+ UpsertScheduledRequest,+ UpsertScheduledResponse,} from './generated/schemas';import type { EmptyResponse } from './generated/schemas/emptyResponse';@@ -150,6 +152,32 @@ export const emailClient = {);},+ async scheduleMessage(args: { draftID: string } & UpsertScheduledRequest) {+ const { draftID, ...rest } = args;+ return mapOk(+ await emailFetch<UpsertScheduledResponse>(+ `/email/drafts/scheduled/${draftID}`,+ {+ method: 'PUT',+ body: JSON.stringify(rest),+ }+ ),+ (result) => result+ );+ },++ async unscheduleMessage(args: { draftID: string }) {+ return mapOk(+ await emailFetch<EmptyResponse>(+ `/email/drafts/scheduled/${args.draftID}`,+ {+ method: 'DELETE',+ }+ ),+ (result) => result+ );+ },+async getLinks() {return mapOk(await emailFetch<ListLinksResponse>('/email/links', {