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.

63.2 KB
Raw Blame
import {
  attachmentLimitBytes,
  MACRO_EMAIL_SIGNATURE,
} from '@app/features/email-compose/core/constants';
import type { EmailMessage } from '@app/features/email-message/core/email-message';
import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';
import { setEditorStateFromHtml } from '@core/component/LexicalMarkdown/utils/setEditorStateFromHtml';
import { fireAndForget } from '@core/util/fireAndForget';
import { $generateHtmlFromNodes } from '@lexical/html';
import {
  $appendWatermarkNodeToLast,
  $removeAllWatermarkNodes,
} from '@macro-inc/lexical-core';
import type { LexicalEditor } from 'lexical';
import { $addUpdateTag, $getRoot } from 'lexical';
import {
  type Accessor,
  createEffect,
  createMemo,
  createSignal,
  on,
  onCleanup,
  onMount,
  type Setter,
  untrack,
} from 'solid-js';
import type { MessageOperationSourceFactory } from '../../email-message/context/message-operation-source';
import {
  operationBlocksEditing,
  operationBlocksInboxSwitch,
  operationBlocksSending,
  operationSending,
} from '../../email-message/core/message-operation';
import type {
  EmailAttachmentStorage,
  EmailComposeAccounts,
  EmailComposeFeedback,
  EmailComposeHost,
  EmailConnectivity,
  EmailDelivery,
  EmailDraftLifecycleSource,
  EmailDraftStorage,
  EmailEditorFiles,
  EmailUndoHandle,
} from '../context/compose-capabilities';
import type { EmailReplySession } from '../context/email-form-inputs';
import { decodeBase64Utf8 } from '../core/decode-base64';
import type { EmailDraft } from '../core/email-draft';
import { plainTextToHtml } from '../core/plain-text-to-html';
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 {
  createAttachmentPersistence,
  refuseAttachmentsOffline,
} from './attachment-persistence';
import { createDraftAutosave } from './draft-autosave';
import { observeDraftIdentity } from './draft-identity';
import {
  createDraftPersistence,
  deleteDraftForDiscard,
  type KeptAsNewDraftReason,
  recordKeptAsNewDraft,
} from './draft-persistence';
import { observeDraftRestoration } from './draft-restoration';
import { createDraftSaveNotice } from './draft-save-notice';
import { createDraftSession } from './draft-session';
import { createDraftTransfer } from './draft-transfer';
import type { DraftFormAttachment } from './email-form-state';
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,
  prepareMacroBody,
  TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
} from './prepare-email-body';
import { announceQueuedSend } from './queued-send-notice';
import {
  createReplyComposerFocus,
  takesFocusOnMount,
} from './reply-composer-focus';
import { createReplyRecipientFields } from './reply-recipient-fields';
import {
  pendingInlineMedia,
  refuseSend,
  sendRefusalAfterSave,
  sendRefusalBeforeSave,
} from './send-readiness';
import { endUndoSend } from './undo-send-claim';
import { createEmailUndoStore } from './undo-store';

type UndoReplySnapshot = {
  threadId: string;
  inboxId: string | undefined;
  draftId: string;
  bodyHtml: string;
  attachments: DraftFormAttachment[];
  includeSignature: boolean;
  /** Whether the quoted thread was appended in the editor at send time.
   * Restored so the quoted-text toggle matches the restored body — otherwise
   * it reads as "not appended" and appends a duplicate quote block. */
  replyAppended: boolean;
  /** Draft payload for restoring the server-side draft on undo. The
   * unscheduled message keeps the sent body (appended reply chain, injected
   * signature), so undo re-saves the draft with the pre-send content —
   * bodyHtml above, prepared at undo time, fills body_html. */
  draftRestore: EmailDraft;
};
const replyUndo = createEmailUndoStore<UndoReplySnapshot>();

export type ReplyComposerOptions = {
  operations?: MessageOperationSourceFactory;
  drafts: EmailDraftStorage;
  attachmentStorage: EmailAttachmentStorage;
  delivery: EmailDelivery;
  draftLifecycle: EmailDraftLifecycleSource;
  notices: EmailComposeFeedback;
  accounts: EmailComposeAccounts;
  connectivity: EmailConnectivity;
  editorFiles: Pick<EmailEditorFiles, 'uploadDocuments' | 'makePublic'>;
  viewerEmail: Accessor<string | undefined>;
  hasPaidAccess: Accessor<boolean>;
  recordMention(sourceId: string, targetId: string): void;
  focusAfterReplyRequest: Accessor<boolean>;
  session: EmailReplySession;
  sourceEntityId: string;
  replyingTo: Accessor<EmailMessage | undefined>;
  isEditingExisting?: boolean;
  draft?: EmailMessage;
  localDraft?: import('../core/local-draft').LocalDraft;
  localAttachments?: DraftFormAttachment[];
  preloadedHtml?: string;
  /** Seed identity of the draft this composer mounted from — becomes part of
   * the form-state cache key so a remount on a newer draft version gets a
   * freshly seeded form. See ThreadReplyInput's seed key. */
  formSeed?: string;
  /** Reports the composer gaining local state worth keeping — a first edit
   * or save (every modification funnels through scheduleDraftSave) or an
   * undo-send restore. The parent latches the seed key on it so the input
   * stops remounting on later draft versions. */
  onEngaged?: () => void;
  sideEffectOnSend?: (
    newMessageId: string | null,
    /** Offline sends wait on this device, so the thread cannot show them yet. */
    sent?: { queuedOffline: boolean }
  ) => void | Promise<void>;
  onMarkDone?: (opts?: {
    silent?: boolean;
    onUndoHandle?: (handle: EmailUndoHandle) => void;
    /** False keeps the view on this thread instead of opening the next one. */
    navigate?: boolean;
    /** True once the send was undone or failed; marking done may still be pending. */
    cancelled?: () => boolean;
  }) => void;
  setShowReply?: Setter<boolean>;
  /** Reopens this reply's thread when the composer is no longer on screen. */
  host?: Pick<EmailComposeHost, 'showThread'>;
};

