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-compose): reopen forwards as forwards and swap quoted threads on kind change (#8798)

teo007c26daa2b2
diff --git a/apps/web/src/features/email-compose/core/reply-type.ts b/apps/web/src/features/email-compose/core/reply-type.ts
index 24fbe7b8f6..6dd249c25b 100644
--- a/apps/web/src/features/email-compose/core/reply-type.ts
+++ b/apps/web/src/features/email-compose/core/reply-type.ts
@@ -1 +1,15 @@
export type ReplyType = 'reply' | 'reply-all' | 'forward';
+
+export const FORWARDED_MESSAGE_HEADER =
+ '---------- Forwarded message ----------';
+
+/**
+ * Whether an email body forwards a message. Provider sync rewrites markup, so
+ * this reads the header's text; a header inside a quote belongs to the quoted
+ * message.
+ */
+export function forwardsMessage(html: string) {
+ const { body } = new DOMParser().parseFromString(html, 'text/html');
+ for (const quote of body.querySelectorAll('blockquote')) quote.remove();
+ return body.textContent?.includes(FORWARDED_MESSAGE_HEADER) ?? false;
+}
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 ff527d69a3..3947663e9b 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -26,6 +26,7 @@ import type {
} from '../../email-message/core/email-message';
import {
operationBlocksEditing,
+ operationBlocksInboxSwitch,
operationBlocksSending,
operationSending,
} from '../../email-message/core/message-operation';
@@ -497,6 +498,9 @@ export function createEmailComposer(props: EmailComposerOptions) {
const deliveryBlocked = () =>
operationSource?.needsReload?.() ||
operationBlocksSending(currentOperation());
+ const inboxSwitchBlocked = () =>
+ operationSource?.needsReload?.() ||
+ operationBlocksInboxSwitch(currentOperation());
const operationBlocked = () =>
operationSource?.needsReload?.() ||
operationBlocksEditing(currentOperation());
@@ -1300,7 +1304,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
if (
sendLocked() ||
restoring() ||
- (!draftTransfer?.pending() && deliveryBlocked()) ||
+ (!draftTransfer?.pending() && inboxSwitchBlocked()) ||
submitting() ||
discarding() ||
movingInbox() ||
diff --git a/apps/web/src/features/email-compose/primitives/email-form-state.ts b/apps/web/src/features/email-compose/primitives/email-form-state.ts
index 10241399b1..294b16b576 100644
--- a/apps/web/src/features/email-compose/primitives/email-form-state.ts
+++ b/apps/web/src/features/email-compose/primitives/email-form-state.ts
@@ -16,7 +16,7 @@ import {
getReplyAllRecipients,
getReplyRecipientsFromParent,
} from '../core/recipient-conversion';
-import type { ReplyType } from '../core/reply-type';
+import { forwardsMessage, type ReplyType } from '../core/reply-type';
import { getSubjectText } from '../core/subject-text';
export type DraftFormAttachment =
@@ -157,21 +157,26 @@ export function createEmailFormState(
].filter((address): address is string => !!address);
const [recipientsEdited, setRecipientsEdited] = createSignal(false);
- const draftContainsAppendedReply = (message = draft) => {
+ const decodedBody = (message?: EmailMessage) => {
const encoded = message?.body_html_sanitized;
- if (!encoded) return false;
- const decodedHtml = decodeBase64Utf8(encoded);
+ return encoded ? decodeBase64Utf8(encoded) : undefined;
+ };
+
+ const draftContainsAppendedReply = (message = draft) => {
+ const decodedHtml = decodedBody(message);
if (!decodedHtml) return false;
const parsed = new DOMParser().parseFromString(decodedHtml, 'text/html');
return parsed.body.querySelector('div.macro_quote') !== null;
};
+ const defaultReplyType = (): ReplyType =>
+ (replyingTo?.to.length ?? 0) + (replyingTo?.cc.length ?? 0) > 1
+ ? 'reply-all'
+ : 'reply';
+
const getInitialState = () => {
- const replyType =
- (replyingTo?.to.length ?? 0) + (replyingTo?.cc.length ?? 0) > 1
- ? 'reply-all'
- : 'reply';
+ const replyType = defaultReplyType();
let initialSubject = draft?.subject;
@@ -346,6 +351,12 @@ export function createEmailFormState(
setEditRevision((revision) => revision + 1);
};
+ // No draft field records whether it is a forward; only its body does.
+ const restoredReplyType = (bodyHtml: string | undefined): ReplyType => {
+ if (bodyHtml && forwardsMessage(bodyHtml)) return 'forward';
+ return state.replyType === 'forward' ? defaultReplyType() : state.replyType;
+ };
+
const reset = (next: EmailFormState) => {
setState(reconcile(next));
const recipients = state.recipients;
@@ -364,6 +375,7 @@ export function createEmailFormState(
setSenderChoice({ email: message.from?.email });
setRecipientsEdited(true);
setState({
+ replyType: restoredReplyType(decodedBody(message)),
subject: message.subject ?? '',
recipients: {
to: message.to.map(convertContactInfoToEmailRecipient),
@@ -381,6 +393,10 @@ export function createEmailFormState(
])
);
},
+ /** Match the kind to a body loaded into the editor, keeping recipients. */
+ restoreReplyType(bodyHtml: string) {
+ setState('replyType', restoredReplyType(bodyHtml));
+ },
replyAppended: () => state.withQuotedText,
setReplyAppended: (next: boolean) => setState('withQuotedText', next),
recipients: () => {
diff --git a/apps/web/src/features/email-compose/primitives/prepare-email-body.ts b/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
index 9994cc7eeb..0a7320e139 100644
--- a/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
+++ b/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
@@ -9,7 +9,7 @@ import { staticFileReferenceEndpoint } from '@core/constant/servers';
import { encodeBase64UrlUtf8 } from '@core/util/base64';
import { formatEmailDate } from '@core/util/date';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
-import { $createQuoteNode } from '@lexical/rich-text';
+import { $createQuoteNode, $isQuoteNode } from '@lexical/rich-text';
import { $dfsIterator } from '@lexical/utils';
import { sanitizeEmailHtml } from '@macro-inc/email-renderer';
import type { DocumentMentionInfo } from '@macro-inc/lexical-core';
@@ -32,7 +32,7 @@ import {
type LexicalEditor,
type LexicalNode,
} from 'lexical';
-import type { ReplyType } from '../core/reply-type';
+import { FORWARDED_MESSAGE_HEADER, type ReplyType } from '../core/reply-type';
import { TOGGLE_APPEND_EMAIL_THREAD_COMMAND } from './email-editor-commands';
import { flattenConsecutiveParagraphs } from './flatten-consecutive-paragraphs';
@@ -64,7 +64,7 @@ function buildHeaderDescriptor(
if (replyType === 'forward') {
const lines: string[] = [];
- lines.push('---------- Forwarded message ----------');
+ lines.push(FORWARDED_MESSAGE_HEADER);
const fromName = replyingTo.from?.name ?? replyingTo.from?.email ?? '';
const fromEmail = replyingTo.from?.email ?? '';
lines.push(`From: ${fromName} <${fromEmail}>`);
@@ -263,6 +263,25 @@ function removeAppendedThread(
);
}
+/** Whether the appended thread forwards or quotes, read from its header. */
+export function appendedThreadKind(
+ editor: LexicalEditor,
+ replyingToId: string
+): 'forward' | 'reply' | undefined {
+ return editor.read(() => {
+ for (const node of $findPreviousEmailNode(replyingToId)) {
+ if (!node) continue;
+ const header = node
+ .getChildren()
+ .filter((child) => !$isQuoteNode(child))
+ .map((child) => child.getTextContent())
+ .join('');
+ return header.includes(FORWARDED_MESSAGE_HEADER) ? 'forward' : 'reply';
+ }
+ return undefined;
+ });
+}
+
export function registerToggleAppendedThread(editor: LexicalEditor) {
return editor.registerCommand(
TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
@@ -349,10 +368,14 @@ async function _appendItemsAsMacroMentions(
function getAppendedReplyElement(
replyingTo: EmailMessage,
- replyType: ReplyType | undefined
+ replyType: ReplyType | undefined,
+ reopenable = false
) {
const wrapper = document.createElement('div');
wrapper.classList.add('macro_quote', 'gmail_quote');
+ // The editor imports only marked blocks as its appended thread; unmarked, a
+ // reopened draft would append the thread a second time.
+ if (reopenable) wrapper.setAttribute('data-classed-block', 'true');
const spacing = document.createElement('p');
spacing.textContent = '\n';
wrapper.appendChild(spacing);
@@ -409,13 +432,17 @@ function applyMediaScale(container: Element) {
});
}
+type AppendedReply = {
+ replyType: ReplyType | undefined;
+ replyingTo: EmailMessage;
+ /** For a saved draft: mark the thread so reopening it recognises it. */
+ reopenable?: boolean;
+};
+
export function prepareEmailBody(
editor: LexicalEditor | undefined,
// if this argument is provided, we append the message being replied to the html email body
- appendReply?: {
- replyType: ReplyType | undefined;
- replyingTo: EmailMessage;
- }
+ appendReply?: AppendedReply
): {
bodyHtml: string;
bodyText: string;
@@ -436,10 +463,7 @@ export function prepareEmailBody(
*/
export function prepareEmailBodyFromHtml(
generatedHtml: string,
- appendReply?: {
- replyType: ReplyType | undefined;
- replyingTo: EmailMessage;
- }
+ appendReply?: AppendedReply
): {
bodyHtml: string;
bodyText: string;
@@ -468,7 +492,8 @@ export function prepareEmailBodyFromHtml(
if (appendReply && !parsed.body.querySelector('.macro_quote')) {
const appendedReplyElement = getAppendedReplyElement(
appendReply.replyingTo,
- appendReply.replyType
+ appendReply.replyType,
+ appendReply.reopenable
);
parsed.body.appendChild(appendedReplyElement);
}
diff --git a/apps/web/src/features/email-compose/primitives/rejected-draft-inbox-switch.test.ts b/apps/web/src/features/email-compose/primitives/rejected-draft-inbox-switch.test.ts
new file mode 100644
index 0000000000..ceee2e66b6
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/rejected-draft-inbox-switch.test.ts
@@ -0,0 +1,103 @@
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { MessageOperation } from '../../email-message/core/message-operation';
+import { message } from '../../email-message/tests/messages';
+import { createComposeContext } from '../tests/capabilities';
+import { mountEmailComposer } from '../tests/composer';
+import { mountReplyComposer } from '../tests/reply';
+
+beforeEach(() => vi.useFakeTimers({ now: new Date('2026-09-01T12:00:00Z') }));
+afterEach(() => vi.useRealTimers());
+
+function mountDraft(kind: 'compose' | 'reply', seeded: MessageOperation) {
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [
+ { id: 'inbox', email_address: '[email protected]', settings: {} },
+ { id: 'other', email_address: '[email protected]', settings: {} },
+ ];
+ const [operation] = createSignal(seeded);
+ context.operations = () => ({ operation, resolve: vi.fn() });
+ context.setDraftLifecycle({
+ type: 'editing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ const draft = message('draft', {
+ is_draft: true,
+ replying_to_id: kind === 'reply' ? 'parent' : null,
+ operation: seeded,
+ });
+ const compose =
+ kind === 'compose'
+ ? mountEmailComposer(context, undefined, { draft })
+ : undefined;
+ const reply =
+ kind === 'reply'
+ ? mountReplyComposer(context, undefined, { draft })
+ : undefined;
+ return {
+ context,
+ async switchInbox() {
+ const switched = compose
+ ? compose.state.context.onSelectInbox?.('other')
+ : reply?.persistDraftOnSenderSwitch('other');
+ await vi.advanceTimersByTimeAsync(0);
+ await switched;
+ },
+ dispose() {
+ compose?.dispose();
+ reply?.dispose();
+ },
+ };
+}
+
+it.each(['compose', 'reply'] as const)(
+ 'moves a %s draft the provider rejected to another inbox',
+ async (kind) => {
+ const draft = mountDraft(kind, {
+ state: 'FAILED',
+ issue: 'INVALID_CONTENT',
+ revision: '3',
+ });
+ try {
+ await draft.switchInbox();
+ expect(draft.context.drafts.transferDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftId: 'draft',
+ sourceInboxId: 'inbox',
+ destinationInboxId: 'other',
+ })
+ );
+ } finally {
+ draft.dispose();
+ }
+ }
+);
+
+it.each([
+ [
+ 'compose',
+ 'an unfinished move',
+ { state: 'PENDING', issue: 'MOVE_PENDING' },
+ ],
+ ['reply', 'an unfinished move', { state: 'PENDING', issue: 'MOVE_PENDING' }],
+ [
+ 'compose',
+ 'a draft conflict',
+ { state: 'CONFLICT', issue: 'DRAFT_CONFLICT' },
+ ],
+ ['reply', 'a draft conflict', { state: 'CONFLICT', issue: 'DRAFT_CONFLICT' }],
+] as const)(
+ 'keeps a %s draft with %s in its inbox',
+ async (kind, _label, seeded) => {
+ const draft = mountDraft(kind, { ...seeded, revision: '3' });
+ try {
+ await draft.switchInbox();
+ expect(draft.context.drafts.transferDraft).not.toHaveBeenCalled();
+ } finally {
+ draft.dispose();
+ }
+ }
+);
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 48b9178a0a..159c33fce9 100644
--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts
@@ -27,6 +27,7 @@ import {
import type { MessageOperationSourceFactory } from '../../email-message/context/message-operation-source';
import {
operationBlocksEditing,
+ operationBlocksInboxSwitch,
operationBlocksSending,
operationSending,
} from '../../email-message/core/message-operation';
@@ -50,6 +51,7 @@ import {
convertContactInfoToEmailRecipient,
convertEmailRecipientToContactInfo,
} from '../core/recipient-conversion';
+import type { ReplyType } from '../core/reply-type';
import { partitionByAttachmentLimit } from './attachment-limit';
import { createAttachmentLinkOffer } from './attachment-links';
import {
@@ -71,6 +73,7 @@ import type { EmailFormContextValue, FormAccessKey } from './email-form-types';
import { createEmailSendSchedule } from './email-send-schedule';
import { addUserMentionToCc } from './mention-to-cc';
import {
+ appendedThreadKind,
clearEmailBody,
hasDraftContent,
prepareEmailBody,
@@ -310,6 +313,9 @@ export function createReplyComposer(
const deliveryBlocked = () =>
operationSource?.needsReload?.() ||
operationBlocksSending(currentOperation());
+ const inboxSwitchBlocked = () =>
+ operationSource?.needsReload?.() ||
+ operationBlocksInboxSwitch(currentOperation());
function operationBlocked() {
return (
operationSource?.needsReload?.() ||
@@ -435,6 +441,7 @@ export function createReplyComposer(
});
restoreEnvelope(snapshot);
setRestoredBodyHtml(snapshot.bodyHtml ?? plainTextToHtml(''));
+ if (snapshot.bodyHtml) form.restoreReplyType(snapshot.bodyHtml);
const currentEditor = editor();
if (currentEditor && snapshot.bodyHtml) {
setEditorStateFromHtml(currentEditor, snapshot.bodyHtml);
@@ -454,6 +461,9 @@ export function createReplyComposer(
const initialHtml = () =>
restoredBodyHtml() ?? restoredSnapshot?.bodyHtml ?? props.preloadedHtml;
+ // The editor may load a local copy that is newer than the thread's draft.
+ const loadedHtml = untrack(initialHtml);
+ if (loadedHtml) form.restoreReplyType(loadedHtml);
const [editorConnected, setEditorConnected] = createSignal(false);
const handleEditorConnect = () => {
const currentEditor = editor();
@@ -521,40 +531,65 @@ export function createReplyComposer(
on(form.editRevision, () => scheduleDraftSave(), { defer: true })
);
+ // A forward carries the forwarded message and a reply never does, so a
+ // kind change swaps whichever thread the other kind appended.
+ const matchAppendedThread = (
+ currentEditor: LexicalEditor,
+ message: EmailMessage,
+ rt: ReplyType,
+ kindChanged: boolean
+ ) => {
+ const forwarding = rt === 'forward';
+ const appended = kindChanged
+ ? appendedThreadKind(currentEditor, message.db_id)
+ : undefined;
+ if (appended && (appended === 'forward') !== forwarding) {
+ currentEditor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo: message,
+ replyType: rt,
+ visible: false,
+ });
+ if (!forwarding) form.setReplyAppended(false);
+ }
+ if (!forwarding || !form.replyAppended()) return;
+ if (appendedThreadKind(currentEditor, message.db_id)) return;
+ setQuoteCollapsed(true);
+ currentEditor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo: message,
+ replyType: rt,
+ visible: true,
+ isPersonal: ctx.isPersonalReply(),
+ });
+ };
+
// The mounted composer owns focus, editor commands, and their cleanup.
+ let shownReplyType: ReplyType | undefined;
createEffect(() => {
const rt = form.replyType();
if (!editorConnected()) return;
+ // A loaded body already matches its kind; only later changes swap threads.
+ const kindChanged = shownReplyType !== undefined && shownReplyType !== rt;
+ shownReplyType = rt;
// Later reply-type changes are the user's, and always take focus.
const takeFocus = mountFocus;
mountFocus = true;
untrack(() => {
setComposerExpanded(false);
if (rt === 'forward') {
- setQuoteCollapsed(true);
if (takeFocus) focus.forward();
- const message = replyTarget;
- const currentEditor = editor();
- if (message && currentEditor && form.replyAppended()) {
- // The editor's lazy command registration completes after this batch.
- const timer = setTimeout(
- () =>
- currentEditor.dispatchCommand(
- TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
- {
- replyingTo: message,
- replyType: rt,
- visible: true,
- isPersonal: ctx.isPersonalReply(),
- }
- ),
- 0
- );
- onCleanup(() => clearTimeout(timer));
- }
} else if (takeFocus) {
focus.reply();
}
+ const message = replyTarget;
+ const currentEditor = editor();
+ if (!message || !currentEditor) return;
+ if (!kindChanged && (rt !== 'forward' || !form.replyAppended())) return;
+ // The editor's lazy command registration completes after this batch.
+ const timer = setTimeout(
+ () => matchAppendedThread(currentEditor, message, rt, kindChanged),
+ 0
+ );
+ onCleanup(() => clearTimeout(timer));
});
});
@@ -571,12 +606,16 @@ export function createReplyComposer(
function collectDraft(forDelivery = false) {
if (!forDelivery) $removeAllWatermarkNodes(editor());
+ // A saved forward keeps its forwarded message even while it is hidden:
+ // the header is the only record that the draft is a forward.
+ const appendsToBody = forDelivery || form.replyType() === 'forward';
const prepared = prepareEmailBody(
editor(),
- forDelivery && replyTarget && appendsQuotedThread()
+ appendsToBody && replyTarget && appendsQuotedThread()
? {
replyType: form.replyType(),
replyingTo: replyTarget,
+ reopenable: !forDelivery,
}
: undefined
);
@@ -857,7 +896,7 @@ export function createReplyComposer(
const saveSelectedInbox = async (inboxId: string, senderEmail?: string) => {
if (
restoring() ||
- (!draftTransfer?.pending() && deliveryBlocked()) ||
+ (!draftTransfer?.pending() && inboxSwitchBlocked()) ||
submitting() ||
pendingDeletion() ||
movingInbox() ||
diff --git a/apps/web/src/features/email-compose/primitives/reply-forward-kind.test.ts b/apps/web/src/features/email-compose/primitives/reply-forward-kind.test.ts
new file mode 100644
index 0000000000..8461f852d6
--- /dev/null
+++ b/apps/web/src/features/email-compose/primitives/reply-forward-kind.test.ts
@@ -0,0 +1,455 @@
+import type { LexicalEditor } from 'lexical';
+import { $createParagraphNode, $createTextNode, $getRoot } from 'lexical';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { message } from '../../email-message/tests/messages';
+import type {
+ EmailComposeContext,
+ EmailDraftRestoration,
+ EmailInbox,
+} from '../context/compose-capabilities';
+import { decodeBase64Utf8 } from '../core/decode-base64';
+import type { EmailRecipient } from '../core/email-recipient';
+import type { ReplyType } from '../core/reply-type';
+import { createComposeContext } from '../tests/capabilities';
+import { createEmailEditor } from '../tests/editor';
+import { mountReplyComposer } from '../tests/reply';
+import {
+ prepareEmailBody,
+ registerToggleAppendedThread,
+ TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
+} from './prepare-email-body';
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+const parent = message('parent', {
+ from: { name: 'Ada Lovelace', email: '[email protected]' },
+ to: [{ email: '[email protected]' }],
+ subject: 'Numbers',
+ body_html_sanitized: '<p>Original message text</p>',
+});
+const teammate: EmailRecipient = {
+ kind: 'custom',
+ data: {
+ email: '[email protected]',
+ invalid: false,
+ },
+};
+const providers = ['GMAIL', 'OUTLOOK'] as const;
+
+function inboxContext(provider: EmailInbox['provider']) {
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [
+ { id: 'inbox', email_address: '[email protected]', provider, settings: {} },
+ ];
+ // Undo restores by the sent draft's identity.
+ context.delivery.sendMessage = vi.fn(async () => ({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ }));
+ return context;
+}
+
+/** The message card's Reply and Forward buttons. */
+function cardActions(initial?: ReplyType) {
+ const [replyType, setReplyType] = createSignal<ReplyType | undefined>(
+ initial
+ );
+ return {
+ replyType,
+ clear: () => setReplyType(undefined),
+ click: async (next: ReplyType) => {
+ setReplyType(next);
+ // The composer appends quoted content once the editor registers it.
+ await vi.advanceTimersByTimeAsync(0);
+ },
+ };
+}
+
+/** A draft saved from a real editor, as the thread's draft slot returns it. */
+function savedDraft(
+ replyType: ReplyType,
+ text: string,
+ quoted = parent,
+ overrides: Parameters<typeof message>[1] = {}
+) {
+ const editor = createEmailEditor(text);
+ registerToggleAppendedThread(editor);
+ editor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo: quoted,
+ replyType,
+ visible: true,
+ });
+ return message('draft', {
+ is_draft: true,
+ replying_to_id: 'parent',
+ from: { email: '[email protected]' },
+ body_html_sanitized: prepareEmailBody(editor)!.bodyHtml,
+ ...overrides,
+ });
+}
+
+function savedForward() {
+ return savedDraft('forward', 'FYI, see below', parent, {
+ to: [{ email: '[email protected]' }],
+ subject: 'Fwd: Numbers',
+ });
+}
+
+function typeAboveQuote(
+ reply: ReturnType<typeof mountReplyComposer>,
+ text: string
+) {
+ const editor: LexicalEditor = reply.editor;
+ editor.update(
+ () => {
+ const paragraph = $createParagraphNode().append($createTextNode(text));
+ const first = $getRoot().getFirstChild();
+ if (first) first.insertBefore(paragraph);
+ else $getRoot().append(paragraph);
+ },
+ { discrete: true }
+ );
+ reply.onContentChange(text);
+}
+
+function delivered(context: EmailComposeContext, call = 0) {
+ const sent = vi.mocked(context.delivery.sendMessage).mock.calls[call][0];
+ return {
+ body: decodeBase64Utf8(sent.message.body_html ?? ''),
+ to: sent.message.to?.map((contact) => contact.email),
+ subject: sent.message.subject,
+ };
+}
+
+it.each(providers)(
+ 'sends a %s reply without the forward the same composer failed to send',
+ async (provider) => {
+ const context = inboxContext(provider);
+ vi.mocked(context.delivery.sendMessage).mockRejectedValueOnce(
+ new Error('provider rejected the forward')
+ );
+ const actions = cardActions();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {},
+ {
+ replyRequest: actions,
+ }
+ );
+ try {
+ await actions.click('forward');
+ reply.form.setRecipients('to', [teammate]);
+ await reply.sendEmail();
+ expect(context.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Failed to send email'
+ );
+
+ await actions.click('reply');
+ typeAboveQuote(reply, 'Reply test body');
+ await reply.sendEmail();
+
+ expect(context.delivery.sendMessage).toHaveBeenCalledTimes(2);
+ const sent = delivered(context, 1);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.body).toContain('Reply test body');
+ expect(sent.body).toContain('wrote:');
+ expect(sent.body).not.toContain('Forwarded message');
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'sends a %s forward with the forwarded message to its recipient',
+ async (provider) => {
+ const context = inboxContext(provider);
+ const actions = cardActions();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {},
+ {
+ replyRequest: actions,
+ }
+ );
+ try {
+ await actions.click('forward');
+ reply.form.setRecipients('to', [teammate]);
+ await reply.sendEmail();
+
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.subject).toBe('Fwd: Numbers');
+ expect(sent.body).toContain('Forwarded message');
+ expect(sent.body).toContain('Original message text');
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'forwards a %s reply that was showing its quote with the forwarded message',
+ async (provider) => {
+ const context = inboxContext(provider);
+ const actions = cardActions();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {},
+ {
+ replyRequest: actions,
+ }
+ );
+ try {
+ reply.toggleQuotedText();
+ await actions.click('forward');
+ reply.form.setRecipients('to', [teammate]);
+ await reply.sendEmail();
+
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ expect(sent.body).toContain('Forwarded message');
+ expect(sent.body).not.toContain('wrote:');
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'turns a saved %s forward into a reply when Reply reopens its slot',
+ async (provider) => {
+ const context = inboxContext(provider);
+ const draft = savedForward();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {
+ draft,
+ preloadedHtml: decodeBase64Utf8(draft.body_html_sanitized ?? ''),
+ },
+ { replyRequest: cardActions('reply') }
+ );
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ await reply.sendEmail();
+
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.subject).toBe('Re: Numbers');
+ expect(sent.body).toContain('FYI, see below');
+ expect(sent.body).toContain('wrote:');
+ expect(sent.body).not.toContain('Forwarded message');
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'keeps a saved %s forward and its recipients when Forward reopens its slot',
+ async (provider) => {
+ const context = inboxContext(provider);
+ const draft = savedForward();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {
+ draft,
+ preloadedHtml: decodeBase64Utf8(draft.body_html_sanitized ?? ''),
+ },
+ { replyRequest: cardActions('forward') }
+ );
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ await reply.sendEmail();
+
+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.subject).toBe('Fwd: Numbers');
+ expect(sent.body).toContain('FYI, see below');
+ expect(sent.body.match(/Forwarded message/g)).toHaveLength(1);
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'keeps a %s forward restored from its local copy a forward',
+ async (provider) => {
+ const context = inboxContext(provider);
+ let restore: ((change: EmailDraftRestoration) => void) | undefined;
+ context.drafts.watchRestorations = (listener) => {
+ restore = listener;
+ return () => {};
+ };
+ context.drafts.readDraft = vi.fn(async () => ({
+ draft: savedForward(),
+ persistence: 'committed' as const,
+ }));
+ const actions = cardActions();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {},
+ {
+ replyRequest: actions,
+ }
+ );
+ try {
+ restore?.({
+ draftId: 'draft',
+ originalDraftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ replyingToId: 'parent',
+ });
+ await vi.waitFor(() => expect(reply.savedDraftId()).toBe('draft'));
+
+ await actions.click('forward');
+ await reply.sendEmail();
+
+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.body.match(/Forwarded message/g)).toHaveLength(1);
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'reopens an undone %s forward as a forward',
+ async (provider) => {
+ const context = inboxContext(provider);
+ context.delivery.undoSend = vi.fn(async (input) => {
+ await input.onUndone();
+ });
+ const actions = cardActions();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ {},
+ {
+ replyRequest: actions,
+ }
+ );
+ try {
+ await actions.click('forward');
+ reply.form.setRecipients('to', [teammate]);
+ await reply.sendEmail();
+ const undo = vi
+ .mocked(context.notices.feedback.success)
+ .mock.calls.flatMap(([, options]) => options?.actions ?? [])
+ .find((action) => action.label === 'Undo');
+ undo?.onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(0);
+
+ await actions.click('forward');
+ await reply.sendEmail();
+
+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();
+ expect(context.delivery.sendMessage).toHaveBeenCalledTimes(2);
+ const sent = delivered(context, 1);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.body.match(/Forwarded message/g)).toHaveLength(1);
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'keeps a reopened %s reply that quotes a forwarded message a reply',
+ async (provider) => {
+ const context = inboxContext(provider);
+ const forwardedToMe = message('parent', {
+ ...parent,
+ body_html_sanitized:
+ '<p>Passing this along</p><div class="gmail_quote"><div class="gmail_attr">---------- Forwarded message ----------<br>From: Bob</div><p>Bob wrote this</p></div>',
+ });
+ const draft = savedDraft('reply', 'Thanks, noted', forwardedToMe, {
+ to: [{ email: '[email protected]' }],
+ cc: [{ email: '[email protected]' }],
+ subject: 'Re: Numbers',
+ });
+ const reply = mountReplyComposer(
+ context,
+ () => forwardedToMe,
+ {
+ draft,
+ preloadedHtml: decodeBase64Utf8(draft.body_html_sanitized ?? ''),
+ },
+ { replyRequest: cardActions('reply') }
+ );
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ await reply.sendEmail();
+
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ const { message: sentMessage } = vi.mocked(context.delivery.sendMessage)
+ .mock.calls[0][0];
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sentMessage.cc?.map((contact) => contact.email)).toEqual([
+ ]);
+ expect(sent.body).toContain('wrote:');
+ expect(sent.body).toContain('Bob wrote this');
+ } finally {
+ reply.dispose();
+ }
+ }
+);
+
+it.each(providers)(
+ 'drops a %s forward newer than the thread draft when Reply is clicked',
+ async (provider) => {
+ const context = inboxContext(provider);
+ // The thread still holds the saved reply; the editor loads the newer
+ // local copy, which became a forward.
+ const draft = savedDraft('reply', 'FYI, see below', parent, {
+ to: [{ email: '[email protected]' }],
+ subject: 'Re: Numbers',
+ });
+ const localCopy = decodeBase64Utf8(
+ savedForward().body_html_sanitized ?? ''
+ );
+ const actions = cardActions();
+ const reply = mountReplyComposer(
+ context,
+ () => parent,
+ { draft, preloadedHtml: localCopy },
+ { replyRequest: actions }
+ );
+ try {
+ await vi.advanceTimersByTimeAsync(0);
+ await actions.click('reply');
+ await reply.sendEmail();
+
+ expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
+ const sent = delivered(context);
+ expect(sent.to).toEqual(['[email protected]']);
+ expect(sent.body).toContain('FYI, see below');
+ expect(sent.body).not.toContain('Forwarded message');
+ } finally {
+ reply.dispose();
+ }
+ }
+);
diff --git a/apps/web/src/features/email-compose/tests/reply.ts b/apps/web/src/features/email-compose/tests/reply.ts
index f9e1066338..d7cf69b701 100644
--- a/apps/web/src/features/email-compose/tests/reply.ts
+++ b/apps/web/src/features/email-compose/tests/reply.ts
@@ -3,13 +3,14 @@ import { message } from '../../email-message/tests/messages';
import type { EmailComposeContext } from '../context/compose-capabilities';
import type { EmailReplySession } from '../context/email-form-inputs';
import { createEmailFormState } from '../primitives/email-form-state';
+import { registerToggleAppendedThread } from '../primitives/prepare-email-body';
import {
createReplyComposer,
type ReplyComposerOptions,
} from '../primitives/reply-composer';
import { createEmailEditor, setEmailEditorText } from './editor';
-/** A reply composer on a real editor, addressed to a thread of one message. */
+/** A reply composer on a real, connected editor, addressed to a thread of one message. */
export function mountReplyComposer(
composeContext: EmailComposeContext,
replyingTo = () => message('parent'),
@@ -28,6 +29,7 @@ export function mountReplyComposer(
) {
return createRoot((dispose) => {
const editor = createEmailEditor('Ready to send');
+ registerToggleAppendedThread(editor);
const parent = replyingTo();
const form = createEmailFormState(
{
@@ -67,6 +69,7 @@ export function mountReplyComposer(
{ container: () => undefined, footer: () => undefined },
() => form
);
+ state.handleEditorConnect();
state.onContentChange('Ready to send');
return {
...state,
diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsx
index 7ef75c3ad0..ee5d3a61e2 100644
--- a/apps/web/src/features/email-compose/views/reply-input.tsx
+++ b/apps/web/src/features/email-compose/views/reply-input.tsx
@@ -212,6 +212,10 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {
composeContext.presentation.isTouch() &&
!state.hasBodyText() &&
state.replyType() !== 'forward';
+ const quotedContent = () =>
+ state.replyType() === 'forward' ? 'forwarded message' : 'quoted text';
+ const quoteToggleLabel = () =>
+ `${form.replyAppended() ? 'Hide' : 'Show'} ${quotedContent()}`;
const signatureHtml = () =>
composeContext.presentation.signaturesEnabled()
? state.signatureHtml()
@@ -673,7 +677,7 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {
placeholder={
isMobileCompose()
? 'Use `@` to reference files'
- : 'Reply — @mention to share or cc people'
+ : `${state.replyType() === 'forward' ? 'Forward' : 'Reply'} — @mention to share or cc people`
}
portalScope={isMobileCompose() ? 'local' : 'split'}
refFn={(el) => props.markdownDomRef?.(el)}
@@ -719,16 +723,16 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {
<div class="shrink-0 flex items-center pt-1" data-corvu-no-drag="">
<Button
variant="ghost"
- size="icon-sm"
+ size="xs"
class="text-ink-extra-muted hover:text-ink-muted hover:bg-active"
- tooltip="Show quoted text"
- onclick={(e: MouseEvent) => {
+ onClick={(e: MouseEvent) => {
e.stopPropagation();
setQuoteCollapsed(false);
setComposerExpanded(true);
}}
>
<DotsThree class="size-3.5 shrink-0 pointer-events-none" />
+ Show {quotedContent()}
</Button>
</div>
</Show>
@@ -744,13 +748,10 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {
data-corvu-no-drag=""
onClick={(e) => e.stopPropagation()}
>
- <Tooltip
- label={
- form.replyAppended() ? 'Hide quoted text' : 'Show quoted text'
- }
- >
+ <Tooltip label={quoteToggleLabel()}>
<KToggleButton
as={Button}
+ aria-label={quoteToggleLabel()}
variant="ghost"
size="icon-sm"
class="size-5 rounded bg-transparent p-0 text-ink-extra-muted hover:text-ink-muted"
diff --git a/apps/web/src/features/email-message/core/message-operation.ts b/apps/web/src/features/email-message/core/message-operation.ts
index 2c2dfeac2d..32db0eb268 100644
--- a/apps/web/src/features/email-message/core/message-operation.ts
+++ b/apps/web/src/features/email-message/core/message-operation.ts
@@ -51,6 +51,15 @@ export function operationBlocksEditing(
);
}
+/** Moving a draft is how rejected content recovers, but not mid-move. */
+export function operationBlocksInboxSwitch(
+ operation?: MessageOperation | null
+): boolean {
+ return (
+ operationBlocksEditing(operation) || !!operation?.issue?.startsWith('MOVE_')
+ );
+}
+
export function operationActions(
operation: MessageOperation
): MessageResolutionAction[] {
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index 93824c4d06..57e5d51d10 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -97,6 +97,9 @@ provider copy before choosing an explicit resend; a resend in flight shows as
the send button's pending state. Switching the sender
inbox copies the draft and attachments into the destination; wait for completion
before sending. If the copy is interrupted, use retry or keep the original.
+A draft the provider could not save can still switch From, which moves it to an
+inbox that may accept it; a draft with an unfinished move or a conflict stays in
+its inbox until that is resolved.
A draft opened from Drafts then shows its thread in the destination inbox,
never the not-found page; a draft in compose stays open there. Keep editing
after the switch and check that no "This draft changed while saving" notice
@@ -606,6 +609,15 @@ inbox, saving, and reopening the draft. Send must fetch the original files from
the receiving inbox while using the selected From inbox for delivery. A scheduled
cross-inbox forward must not download a source whose inbox access was revoked
after saving.
+Switch one message's composer between Reply and Forward on Gmail and Outlook.
+A reply sends without the forwarded message, including after a forward from that
+composer failed to send. A reply showing its quoted text sends the forwarded
+message once switched to Forward. A saved forward reopened from its thread, its
+local copy, or Undo still reads **Forwarding** with a `Forward — @mention…`
+placeholder: Forward keeps its recipients, and Reply turns it into a reply
+without the forwarded message. A reply quoting a message that was itself
+forwarded stays a reply. Collapsed content is named: **Show forwarded message**
+on a forward, **Show quoted text** on a reply.
When checking draft autosave, edit the body of a draft with uploaded or forwarded
attachments, wait for the save, and reopen it; the attachments should remain visible.
In a long thread, scroll away from the bottom while a draft save is pending.