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
feat(email): correct behavior on creating and deleting drafts (#5940)
Peter Chinman19a988b001be
diff --git a/.sqlx/query-7560f5929cf5e8b1cd8b7afd4cad52a6c1fd612db386416870c4b6bca7f97421.json b/.sqlx/query-7560f5929cf5e8b1cd8b7afd4cad52a6c1fd612db386416870c4b6bca7f97421.jsondeleted file mode 100644index 242f4f5c93..0000000000--- a/.sqlx/query-7560f5929cf5e8b1cd8b7afd4cad52a6c1fd612db386416870c4b6bca7f97421.json+++ /dev/null@@ -1,48 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO calendar_events (\n id, owner_id, source_link_id, ical_uid, title, description, location,\n status, visibility, transparency,\n starts_at, ends_at, start_date, end_date, time_zone,\n recurrence_lines, organizer_email, organizer_name,\n conference_url, conference_provider, sequence, is_read_only,\n canonical_source_kind,\n canonical_source_updated_at,\n reminders_use_default, reminder_overrides,\n created_at, updated_at\n )\n VALUES (\n $1, $2, $3, $4, $5, $6, $7,\n $8, $9, $10,\n $11, $12, $13, $14, $15,\n $16, $17, $18,\n $19, $27, $20, $21, $22, $24,\n $25, $26,\n $23, $24\n )\n ON CONFLICT (owner_id, source_link_id, ical_uid) DO UPDATE SET\n title = EXCLUDED.title,\n description = EXCLUDED.description,\n location = EXCLUDED.location,\n status = EXCLUDED.status,\n visibility = EXCLUDED.visibility,\n transparency = EXCLUDED.transparency,\n starts_at = EXCLUDED.starts_at,\n ends_at = EXCLUDED.ends_at,\n start_date = EXCLUDED.start_date,\n end_date = EXCLUDED.end_date,\n time_zone = EXCLUDED.time_zone,\n recurrence_lines = EXCLUDED.recurrence_lines,\n organizer_email = EXCLUDED.organizer_email,\n organizer_name = EXCLUDED.organizer_name,\n conference_url = EXCLUDED.conference_url,\n conference_provider = EXCLUDED.conference_provider,\n sequence = EXCLUDED.sequence,\n is_read_only = EXCLUDED.is_read_only,\n canonical_source_kind = EXCLUDED.canonical_source_kind,\n canonical_source_updated_at = EXCLUDED.canonical_source_updated_at,\n reminders_use_default = EXCLUDED.reminders_use_default,\n reminder_overrides = EXCLUDED.reminder_overrides,\n updated_at = GREATEST(calendar_events.updated_at, EXCLUDED.updated_at)\n WHERE\n EXCLUDED.sequence > calendar_events.sequence\n OR (\n EXCLUDED.sequence = calendar_events.sequence\n AND EXCLUDED.canonical_source_updated_at\n >= calendar_events.canonical_source_updated_at\n )\n RETURNING id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- "Uuid",- "Text",- "Text",- "Text",- "Text",- "Text",- "Text",- "Text",- "Timestamptz",- "Timestamptz",- "Date",- "Date",- "Text",- "TextArray",- "Text",- "Text",- "Text",- "Int4",- "Bool",- "Text",- "Timestamptz",- "Timestamptz",- "Bool",- "Jsonb",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "7560f5929cf5e8b1cd8b7afd4cad52a6c1fd612db386416870c4b6bca7f97421"-}diff --git a/.sqlx/query-800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35.json b/.sqlx/query-800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35.jsonnew file mode 100644index 0000000000..167fa20e8b--- /dev/null+++ b/.sqlx/query-800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35.json@@ -0,0 +1,23 @@+{+ "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 RETURNING link_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "800ca32851afd60d31bc14325d2a8e9c76d503668d2917266edaecec7cd1ec35"+}diff --git a/.sqlx/query-856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7.json b/.sqlx/query-856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7.jsondeleted file mode 100644index 8efe010549..0000000000--- a/.sqlx/query-856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7.json+++ /dev/null@@ -1,18 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO bot_tokens (id, bot_id, token_hash, token_prefix, revoked_at)\n VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() ELSE NULL END)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Bytea",- "Text",- "Bool"- ]- },- "nullable": []- },- "hash": "856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7"-}diff --git a/.sqlx/query-8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024.json b/.sqlx/query-8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024.jsondeleted file mode 100644index 4163a5425a..0000000000--- a/.sqlx/query-8d8e2f6bf38b4b18f2b47c282a351aee78b249f6d66133c572c39a7ca8e11024.json+++ /dev/null@@ -1,15 +0,0 @@-{- "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/.sqlx/query-cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d.json b/.sqlx/query-cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d.jsondeleted file mode 100644index 3ea560cf3a..0000000000--- a/.sqlx/query-cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT source_link_id, ical_uid\n FROM calendar_events\n WHERE id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "source_link_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "ical_uid",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false- ]- },- "hash": "cbd7fc8fc7f1e6115f065b2a52c656b81d0afbcba06b24ce33da49e66b45657d"-}diff --git a/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json b/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.jsondeleted file mode 100644index f55b5927f0..0000000000--- a/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT digest(convert_to($1, 'UTF8'), 'sha256')",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "digest",- "type_info": "Bytea"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835"-}diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.tsindex 37b498da45..0320d83f42 100644--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.test.ts@@ -30,6 +30,18 @@ describe('mail view presets', () => {expect(getViewPreset('mail', tab)?.groupBy).toBe('date');}});++ it('keeps threads with saved drafts in every thread-listing tab', () => {+ // A saved draft becomes the thread's latest message, flipping the+ // entity's isDraft on. Filtering on 'no-drafts' would eject the whole+ // conversation from its tab, leaving it visible only under Drafts.+ for (const tab of mailTabs.filter((tab) => tab !== 'drafts')) {+ expect(+ getViewPreset('mail', tab)?.clientFilters.and,+ `mail '${tab}' tab must not exclude drafted threads`+ ).not.toContain('no-drafts');+ }+ });});describe('task view presets', () => {diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.tsindex b7076d7c71..78aea04b34 100644--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts@@ -284,6 +284,10 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {mail: {default: 'important',tabs: {+ // No 'no-drafts' on any thread-listing tab: a thread whose latest+ // message is a saved draft must stay in Signal/Noise/Calendar/Sent (it+ // also shows under Drafts). The server counts drafts toward is_signal+ // and inbox visibility for the same reason.important: () => ({filters: defineQueryFilters({include: {@@ -293,7 +297,7 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {},emailView: 'inbox',}),- clientFilters: { and: ['email', 'no-drafts'] },+ clientFilters: { and: ['email'] },groupBy: 'date',}),noise: () => ({@@ -305,7 +309,7 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {},emailView: 'inbox',}),- clientFilters: { and: ['email', 'no-drafts'] },+ clientFilters: { and: ['email'] },groupBy: 'date',}),calendar: () => ({@@ -317,7 +321,7 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {emailView: 'all',}),- clientFilters: { and: ['email', 'no-drafts'] },+ clientFilters: { and: ['email'] },groupBy: 'date',}),drafts: () => ({@@ -335,7 +339,7 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {filters: defineQueryFilters({emailView: 'sent',}),- clientFilters: { and: ['email', 'no-drafts'] },+ clientFilters: { and: ['email'] },groupBy: 'date',}),shared: () => ({diff --git a/apps/web/src/lib/queries/email/draft.ts b/apps/web/src/lib/queries/email/draft.tsindex 6fccb656a7..3bfd9fa20c 100644--- a/apps/web/src/lib/queries/email/draft.ts+++ b/apps/web/src/lib/queries/email/draft.ts@@ -1,6 +1,6 @@import { toast } from '@core/component/Toast/Toast';import { throwOnErr } from '@core/util/result';-import { refetchSoupEntity } from '@queries/soup/cache';+import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';import { emailClient } from '@service-email/client';import type {ApiDraftInput,@@ -99,13 +99,18 @@ export function useDeleteDraftMutation(queryClient.invalidateQueries({queryKey: emailKeys.previews._def,});- // Refetch the thread (not the deleted draft) so it drops from the- // drafts tab without a manual refresh. No-op for compose drafts,- // whose thread is deleted along with the draft, so the refetch- // finds nothing to update.- if (vars.threadId && !vars.skipSoupRefetch) {+ if (vars.skipSoupRefetch) return;+ // Refetch the thread (not the deleted draft) so its draft-derived+ // fields settle. No-op for compose drafts, whose thread is deleted+ // along with the draft, so the refetch finds nothing to update.+ if (vars.threadId) {refetchSoupEntity(vars.threadId, 'emailThread');}+ // Discarding a draft changes view membership — the thread leaves+ // Signal/Drafts and a noise thread re-enters Noise — which a+ // single-entity patch can't express, so the soup list queries must+ // refetch. Mirrors the archive flow in EmailContext.+ invalidateAllSoup();},},callbacksdiff --git a/crates/email/fixtures/email_signal_flag.sql b/crates/email/fixtures/email_signal_flag.sqlindex 3aeafa62d9..f3f671370b 100644--- a/crates/email/fixtures/email_signal_flag.sql+++ b/crates/email/fixtures/email_signal_flag.sql@@ -8,10 +8,15 @@-- Thread e203 (is_signal=true, stale on purpose): only a CATEGORY_PROMOTIONS-- message — update_thread_metadata must clear it.-- Thread e204 (is_signal=true, correct): promotions message + macro draft —--- discarding the draft via delete_draft_message must flip the flag.+-- discarding the draft via delete_draft_message must flip the flag and+-- deflate the draft-inflated metadata (see the UPDATE at the bottom).-- Thread e205 (is_signal=true, correct): unlabeled message from-- [email protected] — same domain as e201's sender but no address-- exception, for the domain-mute fan-out tests.+-- Thread e206 (is_signal=true, correct): SENT-only message + macro draft —+-- a done sent thread the draft resurfaced into the inbox; discarding the+-- draft must send it back out of the inbox (is_signal stays true via the+-- SENT label, but inbox_visible/latest_inbound_message_ts reset).INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)VALUES ('00000000-0000-0000-0000-000000000e01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000e01',@@ -23,14 +28,16 @@ VALUES ('00000000-0000-0000-0000-0000000ce001', '00000000-0000-0000-0000-0000000('00000000-0000-0000-0000-0000000ce003', '00000000-0000-0000-0000-000000000e01', '[email protected]', NOW(), NOW());INSERT INTO email_labels (id, link_id, provider_label_id, name, created_at)-VALUES ('00000000-0000-0000-0000-0000000be001', '00000000-0000-0000-0000-000000000e01', 'CATEGORY_PROMOTIONS', 'CATEGORY_PROMOTIONS', NOW());+VALUES ('00000000-0000-0000-0000-0000000be001', '00000000-0000-0000-0000-000000000e01', 'CATEGORY_PROMOTIONS', 'CATEGORY_PROMOTIONS', NOW()),+ ('00000000-0000-0000-0000-0000000be002', '00000000-0000-0000-0000-000000000e01', 'SENT', 'SENT', NOW());INSERT INTO email_threads (id, link_id, inbox_visible, is_read, is_signal, created_at, updated_at)VALUES ('00000000-0000-0000-0000-00000000e201', '00000000-0000-0000-0000-000000000e01', true, false, true, NOW(), NOW()),('00000000-0000-0000-0000-00000000e202', '00000000-0000-0000-0000-000000000e01', true, false, false, NOW(), NOW()),('00000000-0000-0000-0000-00000000e203', '00000000-0000-0000-0000-000000000e01', true, false, true, NOW(), NOW()),('00000000-0000-0000-0000-00000000e204', '00000000-0000-0000-0000-000000000e01', true, false, true, NOW(), NOW()),- ('00000000-0000-0000-0000-00000000e205', '00000000-0000-0000-0000-000000000e01', true, false, true, NOW(), NOW());+ ('00000000-0000-0000-0000-00000000e205', '00000000-0000-0000-0000-000000000e01', true, false, true, NOW(), NOW()),+ ('00000000-0000-0000-0000-00000000e206', '00000000-0000-0000-0000-000000000e01', true, true, true, NOW(), NOW());INSERT INTO email_messages (id, thread_id, link_id, provider_id, global_id, is_sent, from_contact_id, internal_date_ts,has_attachments, is_read, is_starred, is_draft, created_at, updated_at)@@ -51,9 +58,26 @@ VALUES ('00000000-0000-0000-0000-00000000e501', '00000000-0000-0000-0000-0000000false, false, false, true, NOW(), NOW()),('00000000-0000-0000-0000-00000000e506', '00000000-0000-0000-0000-00000000e205', '00000000-0000-0000-0000-000000000e01','provider-msg-e506', 'gid-e506', FALSE, '00000000-0000-0000-0000-0000000ce003', '2025-01-05 15:00:00 +00:00',- false, false, false, false, NOW(), NOW());+ false, false, false, false, NOW(), NOW()),+ ('00000000-0000-0000-0000-00000000e507', '00000000-0000-0000-0000-00000000e206', '00000000-0000-0000-0000-000000000e01',+ 'provider-msg-e507', 'gid-e507', TRUE, '00000000-0000-0000-0000-0000000ce001', '2025-01-05 16:00:00 +00:00',+ false, true, false, false, NOW(), NOW()),+ ('00000000-0000-0000-0000-00000000e508', '00000000-0000-0000-0000-00000000e206', '00000000-0000-0000-0000-000000000e01',+ NULL, NULL, FALSE, '00000000-0000-0000-0000-0000000ce001', '2025-01-05 17:00:00 +00:00',+ false, true, false, true, NOW(), NOW());INSERT INTO email_message_labels (message_id, label_id)VALUES ('00000000-0000-0000-0000-00000000e502', '00000000-0000-0000-0000-0000000be001'),('00000000-0000-0000-0000-00000000e503', '00000000-0000-0000-0000-0000000be001'),- ('00000000-0000-0000-0000-00000000e504', '00000000-0000-0000-0000-0000000be001');+ ('00000000-0000-0000-0000-00000000e504', '00000000-0000-0000-0000-0000000be001'),+ ('00000000-0000-0000-0000-00000000e507', '00000000-0000-0000-0000-0000000be002');++-- Saving the macro drafts left e204's and e206's metadata draft-inflated:+-- drafts count toward latest_inbound_message_ts (and inbox_visible, already+-- true above). Discarding each draft must reset both.+UPDATE email_threads+SET latest_inbound_message_ts = '2025-01-05 14:00:00 +00:00'+WHERE id = '00000000-0000-0000-0000-00000000e204';+UPDATE email_threads+SET latest_inbound_message_ts = '2025-01-05 17:00:00 +00:00'+WHERE id = '00000000-0000-0000-0000-00000000e206';diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rsindex 93b74b4372..4600ed05c4 100644--- a/crates/email/src/domain/ports.rs+++ b/crates/email/src/domain/ports.rs@@ -219,6 +219,9 @@ pub trait EmailRepo: Send + Sync + 'static {) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;/// Delete a draft message and its thread if the thread is left empty.+ /// A surviving thread gets its denormalized metadata (inbox visibility,+ /// latest timestamps, is_signal) recomputed, since drafts count toward+ /// those fields.fn delete_draft_message(&self,message_id: Uuid,diff --git a/crates/email/src/outbound/email_pg_repo/message.rs b/crates/email/src/outbound/email_pg_repo/message.rsindex 3ddc501418..df38a27816 100644--- a/crates/email/src/outbound/email_pg_repo/message.rs+++ b/crates/email/src/outbound/email_pg_repo/message.rs@@ -354,20 +354,21 @@ pub(crate) async fn delete_draft_message() -> Result<(), sqlx::Error> {let mut tx = pool.begin().await?;- let deleted = sqlx::query!(+ let deleted_link_id = sqlx::query_scalar!(r#"DELETE FROM email_messagesWHERE id = $1 AND thread_id = $2 AND is_draft = true AND is_sent = false+ RETURNING link_id"#,message_id,thread_db_id,)- .execute(&mut *tx)+ .fetch_optional(&mut *tx).await?;- if deleted.rows_affected() == 0 {+ let Some(link_id) = deleted_link_id else {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!""#,@@ -381,8 +382,11 @@ pub(crate) async fn delete_draft_message(.execute(&mut *tx).await?;} else {- // The discarded draft may have been the thread's only signal message.- super::thread::sync_thread_signal_flag(&mut tx, thread_db_id).await?;+ // Saving the draft inflated the thread's denormalized state — drafts+ // count toward inbox_visible, latest_inbound_message_ts, and+ // is_signal — so a full metadata recompute (which piggybacks the+ // is_signal sync) is needed to put the thread back where it was.+ super::thread::update_thread_metadata(&mut tx, thread_db_id, link_id).await?;}tx.commit().await?;diff --git a/crates/email/src/outbound/email_pg_repo/test/signal_flag.rs b/crates/email/src/outbound/email_pg_repo/test/signal_flag.rsindex f27417a402..62ce1a58b1 100644--- a/crates/email/src/outbound/email_pg_repo/test/signal_flag.rs+++ b/crates/email/src/outbound/email_pg_repo/test/signal_flag.rs@@ -96,15 +96,40 @@ async fn update_thread_metadata_syncs_signal_flag(pool: Pool<Postgres>) -> anyhoconst THREAD_DRAFT_SIGNAL: &str = "00000000-0000-0000-0000-00000000e204";const DRAFT_MSG: &str = "00000000-0000-0000-0000-00000000e505";-// Discarding a draft via the new-crate delete_draft_message (no metadata-// recompute on this path) still refreshes is_signal.+struct ThreadInboxState {+ inbox_visible: bool,+ latest_inbound_message_ts: Option<chrono::DateTime<chrono::Utc>>,+}++async fn fetch_inbox_state(+ pool: &Pool<Postgres>,+ thread_id: &str,+) -> anyhow::Result<ThreadInboxState> {+ Ok(sqlx::query_as!(+ ThreadInboxState,+ "SELECT inbox_visible, latest_inbound_message_ts FROM email_threads WHERE id = $1",+ Uuid::parse_str(thread_id)?+ )+ .fetch_one(pool)+ .await?)+}++// Discarding a draft via delete_draft_message recomputes the thread metadata+// the draft inflated: is_signal, inbox_visible, and+// latest_inbound_message_ts all count drafts.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../../fixtures", scripts("email_signal_flag")))]-async fn delete_draft_message_syncs_signal_flag(pool: Pool<Postgres>) -> anyhow::Result<()> {- // The draft is the thread's only signal message.+async fn delete_draft_message_recomputes_thread_metadata(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // The draft is the thread's only signal message and its stand-in+ // inbound timestamp.assert!(fetch_signal(&pool, THREAD_DRAFT_SIGNAL).await?);+ let before = fetch_inbox_state(&pool, THREAD_DRAFT_SIGNAL).await?;+ assert!(before.inbox_visible);+ assert!(before.latest_inbound_message_ts.is_some());let repo = EmailPgRepo::new(pool.clone());repo.delete_draft_message(@@ -114,6 +139,41 @@ async fn delete_draft_message_syncs_signal_flag(pool: Pool<Postgres>) -> anyhow:.await?;assert!(!fetch_signal(&pool, THREAD_DRAFT_SIGNAL).await?);+ let after = fetch_inbox_state(&pool, THREAD_DRAFT_SIGNAL).await?;+ assert!(!after.inbox_visible);+ assert!(after.latest_inbound_message_ts.is_none());+ Ok(())+}++const THREAD_SENT_DONE: &str = "00000000-0000-0000-0000-00000000e206";+const SENT_THREAD_DRAFT_MSG: &str = "00000000-0000-0000-0000-00000000e508";++// Starting a draft on a done sent thread resurfaces it into the inbox+// (Signal); discarding the draft must send it back out. is_signal stays+// true via the SENT label, so the inbox_visible / latest_inbound reset is+// the only thing keeping the thread out of inbox views.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_signal_flag"))+)]+async fn delete_draft_message_returns_sent_thread_out_of_inbox(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let before = fetch_inbox_state(&pool, THREAD_SENT_DONE).await?;+ assert!(before.inbox_visible);+ assert!(before.latest_inbound_message_ts.is_some());++ let repo = EmailPgRepo::new(pool.clone());+ repo.delete_draft_message(+ Uuid::parse_str(SENT_THREAD_DRAFT_MSG)?,+ Uuid::parse_str(THREAD_SENT_DONE)?,+ )+ .await?;++ assert!(fetch_signal(&pool, THREAD_SENT_DONE).await?);+ let after = fetch_inbox_state(&pool, THREAD_SENT_DONE).await?;+ assert!(!after.inbox_visible);+ assert!(after.latest_inbound_message_ts.is_none());Ok(())}diff --git a/crates/email_db_client/fixtures/sync_thread_signal_flag.sql b/crates/email_db_client/fixtures/sync_thread_signal_flag.sqlindex 7a5159b185..fdcdecb33e 100644--- a/crates/email_db_client/fixtures/sync_thread_signal_flag.sql+++ b/crates/email_db_client/fixtures/sync_thread_signal_flag.sql@@ -15,7 +15,9 @@-- override (no address exception) forces noise.-- Thread d207 (flag=false): draft with a promotions label — drafts are signal.-- Thread d208 (flag=true, correct): promotions message + macro draft — the--- draft is the only signal message; discarding it must flip the flag.+-- draft is the only signal message; discarding it must flip the flag and+-- deflate the draft-inflated metadata (inbox_visible,+-- latest_inbound_message_ts — see the UPDATE at the bottom).INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)VALUES ('00000000-0000-0000-0000-000000000d01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000d01',@@ -85,3 +87,10 @@ VALUES ('00000000-0000-0000-0000-00000000d502', '00000000-0000-0000-0000-0000000('00000000-0000-0000-0000-00000000d506', '00000000-0000-0000-0000-0000000bd002'),('00000000-0000-0000-0000-00000000d508', '00000000-0000-0000-0000-0000000bd002'),('00000000-0000-0000-0000-00000000d509', '00000000-0000-0000-0000-0000000bd002');++-- Saving d208's macro draft left the thread's metadata draft-inflated:+-- drafts count toward latest_inbound_message_ts (and inbox_visible, already+-- true above). Discarding the draft must reset both.+UPDATE email_threads+SET latest_inbound_message_ts = '2025-01-05 19:00:00 +00:00'+WHERE id = '00000000-0000-0000-0000-00000000d208';diff --git a/crates/email_db_client/src/messages/delete.rs b/crates/email_db_client/src/messages/delete.rsindex 71265eff6b..c8e4471df7 100644--- a/crates/email_db_client/src/messages/delete.rs+++ b/crates/email_db_client/src/messages/delete.rs@@ -9,8 +9,6 @@ use sqlx::{Executor, Postgres};pub async fn delete_message_with_tx(tx: &mut sqlx::PgConnection,message: &message::SimpleMessage,- // update thread-object vals (inbox_visible, latest timestamps)- update_thread_metadata: bool,) -> anyhow::Result<Option<Uuid>> {// delete the message itselfdelete_db_message(&mut *tx, message.db_id).await?;@@ -19,7 +17,11 @@ pub async fn delete_message_with_tx(let deleted_thread =threads::delete::delete_thread_if_empty(&mut *tx, message.thread_db_id).await?;- if !deleted_thread && update_thread_metadata {+ // Drafts count toward inbox_visible, latest_inbound_message_ts, and+ // is_signal, so every surviving thread needs the full recompute (which+ // piggybacks the is_signal sync) — a discarded draft would otherwise+ // leave the thread stranded in inbox views.+ if !deleted_thread {threads::update::update_thread_metadata(&mut *tx, message.thread_db_id, message.link_id).await?;}@@ -31,13 +33,6 @@ pub async fn delete_message_with_tx(threads::update::sync_thread_calendar_flag(&mut *tx, message.thread_db_id).await?;}- // Callers that skip the metadata recompute (draft discard) still need- // is_signal refreshed — the deleted message may have been the thread's- // only signal message, and macro drafts get no Gmail echo.- if !deleted_thread && !update_thread_metadata {- threads::update::sync_thread_signal_flag(&mut *tx, message.thread_db_id).await?;- }-if deleted_thread {Ok(Some(message.thread_db_id))} else {diff --git a/crates/email_db_client/src/messages/test.rs b/crates/email_db_client/src/messages/test.rsindex 9e6f6e80cc..9b02da30df 100644--- a/crates/email_db_client/src/messages/test.rs+++ b/crates/email_db_client/src/messages/test.rs@@ -332,8 +332,7 @@ async fn delete_message_clears_calendar_flag_when_last_ics_message_removed(.expect("fixture message present");let mut tx = pool.begin().await?;- let deleted_thread =- crate::messages::delete::delete_message_with_tx(&mut tx, &message, true).await?;+ let deleted_thread = crate::messages::delete::delete_message_with_tx(&mut tx, &message).await?;tx.commit().await?;// The thread survives (a second message remains) and the flag flips offdiff --git a/crates/email_db_client/src/threads/update/test.rs b/crates/email_db_client/src/threads/update/test.rsindex 2bcf5b2018..8f250a1949 100644--- a/crates/email_db_client/src/threads/update/test.rs+++ b/crates/email_db_client/src/threads/update/test.rs@@ -182,19 +182,25 @@ async fn signal_set_for_draft_despite_category_label(pool: Pool<Postgres>) -> anOk(())}-// Discarding a draft via delete_message_with_tx(update_thread_metadata =-// false) — the drafts delete API path — must still refresh is_signal.+// Discarding a draft via delete_message_with_tx — the drafts delete API+// path — must recompute the thread metadata the draft inflated: is_signal,+// inbox_visible, and latest_inbound_message_ts all count drafts, and stale+// values would strand the thread in inbox views (Signal) after the draft+// is gone.#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("sync_thread_signal_flag")))]-async fn draft_discard_without_metadata_recompute_syncs_signal_flag(- pool: Pool<Postgres>,-) -> anyhow::Result<()> {+async fn draft_discard_recomputes_thread_metadata(pool: Pool<Postgres>) -> anyhow::Result<()> {const THREAD: &str = "00000000-0000-0000-0000-00000000d208";const DRAFT_MSG: &str = "00000000-0000-0000-0000-00000000d510";+ // Draft-inflated fixture state: signal, inbox-visible, draft ts standing+ // in for the inbound timestamp.assert!(fetch_signal(&pool, THREAD).await?);+ let before = fetch_inbox_state(&pool, THREAD).await?;+ assert!(before.inbox_visible);+ assert!(before.latest_inbound_message_ts.is_some());let now = chrono::Utc::now();let draft = models_email::email::service::message::SimpleMessage {@@ -223,15 +229,36 @@ async fn draft_discard_without_metadata_recompute_syncs_signal_flag(};let mut conn = pool.acquire().await?;- let deleted_thread =- crate::messages::delete::delete_message_with_tx(&mut conn, &draft, false).await?;+ let deleted_thread = crate::messages::delete::delete_message_with_tx(&mut conn, &draft).await?;assert!(deleted_thread.is_none(), "thread should survive");- // The remaining message is CATEGORY_PROMOTIONS-only: noise.+ // The remaining message is CATEGORY_PROMOTIONS-only: noise, and without+ // an INBOX label the thread leaves the inbox and has no inbound ts.assert!(!fetch_signal(&pool, THREAD).await?);+ let after = fetch_inbox_state(&pool, THREAD).await?;+ assert!(!after.inbox_visible);+ assert!(after.latest_inbound_message_ts.is_none());Ok(())}+struct ThreadInboxState {+ inbox_visible: bool,+ latest_inbound_message_ts: Option<chrono::DateTime<chrono::Utc>>,+}++async fn fetch_inbox_state(+ pool: &Pool<Postgres>,+ thread_id: &str,+) -> anyhow::Result<ThreadInboxState> {+ Ok(sqlx::query_as!(+ ThreadInboxState,+ r#"SELECT inbox_visible, latest_inbound_message_ts FROM email_threads WHERE id = $1"#,+ Uuid::parse_str(thread_id)?+ )+ .fetch_one(pool)+ .await?)+}+// update_thread_metadata piggybacks the is_signal sync, so every existing// metadata-recompute call site keeps the flag fresh.#[sqlx::test(diff --git a/services/email_service/src/api/email/drafts/delete.rs b/services/email_service/src/api/email/drafts/delete.rsindex f680cf39c1..a6e80c957e 100644--- a/services/email_service/src/api/email/drafts/delete.rs+++ b/services/email_service/src/api/email/drafts/delete.rs@@ -91,12 +91,9 @@ pub async fn handler(let mut tx = ctx.db.begin().await?;- let result = email_db_client::messages::delete::delete_message_with_tx(- &mut tx,- &message_replying_to,- false,- )- .await;+ let result =+ email_db_client::messages::delete::delete_message_with_tx(&mut tx, &message_replying_to)+ .await;match result {Ok(_deleted_thread) => {diff --git a/services/email_service/src/pubsub/inbox_sync/operations/delete_message.rs b/services/email_service/src/pubsub/inbox_sync/operations/delete_message.rsindex ce1c0d9063..9021ae4933 100644--- a/services/email_service/src/pubsub/inbox_sync/operations/delete_message.rs+++ b/services/email_service/src/pubsub/inbox_sync/operations/delete_message.rs@@ -98,15 +98,14 @@ pub async fn delete_message(})?;let result = async {- let result =- email_db_client::messages::delete::delete_message_with_tx(&mut tx, &message, true)- .await- .map_err(|e| {- ProcessingError::Retryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to delete message with transaction".to_string()),- })- })?;+ let result = email_db_client::messages::delete::delete_message_with_tx(&mut tx, &message)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to delete message with transaction".to_string()),+ })+ })?;Ok::<Option<Uuid>, ProcessingError>(result)}.await;