export function createReplyComposer(
  props: ReplyComposerOptions,
  editor: Accessor<LexicalEditor | undefined>,
  dom: {
    container: Accessor<HTMLDivElement | undefined>;
    footer: Accessor<HTMLDivElement | undefined>;
  },
  forms: (key?: FormAccessKey) => EmailFormContextValue
) {
  const ctx = props.session;
  // Each keyed composer owns a target and draft version. Parent props can already
  // point at the next target when Solid disposes this editor and flushes its save.
  const replyTarget = props.replyingTo();
  const draftSeed = props.draft;
  const initialThread = ctx.thread();
  const thread = () => {
    const current = ctx.thread();
    return current?.db_id === initialThread?.db_id ? current : initialThread;
  };
  const form = forms(
    replyTarget?.db_id
      ? {
          type: 'replying_to',
          messageId: replyTarget.db_id,
          seed: props.formSeed,
        }
      : draftSeed?.db_id
        ? {
            type: 'draft',
            messageId: draftSeed.db_id,
            seed: props.formSeed,
          }
        : undefined
  );
  const sourceEntityId = props.sourceEntityId;
  const undoKey = `${sourceEntityId}:${replyTarget?.db_id ?? draftSeed?.replying_to_id ?? draftSeed?.db_id ?? 'new'}`;
  const userEmail = props.viewerEmail;

  const primaryInboxId = props.accounts.primaryId;
  // A thread shared with the viewer sits in its owner's inbox; reply from one
  // of the viewer's own instead.
  const threadInboxId = () =>
    ctx.ownsThreadInbox() ? thread()?.link_id : undefined;
  // Capture this domain inbox ID for each asynchronous operation.
  const activeInboxId = () =>
    form.selectedInboxId() ??
    threadInboxId() ??
    draftSeed?.link_id ??
    primaryInboxId() ??
    props.accounts.inboxes()[0]?.id;
  // The address of the inbox this input sends from, for the "from" display.
  const activeInboxEmail = () =>
    form.senderEmail() ??
    props.accounts.inboxes().find((l) => l.id === activeInboxId())
      ?.email_address ??
    userEmail();

  // The full Link object for the sending inbox (for its saved signature and the
  // "add to replies & forwards" preference).
  const sendingInbox = createMemo(() =>
    props.accounts.inboxes().find((l) => l.id === activeInboxId())
  );
  const signature = () => sendingInbox()?.settings.signature ?? undefined;
  // Whether this reply includes the signature. Defaults on, reset per reply,
  // and dismissable via the preview ✕.
  const [includeSignature, setIncludeSignature] = createSignal(true);
  const [draftGeneration, setDraftGeneration] = createSignal(
    props.localDraft?.content.draft_generation ??
      props.draft?.draft_generation ??
      0
  );
  // Signature HTML for the preview (and whether to show it): only for
  // replies/forwards, when the inbox's "add to replies & forwards" setting is on
  // and the user hasn't dismissed it. The backend does the actual injection on
  // send — this just mirrors when that will happen.
  const replySignatureHtml = (): string | undefined =>
    replyTarget &&
    includeSignature() &&
    sendingInbox()?.settings.signature_on_replies_forwards
      ? signature()
      : undefined;

  const [bodyMacro, setBodyMacro] = createSignal<string>('');
  const [restoring, setRestoring] = createSignal(false);
  const [scrollContainer, setScrollContainer] = createSignal<HTMLElement>();
  // Gmail-style sizing: the composer opens compact and grows to the full cap
  // once the user scrolls the content
  const [composerExpanded, setComposerExpanded] = createSignal(false);
  const [terminalState, setTerminalState] = createSignal<
    'sent' | 'missing' | undefined
  >();
  let schedule: ReturnType<typeof createEmailSendSchedule>;
  let operationSource: ReturnType<MessageOperationSourceFactory> | undefined;
  // Appended quoted thread starts hidden behind a "⋯" pill (desktop). A
  // draft reloaded with the quote already appended opens expanded instead —
  // that's how the composer looked when the draft was saved.
  const [quoteCollapsed, setQuoteCollapsed] = createSignal(
    !form.replyAppended()
  );
  // A pending undo-send restore that belongs to this thread (inline reply
  // remount case). It carries a just-undone send. Consumed below.
  const restoredSnapshot = replyUndo.takePending(undoKey);
  let mountFocus = takesFocusOnMount({
    savedReply: draftSeed !== undefined && replyTarget !== undefined,
    requested: untrack(() => ctx.replyRequest.replyType()) !== undefined,
    restoredSend: restoredSnapshot !== undefined,
    desktop: untrack(props.focusAfterReplyRequest),
  });

  // Switching inboxes can move a draft out of the displayed thread. Keep its
  // persisted identity together for subsequent saves, discard, schedule and undo.
  const session = createDraftSession(
    restoredSnapshot
      ? {
          draftId: restoredSnapshot.draftId,
          threadId: restoredSnapshot.threadId,
          inboxId: restoredSnapshot.inboxId,
        }
      : draftSeed?.db_id
        ? {
            draftId: draftSeed.db_id,
            threadId: draftSeed.thread_db_id,
            // A cached seed may still use local IDs. Only a cache read or save
            // can confirm it for REST actions.
            persistence: props.drafts.readDraft ? 'queued' : undefined,
            inboxId: draftSeed.link_id,
          }
        : undefined
  );
  if (props.localAttachments) {
    form.attachments.clear();
    for (const attachment of props.localAttachments)
      form.attachments.add(attachment);
  }
  if (
    props.localDraft &&
    ['failed', 'unconfirmed', 'delete-failed'].includes(props.localDraft.status)
  )
    session.dispatch({
      type: 'rejected',
      epoch: session.epoch(),
      code: 'INTERNAL',
    });
  const savedDraftId = session.draftId;
  operationSource = props.operations?.(
    () => (session.serverConfirmed() ? savedDraftId() : undefined),
    () => props.sourceEntityId
  );
  const currentOperation = () => {
    const live = operationSource?.operation();
    return live === undefined ? props.draft?.operation : live;
  };
  const deliveryBlocked = () =>
    operationSource?.needsReload?.() ||
    operationBlocksSending(currentOperation());
  const inboxSwitchBlocked = () =>
    operationSource?.needsReload?.() ||
    operationBlocksInboxSwitch(currentOperation());
  function operationBlocked() {
    return (
      operationSource?.needsReload?.() ||
      operationBlocksEditing(currentOperation())
    );
  }
  const sendLocked = () => props.delivery.sendLocked?.(savedDraftId()) ?? false;
  const recipients = createReplyRecipientFields({
    values: form.recipients,
    setValues: form.setRecipients,
    onChange: scheduleDraftSave,
    container: dom.container,
    disabled: () =>
      operationBlocked() ||
      !!draftTransfer?.pending() ||
      restoring() ||
      submitting() ||
      pendingDeletion() ||
      movingInbox() ||
      schedule?.pending() ||
      schedule?.state().type === 'scheduled' ||
      terminalState() !== undefined ||
      sendLocked(),
  });
  const focus = createReplyComposerFocus({
    editor,
    container: dom.container,
    footer: dom.footer,
    scrollContainer,
    toInput: recipients.toRef,
    expandRecipients: () => recipients.setShowExpandedRecipients(true),
  });

  const savedDraftThreadId = session.threadId;
  observeDraftIdentity(
    props.drafts,
    session,
    props.notices,
    () => {
      if (scheduleBlocked() || schedule.state().type === 'scheduled') return;
      if (props.drafts.retryDraft) {
        void retryDraft().catch(props.notices.reportError);
      } else
        detachFromObsoleteDraft(
          'save-rejected',
          'Saving your edits as a new draft.'
        );
    },
    handleAlreadySent,
    async () => {
      if (
        sendLocked() ||
        schedule.state().type === 'scheduled' ||
        !session.autosaveAllowed() ||
        props.connectivity.looksOffline()
      )
        return false;
      const draftId = session.draftId();
      if (draftId && session.serverConfirmed())
        await attachmentPersistence.upload(draftId);
    },
    (local) => {
      const edit = persistence.acknowledgedEdit(local);
      if (edit !== undefined)
        persistedEditVersion = Math.max(persistedEditVersion, edit);
    }
  );
  const persistedInboxId = session.inboxId;
  const [movingInbox, setMovingInbox] = createSignal(false);
  let draftTransfer: ReturnType<typeof createDraftTransfer> | undefined;
  let identityVersion = 0;
  let editVersion = 0;
  let persistedEditVersion = 0;
  const lifecycle = props.draftLifecycle.observe({
    draftId: () => (session.serverConfirmed() ? savedDraftId() : undefined),
    threadId: savedDraftThreadId,
    inboxId: persistedInboxId,
  });

  // Consume the undo-send snapshot so a later composer mount doesn't restore
  // it again. Use bodyHtml as initialHtml for the editor, restore attachments
  // on mount.
  const [restoredBodyHtml, setRestoredBodyHtml] = createSignal<string>();
  const restoreEnvelope = (snapshot: UndoReplySnapshot) => {
    form.setSelectedInbox(snapshot.inboxId, snapshot.draftRestore.sender_email);
    form.setSubject(snapshot.draftRestore.subject);
    for (const field of ['to', 'cc', 'bcc'] as const) {
      form.setRecipients(
        field,
        (snapshot.draftRestore[field] ?? []).map(
          convertContactInfoToEmailRecipient
        )
      );
    }
  };
  if (restoredSnapshot) {
    restoreEnvelope(restoredSnapshot);
    onMount(() => {
      // Restored content is local state worth keeping — latch the seed.
      props.onEngaged?.();
      form.attachments.replace(restoredSnapshot.attachments);
      setIncludeSignature(restoredSnapshot.includeSignature);
      form.setReplyAppended(restoredSnapshot.replyAppended);
      // Reopen with the quote visible, as it was when the send was undone.
      if (restoredSnapshot.replyAppended) setQuoteCollapsed(false);
    });
  }

  // Register a callback so stale undoSend closures from a previous mount can
  // restore state into this (the live) component instance.
  let hasLocalChanges = false;
  const restoreMountedReply = (snapshot: UndoReplySnapshot) => {
    const currentDraftId = savedDraftId();
    if (
      hasLocalChanges ||
      (currentDraftId !== undefined && currentDraftId !== snapshot.draftId)
    ) {
      props.notices.feedback.alert(
        'Your newer reply was kept. The earlier message was not reopened.'
      );
      props.setShowReply?.(true);
      return;
    }
    const draftId = snapshot.draftId;
    hasLocalChanges = false;
    props.onEngaged?.();
    session.dispatch({
      type: 'seeded',
      draftId,
      threadId: snapshot.threadId,
      inboxId: snapshot.inboxId,
    });
    restoreEnvelope(snapshot);
    setRestoredBodyHtml(snapshot.bodyHtml ?? plainTextToHtml(''));
    if (snapshot.bodyHtml) form.restoreReplyType(snapshot.bodyHtml);
    const currentEditor = editor();
    if (currentEditor && snapshot.bodyHtml) {
      setEditorStateFromHtml(currentEditor, snapshot.bodyHtml);
    }
    form.attachments.replace(snapshot.attachments);
    setIncludeSignature(snapshot.includeSignature);
    form.setReplyAppended(snapshot.replyAppended);
    // Reopen with the quote visible, as it was when the send was undone.
    if (snapshot.replyAppended) setQuoteCollapsed(false);
  };
  let mounted = true;
  const unregisterUndo = replyUndo.register(undoKey, restoreMountedReply);
  onCleanup(() => {
    mounted = false;
    unregisterUndo();
  });

  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();
    if (!currentEditor) return;
    const html = initialHtml();
    if (html) {
      // Restore content without letting selection reconciliation grab focus
      currentEditor.update(() => {
        $addUpdateTag('skip-dom-selection');
        setEditorStateFromHtml(currentEditor, html, true);
      });
    }
    setEditorConnected(true);
  };

  // Everything that follows a successful unschedule: consume the send
  // snapshot, scrub the sent message from the thread cache, restore the
  // server-side draft and the composer.
  const restoreAfterUndoSend = async (
    draftId: string,
    sentThreadId: string | undefined,
    inboxId: string | undefined,
    draftRestored = false
  ) => {
    const snapshot = replyUndo.peek(draftId);

    // Reconcile the actual message thread, which can differ from the host when
    // replying from another inbox. The host's undoKey still owns local recovery.
    const threadId = sentThreadId ?? snapshot?.threadId;
    if (!draftRestored)
      await props.drafts.restoreDraft({
        draftId,
        threadId,
        draft: snapshot?.draftRestore,
        html: snapshot?.bodyHtml,
        inboxId,
      });

    if (snapshot) {
      // Keep the recovery snapshot available if restoring the server draft
      // fails. Consume it only after the authoritative restore succeeds.
      replyUndo.take(draftId);
      // Resolve the live registration after cache updates and unmounts settle.
      if (!draftRestored)
        setTimeout(() => replyUndo.restore(undoKey, snapshot), 0);
      props.setShowReply?.(true);
    }
  };

  const attachmentPersistence = createAttachmentPersistence({
    draftGeneration,
    confirmRemoval: !!props.drafts.saveLocalDraft,
    allowed: () =>
      !sendLocked() &&
      schedule.state().type !== 'scheduled' &&
      !props.connectivity.looksOffline(),
    services: props.attachmentStorage,
    attachments: form.attachments,
    draftId: () =>
      session.identity().kind === 'server' ? savedDraftId() : undefined,
    inboxId: persistedInboxId,
  });

  createEffect(
    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') {
        if (takeFocus) focus.forward();
      } 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));
    });
  });

  const [sendPhase, setSendPhase] = createSignal<
    'idle' | 'preparing' | 'sending'
  >('idle');
  const submitting = () => sendPhase() !== 'idle';
  let sendOperationVersion = 0;
  const [pendingDeletion, setPendingDeletion] = createSignal(false);

  // A reloaded draft keeps its quoted thread as plain blocks (the server
  // strips the editor's markers), so only the saved body knows it is there.
  const appendsQuotedThread = () => !!replyTarget && !form.replyAppended();

  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(),
      appendsToBody && replyTarget && appendsQuotedThread()
        ? {
            replyType: form.replyType(),
            replyingTo: replyTarget,
            reopenable: !forDelivery,
          }
        : undefined
    );
    if (!prepared) {
      props.notices.reportError(
        new Error('Unable to prepare email body for draft collection.')
      );
      return null;
    }
    const recipients = form.recipients();
    if (
      !hasDraftContent(
        prepared.bodyText,
        form.subject(),
        form.attachments.list().length,
        // A forward's recipients are typed in, not derived from the thread,
        // so they keep a forward with no note of its own alive.
        form.replyType() === 'forward'
          ? recipients.to.length + recipients.cc.length + recipients.bcc.length
          : undefined
      )
    ) {
      return null;
    }
    // We attach the drafts entirely using bodyHTML (because this is how the appended reply parsing works) so we are not including bodyMacro or bodyText
    return {
      sender_email: activeInboxEmail(),
      bcc: form.recipients().bcc.map(convertEmailRecipientToContactInfo),
      body_html: prepared.bodyHtml,
      cc: form.recipients().cc.map(convertEmailRecipientToContactInfo),
      provider_id: draftSeed?.provider_id,
      replying_to_id: replyTarget?.db_id,
      subject: form.subject(),
      to: form.recipients().to.map(convertEmailRecipientToContactInfo),
      body_macro: forDelivery ? prepareMacroBody(bodyMacro()) : undefined,
      include_signature: includeSignature() ? undefined : false,
      draft_generation: draftGeneration(),
    };
  }

  const captureSave = (completingThread = false, forDelivery = false) => ({
    draft: collectDraft(forDelivery),
    thread: thread(),
    inboxId: activeInboxId(),
    completingThread,
    generation: identityVersion,
    revision: editVersion,
    attachments: [...form.attachments.list()],
  });

  async function reportPersistenceFailure(
    error: unknown,
    operation: 'save' | 'delete'
  ) {
    props.notices.reportError(error);
    const failureMessage =
      operation === 'save' && props.drafts.saveLocalDraft
        ? 'Draft could not be synced'
        : `Failed to ${operation} draft`;
    if (!session.serverConfirmed()) {
      // A best-effort pre-send save may fail while delivery still succeeds.
      // Background saves and explicit draft actions report their own failure.
      if (schedule?.pending() || !submitting()) {
        props.notices.feedback.failure(failureMessage);
      }
      return;
    }
    let state;
    try {
      state = await lifecycle.refresh();
    } catch (refreshError) {
      props.notices.reportError(refreshError);
    }
    if (
      state?.type === 'sent' &&
      state.draftId === savedDraftId() &&
      state.threadId === savedDraftThreadId() &&
      state.inboxId === persistedInboxId()
    ) {
      props.notices.feedback.alert(
        'This scheduled email was sent. Your composer has been updated.'
      );
      return;
    }
    props.notices.feedback.failure(failureMessage);
  }

  // Reset notifications must not autosave the draft that was just discarded.
  const withDeletionGuard = async (run: () => Promise<void> | void) => {
    setPendingDeletion(true);
    autosave.cancel();
    try {
      await run();
    } finally {
      setTimeout(() => {
        autosave.cancel();
        setPendingDeletion(false);
      }, 0);
    }
  };
  function handleAlreadySent() {
    identityVersion += 1;
    fireAndForget(
      withDeletionGuard(() => {
        resetState();
        clearDraftState();
      }),
      'email-compose'
    );
  }

  const persistence = createDraftPersistence({
    draftGeneration,
    session,
    drafts: props.drafts,
    attachments: attachmentPersistence,
    localDraft: props.localDraft,
    mintThreadHandle: false,
    onAlreadySent: handleAlreadySent,
  });

  async function persistDraft({
    draft,
    thread: currentThread,
    inboxId,
    completingThread,
    generation,
    revision,
  }: ReturnType<typeof captureSave>) {
    if (generation !== identityVersion) return;
    try {
      if (!draft) {
        await persistence.remove({ inboxId, completingThread });
        if (generation === identityVersion)
          persistedEditVersion = Math.max(persistedEditVersion, revision);
        return;
      }
      if (!currentThread) {
        props.notices.reportError(
          new Error('Failed to save draft: thread not found')
        );
        return;
      }
      const saved = await persistence.save({
        draft: {
          ...draft,
          provider_thread_id:
            session.threadId() && session.threadId() !== currentThread.db_id
              ? undefined
              : currentThread.provider_id,
          thread_db_id: session.threadId() ?? currentThread.db_id,
        },
        inboxId,
        completingThread,
      });
      if (generation !== identityVersion || !saved) return;
      if (saved.persistence !== 'queued')
        persistedEditVersion = Math.max(persistedEditVersion, revision);
      return saved.draftId;
    } catch (error) {
      if (generation === identityVersion)
        await reportPersistenceFailure(error, draft ? 'save' : 'delete');
      throw error;
    }
  }

  const autosave = createDraftAutosave({
    ...createDraftSaveNotice(props.notices.feedback),
    capture: captureSave,
    persist: persistDraft,
    saveLocalSnapshot: async (snapshot) => {
      if (snapshot.generation !== identityVersion) return;
      await persistence.saveLocally({
        draft: snapshot.draft
          ? {
              ...snapshot.draft,
              thread_db_id: session.threadId() ?? snapshot.thread?.db_id,
              provider_thread_id:
                session.threadId() &&
                session.threadId() !== snapshot.thread?.db_id
                  ? undefined
                  : snapshot.thread?.provider_id,
            }
          : null,
        inboxId: snapshot.inboxId,
        attachments: snapshot.attachments,
        edit: snapshot.revision,
      });
    },
    paused: () =>
      restoring() ||
      operationBlocked() ||
      submitting() ||
      pendingDeletion() ||
      movingInbox() ||
      !!draftTransfer?.pending() ||
      schedule?.pending() ||
      schedule?.state().type === 'scheduled' ||
      terminalState() !== undefined ||
      sendLocked(),
  });
  observeDraftRestoration({
    storage: props.drafts,
    accepts: (change) =>
      savedDraftId()
        ? [change.draftId, change.originalDraftId].includes(savedDraftId()!)
        : !hasLocalChanges &&
          change.threadId === thread()?.db_id &&
          change.replyingToId === replyTarget?.db_id,
    ready: () => !sendLocked(),
    version: () => `${identityVersion}:${editVersion}:${session.epoch()}`,
    cancelPendingSave: () => {
      identityVersion += 1;
      sendOperationVersion += 1;
      setSendPhase('idle');
      autosave.cancel();
    },
    setPending: setRestoring,
    restore: (draft, change, restoredPersistence, local, attachments) => {
      persistence.restored(local);
      setDraftGeneration(draft.draft_generation ?? 0);
      session.dispatch({
        type: 'seeded',
        draftId: draft.db_id,
        threadId: draft.thread_db_id,
        inboxId: draft.link_id,
        persistence: restoredPersistence,
      });
      form.restoreDraft(draft);
      if (attachments) form.attachments.replace(attachments);
      setIncludeSignature(change.includeSignature !== false);
      const bodyHtml = draft.body_html_sanitized
        ? decodeBase64Utf8(draft.body_html_sanitized)
        : plainTextToHtml(draft.body_text ?? '');
      setRestoredBodyHtml(bodyHtml);
      const currentEditor = editor();
      if (currentEditor) setEditorStateFromHtml(currentEditor, bodyHtml);
      setQuoteCollapsed(!form.replyAppended());
      hasLocalChanges = false;
      setTerminalState(undefined);
      props.onEngaged?.();
      props.setShowReply?.(true);
    },
    reportError: props.notices.reportError,
  });
  function executeSaveDraft(completingThread = false) {
    return autosave.save(captureSave(completingThread));
  }
  function scheduleDraftSave() {
    if (operationBlocked()) return;
    if (
      restoring() ||
      submitting() ||
      pendingDeletion() ||
      movingInbox() ||
      draftTransfer?.pending() ||
      schedule.pending() ||
      schedule.state().type === 'scheduled' ||
      terminalState() ||
      sendLocked()
    )
      return;
    hasLocalChanges = true;
    editVersion += 1;
    props.onEngaged?.();
    autosave.schedule();
  }

  // Persist the draft immediately when the user switches the sending inbox, even
  // without a text edit, so it moves to the new inbox and the choice survives a
  // refresh. Driven by the explicit switch (below) rather than inbox reactivity.
  draftTransfer = createDraftTransfer({
    draftGeneration,
    onTransferred: () => setDraftGeneration(0),
    session,
    persistence,
    drafts: props.drafts,
    attachments: form.attachments,
    save: () => executeSaveDraft(),
    invalidateOldSaves: () => {
      identityVersion += 1;
      autosave.cancel();
    },
  });
  const saveSelectedInbox = async (inboxId: string, senderEmail?: string) => {
    if (
      restoring() ||
      (!draftTransfer?.pending() && inboxSwitchBlocked()) ||
      submitting() ||
      pendingDeletion() ||
      movingInbox() ||
      schedule.pending() ||
      schedule.state().type === 'scheduled' ||
      terminalState() ||
      sendLocked()
    )
      return;
    hasLocalChanges = true;
    setMovingInbox(true);
    try {
      const sourceInboxId = activeInboxId();
      const destination = props.accounts
        .inboxes()
        .find((inbox) => inbox.id === inboxId);
      if (!sourceInboxId || !destination) return;
      autosave.cancel();
      if (sourceInboxId !== inboxId) {
        await draftTransfer?.move(destination, sourceInboxId);
      }
      form.setSelectedInbox(inboxId, senderEmail);
      editVersion += 1;
      hasLocalChanges = true;
      props.onEngaged?.();
      await executeSaveDraft();
    } catch (error) {
      props.notices.reportError(error);
      props.notices.feedback.failure(
        error instanceof Error
          ? error.message
          : 'Could not change inbox. Retry the same inbox to recover.',
        {
          actions: [
            {
              label: 'Retry inbox change',
              onClick: () => {
                fireAndForget(
                  saveSelectedInbox(inboxId, senderEmail),
                  'email-compose'
                );
              },
            },
          ],
        }
      );
    } finally {
      setMovingInbox(false);
    }
  };
  const persistDraftOnSenderSwitch = (
    inboxId: string,
    senderEmail?: string
  ) => {
    fireAndForget(saveSelectedInbox(inboxId, senderEmail), 'email-compose');
  };

  const saveForSchedule = async () => {
    if (deliveryBlocked()) return undefined;
    const currentEditor = editor();
    const cleanupWatermark = $appendWatermarkNodeToLast(
      currentEditor,
      !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
    );
    try {
      return persistence.confirmed(
        await autosave.save(captureSave(false, true))
      );
    } finally {
      cleanupWatermark();
    }
  };

  schedule = createEmailSendSchedule({
    draftGeneration,
    delivery: props.delivery,
    notices: props.notices,
    initialScheduledTime: draftSeed?.scheduled_send_time
      ? new Date(draftSeed.scheduled_send_time)
      : undefined,
    initialDeliveryStatus: draftSeed?.scheduled_send_status ?? undefined,
    draftId: savedDraftId,
    saveDraft: saveForSchedule,
    threadId: savedDraftThreadId,
    threadInInbox: () => thread()?.inbox_visible,
    inboxId: activeInboxId,
    includeSignature: () => (includeSignature() ? undefined : false),
    generation: () =>
      `${identityVersion}:${editVersion}:${activeInboxId() ?? ''}`,
    lifecycleState: lifecycle.state,
    reconcile: lifecycle.refresh,
    reconcileIdentity: lifecycle.refreshIdentity,
    onScheduleUndone: ({ draftId, threadId, inboxId }) =>
      restoreAfterUndoSend(draftId, threadId, inboxId),
    // The scheduled reply stays in its thread, locked; bring it back into view.
    onViewScheduled: ({ threadId }) => {
      const container = dom.container();
      if (container?.isConnected) {
        container.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        return;
      }
      if (threadId) props.host?.showThread?.(threadId);
    },
  });
  const cancelSchedule = async () => {
    if (sendLocked() || restoring()) return false;
    if (!(await schedule.cancel())) return false;
    session.dispatch({ type: 'schedule-cancelled' });
    return true;
  };

  createEffect(() => {
    const requestReplyType = ctx.replyRequest.replyType();

    if (!requestReplyType) return;

    // Message-card actions reach this path even while composer controls are disabled.
    // Consume the request so cancelling the send cannot apply a stale Forward later.
    if (sendLocked()) {
      // A fresh composer can be waiting for durable storage initialization.
      // Preserve its initial action; requests against a queued draft are discarded.
      if (savedDraftId()) ctx.replyRequest.clear();
      return;
    }
    if (
      restoring() ||
      submitting() ||
      pendingDeletion() ||
      movingInbox() ||
      schedule.pending() ||
      schedule.state().type === 'scheduled' ||
      terminalState()
    ) {
      ctx.replyRequest.clear();
      return;
    }

    if (form.replyType() !== requestReplyType) {
      form.setReplyType(requestReplyType);
    } else if (requestReplyType === 'forward') {
      // setReplyType is skipped when the type is unchanged, so land the
      // cursor in the To field explicitly
      focus.forward();
    }
    // Forwards focus the To field; focusing the editor would steal it back
    if (requestReplyType !== 'forward') {
      if (props.focusAfterReplyRequest()) focus.editor(() => {});
    }
    ctx.replyRequest.clear();
  });

  // We are consuming the first change, because it is the initial value
  let firstChangeConsumed = false;
  const handleChange = (value: string) => {
    setBodyMacro(value);
    if (!firstChangeConsumed) {
      firstChangeConsumed = true;
      return;
    }
    untrack(scheduleDraftSave);
  };

  const hasPaidAccess = props.hasPaidAccess;

  const sendEmail = async (markDone = false) => {
    if (sendLocked() || restoring()) return;
    if (deliveryBlocked()) return;
    if (scheduling() || movingInbox() || terminalState()) return;
    if (submitting() || pendingDeletion()) return;
    // Thread identity can be available before its account/alias catalog. Wait
    // rather than sending a new reply from the temporary primary fallback.
    if (props.accounts.loading() && !form.draft) {
      props.notices.feedback.alert('Loading email sender addresses...');
      return;
    }

    const to = form.recipients().to.map(convertEmailRecipientToContactInfo);
    const cc = form.recipients().cc.map(convertEmailRecipientToContactInfo);
    const bcc = form.recipients().bcc.map(convertEmailRecipientToContactInfo);

    if ((to?.length ?? 0) + (cc?.length ?? 0) + (bcc?.length ?? 0) === 0) {
      props.notices.feedback.failure(
        'Email failed to send. No recipients provided'
      );
      return;
    }

    const currentThread = thread();
    if (!currentThread) {
      props.notices.reportError(
        new Error("Can't send email, no email thread found")
      );
      props.notices.feedback.failure('Email failed to send');
      return;
    }

    let inboxId = activeInboxId();
    if (!inboxId) {
      if (props.accounts.loading()) {
        props.notices.feedback.alert('Loading email accounts...');
        return;
      }

      if (props.accounts.failed()) {
        props.notices.feedback.failure(
          'Email failed to send: Could not load email accounts'
        );
        props.notices.reportError('Failed to load email links');
        return;
      }

      const inboxes = props.accounts.inboxes();
      if (inboxes.length < 1) {
        props.notices.feedback.failure(
          'Email failed to send: No email account connected'
        );
        props.notices.reportError('No links found');
        return;
      }
      inboxId = primaryInboxId() ?? inboxes[0].id;
    }

    const offline = sendRefusalBeforeSave(
      props.connectivity,
      props.delivery.queueActive?.(sendingInbox()?.id),
      form.attachments
        .list()
        .some(
          (attachment) => attachment.type === 'local' && !attachment.uploaded
        )
    );
    if (offline) return refuseSend(props.notices, offline);
    if (pendingInlineMedia(editor()))
      return refuseSend(props.notices, 'media-not-uploaded');
    if (attachmentLinks.uploading())
      return refuseSend(props.notices, 'files-uploading');
    const currentEditor = editor();
    const rememberCurrentReply = () => {
      if (!currentEditor) return;
      const snapshotDraftId = savedDraftId();
      const snapshotThreadId = savedDraftThreadId();
      if (!snapshotDraftId || !snapshotThreadId) return;
      const snapshotHtml = currentEditor.read(() =>
        $generateHtmlFromNodes(currentEditor)
      );
      replyUndo.remember({
        threadId: snapshotThreadId,
        inboxId,
        draftId: snapshotDraftId,
        bodyHtml: snapshotHtml,
        attachments: [...form.attachments.list()],
        includeSignature: includeSignature(),
        replyAppended: form.replyAppended(),
        draftRestore: {
          sender_email: activeInboxEmail(),
          bcc,
          cc,
          db_id: snapshotDraftId,
          provider_id: draftSeed?.provider_id,
          provider_thread_id: currentThread.provider_id,
          replying_to_id: replyTarget?.db_id,
          subject: form.subject(),
          thread_db_id: snapshotThreadId,
          to,
        },
      });
    };
    // Send Later schedules the saved draft; only immediate sends use the outbox.
    const scheduleAction = schedule.action();
    if (scheduleAction === 'unavailable') {
      props.notices.feedback.alert(
        `This email is scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`
      );
      return;
    }
    if (scheduleAction === 'schedule' || scheduleAction === 'update') {
      const result = await schedule.submit();
      if (result === 'scheduled') {
        const scheduledDraftId = savedDraftId();
        rememberCurrentReply();
        // The scheduled draft stays in the thread with its "Scheduled for"
        // bar, as a reload shows it; clearing it hid it until a refresh.
        void Promise.resolve(
          props.sideEffectOnSend?.(scheduledDraftId ?? null)
        ).catch(props.notices.reportError);
      }
      return;
    }
    if (attachmentPersistence.uploading()) return;

    // Sending a reply marks the thread done. Gated on inbox_visible because
    // onMarkDone (archiveThread) toggles: an already-archived thread (e.g.
    // replying from search or the sent view) would be unarchived.
    const willMarkDone = markDone || currentThread.inbox_visible;

    setSendPhase('preparing');
    const sendOperation = ++sendOperationVersion;
    const sendGeneration = identityVersion;
    try {
      // Ensure draft is saved before sending so undo-send always has a draft to restore
      const epochBeforeSave = session.epoch();
      try {
        if (
          props.delivery.queueActive?.(sendingInbox()?.id) &&
          props.drafts.saveLocalDraft &&
          form.attachments
            .list()
            .every((attachment) =>
              attachment.type === 'local'
                ? attachment.uploaded
                : attachment.type === 'remote'
                  ? !attachment.uploadPending
                  : true
            ) &&
          (form.attachments.list().length === 0 || session.serverConfirmed())
        )
          await autosave.saveLocal(captureSave(willMarkDone));
        else await autosave.save(captureSave(willMarkDone));
      } catch (error) {
        props.notices.reportError(error);
        if (session.isStale(epochBeforeSave)) return;
        return refuseSend(props.notices, 'draft-not-saved');
      }
      if (
        sendGeneration !== identityVersion ||
        session.isStale(epochBeforeSave) ||
        terminalState() ||
        sendLocked()
      )
        return;
      const expectedLocalVersion = props.delivery.queueActive?.(
        sendingInbox()?.id
      )
        ? persistence.localVersion()
        : undefined;
      const refusal = sendRefusalAfterSave({
        identity: session.identity(),
        autosaveAllowed: session.autosaveAllowed(),
        attachments: form.attachments.list(),
        unqueuedHandleMaySend: false,
        queueActive: props.delivery.queueActive?.(sendingInbox()?.id),
      });
      if (refusal) return refuseSend(props.notices, refusal);

      if (pendingInlineMedia(editor()))
        return refuseSend(props.notices, 'media-not-uploaded');

      // Snapshot editor state before watermark so undo-send can restore it.
      // Remember by draft so sends in separate composers cannot replace each other.
      rememberCurrentReply();

      if (scheduling() || schedule.action() !== 'send') {
        return;
      }

      // Append watermark after all validation passes so failed sends don't
      // leave orphaned watermark nodes in the editor tree.
      const restoration = prepareEmailBody(currentEditor);
      const restoreMacro = bodyMacro();
      const cleanupWatermark = $appendWatermarkNodeToLast(
        currentEditor,
        !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
      );

      const replyingTo = replyTarget;

      const prepared = prepareEmailBody(
        currentEditor,
        replyingTo && appendsQuotedThread()
          ? {
              replyType: form.replyType(),
              replyingTo,
            }
          : undefined
      );
      if (!prepared) {
        cleanupWatermark();
        return;
      }

      const processedMacroBody = prepareMacroBody(bodyMacro());

      const currentDraftId = savedDraftId();

      setSendPhase('sending');
      const pendingSend = props.delivery.sendMessage({
        expectedLocalVersion,
        clientHandles: {
          draftId: currentDraftId!,
          threadId: savedDraftThreadId() ?? currentThread.db_id,
        },
        attachmentIds: form.attachments
          .list()
          .filter((a) => a.type === 'local' || a.type === 'remote')
          .flatMap((a) => (a.attachmentId ? [a.attachmentId] : [])),
        forwardedAttachmentIds: form.attachments
          .list()
          .filter((a) => a.type === 'forwarded' || a.type === 'native')
          .flatMap((a) => (a.attachmentId ? [a.attachmentId] : [])),
        restoreBodyHtml: restoration?.bodyHtml,
        restoreBodyText: restoration?.bodyText,
        restoreBodyMacro: restoreMacro,
        message: {
          sender_email: activeInboxEmail(),
          db_id: currentDraftId,
          bcc,
          body_html: prepared.bodyHtml,
          body_macro: processedMacroBody,
          body_text: prepared.bodyText,
          cc,
          provider_id: draftSeed?.provider_id,
          provider_thread_id: currentThread.provider_id,
          replying_to_id: replyTarget?.db_id,
          subject: form.subject(),
          thread_db_id: currentThread.db_id,
          to,
          // Replies/forwards follow the inbox's "add to replies & forwards"
          // setting on the backend; only signal an explicit per-reply dismiss.
          include_signature: includeSignature() ? undefined : false,
          draft_generation: draftGeneration(),
        },
        inboxId,
        completingThread: willMarkDone,
      });

      let result;
      try {
        result = await pendingSend;
      } catch (error) {
        if (
          sendGeneration !== identityVersion ||
          session.isStale(epochBeforeSave)
        )
          return;
        cleanupWatermark();
        autosave.cancel();
        if (mounted && currentDraftId) {
          const snapshot = replyUndo.peek(currentDraftId);
          if (snapshot) restoreMountedReply(snapshot);
        }
        props.notices.reportError(error);
        props.notices.feedback.failure('Failed to send email');
        return;
      }
      if (
        sendGeneration !== identityVersion ||
        session.isStale(epochBeforeSave)
      )
        return;
      // Clear only after the send is durably accepted, including after unmount.
      try {
        resetState();
        clearDraftState();
      } catch (error) {
        props.notices.reportError(error);
      } finally {
        cleanupWatermark();
      }
      autosave.cancel();
      const draftId = result.draftId;
      if (draftId) endUndoSend(draftId);
      // Each undo action retains this send's inbox, thread and mark-done, even
      // if the composer sends again or navigation disposes the view.
      let markDoneUndoHandle: EmailUndoHandle | undefined;
      // Advancing may archive after a page loads; an undo or failure before
      // then must not leave the thread marked done.
      let returnedToInbox = false;
      const returnToInbox = async () => {
        returnedToInbox = true;
        const doneHandle = markDoneUndoHandle;
        markDoneUndoHandle = undefined;
        await doneHandle?.undo({
          onError: () =>
            props.notices.feedback.failure('Failed to restore thread to inbox'),
        });
      };
      const undoSend = (draftId: string) =>
        props.delivery.undoSend({
          sendAttemptId: result.sendAttemptId,
          threadId: result.threadId,
          draftId,
          inboxId,
          onUndone: async (undo) => {
            returnedToInbox = true;
            await restoreAfterUndoSend(
              draftId,
              result.threadId,
              inboxId,
              undo?.draftRestored
            );
            await returnToInbox();
          },
        });
      // The outbox delivers an online send right away; offline it waits on this device.
      const offline = props.connectivity.looksOffline();
      announceQueuedSend({
        notices: props.notices,
        delivery: props.delivery,
        sendAttemptId: result.sendAttemptId,
        queuedOffline: offline,
        undo: draftId
          ? () => {
              void undoSend(draftId).catch(props.notices.reportError);
            }
          : undefined,
        onUndelivered: () => fireAndForget(returnToInbox(), 'email-compose'),
      });
      for (const mention of prepared.mentions) {
        try {
          props.recordMention(sourceEntityId, mention.documentId);
        } catch (error) {
          props.notices.reportError(error);
        }
      }
      if (willMarkDone) {
        try {
          // A plain send stays on the thread; Send and mark done advances to
          // the next thread, like Mark done.
          props.onMarkDone?.({
            silent: true,
            onUndoHandle: (handle) => {
              markDoneUndoHandle = handle;
              // Marking done can finish after the send was undone or failed.
              if (returnedToInbox)
                fireAndForget(returnToInbox(), 'email-compose');
            },
            navigate: markDone,
            cancelled: () =>
              returnedToInbox || sendOperation !== sendOperationVersion,
          });
        } catch (error) {
          props.notices.reportError(error);
          props.notices.feedback.failure(
            'Email sent, but unable to mark thread done'
          );
        }
      }
      try {
        // Presentation refresh must not keep a successfully sent or undone reply disabled.
        void Promise.resolve(
          props.sideEffectOnSend?.(draftId ?? null, {
            // Send and mark done already leaves the thread.
            queuedOffline: offline && !markDone,
          })
        ).catch(props.notices.reportError);
      } catch (error) {
        props.notices.reportError(error);
      }
    } catch (error) {
      props.notices.reportError(error);
    } finally {
      if (sendOperation === sendOperationVersion) setSendPhase('idle');
    }
  };

  const resetState = () => {
    setRestoredBodyHtml(plainTextToHtml(''));
    attachmentLinks.detach();
    clearEmailBody(editor());
    setBodyMacro('');
    session.dispatch({ type: 'reset' });
    setDraftGeneration(0);
    form.reset();
    schedule.reset();
    setTerminalState(undefined);
    hasLocalChanges = false;
  };

  const clearDraftState = () => {
    ctx.onDraftRemoved();
    props.setShowReply?.(false);
  };

  const deleteDraftAndReset = async () => {
    if (sendLocked() || restoring()) return;
    if (schedule.state().type === 'scheduled') {
      props.notices.feedback.alert(
        'Cancel the schedule before deleting this draft.'
      );
      return;
    }
    if (submitting() || pendingDeletion() || movingInbox() || scheduling())
      return;
    // Keep Lexical's deferred reset notification from recreating a discarded draft.
    setPendingDeletion(true);
    autosave.cancel();
    try {
      await autosave.settled().catch(() => {});
      await autosave.flushLocal().catch(props.notices.reportError);
      const draftId = savedDraftId();
      if (draftId) {
        try {
          await deleteDraftForDiscard(props.drafts, {
            draftId,
            draftGeneration: draftGeneration(),
            threadId: savedDraftThreadId(),
            inboxId: activeInboxId(),
          });
        } catch (error) {
          await reportPersistenceFailure(error, 'delete');
          setPendingDeletion(false);
          void lifecycle.refresh().catch(props.notices.reportError);
          throw error;
        }
      }
      identityVersion += 1;
      resetState();
      form.setReplyAppended(false);
      clearDraftState();
    } finally {
      setTimeout(() => {
        autosave.cancel();
        setPendingDeletion(false);
      }, 0);
    }
  };

  const handleUserMention = (mention: UserMentionRecord) => {
    if (recipients.disabled()) return;
    addUserMentionToCc({
      mention,
      recipientOptions: ctx.recipientOptions(),
      toRecipients: form.recipients().to,
      ccRecipients: form.recipients().cc,
      bccRecipients: form.recipients().bcc,
      setCc: (next) => form.setRecipients('cc', next),
      onRecipientAdded: (email) => {
        props.notices.feedback.success(`${email} added to CC`);
      },
    });
  };

  const attachmentLinks = createAttachmentLinkOffer({
    editor,
    canEdit: () => !editingDisabled(),
    version: () =>
      `${identityVersion}:${session.epoch()}:${activeInboxId() ?? ''}`,
    notices: props.notices,
    editorFiles: props.editorFiles,
  });

  const handleAddAttachments = async (files: File[]) => {
    if (editingDisabled()) return;
    if (await refuseAttachmentsOffline(props.connectivity, props.notices))
      return;
    if (editingDisabled()) return;
    const limit = attachmentLimitBytes(sendingInbox()?.provider);
    const { attachable, oversized } = partitionByAttachmentLimit(
      files,
      form.attachments.list(),
      limit
    );
    for (const file of attachable) {
      form.attachments.add({ type: 'local', file });
    }
    if (attachable.length > 0) scheduleDraftSave();
    try {
      await attachmentLinks.share(oversized, limit);
    } catch (error) {
      props.notices.reportError(error);
    }
  };

  const handleRemoveAttachment = async (attachment: DraftFormAttachment) => {
    if (editingDisabled()) return;
    try {
      if (!(await attachmentPersistence.remove(attachment))) return;
      scheduleDraftSave();
    } catch (error) {
      props.notices.reportError(error);
    }
  };

  const scheduling = schedule.pending;
  const scheduleBlocked = () =>
    restoring() ||
    deliveryBlocked() ||
    attachmentPersistence.removing() ||
    pendingDeletion() ||
    movingInbox() ||
    !!draftTransfer?.pending() ||
    submitting() ||
    terminalState() !== undefined ||
    sendLocked();
  const handleSendTimeChange = (date: Date | null) =>
    scheduleBlocked() ? false : schedule.select(date);

  const detachFromObsoleteDraft = (
    reason: KeptAsNewDraftReason,
    message: string
  ) => {
    recordKeptAsNewDraft(reason, {
      draftId: session.draftId(),
      unacknowledgedEdits: editVersion - persistedEditVersion,
    });
    identityVersion += 1;
    autosave.cancel();
    session.dispatch({ type: 'reset' });
    setDraftGeneration(0);
    const omittedAttachments = attachmentPersistence.detach();
    attachmentLinks.detach();
    schedule.detach();
    setTerminalState(undefined);
    persistedEditVersion = 0;
    props.notices.feedback.alert(message);
    if (omittedAttachments) {
      props.notices.feedback.alert(
        'Previously saved attachments could not be copied to the new draft. Please attach those files again.'
      );
    }
    void autosave.save().catch(() => {});
  };

  let lastScheduledTime = schedule.confirmedTime()?.toISOString();
  let handledTerminalIdentity: string | undefined;
  let reconcileAfterQueuedSend = false;
  createEffect(
    on(
      [
        lifecycle.state,
        scheduling,
        () => movingInbox() || !!draftTransfer?.pending(),
        () => sendPhase() === 'sending',
        () => sendLocked() || restoring(),
      ],
      ([state, , moving, sending, queued]) => {
        if (queued) {
          reconcileAfterQueuedSend = true;
          return;
        }
        if (reconcileAfterQueuedSend) {
          reconcileAfterQueuedSend = false;
          // Admission's non-draft observation predates the cancellation.
          void lifecycle.refresh().catch(props.notices.reportError);
          return;
        }
        if (
          !state ||
          !session.serverConfirmed() ||
          state.draftId !== savedDraftId() ||
          state.threadId !== savedDraftThreadId() ||
          (state.inboxId !== undefined &&
            state.inboxId !== persistedInboxId()) ||
          moving ||
          sending ||
          pendingDeletion()
        )
          return;

        if (state.type === 'scheduled') {
          if (editVersion > persistedEditVersion) {
            detachFromObsoleteDraft(
              'scheduled-elsewhere',
              'This email was scheduled in another tab. Your newer text was kept as a new draft.'
            );
            return;
          }
          const nextTime = new Date(state.sendTime);
          const changedElsewhere =
            !schedule.confirmedTime() ||
            schedule.confirmedTime()?.getTime() !== nextTime.getTime();
          schedule.observe(state);
          if (changedElsewhere && lastScheduledTime !== state.sendTime) {
            props.notices.feedback.alert(
              `Email scheduled for ${nextTime.toLocaleString()}. Cancel the schedule to edit.`
            );
          }
          lastScheduledTime = state.sendTime;
          return;
        }

        if (state.type === 'editing') {
          const wasScheduled = schedule.state().type === 'scheduled';
          schedule.observe(state);
          if (wasScheduled && schedule.state().type === 'editing') {
            session.dispatch({ type: 'schedule-cancelled' });
            lastScheduledTime = undefined;
            props.notices.feedback.success(
              'Schedule cancelled. This email is editable again.'
            );
          }
          return;
        }

        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' ? 'sent-elsewhere' : 'changed-elsewhere',
            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;
        }

        identityVersion += 1;
        autosave.cancel();
        resetState();
        setTerminalState(state.type);
        clearDraftState();
        if (state.type === 'sent') {
          if (wasScheduled)
            props.notices.feedback.success('Scheduled email sent');
        } else {
          props.notices.feedback.alert('This draft is no longer available.');
        }
      }
    )
  );

  const hasBodyText = () => bodyMacro().trim().length > 0;
  const editingDisabled = () =>
    restoring() ||
    operationBlocked() ||
    submitting() ||
    pendingDeletion() ||
    movingInbox() ||
    !!draftTransfer?.pending() ||
    scheduling() ||
    schedule.state().type === 'scheduled' ||
    terminalState() !== undefined ||
    sendLocked();
  const sendUnavailableReason = () => {
    if (sendLocked()) return 'Queued to send. Cancel the send before editing.';
    if (terminalState() === 'sent') return 'This email has already been sent.';
    if (terminalState() === 'missing')
      return 'This draft is no longer available.';
    if (schedule.operation() === 'committing') return 'Scheduling email…';
    if (schedule.operation() === 'updating') return 'Updating schedule…';
    if (schedule.operation() === 'cancelling') return 'Cancelling schedule…';
    if (submitting() || operationSending(currentOperation())) return 'Sending…';
    if (attachmentLinks.uploading()) return 'Uploading files to share…';
    if (schedule.action() === 'unavailable')
      return `Scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`;
    return undefined;
  };
  const sendActionDisabled = () =>
    restoring() ||
    deliveryBlocked() ||
    submitting() ||
    pendingDeletion() ||
    movingInbox() ||
    !!draftTransfer?.pending() ||
    scheduling() ||
    terminalState() !== undefined ||
    sendLocked() ||
    attachmentPersistence.uploading() ||
    attachmentLinks.uploading() ||
    schedule.action() === 'unavailable';
  const toggleQuotedText = () => {
    if (editingDisabled()) return;
    const replyingTo = replyTarget;
    if (!replyingTo) return;

    const currentlyAppended = form.replyAppended();
    form.setReplyAppended(!currentlyAppended);
    // Explicitly showing quoted text via the toolbar reveals it uncollapsed
    if (!currentlyAppended) setQuoteCollapsed(false);

    editor()?.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
      replyingTo,
      replyType: form.replyType(),
      visible: !currentlyAppended,
      isPersonal: ctx.isPersonalReply(),
    });

    editor()?.update(() => {
      $getRoot().getFirstChild()?.selectStart();
    });
  };

  async function retryDraft() {
    if (scheduleBlocked() || schedule.state().type === 'scheduled') return;
    // Finish this editor's last write before checking the shared revision.
    await autosave.flushLocal().catch(props.notices.reportError);
    await persistence.retry();
    await autosave.save();
  }

  return {
    operationSource,
    retryDraft,
    flushLocal: autosave.flushLocal,
    localSaveState: autosave.localSaveState,
    onContentChange: handleChange,
    handleUserMention,
    scrollContainer,
    form,
    activeInboxId,
    activeInboxEmail,
    replyType: form.replyType,
    signatureHtml: replySignatureHtml,
    setIncludeSignature: (include: boolean) => {
      if (editingDisabled()) return;
      setIncludeSignature(include);
    },
    setScrollContainer,
    composerExpanded,
    setComposerExpanded,
    quoteCollapsed,
    setQuoteCollapsed,
    savedDraftId,
    handleEditorConnect,
    isSending: () =>
      submitting() || scheduling() || operationSending(currentOperation()),
    recipients,
    collectDraft,
    scheduleDraftSave,
    persistDraftOnSenderSwitch,
    hasPaidAccess,
    sendEmail,
    deleteDraftAndReset,
    handleAddAttachments,
    handleRemoveAttachment,
    handleSendTimeChange,
    scheduleState: schedule.state,
    selectedSendTime: schedule.selectedTime,
    confirmedSendTime: schedule.confirmedTime,
    scheduleActionLabel: schedule.actionLabel,
    scheduleOperation: schedule.operation,
    cancelSchedule,
    checkScheduleStatus: schedule.checkStatus,
    schedulePickerDisabled: () =>
      scheduleBlocked() || schedule.pickerDisabled(),
    editingDisabled,
    sendUnavailableReason,
    hasBodyText,
    sendActionDisabled,
    toggleQuotedText,
  };
}