Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): make scheduled send undo, cancel, and send paths consistent (#6941)

gbirman53969a7c7064
diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.ts
index 93d9717db8..27b65ac001 100644
--- a/apps/web/src/features/email-compose/compose-adapter.ts
+++ b/apps/web/src/features/email-compose/compose-adapter.ts
@@ -125,6 +125,30 @@ export function createEmailComposeContext(
});
const reportError = (error: unknown) =>
Telemetry.error(error instanceof Error ? error : new Error(String(error)));
+ // A thread view renders its latest draft as the composer until the thread
+ // is read again, so every delivery change refetches it.
+ const refreshThread = (threadId: string | undefined) => {
+ if (!threadId) return;
+ if (isFeatureEnabled(enableGraphqlSoup)) {
+ void (async () => {
+ const result = await fetchAndCacheThread(threadId);
+ if (result.isErr())
+ reportError(
+ new Error(
+ `Failed to refresh email thread ${threadId}: ${result.error
+ .map((error) => `${error.code}: ${error.message}`)
+ .join(', ')}`
+ )
+ );
+ })().catch(reportError);
+ return;
+ }
+ void queryClient
+ .invalidateQueries({
+ queryKey: emailKeys.threadMessages(threadId).queryKey,
+ })
+ .catch(reportError);
+ };
// Queued writes address a draft by handles: the composer's minted ones, or a
// confirmed draft's server ids, which resolve as their own handles.
@@ -352,8 +376,10 @@ export function createEmailComposeContext(
result.message.db_id,
result.message.link_id
);
- if (result.message.thread_db_id)
+ if (result.message.thread_db_id) {
markThreadDraftSaved(result.message.thread_db_id);
+ refreshThread(result.message.thread_db_id);
+ }
} catch (error) {
reportError(error);
}
@@ -363,7 +389,7 @@ export function createEmailComposeContext(
inboxId: result.message.link_id,
};
},
- async unschedule({ draftId, inboxId }) {
+ async unschedule({ draftId, threadId, inboxId }) {
await unschedule.mutateAsync({
draftID: draftId,
linkId: headerId(inboxId),
@@ -371,11 +397,15 @@ export function createEmailComposeContext(
try {
publishDraftLifecycleChange(draftId, inboxId);
invalidateSoupEntity(draftId);
+ refreshThread(threadId);
} catch (error) {
reportError(error);
}
},
- schedule: async ({ draftId, sendTime, includeSignature }, inboxId) => {
+ schedule: async (
+ { draftId, threadId, sendTime, includeSignature },
+ inboxId
+ ) => {
await scheduleEmailMessage(
{
draftID: draftId,
@@ -386,6 +416,7 @@ export function createEmailComposeContext(
);
try {
publishDraftLifecycleChange(draftId, inboxId);
+ refreshThread(threadId);
void queryClient
.invalidateQueries({
queryKey: emailKeys.scheduledMessages._def,
diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.ts
index 1974fd5642..14432d4f8b 100644
--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts
+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts
@@ -119,10 +119,15 @@ export interface EmailAttachmentStorage {
export interface EmailDelivery {
sendMessage(input: SendEmailDraft): Promise<PersistedEmailIdentity>;
- unschedule(input: { draftId: string; inboxId?: string }): Promise<void>;
+ unschedule(input: {
+ draftId: string;
+ threadId?: string;
+ inboxId?: string;
+ }): Promise<void>;
schedule(
input: {
draftId: string;
+ threadId?: string;
sendTime: string;
includeSignature?: boolean;
},
diff --git a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts b/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts
index dfb0589d18..c90b8e648c 100644
--- a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts
+++ b/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { message } from '../../email-message/tests/messages';
import type { PersistedEmailIdentity } from '../context/compose-capabilities';
import { decodeBase64Utf8 } from '../core/decode-base64';
import { createComposeContext } from '../tests/capabilities';
@@ -330,6 +331,7 @@ it('only commits a selected time through the primary action', async () => {
expect(composeContext.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
{
draftId: 'draft',
+ threadId: 'thread',
sendTime: firstTime.toISOString(),
includeSignature: undefined,
},
@@ -360,17 +362,81 @@ it('only commits a selected time through the primary action', async () => {
host.showThread.mockClear();
scheduledNotice?.[1]?.actions?.[1].onClick();
expect(host.showThread).toHaveBeenCalledExactlyOnceWith('thread');
+ // Showing the thread mounts its own composer on the scheduled draft.
+ const threadView = mountEmailComposer(composeContext, host, {
+ draft: message('draft', {
+ is_draft: true,
+ scheduled_send_time: firstTime.toISOString(),
+ }),
+ });
scheduledNotice?.[1]?.actions?.[0].onClick();
await vi.advanceTimersByTimeAsync(1);
+ threadView.dispose();
expect(composeContext.delivery.unschedule).toHaveBeenCalledExactlyOnceWith({
draftId: 'draft',
+ threadId: 'thread',
inboxId: 'inbox',
});
expect(root.state.context.schedule.state()).toEqual({
type: 'editing',
intent: { type: 'immediate' },
});
+ expect(composeContext.delivery.archive).toHaveBeenLastCalledWith(
+ { threadId: 'thread', value: false },
+ 'inbox'
+ );
+ expect(composeContext.drafts.restoreDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftId: 'draft',
+ threadId: 'thread',
+ draft: expect.objectContaining({ subject: 'Review' }),
+ html: expect.stringContaining('Schedule this'),
+ })
+ );
+ expect(host.showDraft).toHaveBeenCalledExactlyOnceWith('draft');
+ root.dispose();
+
+ // The compose view the undo opens gets the scheduled content back.
+ const reopened = mountEmailComposer(composeContext, host, {
+ draftId: 'draft',
+ });
+ expect(reopened.state.context.subject()).toBe('Review');
+ expect(reopened.state.context.initialHtml()).toContain('Schedule this');
+ reopened.dispose();
+});
+
+it('retires the scheduled notice when the thread view cancels the schedule', async () => {
+ const composeContext = createComposeContext();
+ vi.mocked(composeContext.notices.feedback.success).mockImplementation(
+ (message) => (message === 'Email scheduled' ? 7 : undefined)
+ );
+ const root = mountEmailComposer(composeContext);
+ root.edit('Schedule then cancel');
+ const sendTime = new Date('2026-12-01T12:00:00Z');
+ root.state.context.schedule.onSelect(sendTime);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+ // Scheduling shows the thread, whose own composer holds the draft.
root.dispose();
+ const threadView = mountEmailComposer(composeContext, undefined, {
+ draft: message('draft', {
+ is_draft: true,
+ scheduled_send_time: sendTime.toISOString(),
+ }),
+ });
+ expect(composeContext.notices.feedback.dismiss).not.toHaveBeenCalled();
+
+ expect(await threadView.state.context.schedule.onCancel()).toBe(true);
+ expect(composeContext.notices.feedback.dismiss).toHaveBeenCalledWith(7);
+ // A click that lands during the dismissal must not undo the newer draft.
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.unschedule).toHaveBeenCalledOnce();
+ expect(composeContext.drafts.restoreDraft).not.toHaveBeenCalled();
+ threadView.dispose();
});
it('preserves local intent on schedule failure without falling back to send', async () => {
@@ -463,6 +529,112 @@ it('reconciles an external schedule and cancellation while the composer is open'
root.dispose();
});
+it('reopens an in-place scheduled composer when the schedule is cancelled elsewhere', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Schedule in place');
+ const sendTime = '2026-12-01T12:00:00Z';
+ root.state.context.schedule.onSelect(new Date(sendTime));
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ composeContext.setDraftLifecycle({
+ type: 'scheduled',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime,
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.disabled()).toBe(true);
+
+ composeContext.setDraftLifecycle({
+ type: 'editing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.schedule.state().type).toBe('editing');
+ expect(root.state.context.disabled()).toBe(false);
+ expect(root.state.context.primaryActionDisabled()).toBe(false);
+ root.dispose();
+});
+
+it('does not mistake its own in-flight send for a delivery elsewhere', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Saved once');
+ await vi.advanceTimersByTimeAsync(600);
+ const sending = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(
+ sending.promise
+ );
+ // The pre-send save is best-effort, so the send goes ahead with the final
+ // edit unsaved.
+ vi.mocked(composeContext.drafts.saveDraft).mockRejectedValueOnce(
+ new Error('save offline')
+ );
+ root.edit('Final edit');
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.sendMessage).toHaveBeenCalledOnce();
+
+ composeContext.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ sending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(composeContext.notices.feedback.alert).not.toHaveBeenCalled();
+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
+ expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
+ 'Email sent',
+ expect.anything()
+ );
+ root.dispose();
+});
+
+it('does not announce a plain send as a scheduled one', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Just send this');
+ await vi.advanceTimersByTimeAsync(600);
+ const sending = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(
+ sending.promise
+ );
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+
+ composeContext.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ sending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(composeContext.notices.feedback.success).not.toHaveBeenCalledWith(
+ 'Scheduled email sent'
+ );
+ expect(composeContext.notices.feedback.alert).not.toHaveBeenCalled();
+ expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
+ 'Email sent',
+ expect.anything()
+ );
+ root.dispose();
+});
+
it('keeps the confirmed time authoritative until update or cancellation succeeds', async () => {
const composeContext = createComposeContext();
const root = mountEmailComposer(composeContext);
@@ -591,7 +763,7 @@ it('ignores a stale autosave response and preserves a racing edit under a new dr
'New text that raced delivery'
);
expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
- 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
+ 'This email was already sent. Your newer text was kept as a new draft and was not sent.'
);
expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
root.dispose();
diff --git a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
index 9d2de0c7bd..7368bcda1a 100644
--- a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
@@ -418,6 +418,7 @@ describe.each(['reply', 'compose'] as const)(
expect(context.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
{
draftId: 'scheduled-server',
+ threadId: 'thread',
sendTime: '2027-01-01T12:00:00.000Z',
includeSignature: undefined,
},
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.ts
index 089a97a578..03c2278975 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -103,9 +103,10 @@ export type EmailComposerOptions = {
export function createEmailComposer(props: EmailComposerOptions) {
const initialDraftId = props.draft?.db_id ?? props.draftId;
- const restoredSnapshot = initialDraftId
- ? composeUndo.take(initialDraftId)
- : undefined;
+ // Only the compose view an undo reopens restores its snapshot; the thread
+ // view's composer for the same, still scheduled draft must leave it be.
+ const restoredSnapshot =
+ props.draftId && !props.draft ? composeUndo.take(props.draftId) : undefined;
const hasPaidAccess = props.hasPaidAccess;
const form = createEmailFormState(
@@ -404,10 +405,10 @@ export function createEmailComposer(props: EmailComposerOptions) {
lifecycleState: lifecycle.state,
reconcile: lifecycle.refresh,
reconcileIdentity: lifecycle.refreshIdentity,
- onScheduleUndone: ({ draftId }) => {
+ onScheduleUndone: async ({ draftId, threadId, inboxId }) => {
session.dispatch({ type: 'schedule-cancelled' });
setCompleted(false);
- props.host?.showDraft?.(draftId);
+ await restoreAfterUndoSend(draftId, threadId, inboxId);
},
onViewScheduled: ({ draftId, threadId }) => {
if (threadId) props.host?.showThread?.(threadId);
@@ -465,6 +466,22 @@ export function createEmailComposer(props: EmailComposerOptions) {
const [validationError, setValidationError] =
createSignal<ComposeValidationError | null>(null);
+ // Snapshot the form before any watermark so an undo can reopen it as it was.
+ const rememberForUndo = (draftId: string, inboxId: string) => {
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ composeUndo.remember({
+ inboxId,
+ draftId,
+ threadId: currentThreadId(),
+ recipients: structuredClone(unwrap(form.recipients())),
+ subject: form.subject(),
+ bodyHtml: currentEditor.read(() => $generateHtmlFromNodes(currentEditor)),
+ attachments: [...form.attachments.list()],
+ includeSignature: includeSignature(),
+ });
+ };
+
// Everything that follows a successful unschedule: scrub the new thread's
// cache, restore the server-side draft, and remount the compose view so it
// restores the form from the undo snapshot.
@@ -602,6 +619,8 @@ export function createEmailComposer(props: EmailComposerOptions) {
if (scheduleAction === 'schedule' || scheduleAction === 'update') {
const result = await schedule.submit();
if (result === 'scheduled') {
+ const scheduledDraftId = currentDraftId();
+ if (scheduledDraftId) rememberForUndo(scheduledDraftId, currentLink.id);
setCompleted(true);
const threadId = currentThreadId();
try {
@@ -648,23 +667,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
const draftId = identity.kind === 'server' ? identity.draftId : undefined;
// Snapshot editor state before watermark so undo-send can restore it
- if (currentEditor) {
- const snapshotHtml = currentEditor.read(() =>
- $generateHtmlFromNodes(currentEditor)
- );
- if (draftId) {
- composeUndo.remember({
- inboxId: currentLink.id,
- draftId,
- threadId: currentThreadId(),
- recipients: structuredClone(unwrap(form.recipients())),
- subject: form.subject(),
- bodyHtml: snapshotHtml,
- attachments: [...form.attachments.list()],
- includeSignature: includeSignature(),
- });
- }
- }
+ if (draftId) rememberForUndo(draftId, currentLink.id);
// Append watermark after all validation passes so failed sends don't
// leave orphaned watermark nodes in the editor tree.
@@ -801,8 +804,12 @@ export function createEmailComposer(props: EmailComposerOptions) {
let lastScheduledTime = schedule.confirmedTime()?.toISOString();
let handledTerminalIdentity: string | undefined;
+ const lifecycleInputs = () =>
+ [lifecycle.state(), scheduling(), movingInbox(), submitting()] as const;
createEffect(
- on([lifecycle.state, scheduling, movingInbox], ([state, , moving]) => {
+ on(lifecycleInputs, ([state, , moving, sending]) => {
+ // While this composer sends, the draft turning into a sent message is
+ // its own doing; the send settles the composer and replays the rest.
if (
!state ||
!session.serverConfirmed() ||
@@ -810,6 +817,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
state.threadId !== currentThreadId() ||
(state.inboxId !== undefined && state.inboxId !== persistedInboxId()) ||
moving ||
+ sending ||
discarding()
)
return;
@@ -840,6 +848,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
schedule.observe(state);
if (wasScheduled && schedule.state().type === 'editing') {
session.dispatch({ type: 'schedule-cancelled' });
+ setCompleted(false);
lastScheduledTime = undefined;
props.notices.feedback.success(
'Schedule cancelled. This email is editable again.'
@@ -850,11 +859,16 @@ export function createEmailComposer(props: EmailComposerOptions) {
if (handledTerminalIdentity === `${state.draftId}:${state.type}`) return;
handledTerminalIdentity = `${state.draftId}:${state.type}`;
+ // Only a confirmed schedule makes a delivery "the scheduled email"; any
+ // other draft was sent from another tab or device.
+ const wasScheduled = schedule.state().type === 'scheduled';
if (editVersion > persistedEditVersion) {
detachFromObsoleteDraft(
- state.type === 'sent'
- ? 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
- : 'The draft changed elsewhere. Your newer text was kept as a new draft.'
+ state.type !== 'sent'
+ ? 'The draft changed elsewhere. Your newer text was kept as a new draft.'
+ : wasScheduled
+ ? 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
+ : 'This email was already sent. Your newer text was kept as a new draft and was not sent.'
);
return;
}
@@ -866,7 +880,9 @@ export function createEmailComposer(props: EmailComposerOptions) {
setCompleted(true);
setTerminalState(state.type);
if (state.type === 'sent') {
- props.notices.feedback.success('Scheduled email sent');
+ if (wasScheduled)
+ props.notices.feedback.success('Scheduled email sent');
+ else props.notices.feedback.alert('This email was already sent');
props.host?.showThread?.(state.threadId);
} else {
props.notices.feedback.alert('This draft is no longer available.');
diff --git a/apps/web/src/features/email-compose/primitives/email-send-schedule.ts b/apps/web/src/features/email-compose/primitives/email-send-schedule.ts
index e5bc17d9bf..f96229b415 100644
--- a/apps/web/src/features/email-compose/primitives/email-send-schedule.ts
+++ b/apps/web/src/features/email-compose/primitives/email-send-schedule.ts
@@ -51,6 +51,10 @@ export function getScheduleActionLabel(state: EmailScheduleState) {
const sameTime = (left: Date, right: Date) =>
left.getTime() === right.getTime();
+// A schedule's notice outlives the composer that made it: showing the thread
+// mounts another composer for the same draft, which may cancel or deliver it.
+const scheduledNotices = new Map<string, { toastId: number | undefined }>();
+
export function createEmailSendSchedule(options: {
delivery: Pick<EmailDelivery, 'schedule' | 'unschedule' | 'archive'>;
notices: EmailComposeFeedback;
@@ -58,6 +62,8 @@ export function createEmailSendSchedule(options: {
draftId: Accessor<string | null | undefined>;
saveDraft: () => Promise<string | undefined>;
threadId: Accessor<string | null | undefined>;
+ /** Scheduling marks the thread done only when this reports it in the inbox. */
+ threadInInbox?: Accessor<boolean | undefined>;
inboxId: Accessor<string | undefined>;
includeSignature: Accessor<boolean | undefined>;
/** Changes whenever the persisted draft identity or editable content changes. */
@@ -97,6 +103,18 @@ export function createEmailSendSchedule(options: {
let selectionRevision = 0;
let ignoredLifecycleObservation: EmailDraftLifecycleState | undefined;
let deferredLifecycleObservation: EmailDraftLifecycleState | undefined;
+ // The "Email scheduled" notice offers Undo only while that schedule stands.
+ // Remember the draft it belongs to past a composer's session reset.
+ let scheduledDraftId = options.initialScheduledTime
+ ? (options.draftId() ?? undefined)
+ : undefined;
+ const dismissScheduledNotice = () => {
+ const draftId = scheduledDraftId ?? options.draftId();
+ const notice = draftId ? scheduledNotices.get(draftId) : undefined;
+ if (!draftId || !notice) return;
+ scheduledNotices.delete(draftId);
+ if (notice.toastId != null) notices.feedback.dismiss(notice.toastId);
+ };
const pending = () => operation() !== 'idle';
const selectedTime = () => getScheduleSelection(state());
@@ -138,12 +156,14 @@ export function createEmailSendSchedule(options: {
) {
return;
}
+ scheduledDraftId = options.draftId() ?? scheduledDraftId;
selectionRevision += 1;
setState({ type: 'scheduled', confirmedTime: sendTime });
};
const applyEditing = () => {
if (state().type !== 'scheduled') return;
+ dismissScheduledNotice();
selectionRevision += 1;
setState({ type: 'editing', intent: { type: 'immediate' } });
};
@@ -185,10 +205,12 @@ export function createEmailSendSchedule(options: {
threadId: string | undefined;
inboxId: string | undefined;
sendTime: Date;
+ markedDone: boolean;
}) => {
try {
await delivery.unschedule({
draftId: input.draftId,
+ threadId: input.threadId,
inboxId: input.inboxId,
});
} catch (error) {
@@ -227,6 +249,17 @@ export function createEmailSendSchedule(options: {
}
if (options.draftId() === input.draftId) applyEditing();
+ if (input.markedDone && input.threadId) {
+ try {
+ await delivery.archive(
+ { threadId: input.threadId, value: false },
+ input.inboxId
+ );
+ } catch (error) {
+ notices.reportError(error);
+ notices.feedback.failure('Failed to restore thread to inbox');
+ }
+ }
try {
await options.onScheduleUndone?.(input);
notices.feedback.success('Schedule cancelled.');
@@ -299,6 +332,7 @@ export function createEmailSendSchedule(options: {
await delivery.schedule(
{
draftId,
+ threadId: options.threadId() ?? undefined,
sendTime: requested.toISOString(),
includeSignature: options.includeSignature(),
},
@@ -327,9 +361,14 @@ export function createEmailSendSchedule(options: {
applyScheduled(requested, true);
const threadId = options.threadId();
- if (threadId) {
+ let markedDone = false;
+ const inInbox = options.threadInInbox
+ ? options.threadInInbox() === true
+ : true;
+ if (threadId && inInbox) {
try {
await delivery.archive({ threadId, value: true }, inboxId);
+ markedDone = true;
} catch (error) {
notices.reportError(error);
notices.feedback.failure(
@@ -340,6 +379,7 @@ export function createEmailSendSchedule(options: {
try {
// The title stays terse so it never truncates; the time is the subtext.
let toastId: number | undefined;
+ let notice: { toastId: number | undefined } | undefined;
let undoStarted = false;
const onViewScheduled = options.onViewScheduled;
const viewAction = onViewScheduled
@@ -364,20 +404,29 @@ export function createEmailSendSchedule(options: {
{
label: 'Undo',
onClick: () => {
- if (undoStarted) return;
+ // A dismissing notice stays clickable; only the live one undoes.
+ if (
+ undoStarted ||
+ !notice ||
+ scheduledNotices.get(draftId) !== notice
+ )
+ return;
undoStarted = true;
+ scheduledNotices.delete(draftId);
if (toastId != null) notices.feedback.dismiss(toastId);
void undoInitialSchedule({
draftId,
threadId: threadId ?? undefined,
inboxId,
sendTime: requested,
+ markedDone,
});
},
},
]
: [];
const actions = [...undoAction, ...viewAction];
+ dismissScheduledNotice();
toastId = notices.feedback.success(
action === 'update' ? 'Email rescheduled' : 'Email scheduled',
{
@@ -390,6 +439,8 @@ export function createEmailSendSchedule(options: {
...(actions.length > 0 ? { actions, duration: 8_000 } : {}),
}
);
+ notice = { toastId };
+ scheduledNotices.set(draftId, notice);
} catch (error) {
// Toast rendering is post-commit UI and cannot make a successful
// schedule retryable.
@@ -414,7 +465,11 @@ export function createEmailSendSchedule(options: {
setOperation('cancelling');
try {
try {
- await delivery.unschedule({ draftId, inboxId });
+ await delivery.unschedule({
+ draftId,
+ threadId: options.threadId() ?? undefined,
+ inboxId,
+ });
} catch (error) {
notices.reportError(error);
try {
@@ -454,6 +509,7 @@ export function createEmailSendSchedule(options: {
if (current.type === 'editing') return;
const proposed =
current.type === 'scheduled' ? current.proposedTime : undefined;
+ dismissScheduledNotice();
selectionRevision += 1;
setState(
proposed
@@ -476,6 +532,7 @@ export function createEmailSendSchedule(options: {
observe,
detach,
reset: () => {
+ scheduledDraftId = undefined;
selectionRevision += 1;
setState({ type: 'editing', intent: { type: 'immediate' } });
},
diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.ts
index 96f8ff609f..b60776df97 100644
--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts
@@ -678,6 +678,7 @@ export function createReplyComposer(
draftId: savedDraftId,
saveDraft: saveForSchedule,
threadId: savedDraftThreadId,
+ threadInInbox: () => thread()?.inbox_visible,
inboxId: activeInboxId,
includeSignature: () => (includeSignature() ? undefined : false),
generation: () =>
@@ -1252,11 +1253,16 @@ export function createReplyComposer(
if (handledTerminalIdentity === `${state.draftId}:${state.type}`) return;
handledTerminalIdentity = `${state.draftId}:${state.type}`;
+ // Only a confirmed schedule makes a delivery "the scheduled email"; any
+ // other draft was sent from another tab or device.
+ const wasScheduled = schedule.state().type === 'scheduled';
if (editVersion > persistedEditVersion) {
detachFromObsoleteDraft(
- state.type === 'sent'
- ? 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
- : 'The draft changed elsewhere. Your newer text was kept as a new draft.'
+ state.type !== 'sent'
+ ? 'The draft changed elsewhere. Your newer text was kept as a new draft.'
+ : wasScheduled
+ ? 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
+ : 'This email was already sent. Your newer text was kept as a new draft and was not sent.'
);
return;
}
@@ -1267,7 +1273,9 @@ export function createReplyComposer(
setTerminalState(state.type);
clearDraftState();
if (state.type === 'sent') {
- props.notices.feedback.success('Scheduled email sent');
+ if (wasScheduled)
+ props.notices.feedback.success('Scheduled email sent');
+ else props.notices.feedback.alert('This email was already sent');
} else {
props.notices.feedback.alert('This draft is no longer available.');
}
diff --git a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
index 00e75d0971..9c553c7dcf 100644
--- a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
+++ b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
@@ -23,10 +23,11 @@ vi.mock('@core/cross-tab/cross-tab-bus', () => ({
function composer(
kind: 'standalone' | 'reply',
- composeContext: EmailComposeContext
+ composeContext: EmailComposeContext,
+ thread: { inboxVisible?: boolean } = {}
) {
if (kind === 'reply') {
- const state = mountReplyComposer(composeContext);
+ const state = mountReplyComposer(composeContext, undefined, {}, thread);
return {
dispose: state.dispose,
edit: state.edit,
@@ -114,9 +115,13 @@ describe('send and schedule ordering', () => {
observedAt: Date.now(),
});
await vi.advanceTimersByTimeAsync(0);
- expect(context.notices.feedback.success).toHaveBeenCalledWith(
+ // The time was never confirmed, so this was not the scheduled send.
+ expect(context.notices.feedback.success).not.toHaveBeenCalledWith(
'Scheduled email sent'
);
+ expect(context.notices.feedback.alert).toHaveBeenCalledWith(
+ 'This email was already sent'
+ );
pending.resolve({
draftId: 'draft',
threadId: 'thread',
@@ -329,7 +334,7 @@ describe('send and schedule ordering', () => {
'%s defers stale observations until schedule reconciliation completes',
async (kind) => {
const context = createComposeContext();
- const state = composer(kind, context);
+ const state = composer(kind, context, { inboxVisible: true });
const pending = Promise.withResolvers<void>();
vi.mocked(context.delivery.archive).mockReturnValueOnce(pending.promise);
const lifecycle = vi.mocked(context.draftLifecycle.observe).mock
@@ -599,9 +604,33 @@ describe('send and schedule ordering', () => {
}
});
- it('undoes a scheduled reply with its saved body, envelope, and attachments', async () => {
+ it('leaves a done thread done when a reply is scheduled and undone', async () => {
const composeContext = createComposeContext();
const state = mountReplyComposer(composeContext);
+ try {
+ state.edit('Schedule from a done thread');
+ state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ await state.sendEmail();
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(composeContext.delivery.unschedule).toHaveBeenCalledOnce();
+ expect(composeContext.delivery.archive).not.toHaveBeenCalled();
+ } finally {
+ state.dispose();
+ }
+ });
+
+ it('undoes a scheduled reply with its saved body, envelope, and attachments', async () => {
+ const composeContext = createComposeContext();
+ const state = mountReplyComposer(
+ composeContext,
+ undefined,
+ {},
+ { inboxVisible: true }
+ );
try {
state.form.setSubject('Scheduled reply subject');
state.form.attachments.add({
@@ -623,8 +652,13 @@ describe('send and schedule ordering', () => {
expect(composeContext.delivery.unschedule).toHaveBeenCalledWith({
draftId: 'draft',
+ threadId: 'thread',
inboxId: 'inbox',
});
+ expect(composeContext.delivery.archive).toHaveBeenLastCalledWith(
+ { threadId: 'thread', value: false },
+ 'inbox'
+ );
expect(composeContext.drafts.restoreDraft).toHaveBeenCalledWith(
expect.objectContaining({
draftId: 'draft',
@@ -1173,7 +1207,12 @@ describe('send and schedule ordering', () => {
threadId: 'thread-c',
inboxId: 'c',
});
- const state = mountReplyComposer(composeContext);
+ const state = mountReplyComposer(
+ composeContext,
+ undefined,
+ {},
+ { inboxVisible: true }
+ );
try {
state.edit('Moving between inboxes');
await vi.advanceTimersByTimeAsync(500);
diff --git a/apps/web/src/features/email-compose/tests/reply.ts b/apps/web/src/features/email-compose/tests/reply.ts
index 983f51c6b5..e6ee298855 100644
--- a/apps/web/src/features/email-compose/tests/reply.ts
+++ b/apps/web/src/features/email-compose/tests/reply.ts
@@ -15,7 +15,8 @@ export function mountReplyComposer(
callbacks: Pick<
ReplyComposerOptions,
'draft' | 'sideEffectOnSend' | 'onMarkDone'
- > = {}
+ > = {},
+ thread: { inboxVisible?: boolean } = {}
) {
return createRoot((dispose) => {
const editor = createEmailEditor('Ready to send');
@@ -39,7 +40,7 @@ export function mountReplyComposer(
thread: () => ({
db_id: 'thread',
link_id: 'inbox',
- inbox_visible: false,
+ inbox_visible: thread.inboxVisible ?? false,
}),
recipientOptions: () => [],
isPersonalReply: () => false,