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.

58.7 KB
Raw Blame
import { $createImageNode } from '@macro-inc/lexical-core';
import { $getRoot } from 'lexical';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { message } from '../../email-message/tests/messages';
import type {
  EmailDraftStorage,
  PersistedEmailIdentity,
} from '../context/compose-capabilities';
import { DraftPersistRejected } from '../context/compose-capabilities';
import { decodeBase64Utf8 } from '../core/decode-base64';
import type { LocalDraft } from '../core/local-draft';
import { createComposeContext } from '../tests/capabilities';
import { mountEmailComposer } from '../tests/composer';
import { mountReplyComposer } from '../tests/reply';

const response: PersistedEmailIdentity = {
  draftId: 'saved-id',
  threadId: 'thread',
  inboxId: 'inbox',
};
const providers = ['GMAIL', 'OUTLOOK'] as const;
function providerContext(provider: (typeof providers)[number]) {
  const composeContext = createComposeContext();
  composeContext.accounts.inboxes = () => [
    { id: 'inbox', email_address: '[email protected]', settings: {}, provider },
  ];
  return composeContext;
}
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());

it('flushes the latest pending body and envelope exactly once on disposal', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Last-second edit', 'Launch review');
  root.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  const { draft } = vi.mocked(composeContext.drafts.saveDraft).mock.calls[0][0];
  expect(decodeBase64Utf8(draft.body_html ?? '')).toContain('Last-second edit');
  expect(draft.subject).toBe('Launch review');
  expect(draft.to).toEqual([
    expect.objectContaining({ email: '[email protected]' }),
  ]);
});
it('does not save an untouched composer or repeat a settled autosave on disposal', async () => {
  const composeContext = createComposeContext();
  const untouched = mountEmailComposer(composeContext);
  untouched.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.saveDraft).not.toHaveBeenCalled();
  const edited = mountEmailComposer(composeContext);
  edited.edit('Saved');
  await vi.advanceTimersByTimeAsync(600);
  edited.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
});
it('serializes a disposal flush behind the first save and reuses its returned ID', async () => {
  const pending = Promise.withResolvers<PersistedEmailIdentity>();
  const composeContext = createComposeContext();
  vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
    pending.promise
  );
  const root = mountEmailComposer(composeContext);
  root.edit('First');
  await vi.advanceTimersByTimeAsync(600);
  root.edit('Latest');
  root.dispose();
  await vi.advanceTimersByTimeAsync(600);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  pending.resolve(response);
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
  const { draft } = vi.mocked(composeContext.drafts.saveDraft).mock.calls[1][0];
  expect(draft.db_id).toBe('saved-id');
  expect(decodeBase64Utf8(draft.body_html ?? '')).toContain('Latest');
});
it('discard cancels an unsaved debounce without creating a draft', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Discard me');
  await root.state.deleteDraftAndReset();
  root.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.saveDraft).not.toHaveBeenCalled();
  expect(composeContext.drafts.deleteDraft).not.toHaveBeenCalled();
});
it.each(providers)(
  'Delete leaves a %s draft at once and deletes the ID its in-flight first save returns',
  async (provider) => {
    const pending = Promise.withResolvers<PersistedEmailIdentity>();
    const composeContext = providerContext(provider);
    vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
      pending.promise
    );
    const goBack = vi.fn(() => root.dispose());
    const root = mountEmailComposer(composeContext, { goBack });
    root.edit('First');
    await vi.advanceTimersByTimeAsync(600);
    root.edit('Discard these changes too');
    const discard = root.state.deleteDraftAndReset();
    await vi.advanceTimersByTimeAsync(0);
    expect(goBack).toHaveBeenCalledOnce();
    pending.resolve(response);
    await discard;
    await vi.advanceTimersByTimeAsync(1000);
    expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
    expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(
      expect.objectContaining({ draftId: 'saved-id' })
    );
  }
);
it.each(providers)(
  'Delete leaves a %s draft whose send waits on a pasted image while its save is on the wire',
  async (provider) => {
    const composeContext = providerContext(provider);
    const goBack = vi.fn(() => root.dispose());
    const root = mountEmailComposer(composeContext, { goBack });
    root.edit('Body');
    await vi.advanceTimersByTimeAsync(600);
    const saving = Promise.withResolvers<PersistedEmailIdentity>();
    vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
      saving.promise
    );
    root.editor.update(
      () =>
        $getRoot().append(
          $createImageNode({
            srcType: 'local',
            url: 'blob:http://localhost/pasted',
            alt: 'pasted',
          })
        ),
      { discrete: true }
    );
    root.state.context.onContentChange('Body');
    await vi.advanceTimersByTimeAsync(600);
    expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
    root.state.context.onSend();
    await vi.advanceTimersByTimeAsync(0);
    expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();

    root.state.context.onDelete?.();
    await vi.advanceTimersByTimeAsync(0);
    expect(goBack).toHaveBeenCalledOnce();
    saving.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
    await vi.advanceTimersByTimeAsync(1000);
    expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(
      expect.objectContaining({ draftId: 'draft' })
    );
    expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
  }
);
it('discards a standalone draft at its server generation', async () => {
  const composeContext = createComposeContext();
  // Each send that Undo cancels advances the server's generation twice.
  const root = mountEmailComposer(composeContext, undefined, {
    draft: message('restored', {
      is_draft: true,
      thread_db_id: 'thread',
      draft_generation: 4,
    }),
  });
  await root.state.deleteDraftAndReset();
  root.dispose();
  expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(
    expect.objectContaining({ draftId: 'restored', draftGeneration: 4 })
  );
});

it.each([
  { state: 'CONFLICT', issue: 'DRAFT_CONFLICT', discards: true },
  { state: 'UNCERTAIN', issue: 'ATTACHMENT_UNKNOWN', discards: true },
  { state: 'UNCERTAIN', issue: 'SEND_UNKNOWN', discards: false },
  { state: 'SUBMITTING', issue: null, discards: false },
] as const)(
  'discards a draft whose $state $issue operation locks editing: $discards',
  async ({ state, issue, discards }) => {
    const composeContext = providerContext('OUTLOOK');
    const goBack = vi.fn();
    const root = mountEmailComposer(
      composeContext,
      { goBack },
      {
        draft: message('locked', {
          is_draft: true,
          thread_db_id: 'thread',
          operation: { state, revision: '1', issue },
        }),
      }
    );
    expect(root.state.context.disabled()).toBe(true);
    expect(root.state.context.deleteDisabled?.()).toBe(!discards);
    await root.state.deleteDraftAndReset();
    // A host that cannot leave keeps an empty composer, now unlocked.
    expect(root.state.context.disabled()).toBe(!discards);
    root.dispose();
    expect(goBack).toHaveBeenCalledTimes(discards ? 1 : 0);
    expect(composeContext.drafts.deleteDraft).toHaveBeenCalledTimes(
      discards ? 1 : 0
    );
  }
);

