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): move the draft to the new inbox when the sender is switched (#3740)

gbirmandda525caa1fa
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsx
index 772a7382e0..db75964da4 100644
--- a/js/app/packages/block-email/component/BaseInput.tsx
+++ b/js/app/packages/block-email/component/BaseInput.tsx
@@ -809,6 +809,15 @@ export function BaseInput(props: {
if (draftSaveTimer) window.clearTimeout(draftSaveTimer);
});
+ // Persist the draft immediately when the user switches the sending inbox, even
+ // without a text edit, so it moves to the new inbox and the choice survives a
+ // refresh. Driven by the explicit switch (below) rather than inbox reactivity.
+ const persistDraftOnSenderSwitch = (linkId: string) => {
+ form().setSelectedFromLink(linkId);
+ if (draftSaveTimer) window.clearTimeout(draftSaveTimer);
+ void executeSaveDraft();
+ };
+
// After a send, the bottom input stays mounted and its replyingTo flips to
// the just-sent message once the thread refetches. Cancel the inhibited
// post-send save and re-enable saves so a fresh edit under the new form
@@ -1455,7 +1464,7 @@ export function BaseInput(props: {
<FromInboxSelector
links={emailLinksQuery.data?.links ?? []}
activeLinkId={activeLinkId()}
- onSelect={(id) => form().setSelectedFromLink(id)}
+ onSelect={persistDraftOnSenderSwitch}
/>
</div>
</div>
diff --git a/rust/cloud-storage/.sqlx/query-8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024.json b/rust/cloud-storage/.sqlx/query-8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024.json
new file mode 100644
index 0000000000..4163a5425a
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM email_messages\n WHERE id = $1 AND thread_id = $2 AND is_draft = true AND is_sent = false\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e8bf9c53f71988ac7364aef5680e3cb74f7ddc5bacda3caf78db4b8672a8cf72.json b/rust/cloud-storage/.sqlx/query-e8bf9c53f71988ac7364aef5680e3cb74f7ddc5bacda3caf78db4b8672a8cf72.json
new file mode 100644
index 0000000000..5d56d3b171
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e8bf9c53f71988ac7364aef5680e3cb74f7ddc5bacda3caf78db4b8672a8cf72.json
@@ -0,0 +1,162 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id, provider_id, thread_id, provider_thread_id, replying_to_id,\n global_id, link_id, provider_history_id, internal_date_ts, snippet,\n size_estimate, subject, sent_at, has_attachments, is_read, is_starred,\n is_sent, is_draft, body_text, body_html_sanitized, body_macro,\n headers_jsonb, created_at, updated_at\n FROM email_messages\n WHERE is_draft = true\n AND provider_id IS NULL\n AND replying_to_id = ANY($1)\n AND link_id = ANY($2)\n AND thread_id <> $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "provider_thread_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "global_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "provider_history_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "internal_date_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "snippet",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "size_estimate",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 11,
+ "name": "subject",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 13,
+ "name": "has_attachments",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 14,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 15,
+ "name": "is_starred",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 17,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 18,
+ "name": "body_text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 19,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 20,
+ "name": "body_macro",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 21,
+ "name": "headers_jsonb",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 22,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 23,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "UuidArray",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "e8bf9c53f71988ac7364aef5680e3cb74f7ddc5bacda3caf78db4b8672a8cf72"
+}
diff --git a/rust/cloud-storage/email/fixtures/email_draft.sql b/rust/cloud-storage/email/fixtures/email_draft.sql
index ecc33fd7df..8c0610e5a9 100644
--- a/rust/cloud-storage/email/fixtures/email_draft.sql
+++ b/rust/cloud-storage/email/fixtures/email_draft.sql
@@ -60,3 +60,29 @@ VALUES
INSERT INTO email_message_labels (message_id, label_id)
VALUES
('ee000003-0000-0000-0000-000000000003', 'bb000001-0000-0000-0000-000000000001');
+
+-- thread 3 + msg4: a draft that is the only message in its thread
+-- (for testing empty-thread cleanup when a draft is deleted)
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('33333333-3333-3333-3333-333333333333', NULL, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false, true, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('ee000004-0000-0000-0000-000000000004', '33333333-3333-3333-3333-333333333333', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ 'c0000001-0000-0000-0000-000000000001', 'Draft only thread', true, false, true, false, '2025-03-01 12:00:00+00', '2025-03-01 12:00:00+00');
+
+-- A second inbox (cccc) + msg5: a reply draft to msg1 that was moved here by
+-- switching the sender (lives in a different thread) — for cross_inbox_reply_drafts.
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES
+ ('cccccccc-0000-0000-0000-0000000000c4', NULL, 'cccccccc-cccc-cccc-cccc-cccccccccccc', false, true, NOW(), NOW());
+
+INSERT INTO email_messages (id, thread_id, link_id, from_contact_id, replying_to_id, subject, is_read, is_sent, is_draft, has_attachments, created_at, updated_at)
+VALUES
+ ('ee000005-0000-0000-0000-000000000005', 'cccccccc-0000-0000-0000-0000000000c4', 'cccccccc-cccc-cccc-cccc-cccccccccccc',
+ 'c0000001-0000-0000-0000-000000000001', 'ee000001-0000-0000-0000-000000000001', 'Re: Hello World', true, false, true, false, '2025-04-01 10:00:00+00', '2025-04-01 10:00:00+00');
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 3ae371d033..ae04c4a27d 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -103,6 +103,16 @@ pub trait EmailRepo: Send + Sync + 'static {
limit: i64,
) -> impl Future<Output = Result<Vec<MessageRow>, Self::Err>> + Send;
+ /// Find macro reply drafts (across the given inboxes) that reply to any of
+ /// `replying_to_ids` but live in a thread other than `exclude_thread_id` —
+ /// i.e. a reply moved to another inbox by switching the sender.
+ fn cross_inbox_reply_drafts(
+ &self,
+ replying_to_ids: &[Uuid],
+ link_ids: &[Uuid],
+ exclude_thread_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<MessageRow>, Self::Err>> + Send;
+
/// Fetch sender contact info for a set of message IDs, keyed by message ID.
fn senders_by_message_ids(
&self,
@@ -161,6 +171,13 @@ pub trait EmailRepo: Send + Sync + 'static {
replying_to_id: Uuid,
) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;
+ /// Delete a draft message and its thread if the thread is left empty.
+ fn delete_draft_message(
+ &self,
+ message_id: Uuid,
+ thread_db_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
/// Upsert contacts from the parsed addresses. Must be called outside a transaction
/// to avoid deadlocks (contacts are shared across messages).
fn upsert_contacts(
diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rs
index d6ff5aaefd..d1e954c532 100644
--- a/rust/cloud-storage/email/src/domain/service/draft.rs
+++ b/rust/cloud-storage/email/src/domain/service/draft.rs
@@ -47,7 +47,8 @@ where
let link_id = link.id;
let accessible_link_ids: Vec<Uuid> = accessible_inboxes.iter().map(|l| l.id).collect();
- self.validate_existing_message(link_id, &mut input).await?;
+ self.validate_existing_message(link_id, &accessible_link_ids, &mut input)
+ .await?;
self.validate_replying_to(link_id, &accessible_link_ids, &mut input)
.await?;
@@ -121,6 +122,7 @@ where
async fn validate_existing_message(
&self,
link_id: Uuid,
+ accessible_link_ids: &[Uuid],
input: &mut CreateDraftInput,
) -> Result<(), EmailErr> {
let Some(db_id) = input.db_id else {
@@ -129,7 +131,7 @@ where
let msg = self
.email_repo
- .get_simple_message(db_id, &[link_id])
+ .get_simple_message(db_id, accessible_link_ids)
.await
.map_err(anyhow::Error::from)?
.ok_or(EmailErr::MessageNotFound(db_id))?;
@@ -138,6 +140,22 @@ where
return Err(EmailErr::MessageAlreadySent(db_id));
}
+ if msg.link_id != link_id {
+ // The sender was switched to a different inbox. A draft belongs to a
+ // single inbox, so discard it (and its now-empty thread) and create a
+ // fresh draft in the sending inbox; validate_replying_to re-derives
+ // the thread from the reply target.
+ self.email_repo
+ .delete_draft_message(msg.db_id, msg.thread_db_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+ input.db_id = None;
+ input.provider_id = None;
+ input.thread_db_id = None;
+ input.provider_thread_id = None;
+ return Ok(());
+ }
+
input.thread_db_id = Some(msg.thread_db_id);
input.provider_thread_id = msg.provider_thread_id;
diff --git a/rust/cloud-storage/email/src/domain/service/thread.rs b/rust/cloud-storage/email/src/domain/service/thread.rs
index adfe868ac7..c3ad22733a 100644
--- a/rust/cloud-storage/email/src/domain/service/thread.rs
+++ b/rust/cloud-storage/email/src/domain/service/thread.rs
@@ -56,7 +56,7 @@ where
return Ok(None);
};
- let message_rows = self
+ let mut message_rows = self
.email_repo
.messages_by_thread_id_paginated(thread_id, offset, limit)
.await
@@ -69,7 +69,7 @@ where
}
);
- let message_ids: Vec<Uuid> = message_rows.iter().map(|m| m.db_id).collect();
+ let mut message_ids: Vec<Uuid> = message_rows.iter().map(|m| m.db_id).collect();
if message_ids.is_empty() {
return Ok(Some(ThreadFetchResult {
@@ -83,6 +83,27 @@ where
}));
}
+ // Surface a reply draft the caller moved to another of their inboxes by
+ // switching the sender: it lives in a different thread, so pull it in here
+ // (matched by the message it replies to) and let the reply reopen with it.
+ if let Ok(macro_id) = receipt.get_authenticated_user() {
+ let accessible = self
+ .email_repo
+ .inboxes_for_macro_id(macro_id.clone())
+ .await
+ .map_err(anyhow::Error::from)?;
+ let link_ids: Vec<Uuid> = accessible.iter().map(|l| l.id).collect();
+ let moved_drafts = self
+ .email_repo
+ .cross_inbox_reply_drafts(&message_ids, &link_ids, thread_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+ for draft in moved_drafts {
+ message_ids.push(draft.db_id);
+ message_rows.push(draft);
+ }
+ }
+
let (senders, recipients, labels) = tokio::try_join!(
async {
self.email_repo
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs
index d42d608950..67f0d64af5 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs
@@ -342,6 +342,50 @@ pub(crate) async fn get_draft_replying_to(
Ok(row.map(SimpleMessageInfo::from))
}
+/// Delete an unsent draft in the given thread (dependent rows cascade) and, if
+/// the thread is left empty, delete the thread too. Errors if no matching unsent
+/// draft exists in that thread, so sent mail or a mismatched thread is never
+/// touched.
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn delete_draft_message(
+ pool: &PgPool,
+ message_id: Uuid,
+ thread_db_id: Uuid,
+) -> Result<(), sqlx::Error> {
+ let mut tx = pool.begin().await?;
+
+ let deleted = sqlx::query!(
+ r#"
+ DELETE FROM email_messages
+ WHERE id = $1 AND thread_id = $2 AND is_draft = true AND is_sent = false
+ "#,
+ message_id,
+ thread_db_id,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ if deleted.rows_affected() == 0 {
+ return Err(sqlx::Error::RowNotFound);
+ }
+
+ let messages_remain = sqlx::query_scalar!(
+ r#"SELECT EXISTS(SELECT 1 FROM email_messages WHERE thread_id = $1) AS "exists!""#,
+ thread_db_id
+ )
+ .fetch_one(&mut *tx)
+ .await?;
+
+ if !messages_remain {
+ sqlx::query!("DELETE FROM email_threads WHERE id = $1", thread_db_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ tx.commit().await?;
+ Ok(())
+}
+
/// Upsert or delete a scheduled message based on send_time.
pub(super) async fn process_scheduled_message(
tx: &mut sqlx::PgConnection,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
index b3a727276e..2a9ccdca3c 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
@@ -125,6 +125,16 @@ impl EmailRepo for EmailPgRepo {
thread::messages_by_thread_id_paginated(&self.pool, thread_id, offset, limit).await
}
+ async fn cross_inbox_reply_drafts(
+ &self,
+ replying_to_ids: &[Uuid],
+ link_ids: &[Uuid],
+ exclude_thread_id: Uuid,
+ ) -> Result<Vec<MessageRow>, Self::Err> {
+ thread::cross_inbox_reply_drafts(&self.pool, replying_to_ids, link_ids, exclude_thread_id)
+ .await
+ }
+
async fn senders_by_message_ids(
&self,
message_ids: &[Uuid],
@@ -190,6 +200,14 @@ impl EmailRepo for EmailPgRepo {
message::get_draft_replying_to(&self.pool, link_id, replying_to_id).await
}
+ async fn delete_draft_message(
+ &self,
+ message_id: Uuid,
+ thread_db_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ message::delete_draft_message(&self.pool, message_id, thread_db_id).await
+ }
+
async fn upsert_contacts(
&self,
link_id: Uuid,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs
index 643554f98c..ac56a5c721 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs
@@ -165,6 +165,124 @@ async fn test_get_draft_replying_to_wrong_link(pool: Pool<Postgres>) -> anyhow::
Ok(())
}
+// ── delete_draft_message ──────────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn test_delete_draft_message_keeps_nonempty_thread(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let draft_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+
+ repo.delete_draft_message(draft_id, thread_id).await?;
+
+ assert!(
+ repo.get_simple_message(draft_id, &[link_id])
+ .await?
+ .is_none(),
+ "the draft message should be deleted"
+ );
+ assert!(
+ repo.thread_by_id(thread_id).await?.is_some(),
+ "a thread that still has messages should be kept"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn test_delete_draft_message_removes_empty_thread(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let draft_id = Uuid::parse_str("ee000004-0000-0000-0000-000000000004")?;
+ let thread_id = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;
+
+ repo.delete_draft_message(draft_id, thread_id).await?;
+
+ assert!(
+ repo.thread_by_id(thread_id).await?.is_none(),
+ "a thread left with no messages should be deleted"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn test_delete_draft_message_rejects_sent_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ // ee000003 is a sent message, not a draft; deleting it must not succeed.
+ let sent_id = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;
+ let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;
+
+ assert!(
+ repo.delete_draft_message(sent_id, thread_id).await.is_err(),
+ "deleting a non-draft should error and leave it intact"
+ );
+ assert!(
+ repo.thread_by_id(thread_id).await?.is_some(),
+ "the thread of a non-draft must be untouched"
+ );
+
+ Ok(())
+}
+
+// ── cross_inbox_reply_drafts ──────────────────────────────────────
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn test_cross_inbox_reply_drafts(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool);
+
+ let msg1 = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ let thread1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let own_link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let alt_link = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc")?;
+ let moved_draft = Uuid::parse_str("ee000005-0000-0000-0000-000000000005")?;
+
+ // The reply draft moved to the alt inbox is found, but the same-thread draft
+ // (ee000002 in thread1) is excluded.
+ let found = repo
+ .cross_inbox_reply_drafts(&[msg1], &[own_link, alt_link], thread1)
+ .await?;
+ assert_eq!(
+ found.len(),
+ 1,
+ "should surface only the moved cross-inbox draft"
+ );
+ assert_eq!(found[0].db_id, moved_draft);
+ assert_eq!(found[0].link_id, alt_link);
+
+ // Without the alt inbox in scope, nothing is returned (same-thread draft excluded).
+ let none = repo
+ .cross_inbox_reply_drafts(&[msg1], &[own_link], thread1)
+ .await?;
+ assert!(
+ none.is_empty(),
+ "same-thread drafts and inaccessible inboxes must be excluded"
+ );
+
+ Ok(())
+}
+
// ── upsert_contacts ───────────────────────────────────────────────
#[sqlx::test(
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs
index 40f69947f5..74b081e353 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs
@@ -60,6 +60,42 @@ pub(super) async fn messages_by_thread_id_paginated(
Ok(rows.into_iter().map(MessageRow::from).collect())
}
+/// Find macro drafts that reply to any of the given messages but live in a
+/// different thread within one of the accessible inboxes. These are reply drafts
+/// the user moved to another of their inboxes by switching the sender; surfacing
+/// them lets the original conversation reopen the draft with its sender.
+pub(super) async fn cross_inbox_reply_drafts(
+ pool: &PgPool,
+ replying_to_ids: &[Uuid],
+ link_ids: &[Uuid],
+ exclude_thread_id: Uuid,
+) -> Result<Vec<MessageRow>, sqlx::Error> {
+ let rows = sqlx::query_as!(
+ DbMessageRow,
+ r#"
+ SELECT
+ id, provider_id, thread_id, provider_thread_id, replying_to_id,
+ global_id, link_id, provider_history_id, internal_date_ts, snippet,
+ size_estimate, subject, sent_at, has_attachments, is_read, is_starred,
+ is_sent, is_draft, body_text, body_html_sanitized, body_macro,
+ headers_jsonb, created_at, updated_at
+ FROM email_messages
+ WHERE is_draft = true
+ AND provider_id IS NULL
+ AND replying_to_id = ANY($1)
+ AND link_id = ANY($2)
+ AND thread_id <> $3
+ "#,
+ replying_to_ids,
+ link_ids,
+ exclude_thread_id,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows.into_iter().map(MessageRow::from).collect())
+}
+
/// Insert a new thread record within a transaction.
pub(super) async fn insert_thread(
tx: &mut sqlx::PgConnection,