Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): list Outlook sends in Sent at once and stop false alarms (#8794)
teoa41f83e55be7
diff --git a/.sqlx/query-162efb7e66ea54abedc91a557d6860b4d3b78a6e10be0ec56194855b703e2a70.json b/.sqlx/query-bb0b99d700013bacc3e9f31ae8d671891363fa936c05fd07ea90755b9677a123.jsonsimilarity index 66%rename from .sqlx/query-162efb7e66ea54abedc91a557d6860b4d3b78a6e10be0ec56194855b703e2a70.jsonrename to .sqlx/query-bb0b99d700013bacc3e9f31ae8d671891363fa936c05fd07ea90755b9677a123.jsonindex 6f9defc23a..7f3d695d1f 100644--- a/.sqlx/query-162efb7e66ea54abedc91a557d6860b4d3b78a6e10be0ec56194855b703e2a70.json+++ b/.sqlx/query-bb0b99d700013bacc3e9f31ae8d671891363fa936c05fd07ea90755b9677a123.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE email_messages SET is_draft = false,is_sent = true,\n mailbox_state = (COALESCE(mailbox_state,'{}'::jsonb) - 'provider_missing') || '{\"is_draft\":false}'::jsonb,\n sent_at = now(),updated_at = now()\n WHERE id = $1 RETURNING thread_id\n ",+ "query": "\n UPDATE email_messages SET is_draft = false,is_sent = true,\n mailbox_state = (COALESCE(mailbox_state,'{}'::jsonb) - 'provider_missing') || '{\"is_draft\":false}'::jsonb,\n sent_at = now(),internal_date_ts = now(),updated_at = now()\n WHERE id = $1 RETURNING thread_id\n ","describe": {"columns": [{@@ -18,5 +18,5 @@false]},- "hash": "162efb7e66ea54abedc91a557d6860b4d3b78a6e10be0ec56194855b703e2a70"+ "hash": "bb0b99d700013bacc3e9f31ae8d671891363fa936c05fd07ea90755b9677a123"}diff --git a/apps/web/src/features/email-compose/queued-send-status.test.tsx b/apps/web/src/features/email-compose/queued-send-status.test.tsxindex 3c9dff37e6..b685fb8241 100644--- a/apps/web/src/features/email-compose/queued-send-status.test.tsx+++ b/apps/web/src/features/email-compose/queued-send-status.test.tsx@@ -1,4 +1,9 @@import type { EmailSendIntent } from '@queries/email/send-queue';+import {+ serverEmailSends,+ setServerSendSession,+} from '@queries/email/server-sends';+import { readPendingEmailSends } from '@service-storage/email-send';import {cleanup,fireEvent,@@ -6,12 +11,13 @@ import {screen,waitFor,} from '@solidjs/testing-library';-import type { ComponentProps } from 'solid-js';+import { type ComponentProps, createSignal } from 'solid-js';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { QueuedSendStatus } from './queued-send-status';const mocks = vi.hoisted(() => ({intents: [] as EmailSendIntent[],+ readIntents: undefined as (() => EmailSendIntent[]) | undefined,refresh: vi.fn(async () => {}),cancel: vi.fn(async () => {}),restore: vi.fn(async () => {}),@@ -20,10 +26,14 @@ const mocks = vi.hoisted(() => ({vi.mock('@queries/email/draft-queue', () => ({ draftQueueActive: () => true }));vi.mock('@queries/email/queued-sends', () => ({useQueuedEmailSends: () => ({- intents: () => mocks.intents,+ intents: () => mocks.readIntents?.() ?? mocks.intents,refresh: mocks.refresh,}),}));+vi.mock('@service-storage/email-send', () => ({+ cancelEmailSend: vi.fn(),+ readPendingEmailSends: vi.fn(),+}));vi.mock('@queries/email/send-queue', () => ({cancelEmailSendQueued: mocks.cancel,restoreCancelledEmailSend: mocks.restore,@@ -35,64 +45,73 @@ vi.mock('@queries/email/send-queue', () => ({vi.mock('@ui', () => ({Button: (props: ComponentProps<'button'>) => <button {...props} />,}));-afterEach(cleanup);+afterEach(() => {+ cleanup();+ setServerSendSession(undefined);+});beforeEach(() => {vi.clearAllMocks();+ mocks.readIntents = undefined;});function showStatus(+ status: 'ACCEPTED' | 'FAILED' | 'DELIVERY_UNCONFIRMED',+ options: Parameters<typeof queuedIntent>[1] = {}+) {+ mocks.intents = [queuedIntent(status, options)];+ return render(() => <QueuedSendStatus />);+}++function queuedIntent(status: 'ACCEPTED' | 'FAILED' | 'DELIVERY_UNCONFIRMED',{cancellationPending = false,sendTime = null as string | null,failures = 0,} = {}-) {- mocks.intents = [- {- uuid: 'attempt',- phase: cancellationPending ? 'pending' : 'committed',- locallyCancelled: false,- dispatchVersion: 2,- cancellationRequested: cancellationPending,- dispatch: { generation: 1, leaseUntil: 0, nextAttemptAt: 0, failures },- metadata: {- kind: 'email-send-v1',- payload: {- draft: {+): EmailSendIntent {+ return {+ uuid: 'attempt',+ phase: cancellationPending ? 'pending' : 'committed',+ locallyCancelled: false,+ dispatchVersion: 2,+ cancellationRequested: cancellationPending,+ dispatch: { generation: 1, leaseUntil: 0, nextAttemptAt: 0, failures },+ metadata: {+ kind: 'email-send-v1',+ payload: {+ draft: {+ draftId: 'draft',+ threadDbId: 'thread',+ senderLinkId: 'inbox',+ senderEmail: '[email protected]',+ subject: 'Saved message',+ optimisticBodyHtml: null,+ },+ input: {+ attempt: { attemptId: 'attempt', linkId: 'inbox' },+ message: {draftId: 'draft',- threadDbId: 'thread',- senderLinkId: 'inbox',- senderEmail: '[email protected]',subject: 'Saved message',- optimisticBodyHtml: null,- },- input: {- attempt: { attemptId: 'attempt', linkId: 'inbox' },- message: {- draftId: 'draft',- subject: 'Saved message',- sendTime,- },- attachmentIds: [],- forwardedAttachmentIds: [],+ sendTime,},+ attachmentIds: [],+ forwardedAttachmentIds: [],},},- response: {- sendEmailMessage: {- attempt: {- attemptId: 'attempt',- status,- sendTime: null,- threadId: 'thread',- message: null,- },+ },+ response: {+ sendEmailMessage: {+ attempt: {+ attemptId: 'attempt',+ status,+ sendTime: null,+ threadId: 'thread',+ message: null,},},},- ];- return render(() => <QueuedSendStatus />);+ };}it('stays silent while an immediate send is accepted and delivering', () => {@@ -158,3 +177,37 @@ it('shows a status refresh error and permits checking again', async () => {expect(screen.queryByRole('alert')).toBeNull();expect(mocks.cancel).not.toHaveBeenCalled();});++it('rereads server sends when a send leaves this device, so a sent message stops showing', async () => {+ const listed = {+ linkId: 'inbox',+ attempt: {+ attemptId: 'attempt',+ status: 'ACCEPTED' as const,+ message: null,+ threadId: 'thread',+ sendTime: '2026-10-24T12:00:05.000Z',+ },+ };+ vi.mocked(readPendingEmailSends)+ .mockResolvedValueOnce({+ id: 'owner',+ pendingEmailSends: { nextCursor: null, attempts: [listed] },+ })+ .mockResolvedValue({+ id: 'owner',+ pendingEmailSends: { nextCursor: null, attempts: [] },+ });+ setServerSendSession('owner');+ await waitFor(() => expect(serverEmailSends()).toEqual([listed]));+ const [local, setLocal] = createSignal([queuedIntent('ACCEPTED')]);+ mocks.readIntents = local;+ render(() => <QueuedSendStatus />);+ expect(screen.queryByLabelText('Queued email sends')).toBeNull();++ setLocal([]);+ await waitFor(() => expect(readPendingEmailSends).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(screen.queryByLabelText('Queued email sends')).toBeNull()+ );+});diff --git a/apps/web/src/features/email-compose/queued-send-status.tsx b/apps/web/src/features/email-compose/queued-send-status.tsxindex 28b04bf5d9..a4a81de3b6 100644--- a/apps/web/src/features/email-compose/queued-send-status.tsx+++ b/apps/web/src/features/email-compose/queued-send-status.tsx@@ -20,7 +20,7 @@ import {serverEmailSendsError,} from '@queries/email/server-sends';import { Button } from '@ui';-import { createSignal, For, Show } from 'solid-js';+import { createEffect, createSignal, For, on, Show } from 'solid-js';/*** Routine delivery is silent. A send shows here only while it waits on this@@ -85,12 +85,21 @@ export function QueuedSendStatus(props: {(!props.threadId || row.attempt.threadId === props.threadId) &&(!props.inboxIds?.length || props.inboxIds.includes(row.linkId)));+ // The last server poll can still list a send this device just retired.+ createEffect(+ on(+ () => sends.intents().map((intent) => intent.uuid),+ (ids, previous) => {+ if (previous?.some((id) => !ids.includes(id)))+ fireAndForget(refreshServerEmailSends(), 'email-server-sends');+ }+ )+ );return (<Showwhen={visible().length > 0 ||visibleServer().length > 0 ||- serverEmailSendsError() ||emailSendStorageWarning()}>@@ -113,7 +122,7 @@ export function QueuedSendStatus(props: {<For each={visibleServer()}>{(row) => <ServerSendStatus row={row} />}</For>- <Show when={serverEmailSendsError()}>+ <Show when={visibleServer().length > 0 && serverEmailSendsError()}><p class="text-xs text-ink-muted" role="status">{serverEmailSendsError()}</p>diff --git a/apps/web/src/lib/queries/email/server-sends.test.ts b/apps/web/src/lib/queries/email/server-sends.test.tsindex 45e3804cb3..7a481a442a 100644--- a/apps/web/src/lib/queries/email/server-sends.test.ts+++ b/apps/web/src/lib/queries/email/server-sends.test.ts@@ -44,9 +44,10 @@ afterEach(() => {it('loads sends from other devices on sign-in without a local send or rollout flag', async () => {setServerSendSession('owner');- await refreshServerEmailSends();+ await vi.waitFor(() =>+ expect(serverEmailSends()).toEqual(pending.pendingEmailSends.attempts)+ );expect(readPendingEmailSends).toHaveBeenCalledTimes(1);- expect(serverEmailSends()).toEqual(pending.pendingEmailSends.attempts);});it('waits offline and refreshes server sends on reconnect', async () => {@@ -60,6 +61,22 @@ it('waits offline and refreshes server sends on reconnect', async () => {expect(serverEmailSends()).toEqual(pending.pendingEmailSends.attempts);});+it('answers a refresh made during a read with a read that started after it', async () => {+ const first = Promise.withResolvers<PendingEmailSendsQuery['user']>();+ vi.mocked(readPendingEmailSends)+ .mockImplementationOnce(() => first.promise)+ .mockResolvedValueOnce({+ ...pending,+ pendingEmailSends: { nextCursor: null, attempts: [] },+ });+ setServerSendSession('owner');+ const refresh = refreshServerEmailSends();+ first.resolve(pending);+ await refresh;+ expect(readPendingEmailSends).toHaveBeenCalledTimes(2);+ expect(serverEmailSends()).toEqual([]);+});+it('discards an in-flight status response after sign-out', async () => {const response = Promise.withResolvers<PendingEmailSendsQuery['user']>();const started = Promise.withResolvers<AbortSignal>();diff --git a/apps/web/src/lib/queries/email/server-sends.ts b/apps/web/src/lib/queries/email/server-sends.tsindex 1d9fd0ea85..083eaf49b8 100644--- a/apps/web/src/lib/queries/email/server-sends.ts+++ b/apps/web/src/lib/queries/email/server-sends.ts@@ -38,6 +38,7 @@ function createServerSendObserver(accountId: string) {let disposed = false;let pages = 1;let running: Promise<void> | undefined;+ let rerun: Promise<void> | undefined;let timer: ReturnType<typeof setTimeout> | undefined;let controller: AbortController | undefined;async function load() {@@ -72,14 +73,25 @@ function createServerSendObserver(accountId: string) {if (!disposed) timer = setTimeout(wake, 10_000);}}- async function refresh() {- if (disposed || running) return running;+ /** Resolves after a read that started after this call, so callers see their change. */+ async function refresh(): Promise<void> {+ if (disposed) return;+ if (running) {+ rerun ??= (async () => {+ await running;+ rerun = undefined;+ await refresh();+ })();+ return rerun;+ }if (timer !== undefined) clearTimeout(timer);// Defer load so its synchronous early-return cannot race this assignment.running = Promise.resolve().then(load);return running;}- const wake = () => fireAndForget(refresh(), 'email-server-sends');+ const wake = () => {+ if (!running) fireAndForget(refresh(), 'email-server-sends');+ };const visible = () => {if (document.visibilityState === 'visible') wake();};diff --git a/crates/email/src/outbound/email_pg_repo/send_attempt.rs b/crates/email/src/outbound/email_pg_repo/send_attempt.rsindex 8c82ea5cfb..52a155a30c 100644--- a/crates/email/src/outbound/email_pg_repo/send_attempt.rs+++ b/crates/email/src/outbound/email_pg_repo/send_attempt.rs@@ -73,7 +73,10 @@ fn attempt_from_row(row: AttemptRow) -> SendAttempt {SendAttemptStatus::Sent} else if row.delivery_unconfirmed|| row.error_code.as_deref() == Some("send_unknown")- || row.mailbox_stage.as_deref() == Some("confirming")+ // Outlook may have delivered a submission whose worker stopped+ // before it confirmed; while the worker still polls, it is sending.+ || (row.mailbox_stage.as_deref() == Some("confirming")+ && !matches!(row.mailbox_state.as_deref(), Some("pending" | "running")))|| row.delivery_status.as_deref() == Some("unconfirmed")|| (row.delivery_started_at.is_some() && !row.processing){diff --git a/crates/email/src/outbound/mailbox_pg/drafts.rs b/crates/email/src/outbound/mailbox_pg/drafts.rsindex 40a6672bd1..085d0990d8 100644--- a/crates/email/src/outbound/mailbox_pg/drafts.rs+++ b/crates/email/src/outbound/mailbox_pg/drafts.rs@@ -319,7 +319,7 @@ impl DraftRepository for PgMailboxSync {let message = sqlx::query!(r#"UPDATE email_messages SET is_draft = false,is_sent = true,mailbox_state = (COALESCE(mailbox_state,'{}'::jsonb) - 'provider_missing') || '{"is_draft":false}'::jsonb,- sent_at = now(),updated_at = now()+ sent_at = now(),internal_date_ts = now(),updated_at = now()WHERE id = $1 RETURNING thread_id"#,lease.message_id).fetch_one(&mut *tx).await.map_err(db_error)?;sqlx::query!("UPDATE email_scheduled_messages SET sent = true,processing = false,updated_at = now() WHERE message_id = $1 AND link_id = $2",lease.message_id,lease.mailbox.link_id).execute(&mut *tx).await.map_err(db_error)?;diff --git a/crates/email/src/outbound/mailbox_pg/drafts/test.rs b/crates/email/src/outbound/mailbox_pg/drafts/test.rsindex e86fd41147..d099728ef4 100644--- a/crates/email/src/outbound/mailbox_pg/drafts/test.rs+++ b/crates/email/src/outbound/mailbox_pg/drafts/test.rs@@ -12,6 +12,9 @@ use crate::{use email_api_client::domain::models::{MailboxState, SendRequest};use macro_db_migrator::MACRO_DB_MIGRATIONS;+mod delivery_status;+mod sent_view;+const ACTOR: &str = "macro|[email protected]";#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]diff --git a/crates/email/src/outbound/mailbox_pg/drafts/test/delivery_status.rs b/crates/email/src/outbound/mailbox_pg/drafts/test/delivery_status.rsnew file mode 100644index 0000000000..3a7c658a8e--- /dev/null+++ b/crates/email/src/outbound/mailbox_pg/drafts/test/delivery_status.rs@@ -0,0 +1,96 @@+use super::*;+use crate::domain::send_attempt::{EmailSendRepo, SendAttempt, SendAttemptStatus};+use macro_user_id::user_id::MacroUserIdStr;++async fn claim(sync: &PgMailboxSync) -> DraftLease {+ sync.claim_draft(+ Uuid::now_v7(),+ crate::domain::mailbox::drafts::models::DraftClaimMode::All,+ )+ .await+ .unwrap()+ .unwrap()+}++fn actor() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(ACTOR).unwrap()+}++async fn submitted_send(db: &PgPool) -> (PgMailboxSync, EmailPgRepo, DraftLease, Uuid) {+ let (sync, repo, input, link) = setup(db, true).await;+ sqlx::query!("INSERT INTO email_scheduled_messages (link_id,message_id,send_time,actor_id,processing) VALUES ($1,$2,now(),$3,true)",link,input.db_id,ACTOR).execute(db).await.unwrap();+ sqlx::query!("INSERT INTO email_send_attempts (user_id,link_id,attempt_id,message_id,thread_id,send_time) VALUES ($1,$2,$3,$4,$5,now())",ACTOR,link,Uuid::now_v7(),input.db_id,input.thread_db_id).execute(db).await.unwrap();+ let lease = claim(&sync).await;+ sync.checkpoint_draft(&lease, &checkpoint(&lease, DraftStage::Confirming))+ .await+ .unwrap();+ (sync, repo, lease, link)+}++async fn pending_attempt(repo: &EmailPgRepo, link: Uuid) -> SendAttempt {+ let mut attempts = repo+ .pending_send_attempts(&actor(), &[link], None)+ .await+ .unwrap();+ assert_eq!(attempts.len(), 1);+ attempts.remove(0).1+}++async fn pending_status(repo: &EmailPgRepo, link: Uuid) -> SendAttemptStatus {+ pending_attempt(repo, link).await.status+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn routine_outlook_confirmation_reads_as_sending_until_delivery_is_unknown(db: PgPool) {+ let (sync, repo, lease, link) = submitted_send(&db).await;+ assert_eq!(+ pending_status(&repo, link).await,+ SendAttemptStatus::Sending+ );+ sync.release_draft(&lease, 0).await.unwrap();+ assert_eq!(+ pending_status(&repo, link).await,+ SendAttemptStatus::Sending,+ "waiting between confirmation polls is still sending"+ );+ let lease = claim(&sync).await;+ sync.fail_draft(&lease, DraftFailure::SendUnknown)+ .await+ .unwrap();+ assert_eq!(+ pending_status(&repo, link).await,+ SendAttemptStatus::DeliveryUnconfirmed+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn cancelling_while_outlook_confirms_is_too_late(db: PgPool) {+ let (_, repo, lease, link) = submitted_send(&db).await;+ let attempt = pending_attempt(&repo, link).await.attempt_id;+ let cancelled = repo.cancel_send(&actor(), link, attempt).await.unwrap();+ assert_eq!(cancelled.status, SendAttemptStatus::Sending);+ let processing = sqlx::query_scalar!(+ "SELECT processing FROM email_scheduled_messages WHERE message_id = $1",+ lease.message_id+ )+ .fetch_optional(&db)+ .await+ .unwrap();+ assert_eq!(processing, Some(true), "the submitted delivery is kept");+ assert_eq!(+ pending_status(&repo, link).await,+ SendAttemptStatus::Sending,+ "the attempt is still pending, not cancelled"+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn losing_access_after_submission_reads_as_unconfirmed_not_failed(db: PgPool) {+ let (sync, repo, lease, link) = submitted_send(&db).await;+ sync.fail_draft(&lease, DraftFailure::Denied).await.unwrap();+ assert_eq!(+ pending_status(&repo, link).await,+ SendAttemptStatus::DeliveryUnconfirmed,+ "the provider may already have sent it, so a resend risks a duplicate"+ );+}diff --git a/crates/email/src/outbound/mailbox_pg/drafts/test/sent_view.rs b/crates/email/src/outbound/mailbox_pg/drafts/test/sent_view.rsnew file mode 100644index 0000000000..b8c71d1791--- /dev/null+++ b/crates/email/src/outbound/mailbox_pg/drafts/test/sent_view.rs@@ -0,0 +1,92 @@+use super::*;+use crate::domain::models::{PreviewCursorQuery, PreviewView, PreviewViewStandardLabel};+use macro_user_id::user_id::MacroUserIdStr;+use models_pagination::{Query, SimpleSortMethod};++async fn sent_threads(repo: &EmailPgRepo, link: Uuid) -> Vec<Uuid> {+ repo.previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::Sent),+ link_ids: vec![link],+ limit: 50,+ query: Query::new(None, SimpleSortMethod::UpdatedAt, None),+ team_id: None,+ },+ MacroUserIdStr::parse_from_str(ACTOR).unwrap().to_owned(),+ )+ .await+ .unwrap()+ .into_iter()+ .map(|preview| preview.id)+ .collect()+}++async fn latest_outbound(db: &PgPool, thread: Uuid) -> Option<chrono::DateTime<chrono::Utc>> {+ sqlx::query_scalar!(+ "SELECT latest_outbound_message_ts FROM email_threads WHERE id = $1",+ thread+ )+ .fetch_one(db)+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_confirmed_outlook_send_is_in_sent_before_the_provider_copy_syncs(db: PgPool) {+ let (sync, repo, input, link) = setup(&db, true).await;+ let lease = sync+ .claim_draft(+ Uuid::now_v7(),+ crate::domain::mailbox::drafts::models::DraftClaimMode::All,+ )+ .await+ .unwrap()+ .unwrap();+ let mut cp = checkpoint(&lease, DraftStage::Confirming);+ cp.draft.as_mut().unwrap().is_draft = false;+ sync.confirm_sent(&lease, &cp).await.unwrap();+ assert_eq!(sent_threads(&repo, link).await, vec![input.thread_db_id]);++ let work = sync.claim_message(Uuid::now_v7()).await.unwrap().unwrap();+ let mut remote = snapshot(link, "a", MailboxState::default(), "v2");+ remote.content.message.is_sent = true;+ sync.ingest(&work, remote).await.unwrap();+ assert_eq!(+ latest_outbound(&db, input.thread_db_id)+ .await+ .map(|ts| ts.to_rfc3339())+ .as_deref(),+ Some("2026-10-01T12:00:00+00:00"),+ "the provider's sent time replaces the provisional one"+ );+ assert_eq!(sent_threads(&repo, link).await, vec![input.thread_db_id]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_old_outlook_draft_sorts_in_sent_by_when_it_was_sent(db: PgPool) {+ let (sync, _, input, _) = setup(&db, true).await;+ sqlx::query!(+ "UPDATE email_messages SET internal_date_ts = '2026-09-01T09:00:00Z' WHERE id = $1",+ input.db_id+ )+ .execute(&db)+ .await+ .unwrap();+ let lease = sync+ .claim_draft(+ Uuid::now_v7(),+ crate::domain::mailbox::drafts::models::DraftClaimMode::All,+ )+ .await+ .unwrap()+ .unwrap();+ let mut cp = checkpoint(&lease, DraftStage::Confirming);+ cp.draft.as_mut().unwrap().is_draft = false;+ let before = chrono::Utc::now() - chrono::Duration::seconds(5);+ sync.confirm_sent(&lease, &cp).await.unwrap();+ let outbound = latest_outbound(&db, input.thread_db_id).await.unwrap();+ assert!(+ outbound >= before,+ "sent thread sorts by its send time, not the draft's {outbound}"+ );+}