it('discards a reply draft at its server generation', async () => {
  const composeContext = createComposeContext();
  const root = mountReplyComposer(composeContext, () => message('parent'), {
    draft: message('restored', {
      is_draft: true,
      replying_to_id: 'parent',
      thread_db_id: 'thread',
      draft_generation: 4,
    }),
  });
  await root.deleteDraftAndReset();
  root.dispose();
  expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(
    expect.objectContaining({ draftId: 'restored', draftGeneration: 4 })
  );
});

it('sends a reloaded reply without appending its quoted thread again', async () => {
  const composeContext = createComposeContext();
  // The server keeps the quote's class but strips the editor's markers.
  const root = mountReplyComposer(composeContext, () => message('parent'), {
    draft: message('draft', {
      is_draft: true,
      replying_to_id: 'parent',
      thread_db_id: 'thread',
      body_html_sanitized:
        '<p>Reply</p><div class="macro_quote gmail_quote"><blockquote>Earlier</blockquote></div>',
    }),
  });
  await root.sendEmail();
  root.dispose();
  const sent = vi.mocked(composeContext.delivery.sendMessage).mock.calls[0][0];
  expect(decodeBase64Utf8(sent.message.body_html ?? '')).not.toContain(
    'macro_quote'
  );
});

it('reports a failed deletion and keeps a draft its host still shows editable', async () => {
  const composeContext = createComposeContext();
  const goBack = vi.fn();
  const root = mountEmailComposer(composeContext, { goBack });
  root.edit('Saved');
  await vi.advanceTimersByTimeAsync(600);
  vi.mocked(composeContext.drafts.deleteDraft).mockRejectedValueOnce(
    new Error('offline')
  );
  await expect(root.state.deleteDraftAndReset()).rejects.toThrow('offline');
  expect(goBack).toHaveBeenCalledOnce();
  expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
    'Failed to delete draft'
  );
  root.edit('Still here');
  await vi.advanceTimersByTimeAsync(600);
  root.dispose();
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
});
it('reports a failed deletion after the composer has left without saving the draft again', async () => {
  const composeContext = createComposeContext();
  const goBack = vi.fn(() => root.dispose());
  const root = mountEmailComposer(composeContext, { goBack });
  root.edit('Saved');
  await vi.advanceTimersByTimeAsync(600);
  vi.mocked(composeContext.drafts.deleteDraft).mockRejectedValueOnce(
    new Error('offline')
  );
  await expect(root.state.deleteDraftAndReset()).rejects.toThrow('offline');
  await vi.advanceTimersByTimeAsync(1000);
  expect(goBack).toHaveBeenCalledOnce();
  expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
    'Failed to delete draft'
  );
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
});

it.each(providers)(
  'toolbar discard leaves a %s draft before deleting it and does not recreate it on disposal',
  async (provider) => {
    const composeContext = providerContext(provider);
    const pending = Promise.withResolvers<void>();
    const goBack = vi.fn(() => root.dispose());
    const root = mountEmailComposer(composeContext, { goBack });
    root.edit('Discard this standalone thread');
    await vi.advanceTimersByTimeAsync(600);
    // Deleting a draft-only thread empties the open thread as soon as the
    // delete starts, so the composer has to be gone by then.
    let leftBeforeDelete = false;
    vi.mocked(composeContext.drafts.deleteDraft).mockImplementationOnce(() => {
      leftBeforeDelete = goBack.mock.calls.length > 0;
      return pending.promise;
    });

    root.state.context.onDelete?.();
    await vi.advanceTimersByTimeAsync(0);
    expect(goBack).toHaveBeenCalledOnce();
    expect(leftBeforeDelete).toBe(true);
    pending.resolve();
    await vi.advanceTimersByTimeAsync(1000);

    expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(
      expect.objectContaining({ draftId: 'draft' })
    );
    expect(root.state.context.hasDraft()).toBe(false);
    expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  }
);
it.each(providers)(
  'Delete still deletes a %s draft and frees the composer when its host cannot leave',
  async (provider) => {
    const composeContext = providerContext(provider);
    const navigation = new Error('navigation failed');
    const goBack = vi.fn(() => {
      throw navigation;
    });
    const root = mountEmailComposer(composeContext, { goBack });
    root.edit('Discard this draft');
    await vi.advanceTimersByTimeAsync(600);

    root.state.context.onDelete?.();
    await vi.advanceTimersByTimeAsync(1000);

    expect(composeContext.drafts.deleteDraft).toHaveBeenCalledWith(
      expect.objectContaining({ draftId: 'draft' })
    );
    expect(root.state.context.disabled()).toBe(false);
    expect(goBack).toHaveBeenCalledOnce();
    expect(composeContext.notices.reportError).toHaveBeenCalledWith(navigation);
    root.dispose();
    await vi.advanceTimersByTimeAsync(1000);
    expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  }
);
it('waits for the saved draft ID, prevents duplicate sends, and does not recreate the sent draft on disposal', async () => {
  const pending = Promise.withResolvers<PersistedEmailIdentity>();
  const composeContext = createComposeContext();
  vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
    pending.promise
  );
  const root = mountEmailComposer(composeContext);
  root.edit('Send this');
  root.state.context.onSend();
  root.state.context.onSend();
  expect(root.state.context.disabled()).toBe(true);
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
  pending.resolve(response);
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.sendMessage).toHaveBeenCalledOnce();
  expect(
    vi.mocked(composeContext.delivery.sendMessage).mock.calls[0][0].message
      .db_id
  ).toBe('saved-id');
  root.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
});
it('resumes autosave after a failed send', async () => {
  const composeContext = createComposeContext();
  vi.mocked(composeContext.delivery.sendMessage).mockRejectedValueOnce(
    new Error('offline')
  );
  const root = mountEmailComposer(composeContext);
  root.edit('Send this');
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(root.state.context.disabled()).toBe(false);
  root.edit('Retry with this');
  root.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
  expect(
    composeContext.notices.feedback.failure
  ).toHaveBeenCalledExactlyOnceWith('Failed to send email');
});

