Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(email): return Outlook follow-up reminders through mailbox commands (#8791)

teo2978385c861f
diff --git a/Cargo.lock b/Cargo.lock
index 4de95741b9..4b236e3372 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16284,8 +16284,11 @@ dependencies = [
"axum",
"axum-extra",
"chrono",
+ "crm",
"email",
"entity_access",
+ "entity_access_management",
+ "frecency",
"http-body-util",
"macro_authorization",
"macro_db_migrator",
diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.md
index a2803bc39a..2338aa2fa6 100644
--- a/crates/email/AGENTS.md
+++ b/crates/email/AGENTS.md
@@ -64,6 +64,9 @@ tools — hexagonal, heavily feature-gated.
domain service, never an outbound adapter directly from another crate.
- Sender discovery authorizes the inbox first. Gmail aliases use the sender
provider; Outlook exposes its verified primary address without a Gmail lookup.
+- Outlook links have no system label rows. Move a thread in or out of the inbox
+ through `set_thread_inbox`, and read Outlook inbox, trash, and junk state from
+ `email_message_mailbox_facts`, never from labels.
- Outlook organization commands only run in their link's current
`sync_generation`. Anything that bumps it must rebind unfinished commands as
`pending`, since claims skip `confirming` ones while those still block later
diff --git a/crates/email/fixtures/email_outlook_threads.sql b/crates/email/fixtures/email_outlook_threads.sql
new file mode 100644
index 0000000000..12c7d06b11
--- /dev/null
+++ b/crates/email/fixtures/email_outlook_threads.sql
@@ -0,0 +1,19 @@
+-- Outlook mailbox. Outlook links have no system label rows; folder membership
+-- lives in mailbox_state.
+-- Thread 1: one received message in the Inbox folder.
+-- Thread 2: one sent message in Sent Items, never received.
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('0a000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'user1', '[email protected]', 'OUTLOOK', true, NOW(), NOW());
+
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('0a000000-0000-0000-0000-0000000000a1', 'outlook-conversation-1', '0a000000-0000-0000-0000-000000000001', true, true, NOW(), NOW()),
+ ('0a000000-0000-0000-0000-0000000000a2', 'outlook-conversation-2', '0a000000-0000-0000-0000-000000000001', false, true, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_read, is_starred, is_sent, is_draft, has_attachments, internal_date_ts, mailbox_state, created_at, updated_at)
+VALUES
+ ('0a000000-0000-0000-0000-0000000000b1', '0a000000-0000-0000-0000-0000000000a1', '0a000000-0000-0000-0000-000000000001', 'outlook-message-1', true, false, false, false, false, '2025-01-01T10:00:00Z',
+ '{"in_inbox":true,"in_trash":false,"in_junk":false,"attention":"primary"}', NOW(), NOW()),
+ ('0a000000-0000-0000-0000-0000000000b2', '0a000000-0000-0000-0000-0000000000a2', '0a000000-0000-0000-0000-000000000001', 'outlook-message-2', true, false, true, false, false, '2025-01-01T11:00:00Z',
+ '{"in_inbox":false,"in_trash":false,"in_junk":false,"attention":"primary"}', NOW(), NOW());
diff --git a/crates/email/src/domain/service/followup.rs b/crates/email/src/domain/service/followup.rs
index dd11bcf4cd..b66e9e2666 100644
--- a/crates/email/src/domain/service/followup.rs
+++ b/crates/email/src/domain/service/followup.rs
@@ -4,7 +4,7 @@ use uuid::Uuid;
use crate::domain::{
followup::{EmailFollowupMailbox, EmailFollowupRepo, FollowupThread, ReminderThreadFilter},
- models::{EmailErr, label::system_labels},
+ models::{EmailErr, UserProvider, label::system_labels},
ports::{EmailMessageEnqueuer, EmailRepo},
};
use frecency::domain::ports::FrecencyQueryService;
@@ -159,11 +159,26 @@ where
if messages.is_empty() {
return Ok(None);
}
- let labels = self
- .email_repo
- .labels_by_thread_ids(&[thread_id])
- .await
- .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+ let unavailable = if link.provider == UserProvider::Outlook {
+ self.email_repo
+ .mailbox_action_messages(link.id, thread_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .iter()
+ .any(|message| message.is_present && (message.in_trash || message.in_junk))
+ } else {
+ self.email_repo
+ .labels_by_thread_ids(&[thread_id])
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .iter()
+ .any(|label| {
+ matches!(
+ label.provider_label_id.as_str(),
+ system_labels::TRASH | system_labels::SPAM
+ )
+ })
+ };
let latest = self
.email_repo
.latest_content_message_rows(&[thread_id])
@@ -182,12 +197,7 @@ where
.email_repo
.followup_returned_at(thread_id, link.id)
.await?,
- unavailable: labels.iter().any(|label| {
- matches!(
- label.provider_label_id.as_str(),
- system_labels::TRASH | system_labels::SPAM
- )
- }),
+ unavailable,
messages,
}))
}
@@ -212,24 +222,16 @@ where
.map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
.filter(|link| link.id == facts.link_id)
.ok_or(EmailErr::ThreadNotFound)?;
- let label = self
- .email_repo
- .list_labels_by_link_id(link.id)
- .await
- .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
- .into_iter()
- .find(|label| label.provider_label_id == system_labels::INBOX)
- .ok_or(EmailErr::LabelNotFound)?;
// Persist the explicit return before provider work/events can observe
// INBOX, so sent-only metadata reconciliation sees the same intent.
- // A failed label write leaves a timestamp on an archived thread, which
+ // A failed inbox write leaves a timestamp on an archived thread, which
// remains excluded by inbox visibility and is retried by the workflow.
if visible {
self.email_repo
.set_followup_returned_at(thread_id, link_id, returned_at)
.await?;
}
- self.update_thread_labels_with_actor(&link, thread_id, label.id, visible, Some(user))
+ self.set_thread_inbox(&link, thread_id, user, visible)
.await?;
if !visible {
self.email_repo
diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rs
index e8188ca441..910758b36a 100644
--- a/crates/email/src/domain/service/thread_labels.rs
+++ b/crates/email/src/domain/service/thread_labels.rs
@@ -217,14 +217,21 @@ where
self.ensure_thread_has_received_messages(thread_id, link.id)
.await?;
}
+ self.set_thread_inbox(&link, thread_id, macro_id, !archived)
+ .await
+ }
+
+ /// Outlook folders have no INBOX label row; only Gmail stores one.
+ pub(super) async fn set_thread_inbox(
+ &self,
+ link: &Link,
+ thread_id: Uuid,
+ actor: macro_user_id::user_id::MacroUserIdStr<'static>,
+ in_inbox: bool,
+ ) -> Result<(), EmailErr> {
if link.provider == UserProvider::Outlook {
- self.queue_outlook_action(
- &link,
- thread_id,
- macro_id,
- MailboxAction::Archived(archived),
- )
- .await?;
+ self.queue_outlook_action(link, thread_id, actor, MailboxAction::Archived(!in_inbox))
+ .await?;
return Ok(());
}
let label = self
@@ -235,7 +242,7 @@ where
.into_iter()
.find(|label| label.provider_label_id == system_labels::INBOX)
.ok_or(EmailErr::LabelNotFound)?;
- self.update_thread_labels_with_actor(&link, thread_id, label.id, !archived, Some(macro_id))
+ self.update_thread_labels_with_actor(link, thread_id, label.id, in_inbox, Some(actor))
.await?;
Ok(())
}
diff --git a/crates/email/src/outbound/email_pg_repo/test/followup.rs b/crates/email/src/outbound/email_pg_repo/test/followup.rs
index d3ac6a5b63..f312a9191a 100644
--- a/crates/email/src/outbound/email_pg_repo/test/followup.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/followup.rs
@@ -1,6 +1,327 @@
use super::thread_unread::service;
use super::*;
-use crate::domain::followup::EmailFollowupMailbox;
+use crate::domain::followup::{EmailFollowupMailbox, EmailFollowupRepo};
+use crate::domain::models::EmailErr;
+use crate::domain::models::mailbox_action::{MailboxAction, MailboxOperationState};
+
+const OUTLOOK_LINK: Uuid = uuid::uuid!("0a000000-0000-0000-0000-000000000001");
+const OUTLOOK_RECEIVED: Uuid = uuid::uuid!("0a000000-0000-0000-0000-0000000000a1");
+const OUTLOOK_SENT_ONLY: Uuid = uuid::uuid!("0a000000-0000-0000-0000-0000000000a2");
+
+async fn archive_operations(
+ repo: &EmailPgRepo,
+ thread: Uuid,
+) -> anyhow::Result<Vec<(MailboxAction, bool)>> {
+ Ok(repo
+ .thread_mailbox_operations(OUTLOOK_LINK, thread)
+ .await?
+ .into_iter()
+ .filter(|operation| matches!(operation.action, MailboxAction::Archived(_)))
+ .map(|operation| {
+ (
+ operation.action,
+ matches!(operation.state, MailboxOperationState::Pending),
+ )
+ })
+ .collect())
+}
+
+async fn unavailable(
+ mailbox: &impl EmailFollowupMailbox,
+ owner: &MacroUserIdStr<'static>,
+) -> anyhow::Result<bool> {
+ Ok(mailbox
+ .followup_thread(owner.clone(), OUTLOOK_RECEIVED)
+ .await?
+ .unwrap()
+ .unavailable)
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_outlook_threads"))
+)]
+async fn outlook_followup_moves_the_thread_through_mailbox_commands(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let mailbox = service(pool.clone());
+ let returned_at = Utc.with_ymd_and_hms(2026, 1, 2, 3, 4, 5).unwrap();
+ let facts = mailbox
+ .followup_thread(owner.clone(), OUTLOOK_RECEIVED)
+ .await?
+ .unwrap();
+ assert_eq!(facts.link_id, OUTLOOK_LINK);
+ assert!(facts.inbox_visible);
+ assert!(!facts.unavailable);
+
+ mailbox
+ .set_followup_inbox(owner.clone(), OUTLOOK_RECEIVED, OUTLOOK_LINK, false, None)
+ .await?;
+ let archived = mailbox
+ .email_repo
+ .thread_by_id(OUTLOOK_RECEIVED)
+ .await?
+ .unwrap();
+ assert!(!archived.inbox_visible);
+ assert_eq!(
+ archive_operations(&mailbox.email_repo, OUTLOOK_RECEIVED).await?,
+ vec![(MailboxAction::Archived(true), true)]
+ );
+
+ mailbox
+ .set_followup_inbox(
+ owner.clone(),
+ OUTLOOK_RECEIVED,
+ OUTLOOK_LINK,
+ true,
+ Some(returned_at),
+ )
+ .await?;
+ let returned = mailbox
+ .email_repo
+ .thread_by_id(OUTLOOK_RECEIVED)
+ .await?
+ .unwrap();
+ assert!(returned.inbox_visible);
+ assert_eq!(
+ mailbox
+ .email_repo
+ .followup_returned_at(OUTLOOK_RECEIVED, OUTLOOK_LINK)
+ .await?,
+ Some(returned_at)
+ );
+ assert_eq!(
+ archive_operations(&mailbox.email_repo, OUTLOOK_RECEIVED).await?,
+ vec![(MailboxAction::Archived(false), true)]
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_outlook_threads"))
+)]
+async fn outlook_followup_returns_a_sent_only_thread_to_the_inbox(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let mailbox = service(pool.clone());
+ let facts = mailbox
+ .followup_thread(owner.clone(), OUTLOOK_SENT_ONLY)
+ .await?
+ .unwrap();
+ assert!(facts.messages.iter().all(|message| message.outgoing));
+ assert!(!facts.inbox_visible);
+
+ mailbox
+ .set_followup_inbox(
+ owner.clone(),
+ OUTLOOK_SENT_ONLY,
+ OUTLOOK_LINK,
+ true,
+ Some(Utc::now()),
+ )
+ .await?;
+ let returned = mailbox
+ .email_repo
+ .thread_by_id(OUTLOOK_SENT_ONLY)
+ .await?
+ .unwrap();
+ assert!(returned.inbox_visible);
+ assert!(
+ returned.latest_inbound_message_ts.is_none(),
+ "must not invent an inbound message"
+ );
+
+ mailbox
+ .set_followup_inbox(owner, OUTLOOK_SENT_ONLY, OUTLOOK_LINK, false, None)
+ .await?;
+ let archived = mailbox
+ .email_repo
+ .thread_by_id(OUTLOOK_SENT_ONLY)
+ .await?
+ .unwrap();
+ assert!(!archived.inbox_visible);
+ assert_eq!(
+ mailbox
+ .email_repo
+ .followup_returned_at(OUTLOOK_SENT_ONLY, OUTLOOK_LINK)
+ .await?,
+ None
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_outlook_threads"))
+)]
+async fn outlook_followup_is_unavailable_in_trash_or_junk(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let mailbox = service(pool.clone());
+ sqlx::query!(
+ r#"UPDATE email_messages SET mailbox_state = mailbox_state || '{"in_inbox":false,"in_trash":true}' WHERE thread_id = $1"#,
+ OUTLOOK_RECEIVED
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ unavailable(&mailbox, &owner).await?,
+ "synced into Deleted Items"
+ );
+ assert_return_refused(&mailbox, &mailbox.email_repo, &owner).await?;
+ sqlx::query!(
+ r#"UPDATE email_messages SET mailbox_state = mailbox_state || '{"in_inbox":true,"in_trash":false}' WHERE thread_id = $1"#,
+ OUTLOOK_RECEIVED
+ )
+ .execute(&pool)
+ .await?;
+ assert!(!unavailable(&mailbox, &owner).await?);
+
+ queue(&mailbox.email_repo, &owner, MailboxAction::Junk(true)).await?;
+ assert!(
+ unavailable(&mailbox, &owner).await?,
+ "pending move to Junk Email"
+ );
+ assert_return_refused(&mailbox, &mailbox.email_repo, &owner).await?;
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_outlook_threads"))
+)]
+async fn outlook_followup_ignores_a_category_named_trash(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let mailbox = service(pool.clone());
+ sqlx::query!(
+ "INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type)
+ VALUES ($1, $2, 'TRASH', 'TRASH', 'Show', 'LabelShow', 'User')",
+ Uuid::now_v7(),
+ OUTLOOK_LINK
+ )
+ .execute(&pool)
+ .await?;
+ queue(
+ &mailbox.email_repo,
+ &owner,
+ MailboxAction::Category {
+ name: "TRASH".into(),
+ present: true,
+ },
+ )
+ .await?;
+ assert!(
+ !unavailable(&mailbox, &owner).await?,
+ "a category named TRASH is not the trash folder"
+ );
+ Ok(())
+}
+
+async fn queue(
+ repo: &EmailPgRepo,
+ owner: &MacroUserIdStr<'static>,
+ action: MailboxAction,
+) -> anyhow::Result<()> {
+ let messages = repo
+ .mailbox_action_messages(OUTLOOK_LINK, OUTLOOK_RECEIVED)
+ .await?;
+ repo.enqueue_mailbox_action(
+ OUTLOOK_LINK,
+ owner.clone(),
+ &action,
+ &action.targets(&messages),
+ )
+ .await?;
+ Ok(())
+}
+
+async fn assert_return_refused(
+ mailbox: &impl EmailFollowupMailbox,
+ repo: &EmailPgRepo,
+ owner: &MacroUserIdStr<'static>,
+) -> anyhow::Result<()> {
+ assert!(matches!(
+ mailbox
+ .set_followup_inbox(
+ owner.clone(),
+ OUTLOOK_RECEIVED,
+ OUTLOOK_LINK,
+ true,
+ Some(Utc::now()),
+ )
+ .await,
+ Err(EmailErr::ThreadNotFound)
+ ));
+ assert!(archive_operations(repo, OUTLOOK_RECEIVED).await?.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn gmail_followup_is_unavailable_with_trash_or_spam_labels(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread = uuid::uuid!("11111111-1111-1111-1111-111111111111");
+ let link = uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
+ let message = uuid::uuid!("11111111-aaaa-aaaa-aaaa-111111111111");
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let mailbox = service(pool.clone());
+ assert!(
+ !mailbox
+ .followup_thread(owner.clone(), thread)
+ .await?
+ .unwrap()
+ .unavailable
+ );
+ for system_label in ["TRASH", "SPAM"] {
+ let label = sqlx::query_scalar!(
+ "INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type)
+ VALUES ($1, $2, $3, $4, 'Hide', 'LabelHide', 'System') RETURNING id",
+ Uuid::now_v7(),
+ link,
+ system_label,
+ system_label
+ )
+ .fetch_one(&pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO email_message_labels (message_id, label_id) VALUES ($1, $2)",
+ message,
+ label
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ mailbox
+ .followup_thread(owner.clone(), thread)
+ .await?
+ .unwrap()
+ .unavailable,
+ "{system_label}"
+ );
+ assert!(matches!(
+ mailbox
+ .set_followup_inbox(owner.clone(), thread, link, true, Some(Utc::now()))
+ .await,
+ Err(EmailErr::ThreadNotFound)
+ ));
+ sqlx::query!("DELETE FROM email_labels WHERE id = $1", label)
+ .execute(&pool)
+ .await?;
+ }
+ Ok(())
+}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
diff --git a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs
index 967c90b4a0..d8d8d9d3ec 100644
--- a/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/thread_archive.rs
@@ -336,3 +336,34 @@ async fn unarchive_rejects_sent_only_and_drafts_but_accepts_self_addressed_mail(
assert_inbox_state(&service.email_repo, self_addressed, true).await?;
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_outlook_threads"))
+)]
+async fn outlook_archive_moves_the_thread_through_mailbox_commands(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = service(pool);
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let received = Uuid::parse_str("0a000000-0000-0000-0000-0000000000a1")?;
+ let sent_only = Uuid::parse_str("0a000000-0000-0000-0000-0000000000a2")?;
+ let inbox_visible = |thread| {
+ let repo = &service.email_repo;
+ async move { anyhow::Ok(repo.thread_by_id(thread).await?.unwrap().inbox_visible) }
+ };
+ for archived in [true, false] {
+ service
+ .set_thread_archived_impl(owner.clone(), received, archived)
+ .await?;
+ assert_eq!(inbox_visible(received).await?, !archived);
+ }
+ assert!(matches!(
+ service
+ .set_thread_archived_impl(owner, sent_only, false)
+ .await,
+ Err(EmailErr::ThreadHasNoInboundMessages)
+ ));
+ assert!(!inbox_visible(sent_only).await?);
+ Ok(())
+}
diff --git a/crates/reminders/AGENTS.md b/crates/reminders/AGENTS.md
index 5a84b25b6f..f830774fe4 100644
--- a/crates/reminders/AGENTS.md
+++ b/crates/reminders/AGENTS.md
@@ -37,7 +37,9 @@ follow-up reminders.
## Checks
-- `cargo test -p reminders` (`SQLX_OFFLINE` unset).
+- `cargo test -p reminders --all-features` (`SQLX_OFFLINE` unset). The
+ Postgres tests sit behind the `postgres` feature; the Outlook follow-up tests
+ there run the real `email` service over Postgres.
## Related
diff --git a/crates/reminders/Cargo.toml b/crates/reminders/Cargo.toml
index de1d4c310d..612eddcdd8 100644
--- a/crates/reminders/Cargo.toml
+++ b/crates/reminders/Cargo.toml
@@ -54,6 +54,10 @@ uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+crm = { path = "../crm", default-features = false, features = ["ports"] }
+email = { path = "../email", default-features = false, features = ["outbound"] }
+entity_access_management = { path = "../entity_access_management" }
+frecency = { path = "../frecency", features = ["postgres"] }
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
model_user = { path = "../model_user" }
diff --git a/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs b/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs
index 40b6ec2a80..c6cfee88d7 100644
--- a/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs
+++ b/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs
@@ -892,3 +892,5 @@ async fn undo_and_archive_rollback_restore_original_inbox_order(pool: PgPool) {
service.mailbox.0.lock().unwrap().archive_fails = false;
}
}
+
+mod outlook;
diff --git a/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test/outlook.rs b/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test/outlook.rs
new file mode 100644
index 0000000000..f75f54580d
--- /dev/null
+++ b/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test/outlook.rs
@@ -0,0 +1,172 @@
+use super::*;
+use crm::domain::service::NoOpCrmService;
+use email::domain::{ports::NoOpEnqueuer, service::EmailServiceImpl};
+use email::outbound::EmailPgRepo;
+use entity_access_management::{
+ domain::service::EntityAccessManagementServiceImpl, outbound::PgRepository,
+};
+use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage};
+
+type Email = EmailServiceImpl<
+ EmailPgRepo,
+ FrecencyQueryServiceImpl<FrecencyPgStorage>,
+ NoOpEnqueuer,
+ NoOpCrmService,
+ EntityAccessManagementServiceImpl<PgRepository>,
+>;
+
+struct Delivered;
+
+impl ReminderDispatch for Delivered {
+ async fn sweep(&self) -> Result<SweepSummary, ReminderError> {
+ Ok(SweepSummary::default())
+ }
+
+ async fn deliver(&self, _: DueFiring) -> Result<DeliveryOutcome, ReminderError> {
+ Ok(DeliveryOutcome::Delivered)
+ }
+}
+
+async fn outlook(pool: PgPool) -> EmailFollowupService<PgRemindersRepo, Email, FixedClock> {
+ let owner = user();
+ sqlx::query!(r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, 'followup', '[email protected]', 'followup')"#, Uuid::now_v7()).execute(&pool).await.unwrap();
+ sqlx::query!(r#"INSERT INTO "User" (id, email, macro_user_id) SELECT $1, '[email protected]', id FROM macro_user WHERE email = '[email protected]'"#, owner.as_ref()).execute(&pool).await.unwrap();
+ sqlx::query!("INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active) VALUES ($1, $2, 'followup', '[email protected]', 'OUTLOOK', true)", LINK, owner.as_ref()).execute(&pool).await.unwrap();
+ sqlx::query!(
+ "INSERT INTO email_threads (id, link_id, inbox_visible) VALUES ($1, $2, true)",
+ THREAD,
+ LINK
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_read, is_starred, is_sent, is_draft, has_attachments, internal_date_ts, mailbox_state)
+ VALUES ($1, $2, $3, 'outlook-message', true, false, false, false, false, now() - interval '1 day',
+ '{"in_inbox":true,"in_trash":false,"in_junk":false,"attention":"primary"}')"#,
+ Uuid::now_v7(),
+ THREAD,
+ LINK
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ EmailFollowupService {
+ repo: PgRemindersRepo::new(pool.clone()),
+ mailbox: EmailServiceImpl::new(
+ EmailPgRepo::new(pool.clone()),
+ FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
+ NoOpEnqueuer,
+ NoOpCrmService,
+ EntityAccessManagementServiceImpl::new(PgRepository::new(pool)),
+ 0,
+ ),
+ clock: FixedClock(Utc::now()),
+ }
+}
+
+async fn inbox_visible(pool: &PgPool) -> bool {
+ sqlx::query_scalar!(
+ "SELECT inbox_visible FROM email_threads WHERE id = $1",
+ THREAD
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+async fn pending_mailbox_intents(pool: &PgPool) -> Vec<serde_json::Value> {
+ sqlx::query_scalar!(
+ "SELECT intent FROM email_mailbox_commands WHERE link_id = $1 AND status = 'pending' ORDER BY accepted_order",
+ LINK
+ )
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn outlook_reminder_archives_then_returns_the_thread_when_due(pool: PgPool) {
+ let service = outlook(pool.clone()).await;
+ let created = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ assert_eq!(created.state, FollowupState::Pending);
+ assert!(!inbox_visible(&pool).await);
+
+ let outcome = EmailReminderDispatch::new(Delivered, service.clone())
+ .deliver(DueFiring {
+ reminder_id: created.reminder_id,
+ scheduled_for: created.remind_at,
+ })
+ .await
+ .unwrap();
+ assert_eq!(outcome, DeliveryOutcome::Delivered);
+ assert!(inbox_visible(&pool).await);
+ assert_eq!(
+ service.get(user(), THREAD).await.unwrap().unwrap().state,
+ FollowupState::Returned
+ );
+ assert_eq!(
+ pending_mailbox_intents(&pool).await,
+ vec![
+ serde_json::json!({"kind": "archived", "value": true}),
+ serde_json::json!({"kind": "archived", "value": false}),
+ ]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn stuck_outlook_returning_reminder_reconciles_on_get(pool: PgPool) {
+ let service = outlook(pool.clone()).await;
+ sqlx::query!(
+ "UPDATE email_links SET is_sync_active = false WHERE id = $1",
+ LINK
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .is_err()
+ );
+ let stuck = service
+ .repo
+ .thread_followup(&user(), THREAD)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(stuck.followup.state, FollowupState::Returning);
+
+ sqlx::query!(
+ "UPDATE email_links SET is_sync_active = true WHERE id = $1",
+ LINK
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let healed = service.get(user(), THREAD).await.unwrap().unwrap();
+ assert_eq!(healed.state, FollowupState::Removed);
+ assert!(inbox_visible(&pool).await);
+ assert_eq!(
+ pending_mailbox_intents(&pool).await,
+ vec![serde_json::json!({"kind": "archived", "value": false})]
+ );
+}