it('keeps a successful send completed when navigation fails', async () => {
  const composeContext = createComposeContext();
  const error = new Error('Navigation failed');
  const root = mountEmailComposer(composeContext, {
    showThread: () => {
      throw error;
    },
  });
  root.edit('Send this');
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.notices.reportError).toHaveBeenCalledWith(error);
  expect(composeContext.notices.feedback.failure).not.toHaveBeenCalled();
  root.state.context.onSend();
  root.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.delivery.sendMessage).toHaveBeenCalledOnce();
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
});

it('keeps completion independent when two composers share delivery capabilities', async () => {
  const composeContext = createComposeContext();
  const pending = Promise.withResolvers<PersistedEmailIdentity>();
  vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(
    pending.promise
  );
  const first = mountEmailComposer(composeContext);
  const second = mountEmailComposer(composeContext);
  first.edit('First');
  second.edit('Second');
  first.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  second.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.sendMessage).toHaveBeenCalledTimes(2);
  expect(first.state.context.isSending()).toBe(true);
  expect(second.state.context.isSending()).toBe(false);
  pending.resolve(response);
  await vi.advanceTimersByTimeAsync(1);
  expect(first.state.context.isSending()).toBe(false);
  first.dispose();
  second.dispose();
});
it('waits for an existing attachment upload before flushing newer body edits', async () => {
  const pending = Promise.withResolvers<void>();
  const composeContext = createComposeContext();
  vi.mocked(
    composeContext.attachmentStorage.uploadAttachments
  ).mockReturnValueOnce(pending.promise);
  const root = mountEmailComposer(composeContext);
  root.edit('With attachment');
  root.state.context.onAddAttachments([
    new File(['notes'], 'notes.txt', { type: 'text/plain' }),
  ]);
  await vi.advanceTimersByTimeAsync(600);
  root.edit('Final attachment note');
  root.dispose();
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  pending.resolve();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
  expect(
    vi.mocked(composeContext.drafts.saveDraft).mock.calls[1][0].draft.db_id
  ).toBe('draft');
});

it('rejects sender/schedule changes and repeated discard while a deletion is pending', async () => {
  const pending = Promise.withResolvers<void>();
  const composeContext = createComposeContext();
  const goBack = vi.fn();
  const root = mountEmailComposer(composeContext, { goBack });
  root.edit('Saved');
  await vi.advanceTimersByTimeAsync(600);
  vi.mocked(composeContext.drafts.deleteDraft).mockReturnValueOnce(
    pending.promise
  );
  const discard = root.state.deleteDraftAndReset();
  expect(await root.state.deleteDraftAndReset()).toBe(false);
  expect(goBack).toHaveBeenCalledOnce();
  root.state.context.onSelectInbox?.('other-inbox');
  root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));
  expect(root.state.context.selectedInboxId?.()).toBe('inbox');
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
  pending.resolve();
  expect(await discard).toBe(true);
  expect(goBack).toHaveBeenCalledOnce();
  root.dispose();
});

it('rejects sender and scheduling changes after send dispatch', async () => {
  const pending = Promise.withResolvers<PersistedEmailIdentity>();
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(
    pending.promise
  );
  root.edit('Send this');
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  root.state.context.onSelectInbox?.('other-inbox');
  root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
  expect(root.state.context.selectedInboxId?.()).toBe('inbox');
  pending.resolve(response);
  await vi.advanceTimersByTimeAsync(1);
  root.dispose();
});

it('uses the captured inbox for attachment upload when a sender switch queues behind a save', async () => {
  const pending = Promise.withResolvers<PersistedEmailIdentity>();
  const composeContext = createComposeContext();
  composeContext.accounts = {
    ...composeContext.accounts,
    inboxes: () => [
      { id: 'inbox', email_address: '[email protected]', settings: {} },
      { id: 'other', email_address: '[email protected]', settings: {} },
    ],
  };
  vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
    pending.promise
  );
  const root = mountEmailComposer(composeContext);
  root.edit('With files');
  root.state.context.onAddAttachments([new File(['notes'], 'notes.txt')]);
  await vi.advanceTimersByTimeAsync(600);
  root.state.context.onSelectInbox?.('other');
  pending.resolve(response);
  await vi.advanceTimersByTimeAsync(1);
  expect(
    vi.mocked(composeContext.attachmentStorage.uploadAttachments).mock
      .calls[0][0].inboxId
  ).toBe('inbox');
  expect(
    vi.mocked(composeContext.drafts.saveDraft).mock.calls[1][0].inboxId
  ).toBe('inbox');
  expect(composeContext.drafts.transferDraft).toHaveBeenCalledWith(
    expect.objectContaining({
      sourceInboxId: 'inbox',
      destinationInboxId: 'other',
    })
  );
  root.dispose();
});

it('keeps a selected or cleared time inert while ordinary autosave continues', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  const selected = new Date('2026-12-01T12:00:00Z');
  root.edit('Autosave this scheduled-send preparation');
  expect(root.state.context.schedule.onSelect(selected)).toBe(true);
  await vi.advanceTimersByTimeAsync(600);

  expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
  expect(
    vi.mocked(composeContext.drafts.saveDraft).mock.calls[0][0]
  ).not.toHaveProperty('sendTime');
  expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
  expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
  expect(composeContext.delivery.archive).not.toHaveBeenCalled();

  expect(root.state.context.schedule.onSelect(null)).toBe(true);
  expect(root.state.context.schedule.selectedTime()).toBeUndefined();
  expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
  root.dispose();
});

it('only commits a selected time through the primary action', async () => {
  const composeContext = createComposeContext();
  const host = { showThread: vi.fn(), showDraft: vi.fn() };
  const root = mountEmailComposer(composeContext, host);
  root.edit('Schedule this');
  const firstTime = new Date(2026, 11, 1, 12);
  expect(root.state.context.schedule.onSelect(firstTime)).toBe(true);
  expect(root.state.context.schedule.selectedTime()).toEqual(firstTime);
  expect(root.state.context.deliveryState?.()).toBe('draft');
  expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
  expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
  expect(composeContext.notices.feedback.success).not.toHaveBeenCalled();

  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
  expect(composeContext.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
    {
      draftGeneration: 0,
      draftId: 'draft',
      threadId: 'thread',
      sendTime: firstTime.toISOString(),
      includeSignature: undefined,
    },
    'inbox'
  );
  expect(root.state.context.schedule.confirmedTime()).toEqual(firstTime);
  expect(root.state.context.deliveryState?.()).toBe('scheduled');
  expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
    'Email scheduled',
    expect.objectContaining({
      // The year appears only when the send is not this year.
      subtext: expect.stringMatching(/^Sends Tue, Dec 1(, 2026)? at 12:00 PM$/),
      actions: [
        expect.objectContaining({ label: 'Undo' }),
        expect.objectContaining({ label: 'View message', kind: 'open' }),
      ],
      duration: 8_000,
    })
  );
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.schedule).toHaveBeenCalledOnce();
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();

  const scheduledNotice = vi
    .mocked(composeContext.notices.feedback.success)
    .mock.calls.find(([message]) => message === 'Email scheduled');
  host.showThread.mockClear();
  scheduledNotice?.[1]?.actions?.[1].onClick();
  expect(host.showThread).toHaveBeenCalledExactlyOnceWith('thread');
  // Showing the thread mounts its own composer on the scheduled draft.
  const threadView = mountEmailComposer(composeContext, host, {
    draft: message('draft', {
      is_draft: true,
      scheduled_send_time: firstTime.toISOString(),
    }),
  });
  scheduledNotice?.[1]?.actions?.[0].onClick();
  await vi.advanceTimersByTimeAsync(1);
  threadView.dispose();
  expect(composeContext.delivery.unschedule).toHaveBeenCalledExactlyOnceWith({
    draftGeneration: 0,
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
  });
  expect(root.state.context.schedule.state()).toEqual({
    type: 'editing',
    intent: { type: 'immediate' },
  });
  expect(composeContext.delivery.archive).toHaveBeenLastCalledWith(
    { threadId: 'thread', value: false },
    'inbox'
  );
  expect(composeContext.drafts.restoreDraft).toHaveBeenCalledWith(
    expect.objectContaining({
      draftId: 'draft',
      threadId: 'thread',
      draft: expect.objectContaining({ subject: 'Review' }),
      html: expect.stringContaining('Schedule this'),
    })
  );
  expect(host.showDraft).toHaveBeenCalledExactlyOnceWith('draft');
  root.dispose();

  // The compose view the undo opens gets the scheduled content back.
  const reopened = mountEmailComposer(composeContext, host, {
    draftId: 'draft',
  });
  expect(reopened.state.context.subject()).toBe('Review');
  expect(reopened.state.context.initialHtml()).toContain('Schedule this');
  reopened.dispose();
});

it('retires the scheduled notice when the thread view cancels the schedule', async () => {
  const composeContext = createComposeContext();
  vi.mocked(composeContext.notices.feedback.success).mockImplementation(
    (message) => (message === 'Email scheduled' ? 7 : undefined)
  );
  const root = mountEmailComposer(composeContext);
  root.edit('Schedule then cancel');
  const sendTime = new Date('2026-12-01T12:00:00Z');
  root.state.context.schedule.onSelect(sendTime);
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  const scheduledNotice = vi
    .mocked(composeContext.notices.feedback.success)
    .mock.calls.find(([text]) => text === 'Email scheduled');
  // Scheduling shows the thread, whose own composer holds the draft.
  root.dispose();
  const threadView = mountEmailComposer(composeContext, undefined, {
    draft: message('draft', {
      is_draft: true,
      scheduled_send_time: sendTime.toISOString(),
    }),
  });
  expect(composeContext.notices.feedback.dismiss).not.toHaveBeenCalled();

  expect(await threadView.state.context.schedule.onCancel()).toBe(true);
  expect(composeContext.notices.feedback.dismiss).toHaveBeenCalledWith(7);
  // A click that lands during the dismissal must not undo the newer draft.
  scheduledNotice?.[1]?.actions?.[0].onClick();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.unschedule).toHaveBeenCalledOnce();
  expect(composeContext.drafts.restoreDraft).not.toHaveBeenCalled();
  threadView.dispose();
});

it('preserves local intent on schedule failure without falling back to send', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Schedule carefully');
  const sendTime = new Date('2026-12-01T12:00:00Z');
  vi.mocked(composeContext.delivery.schedule).mockRejectedValueOnce(
    new Error('schedule offline')
  );

  expect(root.state.context.schedule.onSelect(sendTime)).toBe(true);
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(root.state.context.schedule.selectedTime()).toEqual(sendTime);
  expect(root.state.context.schedule.state().type).toBe('editing');
  expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
    'Failed to schedule email'
  );
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
  root.dispose();
});

it('stops an open scheduled composer when delivery is observed', async () => {
  const composeContext = createComposeContext();
  const showThread = vi.fn();
  const root = mountEmailComposer(composeContext, { showThread });
  root.edit('Deliver this');
  root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  showThread.mockClear();

  composeContext.setDraftLifecycle({
    type: 'sent',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);

  expect(root.state.context.deliveryState?.()).toBe('sent');
  expect(root.state.context.disabled()).toBe(true);
  expect(showThread).toHaveBeenCalledExactlyOnceWith('thread');
  expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
    'Scheduled email sent'
  );
  root.state.context.onSend();
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
  root.dispose();
  await vi.advanceTimersByTimeAsync(1000);
  expect(composeContext.drafts.deleteDraft).not.toHaveBeenCalled();
});

it('reconciles an external schedule and cancellation while the composer is open', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Coordinate this draft');
  await vi.advanceTimersByTimeAsync(600);
  const sendTime = '2026-12-01T12:00:00Z';

  composeContext.setDraftLifecycle({
    type: 'scheduled',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    sendTime,
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  expect(root.state.context.schedule.confirmedTime()).toEqual(
    new Date(sendTime)
  );
  expect(root.state.context.disabled()).toBe(true);

  composeContext.setDraftLifecycle({
    type: 'editing',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  expect(root.state.context.schedule.confirmedTime()).toBeUndefined();
  expect(root.state.context.disabled()).toBe(false);
  expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
    'Schedule cancelled. This email is editable again.'
  );
  root.dispose();
});

it('reopens an in-place scheduled composer when the schedule is cancelled elsewhere', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Schedule in place');
  const sendTime = '2026-12-01T12:00:00Z';
  root.state.context.schedule.onSelect(new Date(sendTime));
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  composeContext.setDraftLifecycle({
    type: 'scheduled',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    sendTime,
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  expect(root.state.context.disabled()).toBe(true);

  composeContext.setDraftLifecycle({
    type: 'editing',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  expect(root.state.context.schedule.state().type).toBe('editing');
  expect(root.state.context.disabled()).toBe(false);
  expect(root.state.context.primaryActionDisabled()).toBe(false);
  root.dispose();
});

it('does not mistake its own in-flight send for a delivery elsewhere', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Saved once');
  await vi.advanceTimersByTimeAsync(600);
  const sending = Promise.withResolvers<PersistedEmailIdentity>();
  vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(
    sending.promise
  );
  // The pre-send save is best-effort, so the send goes ahead with the final
  // edit unsaved.
  vi.mocked(composeContext.drafts.saveDraft).mockRejectedValueOnce(
    new Error('save offline')
  );
  root.edit('Final edit');
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.sendMessage).toHaveBeenCalledOnce();

  composeContext.setDraftLifecycle({
    type: 'sent',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  sending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
  await vi.advanceTimersByTimeAsync(1000);

  expect(composeContext.notices.feedback.alert).not.toHaveBeenCalled();
  expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(2);
  expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
    expect.any(String),
    expect.objectContaining({
      actions: [expect.objectContaining({ label: 'Undo' })],
    })
  );
  root.dispose();
});

it('does not announce a plain send as a scheduled one', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Just send this');
  await vi.advanceTimersByTimeAsync(600);
  const sending = Promise.withResolvers<PersistedEmailIdentity>();
  vi.mocked(composeContext.delivery.sendMessage).mockReturnValueOnce(
    sending.promise
  );
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);

  composeContext.setDraftLifecycle({
    type: 'sent',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  sending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
  await vi.advanceTimersByTimeAsync(0);

  expect(composeContext.notices.feedback.success).not.toHaveBeenCalledWith(
    'Scheduled email sent'
  );
  expect(composeContext.notices.feedback.alert).not.toHaveBeenCalled();
  expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
    expect.any(String),
    expect.objectContaining({
      actions: [expect.objectContaining({ label: 'Undo' })],
    })
  );
  root.dispose();
});

it('keeps the confirmed time authoritative until update or cancellation succeeds', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Manage this schedule');
  await vi.advanceTimersByTimeAsync(600);
  const original = new Date('2026-12-01T12:00:00Z');
  const replacement = new Date('2026-12-02T14:30:00Z');
  composeContext.setDraftLifecycle({
    type: 'scheduled',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    sendTime: original.toISOString(),
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);

  expect(root.state.context.schedule.onSelect(replacement)).toBe(true);
  expect(root.state.context.schedule.confirmedTime()).toEqual(original);
  expect(root.state.context.schedule.selectedTime()).toEqual(replacement);
  expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
  expect(root.state.context.schedule.onSelect(null)).toBe(true);
  expect(root.state.context.schedule.confirmedTime()).toEqual(original);
  expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();

  root.state.context.schedule.onSelect(replacement);
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
    expect.objectContaining({
      draftId: 'draft',
      sendTime: replacement.toISOString(),
    }),
    'inbox'
  );
  expect(root.state.context.schedule.confirmedTime()).toEqual(replacement);
  composeContext.setDraftLifecycle({
    type: 'scheduled',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    sendTime: replacement.toISOString(),
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);

  vi.mocked(composeContext.delivery.unschedule).mockRejectedValueOnce(
    new Error('cancel offline')
  );
  expect(await root.state.context.schedule.onCancel()).toBe(false);
  expect(root.state.context.schedule.confirmedTime()).toEqual(replacement);
  expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
    'Failed to cancel schedule'
  );

  expect(await root.state.context.schedule.onCancel()).toBe(true);
  expect(root.state.context.schedule.state().type).toBe('editing');
  expect(root.state.context.disabled()).toBe(false);
  root.dispose();
});

it('unlocks a composer that stays mounted after its schedule is cancelled', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Schedule, then change my mind');
  expect(
    root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'))
  ).toBe(true);
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(1);
  expect(composeContext.delivery.schedule).toHaveBeenCalledOnce();
  expect(root.state.context.disabled()).toBe(true);

  expect(await root.state.context.schedule.onCancel()).toBe(true);
  expect(root.state.context.schedule.state().type).toBe('editing');
  expect(root.state.context.disabled()).toBe(false);
  expect(root.state.context.primaryActionDisabled()).toBe(false);
  root.dispose();
});

it('blocks a past local time at submission without sending immediately', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Do not send early');
  const past = new Date(Date.now() - 1_000);
  expect(root.state.context.schedule.onSelect(past)).toBe(true);
  root.state.context.onSend();
  await vi.advanceTimersByTimeAsync(0);
  expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
  expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
    'That send time has passed. Choose a future time.'
  );
  expect(root.state.context.schedule.selectedTime()).toEqual(past);
  root.dispose();
});

it('ignores a stale autosave response and preserves a racing edit under a new draft ID', async () => {
  const composeContext = createComposeContext();
  const root = mountEmailComposer(composeContext);
  root.edit('Persisted version');
  await vi.advanceTimersByTimeAsync(600);
  const pending = Promise.withResolvers<PersistedEmailIdentity>();
  vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
    pending.promise
  );
  root.edit('New text that raced delivery');
  await vi.advanceTimersByTimeAsync(600);

  composeContext.setDraftLifecycle({
    type: 'sent',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);
  pending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
  await vi.advanceTimersByTimeAsync(0);

  expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(3);
  const preserved = vi.mocked(composeContext.drafts.saveDraft).mock.calls[2][0]
    .draft;
  expect(preserved.db_id).toBeUndefined();
  expect(decodeBase64Utf8(preserved.body_html ?? '')).toContain(
    'New text that raced delivery'
  );
  expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
    'This email was already sent. Your newer text was kept as a new draft and was not sent.'
  );
  expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
  root.dispose();
});

it('reports delivery specifically when it races draft deletion', async () => {
  const composeContext = createComposeContext();
  const showThread = vi.fn();
  const root = mountEmailComposer(composeContext, { showThread });
  root.edit('Saved before delete');
  await vi.advanceTimersByTimeAsync(600);
  const pending = Promise.withResolvers<void>();
  vi.mocked(composeContext.drafts.deleteDraft).mockReturnValueOnce(
    pending.promise
  );

  const deletion = root.state.deleteDraftAndReset();
  composeContext.setDraftLifecycle({
    type: 'sent',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  pending.reject(new Error('message already sent'));
  await expect(deletion).rejects.toThrow('message already sent');
  await vi.advanceTimersByTimeAsync(0);

  expect(composeContext.notices.feedback.failure).not.toHaveBeenCalledWith(
    'Failed to delete draft'
  );
  expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
    'This scheduled email was sent. Your composer has been updated.'
  );
  expect(showThread).toHaveBeenCalledWith('thread');
  root.dispose();
});

it.each([true, false])(
  'does not send a recovery draft when pre-send persistence discovers delivery (immediate effect: %s)',
  async (immediateEffect) => {
    const context = createComposeContext();
    const root = mountEmailComposer(context);
    root.edit('Previously saved');
    await vi.advanceTimersByTimeAsync(600);
    const lifecycle = vi.mocked(context.draftLifecycle.observe).mock.results[0]
      .value;
    const sent = {
      type: 'sent' as const,
      draftId: 'draft',
      threadId: 'thread',
      inboxId: 'inbox',
      observedAt: Date.now(),
    };
    vi.mocked(lifecycle.refresh).mockImplementationOnce(async () => {
      if (immediateEffect) context.setDraftLifecycle(sent);
      return sent;
    });
    vi.mocked(context.drafts.saveDraft)
      .mockRejectedValueOnce(new Error('Message already sent'))
      .mockResolvedValue({ ...response, draftId: 'recovered' });
    root.edit('Keep this newer text unsent');
    root.state.context.onSend();
    await vi.advanceTimersByTimeAsync(0);

    expect(context.delivery.sendMessage).not.toHaveBeenCalled();
    if (!immediateEffect) {
      expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
      // The refresh result already stopped Send before Solid applies the state.
      context.setDraftLifecycle(sent);
      await vi.advanceTimersByTimeAsync(0);
    }
    expect(context.drafts.saveDraft).toHaveBeenCalledTimes(3);
    expect(
      vi.mocked(context.drafts.saveDraft).mock.lastCall?.[0].draft.db_id
    ).toBeUndefined();
    expect(root.state.context.disabled()).toBe(false);
    root.dispose();
  }
);

it('recovers local and forwarded attachments without retaining remote-only attachment pills', async () => {
  const context = createComposeContext();
  vi.mocked(context.attachmentStorage.uploadAttachments).mockImplementation(
    async (input) => {
      for (const file of input.attachments)
        input.onAttachmentAdded?.(file, `${input.draftId}-attachment`);
    }
  );
  const root = mountEmailComposer(context);
  const file = new File(['notes'], 'notes.txt');
  root.edit('Saved with files');
  await root.state.context.onAddAttachments([file]);
  root.state.form.attachments.add({
    type: 'remote',
    attachmentId: 'remote',
    url: 'https://example.com/file',
    fileName: 'remote.txt',
    contentType: 'text/plain',
    fileSize: 10,
  });
  root.state.form.attachments.add({
    type: 'forwarded',
    attachmentId: 'original-file',
    fileName: 'forward.txt',
    mimeType: 'text/plain',
    fileSize: 10,
  });
  await vi.advanceTimersByTimeAsync(600);
  vi.mocked(context.drafts.saveDraft).mockResolvedValue({
    ...response,
    draftId: 'recovered',
  });
  root.edit('New text to recover');
  context.setDraftLifecycle({
    type: 'sent',
    draftId: 'draft',
    threadId: 'thread',
    inboxId: 'inbox',
    observedAt: Date.now(),
  });
  await vi.advanceTimersByTimeAsync(0);

  expect(context.attachmentStorage.uploadAttachments).toHaveBeenCalledTimes(2);
  expect(context.attachmentStorage.uploadAttachments).toHaveBeenLastCalledWith(
    expect.objectContaining({ draftId: 'recovered', attachments: [file] })
  );
  expect(
    context.attachmentStorage.addForwardedAttachments
  ).toHaveBeenLastCalledWith(
    expect.objectContaining({
      draftId: 'recovered',
      attachments: [{ attachmentId: 'original-file' }],
    })
  );
  expect(
    root.state.context
      .attachments()
      .map((attachment) => attachment.attachmentId)
  ).toEqual(['recovered-attachment', 'original-file']);
  expect(context.notices.feedback.alert).toHaveBeenCalledWith(
    'Previously saved attachments could not be copied to the new draft. Please attach those files again.'
  );
  root.dispose();
});

it.each(['standalone', 'reply'] as const)(
  'reports one failed autosave notice for a confirmed %s draft',
  async (surface) => {
    const context = createComposeContext();
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('First save');
      await vi.advanceTimersByTimeAsync(600);
      const error = new Error('save failed');
      vi.mocked(context.drafts.saveDraft).mockRejectedValueOnce(error);
      root.edit('Failed edit');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.notices.feedback.failure).toHaveBeenCalledExactlyOnceWith(
        'Failed to save draft'
      );
      expect(context.notices.reportError).toHaveBeenCalledExactlyOnceWith(
        error
      );
    } finally {
      root.dispose();
    }
  }
);

it.each(['standalone', 'reply'] as const)(
  'reports one local-save failure for an unconfirmed %s draft',
  async (surface) => {
    const context = createComposeContext();
    const error = new Error('local storage failed');
    vi.mocked(context.drafts.saveDraft).mockRejectedValue(error);
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('Unsaved edit');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.notices.feedback.failure).toHaveBeenCalledExactlyOnceWith(
        'Failed to save draft'
      );
      expect(context.notices.reportError).toHaveBeenCalledExactlyOnceWith(
        error
      );
    } finally {
      root.dispose();
    }
  }
);

it.each(['standalone', 'reply'] as const)(
  'keeps rejected %s edits unsaved until explicit recovery creates a fresh draft',
  async (surface) => {
    const context = createComposeContext();
    let changed!: Parameters<NonNullable<EmailDraftStorage['watchDrafts']>>[0];
    context.drafts.watchDrafts = (callback) => {
      changed = callback;
      return () => {};
    };
    context.drafts.readDraft = vi.fn(async () => undefined);
    vi.mocked(context.drafts.saveDraft).mockImplementation(
      async ({ clientHandles }) => ({
        draftId: clientHandles?.draftId,
        threadId: clientHandles?.threadId,
        inboxId: 'inbox',
        persistence: 'queued',
      })
    );
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('Queued text');
      await vi.advanceTimersByTimeAsync(600);
      const original = vi.mocked(context.drafts.saveDraft).mock.calls[0][0];
      expect(original.clientHandles?.draftId).toBeTruthy();
      changed({ mutationUuid: original.clientHandles?.draftId, failed: true });
      await vi.advanceTimersByTimeAsync(0);
      expect(context.notices.feedback.failure).toHaveBeenCalledOnce();
      root.edit('Newest unsaved text');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
      const action = vi.mocked(context.notices.feedback.failure).mock
        .calls[0][1]?.actions?.[0];
      expect(action?.label).toBe('Save as new draft');
      action?.onClick();
      await vi.advanceTimersByTimeAsync(0);
      expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
      const recovered = vi.mocked(context.drafts.saveDraft).mock.calls[1][0];
      expect(recovered.draft.db_id).toBeUndefined();
      expect(recovered.clientHandles?.draftId).not.toBe(
        original.clientHandles?.draftId
      );
      expect(decodeBase64Utf8(recovered.draft.body_html ?? '')).toContain(
        'Newest unsaved text'
      );
      if (surface === 'reply')
        expect(recovered.draft.thread_db_id).toBe('thread');
      action?.onClick();
      await vi.advanceTimersByTimeAsync(0);
      expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
    } finally {
      root.dispose();
    }
  }
);

it.each(['standalone', 'reply'] as const)(
  'drops an already-sent background %s draft and cancels pending autosave',
  async (surface) => {
    const context = createComposeContext();
    let changed!: Parameters<NonNullable<EmailDraftStorage['watchDrafts']>>[0];
    context.drafts.watchDrafts = (callback) => {
      changed = callback;
      return () => {};
    };
    context.drafts.readDraft = vi.fn(async () => undefined);
    vi.mocked(context.drafts.saveDraft).mockImplementation(
      async ({ clientHandles }) => ({
        draftId: clientHandles?.draftId,
        threadId: clientHandles?.threadId,
        inboxId: 'inbox',
        persistence: 'queued',
      })
    );
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('Already delivered');
      await vi.advanceTimersByTimeAsync(600);
      const original = vi.mocked(context.drafts.saveDraft).mock.calls[0][0];
      root.edit('Edit awaiting autosave');
      changed({
        mutationUuid: original.clientHandles?.draftId,
        failed: true,
        code: 'DRAFT_ALREADY_SENT',
      });
      await vi.advanceTimersByTimeAsync(1000);
      expect(context.notices.feedback.alert).not.toHaveBeenCalled();
      expect(context.notices.feedback.failure).not.toHaveBeenCalled();
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
      expect(context.delivery.sendMessage).not.toHaveBeenCalled();
      expect(context.delivery.schedule).not.toHaveBeenCalled();
      expect(root.editor.read(() => $getRoot().getTextContent())).toBe('');
      if ('state' in root) {
        expect(root.state.context.subject()).toBe('');
        expect(root.state.context.recipients().to).toEqual([]);
      }
    } finally {
      root.dispose();
    }
    await vi.advanceTimersByTimeAsync(1000);
    expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
  }
);

function localSnapshot(
  input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
): LocalDraft {
  const id = input.clientHandles?.draftId ?? input.draft.db_id ?? 'draft';
  return {
    key: id,
    accountId: 'owner',
    generation: 'generation',
    revision: 1,
    acknowledgedRevision: 0,
    draftId: id,
    threadId: input.clientHandles?.threadId,
    content: input.draft,
    attachments: [],
    status: 'dirty',
    updatedAt: Date.now(),
  };
}

it.each(['standalone', 'reply'] as const)(
  'keeps one %s local-save warning until recovery and briefly warns when the write on close fails',
  async (surface) => {
    const context = createComposeContext();
    let diskFailed = true;
    context.drafts.saveLocalDraft = vi.fn(async (input) => {
      if (diskFailed) throw new Error('Disk full');
      return localSnapshot(input);
    });
    vi.mocked(context.notices.feedback.failure)
      .mockReturnValueOnce(7)
      .mockReturnValueOnce(8);
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      for (const text of ['First edit', 'Second edit', 'Third edit']) {
        root.edit(text);
        await vi.advanceTimersByTimeAsync(600);
      }
      expect(context.notices.feedback.failure).toHaveBeenCalledExactlyOnceWith(
        'Draft could not be saved on this device',
        { subtext: 'Error: Disk full', persistent: true }
      );
      expect(context.notices.feedback.dismiss).not.toHaveBeenCalled();
      expect(context.drafts.saveDraft).not.toHaveBeenCalled();

      diskFailed = false;
      root.edit('Recovered edit');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.notices.feedback.dismiss).toHaveBeenCalledExactlyOnceWith(
        7
      );
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();

      diskFailed = true;
      root.edit('Another failure');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.notices.feedback.failure).toHaveBeenCalledTimes(2);
    } finally {
      root.dispose();
    }
    await vi.advanceTimersByTimeAsync(0);
    const closing = vi.mocked(context.drafts.saveLocalDraft!).mock.lastCall;
    expect(decodeBase64Utf8(closing?.[0].draft.body_html ?? '')).toContain(
      'Another failure'
    );
    expect(context.notices.feedback.dismiss).toHaveBeenLastCalledWith(8);
    expect(context.notices.feedback.failure).toHaveBeenCalledTimes(3);
    expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(
      'Draft could not be saved on this device',
      { subtext: 'Error: Disk full', persistent: false }
    );
  }
);

it.each(['standalone', 'reply'] as const)(
  'writes the unsaved %s edit once more on close',
  async (surface) => {
    const context = createComposeContext();
    let diskFailed = true;
    context.drafts.saveLocalDraft = vi.fn(async (input) => {
      if (diskFailed) throw new Error('Draft storage transaction aborted');
      return localSnapshot(input);
    });
    vi.mocked(context.notices.feedback.failure).mockReturnValueOnce(7);
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('Typed before backgrounding');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.drafts.saveDraft).not.toHaveBeenCalled();
    } finally {
      diskFailed = false;
      root.dispose();
    }
    await vi.advanceTimersByTimeAsync(1000);
    const closing = vi.mocked(context.drafts.saveLocalDraft!).mock.lastCall;
    expect(decodeBase64Utf8(closing?.[0].draft.body_html ?? '')).toContain(
      'Typed before backgrounding'
    );
    expect(context.notices.feedback.dismiss).toHaveBeenCalledExactlyOnceWith(7);
    expect(context.notices.feedback.failure).toHaveBeenCalledOnce();
    expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
  }
);

it.each(['standalone', 'reply'] as const)(
  'keeps the %s editor revision after adopting its server ID',
  async (surface) => {
    const context = createComposeContext();
    let revision = 0;
    const saveLocalDraft = vi.fn(
      async (
        input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
      ) => {
        if (
          input.expectedRevision !== undefined &&
          input.expectedRevision !== revision
        )
          throw new Error('Draft changed in another tab');
        return { ...localSnapshot(input), revision: ++revision };
      }
    );
    context.drafts.saveLocalDraft = saveLocalDraft;
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('First save');
      await vi.advanceTimersByTimeAsync(600);
      const editorRevision = revision;
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
      revision += 1; // Another tab commits after the server ID is adopted.
      root.edit('Stale editor edit');
      await vi.advanceTimersByTimeAsync(600);
      expect(saveLocalDraft.mock.lastCall?.[0].expectedRevision).toBe(
        editorRevision
      );
      expect(saveLocalDraft.mock.lastCall?.[0].expectedGeneration).toBe(
        'generation'
      );
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
      expect(context.notices.feedback.failure).toHaveBeenCalledWith(
        'Draft could not be saved on this device',
        expect.anything()
      );
    } finally {
      root.dispose();
    }
  }
);

it.each(['standalone', 'reply'] as const)(
  'waits for the first durable %s snapshot before discarding it',
  async (surface) => {
    const context = createComposeContext();
    const pending = Promise.withResolvers<void>();
    const saveLocalDraft = vi.fn(
      async (
        input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
      ) => {
        await pending.promise;
        return localSnapshot(input);
      }
    );
    context.drafts.saveLocalDraft = saveLocalDraft;
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('Still copying attachment bytes');
      await vi.advanceTimersByTimeAsync(0);
      expect(saveLocalDraft).toHaveBeenCalled();
      const discard =
        'state' in root
          ? root.state.deleteDraftAndReset()
          : root.deleteDraftAndReset();
      await vi.advanceTimersByTimeAsync(0);
      expect(context.drafts.deleteDraft).not.toHaveBeenCalled();
      pending.resolve();
      await discard;
      expect(context.drafts.deleteDraft).toHaveBeenCalledOnce();
      expect(context.drafts.saveDraft).not.toHaveBeenCalled();
    } finally {
      pending.resolve();
      root.dispose();
    }
  }
);

it.each(['standalone', 'reply'] as const)(
  'persists further %s edits locally after rejection and retries the same handle',
  async (surface) => {
    const context = createComposeContext();
    const saveLocalDraft = vi.fn(
      async (
        input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
      ) => localSnapshot(input)
    );
    context.drafts.saveLocalDraft = saveLocalDraft;
    context.drafts.retryDraft = vi.fn(async () => {});
    vi.mocked(context.drafts.saveDraft).mockRejectedValueOnce(
      new DraftPersistRejected('INVALID')
    );
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('Rejected text');
      await vi.advanceTimersByTimeAsync(600);
      const handle = vi.mocked(context.drafts.saveDraft).mock.calls[0][0]
        .clientHandles?.draftId;
      root.edit('New text saved only on this device');
      await vi.advanceTimersByTimeAsync(600);
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
      const latest = saveLocalDraft.mock.lastCall?.[0];
      expect(decodeBase64Utf8(latest?.draft.body_html ?? '')).toContain(
        'New text saved only on this device'
      );
      await ('state' in root ? root.state.retryDraft() : root.retryDraft());
      expect(context.drafts.retryDraft).toHaveBeenCalledWith(handle);
      expect(
        vi.mocked(context.drafts.saveDraft).mock.lastCall?.[0].clientHandles
          ?.draftId
      ).toBe(handle);
    } finally {
      root.dispose();
    }
  }
);

it.each(['standalone', 'reply'] as const)(
  'refuses a stale %s retry without overwriting another tab’s durable edit',
  async (surface) => {
    const context = createComposeContext();
    const saveLocalDraft = vi.fn(
      async (
        input: Parameters<NonNullable<EmailDraftStorage['saveLocalDraft']>>[0]
      ) => localSnapshot(input)
    );
    context.drafts.saveLocalDraft = saveLocalDraft;
    context.drafts.retryDraft = vi.fn(async () => {});
    vi.mocked(context.drafts.saveDraft).mockRejectedValueOnce(
      new DraftPersistRejected('INVALID')
    );
    const root =
      surface === 'standalone'
        ? mountEmailComposer(context)
        : mountReplyComposer(context);
    try {
      root.edit('This tab’s rejected text');
      await vi.advanceTimersByTimeAsync(600);
      const latest = localSnapshot(saveLocalDraft.mock.lastCall![0]);
      latest.revision += 1;
      latest.content = { subject: 'Newer edit in another tab' };
      context.drafts.readDraft = vi.fn(async () => ({
        local: latest,
        persistence: 'queued' as const,
      }));
      const writes = saveLocalDraft.mock.calls.length;
      await expect(
        'state' in root ? root.state.retryDraft() : root.retryDraft()
      ).rejects.toThrow('changed in another tab');
      expect(context.drafts.retryDraft).not.toHaveBeenCalled();
      expect(saveLocalDraft).toHaveBeenCalledTimes(writes);
      expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
      expect(latest.content.subject).toBe('Newer edit in another tab');
    } finally {
      root.dispose();
    }
  }
);