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): scheduled email submission and management (#6708)

gbirmana7a6b9f7f0c9
diff --git a/.sqlx/query-0408ab8d764514d0d8e61b720a83c0965063d1b259db60388230043c469bc701.json b/.sqlx/query-0408ab8d764514d0d8e61b720a83c0965063d1b259db60388230043c469bc701.json
new file mode 100644
index 0000000000..9cc208ac95
--- /dev/null
+++ b/.sqlx/query-0408ab8d764514d0d8e61b720a83c0965063d1b259db60388230043c469bc701.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET is_draft = false WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0408ab8d764514d0d8e61b720a83c0965063d1b259db60388230043c469bc701"
+}
diff --git a/.sqlx/query-040bea8d37690c439ebde8e7695b91442d48ab21bdc26a103a1866dbc156cccb.json b/.sqlx/query-040bea8d37690c439ebde8e7695b91442d48ab21bdc26a103a1866dbc156cccb.json
new file mode 100644
index 0000000000..02e620fa1b
--- /dev/null
+++ b/.sqlx/query-040bea8d37690c439ebde8e7695b91442d48ab21bdc26a103a1866dbc156cccb.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT sent, processing FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "processing",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "040bea8d37690c439ebde8e7695b91442d48ab21bdc26a103a1866dbc156cccb"
+}
diff --git a/.sqlx/query-0b7bcfe72aa7dc8e53033e457ade701bd6593c9cd48b501b32b568e0d738388d.json b/.sqlx/query-0b7bcfe72aa7dc8e53033e457ade701bd6593c9cd48b501b32b568e0d738388d.json
new file mode 100644
index 0000000000..533a99f7de
--- /dev/null
+++ b/.sqlx/query-0b7bcfe72aa7dc8e53033e457ade701bd6593c9cd48b501b32b568e0d738388d.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT is_sent, is_draft, subject FROM email_messages WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "subject",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "0b7bcfe72aa7dc8e53033e457ade701bd6593c9cd48b501b32b568e0d738388d"
+}
diff --git a/.sqlx/query-0ff6ccd655759bbc25265ff97fc59542df3b4fae37bb5d02462bf064b803495b.json b/.sqlx/query-0ff6ccd655759bbc25265ff97fc59542df3b4fae37bb5d02462bf064b803495b.json
new file mode 100644
index 0000000000..3ebf7023db
--- /dev/null
+++ b/.sqlx/query-0ff6ccd655759bbc25265ff97fc59542df3b4fae37bb5d02462bf064b803495b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT is_sent FROM email_messages WHERE id = $1 AND link_id = $2 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_sent",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "0ff6ccd655759bbc25265ff97fc59542df3b4fae37bb5d02462bf064b803495b"
+}
diff --git a/.sqlx/query-1020a69d697f000faf264ca2a1ffd8ee703bea41fd4d39556e3f910d54b699e0.json b/.sqlx/query-1020a69d697f000faf264ca2a1ffd8ee703bea41fd4d39556e3f910d54b699e0.json
new file mode 100644
index 0000000000..491c9edf6c
--- /dev/null
+++ b/.sqlx/query-1020a69d697f000faf264ca2a1ffd8ee703bea41fd4d39556e3f910d54b699e0.json
@@ -0,0 +1,174 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id,\n m.provider_id,\n m.global_id,\n m.thread_id,\n m.provider_thread_id,\n m.replying_to_id,\n m.link_id,\n m.provider_history_id,\n m.internal_date_ts,\n m.snippet,\n m.size_estimate,\n m.subject,\n m.from_name,\n m.from_contact_id,\n m.sent_at,\n m.has_attachments,\n m.is_read,\n m.is_starred,\n m.is_sent,\n m.is_draft,\n m.body_text,\n m.body_html_sanitized,\n m.body_macro,\n m.headers_jsonb,\n m.created_at,\n m.updated_at\n FROM email_messages m\n JOIN email_scheduled_messages sm ON m.id = sm.message_id\n WHERE m.link_id = $1\n AND m.is_draft = true\n AND m.is_sent = false\n AND sm.sent = false\n ORDER BY m.created_at DESC\n LIMIT $2 OFFSET $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "global_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider_thread_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "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": "from_name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 13,
+ "name": "from_contact_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 14,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "has_attachments",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 17,
+ "name": "is_starred",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 18,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 19,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 20,
+ "name": "body_text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 21,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "body_macro",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 23,
+ "name": "headers_jsonb",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 24,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 25,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "1020a69d697f000faf264ca2a1ffd8ee703bea41fd4d39556e3f910d54b699e0"
+}
diff --git a/.sqlx/query-1a4898ee2e492a703cc54762b4ae15d88ffc309fcdb9764c3685a9d50a42ef26.json b/.sqlx/query-1a4898ee2e492a703cc54762b4ae15d88ffc309fcdb9764c3685a9d50a42ef26.json
new file mode 100644
index 0000000000..2de4775d28
--- /dev/null
+++ b/.sqlx/query-1a4898ee2e492a703cc54762b4ae15d88ffc309fcdb9764c3685a9d50a42ef26.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET body_html_sanitized = '<p>Hello</p>', body_text = 'Hello' WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1a4898ee2e492a703cc54762b4ae15d88ffc309fcdb9764c3685a9d50a42ef26"
+}
diff --git a/.sqlx/query-1d7f66dcafd017e02ab21025309ebbf918209c857b1ff7621832ddb7ca33b382.json b/.sqlx/query-1d7f66dcafd017e02ab21025309ebbf918209c857b1ff7621832ddb7ca33b382.json
new file mode 100644
index 0000000000..fd8d14cf4e
--- /dev/null
+++ b/.sqlx/query-1d7f66dcafd017e02ab21025309ebbf918209c857b1ff7621832ddb7ca33b382.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_settings SET signature = '<p>Changed</p>' WHERE link_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1d7f66dcafd017e02ab21025309ebbf918209c857b1ff7621832ddb7ca33b382"
+}
diff --git a/.sqlx/query-1e28520f3ddf16587848a6a543f5111c3f2588464f0ab2e0c7227fd990e67b40.json b/.sqlx/query-1e28520f3ddf16587848a6a543f5111c3f2588464f0ab2e0c7227fd990e67b40.json
new file mode 100644
index 0000000000..7d1447f63f
--- /dev/null
+++ b/.sqlx/query-1e28520f3ddf16587848a6a543f5111c3f2588464f0ab2e0c7227fd990e67b40.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT send_time, sent FROM email_scheduled_messages WHERE message_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "send_time",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 1,
+ "name": "sent",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "1e28520f3ddf16587848a6a543f5111c3f2588464f0ab2e0c7227fd990e67b40"
+}
diff --git a/.sqlx/query-d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d.json b/.sqlx/query-2598443146af46485f7465862c14358b1c34eb1b4790ea0307e7ab43f5a96929.json
similarity index 86%
rename from .sqlx/query-d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d.json
rename to .sqlx/query-2598443146af46485f7465862c14358b1c34eb1b4790ea0307e7ab43f5a96929.json
index 6a80cf5b2d..0fad9be99f 100644
--- a/.sqlx/query-d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d.json
+++ b/.sqlx/query-2598443146af46485f7465862c14358b1c34eb1b4790ea0307e7ab43f5a96929.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO email_messages (\n id, provider_id, link_id, thread_id, provider_thread_id,\n replying_to_id, subject, from_contact_id, sent_at,\n has_attachments, is_read, is_starred, is_sent, is_draft,\n body_text, body_html_sanitized, body_macro, headers_jsonb,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (id) DO UPDATE SET\n provider_id = EXCLUDED.provider_id,\n thread_id = EXCLUDED.thread_id,\n provider_thread_id = EXCLUDED.provider_thread_id,\n replying_to_id = EXCLUDED.replying_to_id,\n subject = EXCLUDED.subject,\n from_contact_id = EXCLUDED.from_contact_id,\n sent_at = EXCLUDED.sent_at,\n is_read = EXCLUDED.is_read,\n is_starred = EXCLUDED.is_starred,\n is_sent = EXCLUDED.is_sent,\n is_draft = EXCLUDED.is_draft,\n body_text = EXCLUDED.body_text,\n body_html_sanitized = EXCLUDED.body_html_sanitized,\n body_macro = EXCLUDED.body_macro,\n headers_jsonb = EXCLUDED.headers_jsonb,\n updated_at = NOW()\n WHERE email_messages.link_id = EXCLUDED.link_id\n AND email_messages.is_draft\n AND NOT email_messages.is_sent\n ",
+ "query": "\n INSERT INTO email_messages (\n id, provider_id, link_id, thread_id, provider_thread_id,\n replying_to_id, subject, from_contact_id, sent_at,\n has_attachments, is_read, is_starred, is_sent, is_draft,\n body_text, body_html_sanitized, body_macro, headers_jsonb,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (id) DO UPDATE SET\n provider_id = EXCLUDED.provider_id,\n thread_id = EXCLUDED.thread_id,\n provider_thread_id = EXCLUDED.provider_thread_id,\n replying_to_id = EXCLUDED.replying_to_id,\n subject = EXCLUDED.subject,\n from_contact_id = EXCLUDED.from_contact_id,\n sent_at = EXCLUDED.sent_at,\n is_read = EXCLUDED.is_read,\n is_starred = EXCLUDED.is_starred,\n is_sent = EXCLUDED.is_sent,\n is_draft = EXCLUDED.is_draft,\n body_text = EXCLUDED.body_text,\n body_html_sanitized = EXCLUDED.body_html_sanitized,\n body_macro = EXCLUDED.body_macro,\n headers_jsonb = EXCLUDED.headers_jsonb,\n updated_at = NOW()\n WHERE email_messages.link_id = EXCLUDED.link_id\n AND email_messages.is_draft AND NOT email_messages.is_sent\n AND NOT EXISTS (SELECT 1 FROM email_scheduled_messages WHERE message_id = EXCLUDED.id AND link_id = EXCLUDED.link_id)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -29,5 +29,5 @@
},
"nullable": []
},
- "hash": "d61d85fbcb608cc93260ebb7eef475d0dfb7602cc4a59a2411fa8304f746131d"
+ "hash": "2598443146af46485f7465862c14358b1c34eb1b4790ea0307e7ab43f5a96929"
}
diff --git a/.sqlx/query-384e4408ce1ee37ed874d189ff99414df9af93a210d3a3b912a4cafc388c3ec0.json b/.sqlx/query-384e4408ce1ee37ed874d189ff99414df9af93a210d3a3b912a4cafc388c3ec0.json
new file mode 100644
index 0000000000..f1ebda7f3a
--- /dev/null
+++ b/.sqlx/query-384e4408ce1ee37ed874d189ff99414df9af93a210d3a3b912a4cafc388c3ec0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM email_message_recipients WHERE message_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "384e4408ce1ee37ed874d189ff99414df9af93a210d3a3b912a4cafc388c3ec0"
+}
diff --git a/.sqlx/query-3cc12a354bd0b48195a8f6b7b1df42d96b19eda98a61750b4405c0a0c55e50b2.json b/.sqlx/query-3cc12a354bd0b48195a8f6b7b1df42d96b19eda98a61750b4405c0a0c55e50b2.json
deleted file mode 100644
index e8ed76ed8e..0000000000
--- a/.sqlx/query-3cc12a354bd0b48195a8f6b7b1df42d96b19eda98a61750b4405c0a0c55e50b2.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE email_scheduled_messages\n SET\n sent = true,\n updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "3cc12a354bd0b48195a8f6b7b1df42d96b19eda98a61750b4405c0a0c55e50b2"
-}
diff --git a/.sqlx/query-3d444801dac44f47578f48713f8affb7aa14a5a823eb6fe8b6f1d62d457ee785.json b/.sqlx/query-3d444801dac44f47578f48713f8affb7aa14a5a823eb6fe8b6f1d62d457ee785.json
new file mode 100644
index 0000000000..a5e956ed91
--- /dev/null
+++ b/.sqlx/query-3d444801dac44f47578f48713f8affb7aa14a5a823eb6fe8b6f1d62d457ee785.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_backend_pid() AS \"pid!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pid!",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3d444801dac44f47578f48713f8affb7aa14a5a823eb6fe8b6f1d62d457ee785"
+}
diff --git a/.sqlx/query-3e7beed2a659e4f8afb75f8da1181378414177725689736cb8efb29319af5d1b.json b/.sqlx/query-3e7beed2a659e4f8afb75f8da1181378414177725689736cb8efb29319af5d1b.json
new file mode 100644
index 0000000000..7f4503f98d
--- /dev/null
+++ b/.sqlx/query-3e7beed2a659e4f8afb75f8da1181378414177725689736cb8efb29319af5d1b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND $1 = ANY(pg_blocking_pids(pid))) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3e7beed2a659e4f8afb75f8da1181378414177725689736cb8efb29319af5d1b"
+}
diff --git a/.sqlx/query-3f5f8573e6a53714acafc8709676cf9a0a6b68d4e2409a45135303d868e97ea2.json b/.sqlx/query-3f5f8573e6a53714acafc8709676cf9a0a6b68d4e2409a45135303d868e97ea2.json
new file mode 100644
index 0000000000..532db7b6ab
--- /dev/null
+++ b/.sqlx/query-3f5f8573e6a53714acafc8709676cf9a0a6b68d4e2409a45135303d868e97ea2.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_scheduled_messages SET processing = false, sent = true WHERE message_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3f5f8573e6a53714acafc8709676cf9a0a6b68d4e2409a45135303d868e97ea2"
+}
diff --git a/.sqlx/query-45db5e3fba77fcbee84ab5f1407d5d29a790a2aa89bf1f43511151c2e5431256.json b/.sqlx/query-45db5e3fba77fcbee84ab5f1407d5d29a790a2aa89bf1f43511151c2e5431256.json
new file mode 100644
index 0000000000..1828708923
--- /dev/null
+++ b/.sqlx/query-45db5e3fba77fcbee84ab5f1407d5d29a790a2aa89bf1f43511151c2e5431256.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET is_draft = true, updated_at = NOW() WHERE id = $1 AND link_id = $2 AND NOT is_sent",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "45db5e3fba77fcbee84ab5f1407d5d29a790a2aa89bf1f43511151c2e5431256"
+}
diff --git a/.sqlx/query-49fb81179d4ceb002cbc92bda592b765422b3c2f29839edecdcfa9995e821eb3.json b/.sqlx/query-49fb81179d4ceb002cbc92bda592b765422b3c2f29839edecdcfa9995e821eb3.json
new file mode 100644
index 0000000000..0fb17a5c0b
--- /dev/null
+++ b/.sqlx/query-49fb81179d4ceb002cbc92bda592b765422b3c2f29839edecdcfa9995e821eb3.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_messages (id, link_id, thread_id, subject, is_draft, is_sent) VALUES ($1, $2, $3, 'confirmed content', true, false)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "49fb81179d4ceb002cbc92bda592b765422b3c2f29839edecdcfa9995e821eb3"
+}
diff --git a/.sqlx/query-61c509d7de04b81793ff8cb4b12eb50fdf6d4d7dd8222377ab3156fcc1b95f62.json b/.sqlx/query-61c509d7de04b81793ff8cb4b12eb50fdf6d4d7dd8222377ab3156fcc1b95f62.json
new file mode 100644
index 0000000000..7527609128
--- /dev/null
+++ b/.sqlx/query-61c509d7de04b81793ff8cb4b12eb50fdf6d4d7dd8222377ab3156fcc1b95f62.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature) VALUES ($1, true, '<p>Regards</p>')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "61c509d7de04b81793ff8cb4b12eb50fdf6d4d7dd8222377ab3156fcc1b95f62"
+}
diff --git a/.sqlx/query-6d8538f77a28ee01a0d8dc13eea092d75350df46212dc93c17a959596a76b439.json b/.sqlx/query-6d8538f77a28ee01a0d8dc13eea092d75350df46212dc93c17a959596a76b439.json
new file mode 100644
index 0000000000..ec75f32d98
--- /dev/null
+++ b/.sqlx/query-6d8538f77a28ee01a0d8dc13eea092d75350df46212dc93c17a959596a76b439.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_scheduled_messages SET send_time = NOW() + INTERVAL '1 hour' WHERE message_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6d8538f77a28ee01a0d8dc13eea092d75350df46212dc93c17a959596a76b439"
+}
diff --git a/.sqlx/query-70e2086750c756b918425cc00b930fda9389a182e38b0da0cffa756deecd7e95.json b/.sqlx/query-70e2086750c756b918425cc00b930fda9389a182e38b0da0cffa756deecd7e95.json
new file mode 100644
index 0000000000..f674ec478c
--- /dev/null
+++ b/.sqlx/query-70e2086750c756b918425cc00b930fda9389a182e38b0da0cffa756deecd7e95.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS(SELECT 1 FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "70e2086750c756b918425cc00b930fda9389a182e38b0da0cffa756deecd7e95"
+}
diff --git a/.sqlx/query-715cfbc5cfc1101acfd623e32ed0e784e45d498e41bc9527e93ee6db3114ee1a.json b/.sqlx/query-715cfbc5cfc1101acfd623e32ed0e784e45d498e41bc9527e93ee6db3114ee1a.json
new file mode 100644
index 0000000000..5051791716
--- /dev/null
+++ b/.sqlx/query-715cfbc5cfc1101acfd623e32ed0e784e45d498e41bc9527e93ee6db3114ee1a.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT processing FROM email_scheduled_messages WHERE message_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "processing",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "715cfbc5cfc1101acfd623e32ed0e784e45d498e41bc9527e93ee6db3114ee1a"
+}
diff --git a/.sqlx/query-7688cca5149914d19c07acb0a2b2f9a56e4801a2a77e289a6b50a2118db8e8c5.json b/.sqlx/query-7688cca5149914d19c07acb0a2b2f9a56e4801a2a77e289a6b50a2118db8e8c5.json
new file mode 100644
index 0000000000..65b15c2319
--- /dev/null
+++ b/.sqlx/query-7688cca5149914d19c07acb0a2b2f9a56e4801a2a77e289a6b50a2118db8e8c5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT body_html_sanitized FROM email_messages WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "7688cca5149914d19c07acb0a2b2f9a56e4801a2a77e289a6b50a2118db8e8c5"
+}
diff --git a/.sqlx/query-7e8ff83fbde71d313ca6e3a426943c3837f17395d5f0956ef62f50c3f853729c.json b/.sqlx/query-7e8ff83fbde71d313ca6e3a426943c3837f17395d5f0956ef62f50c3f853729c.json
new file mode 100644
index 0000000000..9bae0a82cf
--- /dev/null
+++ b/.sqlx/query-7e8ff83fbde71d313ca6e3a426943c3837f17395d5f0956ef62f50c3f853729c.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_scheduled_messages SET sent = true, processing = false WHERE message_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7e8ff83fbde71d313ca6e3a426943c3837f17395d5f0956ef62f50c3f853729c"
+}
diff --git a/.sqlx/query-809c5aa01e78839bf554c5c757ad126a2459193e68149f62ddf31e1047be3647.json b/.sqlx/query-809c5aa01e78839bf554c5c757ad126a2459193e68149f62ddf31e1047be3647.json
new file mode 100644
index 0000000000..ef952aef99
--- /dev/null
+++ b/.sqlx/query-809c5aa01e78839bf554c5c757ad126a2459193e68149f62ddf31e1047be3647.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT send_time, sent, processing FROM email_scheduled_messages WHERE message_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "send_time",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 1,
+ "name": "sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "processing",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "809c5aa01e78839bf554c5c757ad126a2459193e68149f62ddf31e1047be3647"
+}
diff --git a/.sqlx/query-870e4e50d9b48d79f09b34581374521e085f5a6e25722ba95a00882d37679402.json b/.sqlx/query-870e4e50d9b48d79f09b34581374521e085f5a6e25722ba95a00882d37679402.json
new file mode 100644
index 0000000000..c4aab27710
--- /dev/null
+++ b/.sqlx/query-870e4e50d9b48d79f09b34581374521e085f5a6e25722ba95a00882d37679402.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM email_scheduled_messages WHERE link_id = $1 AND message_id = $2 AND NOT sent AND NOT processing",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "870e4e50d9b48d79f09b34581374521e085f5a6e25722ba95a00882d37679402"
+}
diff --git a/.sqlx/query-8987bf7ad2930b97e8d0f29929f87be23c01a243354115f00227818a0307453a.json b/.sqlx/query-8987bf7ad2930b97e8d0f29929f87be23c01a243354115f00227818a0307453a.json
new file mode 100644
index 0000000000..3c161f19a2
--- /dev/null
+++ b/.sqlx/query-8987bf7ad2930b97e8d0f29929f87be23c01a243354115f00227818a0307453a.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET body_html_sanitized = $1, body_text = $2, updated_at = NOW() WHERE id = $3 AND link_id = $4",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8987bf7ad2930b97e8d0f29929f87be23c01a243354115f00227818a0307453a"
+}
diff --git a/.sqlx/query-915dda37616b7a0ae4f2b9d5e2a22797cdde5d177dc6d6f7e0469c42001ec24b.json b/.sqlx/query-915dda37616b7a0ae4f2b9d5e2a22797cdde5d177dc6d6f7e0469c42001ec24b.json
new file mode 100644
index 0000000000..b5ab8331f1
--- /dev/null
+++ b/.sqlx/query-915dda37616b7a0ae4f2b9d5e2a22797cdde5d177dc6d6f7e0469c42001ec24b.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_scheduled_messages SET processing = true WHERE message_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "915dda37616b7a0ae4f2b9d5e2a22797cdde5d177dc6d6f7e0469c42001ec24b"
+}
diff --git a/.sqlx/query-9d18e2de7155b4ccff96e94d488a0366815105394ee53dbf7e6c6a351dbdc66f.json b/.sqlx/query-9d18e2de7155b4ccff96e94d488a0366815105394ee53dbf7e6c6a351dbdc66f.json
new file mode 100644
index 0000000000..55791933b1
--- /dev/null
+++ b/.sqlx/query-9d18e2de7155b4ccff96e94d488a0366815105394ee53dbf7e6c6a351dbdc66f.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_scheduled_messages\n SET\n sent = true,\n processing = false,\n updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2 AND processing AND NOT sent\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9d18e2de7155b4ccff96e94d488a0366815105394ee53dbf7e6c6a351dbdc66f"
+}
diff --git a/.sqlx/query-a2bc347716dd6fcfe2bc061b3820fb8790cc7c0c4dd1ed198ac2f5d1dc6929d4.json b/.sqlx/query-a2bc347716dd6fcfe2bc061b3820fb8790cc7c0c4dd1ed198ac2f5d1dc6929d4.json
new file mode 100644
index 0000000000..b87222d201
--- /dev/null
+++ b/.sqlx/query-a2bc347716dd6fcfe2bc061b3820fb8790cc7c0c4dd1ed198ac2f5d1dc6929d4.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT sent, processing FROM email_scheduled_messages WHERE message_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "processing",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "a2bc347716dd6fcfe2bc061b3820fb8790cc7c0c4dd1ed198ac2f5d1dc6929d4"
+}
diff --git a/.sqlx/query-a939cd7abe81e0f4099bbbdcafd34ec0ddd6f1b08299387468847012ba28cac4.json b/.sqlx/query-a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081.json
similarity index 67%
rename from .sqlx/query-a939cd7abe81e0f4099bbbdcafd34ec0ddd6f1b08299387468847012ba28cac4.json
rename to .sqlx/query-a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081.json
index 328813f714..c8efea155a 100644
--- a/.sqlx/query-a939cd7abe81e0f4099bbbdcafd34ec0ddd6f1b08299387468847012ba28cac4.json
+++ b/.sqlx/query-a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n sent = EXCLUDED.sent,\n actor_id = EXCLUDED.actor_id,\n updated_at = NOW()\n ",
+ "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n actor_id = EXCLUDED.actor_id,\n updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing\n ",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
- "hash": "a939cd7abe81e0f4099bbbdcafd34ec0ddd6f1b08299387468847012ba28cac4"
+ "hash": "a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081"
}
diff --git a/.sqlx/query-aaca1db3775d2031002552cb716f80d3327b5c758bbf9deb3e081833a0b6097d.json b/.sqlx/query-aaca1db3775d2031002552cb716f80d3327b5c758bbf9deb3e081833a0b6097d.json
new file mode 100644
index 0000000000..d4764fbdbd
--- /dev/null
+++ b/.sqlx/query-aaca1db3775d2031002552cb716f80d3327b5c758bbf9deb3e081833a0b6097d.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM email_messages WHERE id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "aaca1db3775d2031002552cb716f80d3327b5c758bbf9deb3e081833a0b6097d"
+}
diff --git a/.sqlx/query-8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b.json b/.sqlx/query-b11c4869137d094ef769b8e79c50476f78389c481e1fc95df68e68639d3619de.json
similarity index 52%
rename from .sqlx/query-8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b.json
rename to .sqlx/query-b11c4869137d094ef769b8e79c50476f78389c481e1fc95df68e68639d3619de.json
index 50c17fbcbf..576262371c 100644
--- a/.sqlx/query-8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b.json
+++ b/.sqlx/query-b11c4869137d094ef769b8e79c50476f78389c481e1fc95df68e68639d3619de.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n DELETE FROM email_messages\n WHERE id = $1\n AND thread_id = $2\n AND link_id = ANY($3)\n AND is_draft = true\n AND is_sent = false\n RETURNING link_id\n ",
+ "query": "\n DELETE FROM email_messages\n WHERE id = $1 AND thread_id = $2 AND link_id = ANY($3) AND is_draft = true AND is_sent = false\n AND NOT EXISTS (SELECT 1 FROM email_scheduled_messages WHERE message_id = $1 AND link_id = email_messages.link_id)\n RETURNING link_id\n ",
"describe": {
"columns": [
{
@@ -20,5 +20,5 @@
false
]
},
- "hash": "8f8e4a2218c8031181728280f8d881f7c820f8343e424b83c04482964de14e8b"
+ "hash": "b11c4869137d094ef769b8e79c50476f78389c481e1fc95df68e68639d3619de"
}
diff --git a/.sqlx/query-b24bf8d106dff1f1d07180fed6ccb9c89f9c86f8b9e7e3520667bc0801035c4f.json b/.sqlx/query-b24bf8d106dff1f1d07180fed6ccb9c89f9c86f8b9e7e3520667bc0801035c4f.json
new file mode 100644
index 0000000000..2d4b41ad51
--- /dev/null
+++ b/.sqlx/query-b24bf8d106dff1f1d07180fed6ccb9c89f9c86f8b9e7e3520667bc0801035c4f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT subject FROM email_messages WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "subject",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "b24bf8d106dff1f1d07180fed6ccb9c89f9c86f8b9e7e3520667bc0801035c4f"
+}
diff --git a/.sqlx/query-bc0bb71825307624ae241d13ee3d1cae2a9e610923e7cd7977b1a7357eebd883.json b/.sqlx/query-b3bde361aa40645dc44aede6d0d9c7782536070c6364d11d743edfb9e17412ea.json
similarity index 58%
rename from .sqlx/query-bc0bb71825307624ae241d13ee3d1cae2a9e610923e7cd7977b1a7357eebd883.json
rename to .sqlx/query-b3bde361aa40645dc44aede6d0d9c7782536070c6364d11d743edfb9e17412ea.json
index 87a29cac69..b5d20139cd 100644
--- a/.sqlx/query-bc0bb71825307624ae241d13ee3d1cae2a9e610923e7cd7977b1a7357eebd883.json
+++ b/.sqlx/query-b3bde361aa40645dc44aede6d0d9c7782536070c6364d11d743edfb9e17412ea.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH old AS (\n SELECT link_id, message_id, send_time, sent, processing, actor_id\n FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ), updated AS (\n UPDATE email_scheduled_messages\n SET processing = true, updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n )\n SELECT link_id, message_id, send_time, sent, processing, actor_id\n FROM old\n ",
+ "query": "\n UPDATE email_scheduled_messages\n SET processing = true, updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n AND NOT sent AND NOT processing AND send_time <= NOW()\n RETURNING link_id, message_id, send_time, sent, processing, actor_id\n ",
"describe": {
"columns": [
{
@@ -49,5 +49,5 @@
true
]
},
- "hash": "bc0bb71825307624ae241d13ee3d1cae2a9e610923e7cd7977b1a7357eebd883"
+ "hash": "b3bde361aa40645dc44aede6d0d9c7782536070c6364d11d743edfb9e17412ea"
}
diff --git a/.sqlx/query-b401a896a9d36c58b2068d611733f5030c82c03957047cf5e49145588ded98a0.json b/.sqlx/query-b401a896a9d36c58b2068d611733f5030c82c03957047cf5e49145588ded98a0.json
new file mode 100644
index 0000000000..217744e097
--- /dev/null
+++ b/.sqlx/query-b401a896a9d36c58b2068d611733f5030c82c03957047cf5e49145588ded98a0.json
@@ -0,0 +1,53 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT thread_id, is_draft, is_sent, replying_to_id, body_html_sanitized, body_text FROM email_messages WHERE id = $1 AND link_id = $2 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "body_text",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "b401a896a9d36c58b2068d611733f5030c82c03957047cf5e49145588ded98a0"
+}
diff --git a/.sqlx/query-c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169.json b/.sqlx/query-b4ae2d46f7ff9706d19e08a451d2cde93241c6411c00be4051e4630a5af96eb6.json
similarity index 63%
rename from .sqlx/query-c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169.json
rename to .sqlx/query-b4ae2d46f7ff9706d19e08a451d2cde93241c6411c00be4051e4630a5af96eb6.json
index b5f354e820..abc77d8b15 100644
--- a/.sqlx/query-c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169.json
+++ b/.sqlx/query-b4ae2d46f7ff9706d19e08a451d2cde93241c6411c00be4051e4630a5af96eb6.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE email_scheduled_messages\n SET\n processing = false,\n updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n ",
+ "query": "\n UPDATE email_scheduled_messages\n SET\n processing = false,\n updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2 AND processing AND NOT sent\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,5 +11,5 @@
},
"nullable": []
},
- "hash": "c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169"
+ "hash": "b4ae2d46f7ff9706d19e08a451d2cde93241c6411c00be4051e4630a5af96eb6"
}
diff --git a/.sqlx/query-c0c2a9e29068b3b344001e3ab47675f5236d0f1bae47c70a015608ce2b999c73.json b/.sqlx/query-c0c2a9e29068b3b344001e3ab47675f5236d0f1bae47c70a015608ce2b999c73.json
new file mode 100644
index 0000000000..4f585e5a13
--- /dev/null
+++ b/.sqlx/query-c0c2a9e29068b3b344001e3ab47675f5236d0f1bae47c70a015608ce2b999c73.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET is_sent = true, is_draft = false WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c0c2a9e29068b3b344001e3ab47675f5236d0f1bae47c70a015608ce2b999c73"
+}
diff --git a/.sqlx/query-d6c8ecc4e3eb3dac27411e0fdc2b336c8e49effde818aeaf15294f88c49173a2.json b/.sqlx/query-d6c8ecc4e3eb3dac27411e0fdc2b336c8e49effde818aeaf15294f88c49173a2.json
new file mode 100644
index 0000000000..8ab1f074af
--- /dev/null
+++ b/.sqlx/query-d6c8ecc4e3eb3dac27411e0fdc2b336c8e49effde818aeaf15294f88c49173a2.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT name FROM email_contacts WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "d6c8ecc4e3eb3dac27411e0fdc2b336c8e49effde818aeaf15294f88c49173a2"
+}
diff --git a/.sqlx/query-dadeb0693a2e5cb939f4bda49b67a6b7823897cc5fe852c77070ae7e8fe8f2a1.json b/.sqlx/query-dadeb0693a2e5cb939f4bda49b67a6b7823897cc5fe852c77070ae7e8fe8f2a1.json
new file mode 100644
index 0000000000..7d11059f6a
--- /dev/null
+++ b/.sqlx/query-dadeb0693a2e5cb939f4bda49b67a6b7823897cc5fe852c77070ae7e8fe8f2a1.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM email_messages WHERE id = $1) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "dadeb0693a2e5cb939f4bda49b67a6b7823897cc5fe852c77070ae7e8fe8f2a1"
+}
diff --git a/.sqlx/query-de302c4797b2da57ad0db73f13dc007bac00408ddd4e581085503b3da6bfa637.json b/.sqlx/query-de302c4797b2da57ad0db73f13dc007bac00408ddd4e581085503b3da6bfa637.json
new file mode 100644
index 0000000000..0547c7a2cf
--- /dev/null
+++ b/.sqlx/query-de302c4797b2da57ad0db73f13dc007bac00408ddd4e581085503b3da6bfa637.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT link_id, is_sent, is_draft FROM email_messages WHERE id = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "is_draft",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "de302c4797b2da57ad0db73f13dc007bac00408ddd4e581085503b3da6bfa637"
+}
diff --git a/.sqlx/query-e35d7fe5ba28b3ef58d279f13afb0a24cb9607fc6c8f73d8860b6124086ad031.json b/.sqlx/query-e35d7fe5ba28b3ef58d279f13afb0a24cb9607fc6c8f73d8860b6124086ad031.json
new file mode 100644
index 0000000000..7ae3ad1427
--- /dev/null
+++ b/.sqlx/query-e35d7fe5ba28b3ef58d279f13afb0a24cb9607fc6c8f73d8860b6124086ad031.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT body_html_sanitized, body_text FROM email_messages WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "body_text",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "e35d7fe5ba28b3ef58d279f13afb0a24cb9607fc6c8f73d8860b6124086ad031"
+}
diff --git a/.sqlx/query-9d88208a8e7ea73f315567eb1f46794e5f09a5a25644028a02e226e3119e229a.json b/.sqlx/query-e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e.json
similarity index 64%
rename from .sqlx/query-9d88208a8e7ea73f315567eb1f46794e5f09a5a25644028a02e226e3119e229a.json
rename to .sqlx/query-e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e.json
index 7a7043c251..894b3435e7 100644
--- a/.sqlx/query-9d88208a8e7ea73f315567eb1f46794e5f09a5a25644028a02e226e3119e229a.json
+++ b/.sqlx/query-e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n sent = EXCLUDED.sent,\n actor_id = EXCLUDED.actor_id,\n updated_at = NOW()\n ",
+ "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n actor_id = EXCLUDED.actor_id,\n updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing\n ",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
- "hash": "9d88208a8e7ea73f315567eb1f46794e5f09a5a25644028a02e226e3119e229a"
+ "hash": "e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e"
}
diff --git a/.sqlx/query-f08cd91cb17544945253c4a83c49660e1136e037095cb7d91130f5ce176b5f3b.json b/.sqlx/query-f08cd91cb17544945253c4a83c49660e1136e037095cb7d91130f5ce176b5f3b.json
new file mode 100644
index 0000000000..f6603be909
--- /dev/null
+++ b/.sqlx/query-f08cd91cb17544945253c4a83c49660e1136e037095cb7d91130f5ce176b5f3b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM email_threads WHERE id = $1) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "f08cd91cb17544945253c4a83c49660e1136e037095cb7d91130f5ce176b5f3b"
+}
diff --git a/.sqlx/query-f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae.json b/.sqlx/query-f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae.json
new file mode 100644
index 0000000000..5aed71dc28
--- /dev/null
+++ b/.sqlx/query-f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_scheduled_messages\n (link_id, message_id, send_time, sent, processing, actor_id, created_at, updated_at)\n VALUES ($1, $2, $3, false, false, $4, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time, actor_id = EXCLUDED.actor_id, updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae"
+}
diff --git a/.sqlx/query-fb9a3fc797421a73fb66c55111908d003e98c9ae81e744612d63ef213e5360fd.json b/.sqlx/query-fb9a3fc797421a73fb66c55111908d003e98c9ae81e744612d63ef213e5360fd.json
new file mode 100644
index 0000000000..f72627d24e
--- /dev/null
+++ b/.sqlx/query-fb9a3fc797421a73fb66c55111908d003e98c9ae81e744612d63ef213e5360fd.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT send_time FROM email_scheduled_messages WHERE message_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "send_time",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "fb9a3fc797421a73fb66c55111908d003e98c9ae81e744612d63ef213e5360fd"
+}
diff --git a/.sqlx/query-fba98a8f2e80f01882a4c00fafbc37e6415ee7ee767cb67c4c49b80b4b16ef24.json b/.sqlx/query-fba98a8f2e80f01882a4c00fafbc37e6415ee7ee767cb67c4c49b80b4b16ef24.json
new file mode 100644
index 0000000000..7c0d9abf02
--- /dev/null
+++ b/.sqlx/query-fba98a8f2e80f01882a4c00fafbc37e6415ee7ee767cb67c4c49b80b4b16ef24.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_scheduled_messages (message_id, link_id, send_time) VALUES ($1, $2, NOW() + INTERVAL '1 hour')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fba98a8f2e80f01882a4c00fafbc37e6415ee7ee767cb67c4c49b80b4b16ef24"
+}
diff --git a/.sqlx/query-fbbf74147f59395c77e63eeb9b7b4c8bead2b2857c5c41e306c5b334da9c134b.json b/.sqlx/query-fbbf74147f59395c77e63eeb9b7b4c8bead2b2857c5c41e306c5b334da9c134b.json
new file mode 100644
index 0000000000..1d797550ce
--- /dev/null
+++ b/.sqlx/query-fbbf74147f59395c77e63eeb9b7b4c8bead2b2857c5c41e306c5b334da9c134b.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_scheduled_messages SET send_time = NOW() - INTERVAL '1 minute' WHERE message_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fbbf74147f59395c77e63eeb9b7b4c8bead2b2857c5c41e306c5b334da9c134b"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 3fa84b6fd5..3bd883332c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6147,6 +6147,7 @@ dependencies = [
"crm",
"doppleganger",
"either",
+ "email_db_client",
"email_utils",
"entity_access",
"entity_access_management",
diff --git a/apps/web/src/components/ui/components/SendButton.tsx b/apps/web/src/components/ui/components/SendButton.tsx
index 5bcf4e9409..4bf328703d 100644
--- a/apps/web/src/components/ui/components/SendButton.tsx
+++ b/apps/web/src/components/ui/components/SendButton.tsx
@@ -10,6 +10,8 @@ export type SendButtonProps = Omit<ButtonProps, 'size' | 'variant'> & {
pending?: boolean;
/** Drop the button from the layout — used to hide on mobile when the input is empty. */
hidden?: boolean;
+ /** Visible desktop action text; touch surfaces retain the compact icon. */
+ actionLabel?: string;
};
export function SendButton(props: SendButtonProps) {
@@ -21,6 +23,7 @@ export function SendButton(props: SendButtonProps) {
'children',
'aria-label',
'tooltip',
+ 'actionLabel',
]);
const resolved = children(() => local.children);
@@ -35,7 +38,11 @@ export function SendButton(props: SendButtonProps) {
class={cn(
'rounded-full touch:size-7.5',
local.appearance === 'composer'
- ? 'not-touch:not-disabled:bg-composer-action not-touch:not-disabled:text-composer-action-ink not-touch:light-mode:shadow-none not-touch:light-mode:backdrop-filter-none not-touch:light-mode:after:hidden'
+ ? cn(
+ 'not-touch:not-disabled:bg-composer-action not-touch:not-disabled:text-composer-action-ink not-touch:light-mode:shadow-none not-touch:light-mode:backdrop-filter-none not-touch:light-mode:after:hidden',
+ local.actionLabel &&
+ 'not-touch:w-auto! not-touch:aspect-auto! not-touch:px-3 not-touch:gap-1.5'
+ )
: 'size-7',
'[&_svg]:stroke-[4px]',
'transition-transform ease-in-out duration-150',
@@ -53,7 +60,16 @@ export function SendButton(props: SendButtonProps) {
when={!local.pending}
fallback={<SpinnerIcon class="animate-spin" />}
>
- {resolved() ?? <ArrowUp />}
+ {resolved() ?? (
+ <>
+ <ArrowUp />
+ <Show when={local.actionLabel}>
+ <span class="hidden whitespace-nowrap text-sm font-medium not-touch:inline">
+ {local.actionLabel}
+ </span>
+ </Show>
+ </>
+ )}
</Show>
</Button>
);
diff --git a/apps/web/src/features/email-compose/browser-test/email-schedule-layout.browser.e2e.ts b/apps/web/src/features/email-compose/browser-test/email-schedule-layout.browser.e2e.ts
new file mode 100644
index 0000000000..3975de5b48
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/email-schedule-layout.browser.e2e.ts
@@ -0,0 +1,206 @@
+import { expect, type Locator, type Page, test } from '@playwright/test';
+
+async function chooseTomorrowAtNine(page: Page) {
+ await page.getByRole('button', { name: 'Choose send time' }).click();
+ await page.getByRole('combobox').fill('tomorrow 9am');
+ await page.getByRole('option').first().click();
+}
+
+async function expectNoOverlap(toolbar: Locator) {
+ const toolbarBox = await toolbar.boundingBox();
+ const controls = await toolbar.getByRole('button').all();
+ const boxes = (
+ await Promise.all(controls.map((control) => control.boundingBox()))
+ ).filter((box) => box !== null);
+ expect(toolbarBox).not.toBeNull();
+ expect(boxes.length).toBeGreaterThanOrEqual(5);
+ for (let index = 0; index < boxes.length; index += 1) {
+ const box = boxes[index];
+ expect(box.x).toBeGreaterThanOrEqual(toolbarBox!.x - 0.5);
+ expect(box.x + box.width).toBeLessThanOrEqual(
+ toolbarBox!.x + toolbarBox!.width + 0.5
+ );
+ expect(box.y).toBeGreaterThanOrEqual(toolbarBox!.y - 0.5);
+ expect(box.y + box.height).toBeLessThanOrEqual(
+ toolbarBox!.y + toolbarBox!.height + 0.5
+ );
+ for (const other of boxes.slice(index + 1)) {
+ const horizontalOverlap =
+ Math.min(box.x + box.width, other.x + other.width) -
+ Math.max(box.x, other.x);
+ const verticalOverlap =
+ Math.min(box.y + box.height, other.y + other.height) -
+ Math.max(box.y, other.y);
+ expect(
+ horizontalOverlap > 0.5 && verticalOverlap > 0.5,
+ 'toolbar buttons must not overlap'
+ ).toBe(false);
+ }
+ }
+}
+
+/**
+ * Desktop shows the time in a bar under the composer with Cancel at its far
+ * edge; touch keeps it inline in the toolbar with Cancel beside the time.
+ */
+async function expectScheduleSummary(page: Page, placement: 'bar' | 'inline') {
+ const toolbarBox = await page.getByTestId('toolbar').boundingBox();
+ const summary = page.getByTestId('schedule-summary');
+ const summaryBox = await summary.boundingBox();
+ const labelBox = await summary
+ .getByTestId('schedule-summary-label')
+ .boundingBox();
+ const cancelBox = await summary.getByRole('button').boundingBox();
+ expect(toolbarBox).not.toBeNull();
+ expect(summaryBox).not.toBeNull();
+ expect(labelBox).not.toBeNull();
+ expect(cancelBox).not.toBeNull();
+ expect(cancelBox!.x + cancelBox!.width).toBeLessThanOrEqual(
+ summaryBox!.x + summaryBox!.width + 0.5
+ );
+ expect(labelBox!.x + labelBox!.width).toBeLessThanOrEqual(cancelBox!.x + 0.5);
+ if (placement === 'inline') {
+ expect(
+ cancelBox!.x - (labelBox!.x + labelBox!.width),
+ 'Cancel must sit beside the time it cancels'
+ ).toBeLessThanOrEqual(8);
+ return;
+ }
+ // The bar's padding scales with browser zoom.
+ expect(
+ summaryBox!.x + summaryBox!.width - (cancelBox!.x + cancelBox!.width),
+ 'Cancel sits at the far edge of the bar'
+ ).toBeLessThanOrEqual(Math.max(24, summaryBox!.width * 0.1));
+ // The bar tucks under the card's rounded corners, so measure its content.
+ expect(
+ cancelBox!.y + 0.5,
+ 'The bar sits below the toolbar'
+ ).toBeGreaterThanOrEqual(toolbarBox!.y + toolbarBox!.height);
+}
+
+test('selected time appears to the left while clock and send stay icon-sized', async ({
+ page,
+}) => {
+ await page.goto('/?width=420');
+ await chooseTomorrowAtNine(page);
+
+ const toolbar = page.getByTestId('toolbar');
+ const summary = page.getByTestId('schedule-summary');
+ await expect(summary).toContainText('Scheduled send:');
+ await expect(
+ summary.getByRole('button', { name: 'Clear send time' })
+ ).toBeVisible();
+
+ const clock = toolbar.getByRole('button', { name: /Send time set to/ });
+ const submit = toolbar.getByRole('button', {
+ name: 'Schedule send',
+ exact: true,
+ });
+ expect((await clock.boundingBox())?.width).toBeLessThanOrEqual(40);
+ expect((await submit.boundingBox())?.width).toBeLessThanOrEqual(40);
+ await expect(submit).toBeEnabled();
+ await expect(clock.locator('svg')).toHaveClass(/text-accent/);
+ await expectNoOverlap(toolbar);
+ await expectScheduleSummary(page, 'bar');
+
+ await summary.getByRole('button', { name: 'Clear send time' }).click();
+ await expect(summary).toHaveCount(0);
+ const clearedClock = toolbar.getByRole('button', {
+ name: 'Choose send time',
+ });
+ await expect(clearedClock.locator('svg')).not.toHaveClass(/text-accent/);
+});
+
+test('narrow and zoomed toolbars wrap deliberately without overlap', async ({
+ page,
+}) => {
+ await page.goto('/?width=260');
+ await chooseTomorrowAtNine(page);
+ const toolbar = page.getByTestId('toolbar');
+ await expectNoOverlap(toolbar);
+ await expectScheduleSummary(page, 'bar');
+
+ await page.evaluate(() => {
+ document.body.style.zoom = '200%';
+ });
+ await expectNoOverlap(toolbar);
+ await expectScheduleSummary(page, 'bar');
+});
+
+test('pointer schedule shows Undo and exposes the message in Scheduled', async ({
+ page,
+}) => {
+ await page.goto('/?width=520');
+ await chooseTomorrowAtNine(page);
+ await page
+ .getByRole('button', { name: 'Schedule send', exact: true })
+ .click();
+
+ const toast = page.getByRole('status').filter({ hasText: 'Email scheduled' });
+ await expect(toast).toContainText('Email scheduled');
+ await expect(toast.getByRole('button', { name: 'Undo' })).toBeVisible();
+ await expect(
+ toast.getByRole('button', { name: 'View message' })
+ ).toBeVisible();
+ await expect(toast).toContainText('Sends ');
+ await expect(page.getByTestId('schedule-summary')).toContainText(
+ 'Scheduled for'
+ );
+ await expect(page.getByTestId('commit-count')).toHaveText('1');
+
+ await page.getByRole('button', { name: /Scheduled \(1\)/ }).click();
+ await expect(page.getByRole('heading', { name: 'Scheduled' })).toBeVisible();
+ await expect(page.getByText('Quarterly notes')).toBeVisible();
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(page.getByTestId('schedule-summary')).toHaveCount(0);
+ await expect(
+ page.getByRole('button', { name: /Scheduled \(0\)/ })
+ ).toBeVisible();
+});
+
+test('Undo cancels only the confirmed schedule and restores an editable draft', async ({
+ page,
+}) => {
+ await page.goto('/?width=520');
+ await chooseTomorrowAtNine(page);
+ await page
+ .getByRole('button', { name: 'Schedule send', exact: true })
+ .click();
+ await page
+ .getByRole('status')
+ .filter({ hasText: 'Email scheduled' })
+ .getByRole('button', { name: 'Undo' })
+ .click();
+
+ await expect(page.getByTestId('schedule-summary')).toHaveCount(0);
+ await expect(
+ page.getByRole('button', { name: /Scheduled \(0\)/ })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Choose send time' })
+ ).toBeVisible();
+});
+
+test('keyboard submission commits a selected time exactly once', async ({
+ page,
+}) => {
+ await page.goto('/?mobile&width=360');
+ await chooseTomorrowAtNine(page);
+ await page.keyboard.press('Control+Enter');
+ await page.keyboard.press('Control+Enter');
+
+ await expect(page.getByTestId('commit-count')).toHaveText('1');
+ await expect(
+ page.getByRole('status').filter({ hasText: 'Email scheduled' })
+ ).toContainText('Email scheduled');
+ await expect(page.getByTestId('schedule-summary')).toContainText(
+ 'Scheduled for'
+ );
+ await expect(
+ page.getByRole('button', {
+ name: /Scheduled for .* cancel the schedule/,
+ })
+ ).toBeVisible();
+ await expectNoOverlap(page.getByTestId('toolbar'));
+ await expectScheduleSummary(page, 'inline');
+});
diff --git a/apps/web/src/features/email-compose/browser-test/fixture.tsx b/apps/web/src/features/email-compose/browser-test/fixture.tsx
new file mode 100644
index 0000000000..b25f0fc5aa
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/fixture.tsx
@@ -0,0 +1,333 @@
+import '@fontsource-variable/inter';
+import '../../../index.css';
+import { toast } from '@core/component/Toast/Toast';
+import { ToastRegion } from '@core/component/Toast/ToastRegion';
+import PaperclipIcon from '@phosphor/paperclip.svg';
+import TextAa from '@phosphor/text-aa.svg';
+import TrashIcon from '@phosphor/trash.svg';
+import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
+import ArrowSquareOut from '@phosphor-icons/core/regular/arrow-square-out.svg?component-solid';
+import { Button, SendButton } from '@ui';
+import { format } from 'date-fns/format';
+import { createSignal, onCleanup, onMount, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { EmailDateSelector } from '../components/email-date-selector';
+import {
+ EmailScheduleBar,
+ EmailScheduleSummary,
+} from '../components/email-schedule-summary';
+import type { EmailScheduleState } from '../primitives/email-send-schedule';
+
+type ScheduledItem = {
+ id: string;
+ subject: string;
+ recipient: string;
+ sendTime: Date;
+};
+
+function Fixture() {
+ const params = new URLSearchParams(location.search);
+ const mobile = params.has('mobile');
+ const width = Number(params.get('width') ?? (mobile ? 360 : 520));
+ const [view, setView] = createSignal<'compose' | 'scheduled'>('compose');
+ const [schedule, setSchedule] = createSignal<EmailScheduleState>({
+ type: 'editing',
+ intent: { type: 'immediate' },
+ });
+ const [operation, setOperation] = createSignal<
+ 'idle' | 'committing' | 'updating' | 'cancelling'
+ >('idle');
+ const [scheduledItems, setScheduledItems] = createSignal<ScheduledItem[]>([]);
+ const [commitCount, setCommitCount] = createSignal(0);
+
+ const selectedTime = () => {
+ const current = schedule();
+ if (current.type === 'scheduled')
+ return current.proposedTime ?? current.confirmedTime;
+ return current.intent.type === 'later'
+ ? current.intent.sendTime
+ : undefined;
+ };
+
+ const selectTime = (date: Date | null) => {
+ const current = schedule();
+ if (current.type === 'scheduled') {
+ setSchedule(
+ date && date.getTime() !== current.confirmedTime.getTime()
+ ? { ...current, proposedTime: date }
+ : { type: 'scheduled', confirmedTime: current.confirmedTime }
+ );
+ } else {
+ setSchedule(
+ date
+ ? { type: 'editing', intent: { type: 'later', sendTime: date } }
+ : { type: 'editing', intent: { type: 'immediate' } }
+ );
+ }
+ return true;
+ };
+
+ const actionLabel = () => {
+ const current = schedule();
+ if (current.type === 'scheduled')
+ return current.proposedTime ? 'Update schedule' : 'Send email';
+ return current.intent.type === 'later' ? 'Schedule send' : 'Send email';
+ };
+
+ const actionDisabled = () => {
+ const current = schedule();
+ return (
+ operation() !== 'idle' ||
+ (current.type === 'scheduled' && !current.proposedTime)
+ );
+ };
+
+ const restoreDraft = () => {
+ setScheduledItems((items) => items.filter((item) => item.id !== 'fixture'));
+ setSchedule({ type: 'editing', intent: { type: 'immediate' } });
+ setView('compose');
+ toast.success('Schedule cancelled.');
+ };
+
+ const cancelSchedule = async () => {
+ const current = schedule();
+ if (current.type !== 'scheduled') return false;
+ setOperation('cancelling');
+ restoreDraft();
+ setOperation('idle');
+ return true;
+ };
+
+ const submit = () => {
+ if (actionDisabled()) return;
+ const current = schedule();
+ setCommitCount((count) => count + 1);
+
+ if (current.type === 'editing' && current.intent.type === 'immediate') {
+ toast.success('Email sent', {
+ actions: [
+ { label: 'Undo', onClick: () => toast.success('Send undone') },
+ ],
+ duration: 5_000,
+ });
+ return;
+ }
+
+ const sendTime =
+ current.type === 'editing' && current.intent.type === 'later'
+ ? current.intent.sendTime
+ : current.type === 'scheduled'
+ ? current.proposedTime
+ : undefined;
+ if (!sendTime) return;
+
+ setOperation(current.type === 'editing' ? 'committing' : 'updating');
+ setSchedule({ type: 'scheduled', confirmedTime: sendTime });
+ setScheduledItems([
+ {
+ id: 'fixture',
+ subject: 'Quarterly notes',
+ recipient: 'Peter',
+ sendTime,
+ },
+ ]);
+ setOperation('idle');
+ // Mirrors the production notice in email-send-schedule.ts.
+ let toastId: number | undefined;
+ const dismissThen = (run: () => void) => () => {
+ if (toastId != null) toast.dismiss(toastId);
+ run();
+ };
+ toastId = toast.success('Email scheduled', {
+ subtext: `Sends ${format(sendTime, "EEE, MMM d 'at' h:mm a")}`,
+ actions: [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: dismissThen(restoreDraft),
+ },
+ {
+ label: 'View message',
+ icon: ArrowSquareOut,
+ onClick: dismissThen(() => setView('compose')),
+ },
+ ],
+ duration: 8_000,
+ });
+ };
+
+ onMount(() => {
+ const handleShortcut = (event: KeyboardEvent) => {
+ if (event.key !== 'Enter' || (!event.metaKey && !event.ctrlKey)) return;
+ event.preventDefault();
+ submit();
+ };
+ window.addEventListener('keydown', handleShortcut);
+ onCleanup(() => window.removeEventListener('keydown', handleShortcut));
+ });
+
+ document.documentElement.dataset.touchDevice = String(mobile);
+
+ return (
+ <main class="min-h-screen bg-surface p-4 text-ink">
+ <div
+ class="mx-auto flex flex-col"
+ style={{ width: `min(${width}px, 100%)` }}
+ >
+ <div class="relative z-10 flex min-h-[380px] flex-col overflow-hidden rounded-2xl border border-edge-muted bg-surface-secondary shadow-xl">
+ <nav
+ class="flex border-b border-edge-muted p-2"
+ aria-label="Email views"
+ >
+ <button
+ class="rounded-lg px-3 py-2 text-sm data-[active=true]:bg-accent/15 data-[active=true]:text-accent"
+ data-active={view() === 'compose'}
+ onClick={() => setView('compose')}
+ >
+ Compose
+ </button>
+ <button
+ class="rounded-lg px-3 py-2 text-sm data-[active=true]:bg-accent/15 data-[active=true]:text-accent"
+ data-active={view() === 'scheduled'}
+ onClick={() => setView('scheduled')}
+ >
+ Scheduled ({scheduledItems().length})
+ </button>
+ </nav>
+
+ <Show
+ when={view() === 'compose'}
+ fallback={
+ <section
+ class="flex flex-1 flex-col p-4"
+ aria-label="Scheduled emails"
+ >
+ <h1 class="mb-3 text-lg font-semibold">Scheduled</h1>
+ <Show
+ when={scheduledItems().length}
+ fallback={
+ <p class="m-auto text-sm text-ink-muted">
+ No scheduled emails
+ </p>
+ }
+ >
+ <div class="rounded-xl border border-edge-muted bg-surface p-3">
+ <div class="flex items-center gap-3">
+ <div class="min-w-0 flex-1">
+ <p class="truncate text-sm font-medium">
+ To: {scheduledItems()[0].recipient}
+ </p>
+ <p class="truncate text-sm text-ink-muted">
+ {scheduledItems()[0].subject}
+ </p>
+ </div>
+ <time class="shrink-0 text-xs font-medium text-accent">
+ {format(scheduledItems()[0].sendTime, 'MMM d, h:mm a')}
+ </time>
+ <button
+ class="shrink-0 rounded-lg px-2 py-1.5 text-xs font-medium text-failure hover:bg-hover"
+ onClick={restoreDraft}
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ </Show>
+ </section>
+ }
+ >
+ <section
+ class="flex flex-1 flex-col p-4"
+ aria-label="Compose email"
+ >
+ <div class="border-b border-edge-muted py-2 text-sm">
+ <span class="mr-2 text-ink-muted">From</span> [email protected]
+ </div>
+ <div class="border-b border-edge-muted py-2 text-sm">
+ <span class="mr-2 text-ink-muted">To</span> [email protected]
+ </div>
+ <label class="border-b border-edge-muted py-2 text-sm">
+ <span class="sr-only">Subject</span>
+ <input
+ class="w-full bg-transparent outline-none"
+ value="Quarterly notes"
+ />
+ </label>
+ <label class="flex flex-1 py-3 text-sm">
+ <span class="sr-only">Message</span>
+ <textarea
+ class="w-full resize-none bg-transparent outline-none"
+ placeholder="Write a message…"
+ >
+ Here are the notes we discussed.
+ </textarea>
+ </label>
+
+ <div
+ data-testid="toolbar"
+ class="flex min-w-0 flex-wrap items-center justify-end gap-y-1 border-t border-edge-muted pt-2"
+ >
+ <Show when={mobile}>
+ <EmailScheduleSummary
+ state={schedule()}
+ operation={operation()}
+ onSelectTime={selectTime}
+ onCancelSchedule={cancelSchedule}
+ />
+ </Show>
+ <div class="ml-auto flex shrink-0 items-center gap-1">
+ <Button label="Delete draft" size="icon-composer">
+ <TrashIcon />
+ </Button>
+ <Button label="Attach" size="icon-composer">
+ <PaperclipIcon />
+ </Button>
+ <Button label="Format" size="icon-composer">
+ <TextAa />
+ </Button>
+ <div class="shrink-0">
+ <EmailDateSelector
+ mobile={mobile}
+ compact
+ state={schedule()}
+ selectedTime={selectedTime()}
+ onSelectTime={selectTime}
+ onCancelSchedule={cancelSchedule}
+ operation={operation()}
+ />
+ </div>
+ <SendButton
+ appearance="composer"
+ disabled={actionDisabled()}
+ aria-label={actionLabel()}
+ tooltip={actionLabel()}
+ onClick={submit}
+ shortcut="cmd+enter"
+ />
+ </div>
+ </div>
+ </section>
+ </Show>
+ </div>
+ <Show when={!mobile && view() === 'compose'}>
+ <EmailScheduleBar
+ state={schedule()}
+ operation={operation()}
+ onSelectTime={selectTime}
+ onCancelSchedule={cancelSchedule}
+ class="-mt-6 rounded-b-[20px] border border-t-0 border-edge-muted px-4 pt-8 pb-2"
+ />
+ </Show>
+ </div>
+
+ <ToastRegion />
+ <output class="sr-only" data-testid="commit-count">
+ {commitCount()}
+ </output>
+ </main>
+ );
+}
+
+const root = document.getElementById('root');
+if (!root) throw new Error('Fixture root missing');
+render(() => <Fixture />, root);
diff --git a/apps/web/src/features/email-compose/browser-test/index.html b/apps/web/src/features/email-compose/browser-test/index.html
new file mode 100644
index 0000000000..a50f0f8dbd
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en" data-modality="keyboard">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Email schedule layout fixture</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/fixture.tsx"></script>
+ </body>
+</html>
diff --git a/apps/web/src/features/email-compose/browser-test/playwright.config.ts b/apps/web/src/features/email-compose/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..7c571ae7e1
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/playwright.config.ts
@@ -0,0 +1,40 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig, devices } from '@playwright/test';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = Number(process.env.EMAIL_COMPOSE_BROWSER_PORT ?? 3018);
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: `${directory}/test-results`,
+ timeout: 60_000,
+ fullyParallel: false,
+ workers: 1,
+ reporter: 'line',
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+ webServer: {
+ command: `bunx vite --config src/features/email-compose/browser-test/vite.config.ts --port ${port}`,
+ cwd: webDirectory,
+ url: `http://127.0.0.1:${port}`,
+ reuseExistingServer: true,
+ timeout: 90_000,
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 720, height: 500 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ },
+ ],
+});
diff --git a/apps/web/src/features/email-compose/browser-test/ui-shim.ts b/apps/web/src/features/email-compose/browser-test/ui-shim.ts
new file mode 100644
index 0000000000..9e2ca89641
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/ui-shim.ts
@@ -0,0 +1,8 @@
+export {
+ Button,
+ buttonClasses,
+} from '../../../components/ui/components/Button';
+export { SendButton } from '../../../components/ui/components/SendButton';
+export { Surface } from '../../../components/ui/components/Surface';
+export { Tooltip } from '../../../components/ui/components/Tooltip';
+export { cn } from '../../../components/ui/utils/classname';
diff --git a/apps/web/src/features/email-compose/browser-test/vite.config.ts b/apps/web/src/features/email-compose/browser-test/vite.config.ts
new file mode 100644
index 0000000000..8f2b390e5e
--- /dev/null
+++ b/apps/web/src/features/email-compose/browser-test/vite.config.ts
@@ -0,0 +1,40 @@
+import { fileURLToPath } from 'node:url';
+import tailwind from '@tailwindcss/vite';
+import { defineConfig } from 'vite';
+import solidPlugin from 'vite-plugin-solid';
+import solidSvg from 'vite-plugin-solid-svg';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+const directory = fileURLToPath(new URL('.', import.meta.url));
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const workspaceDirectory = fileURLToPath(
+ new URL('../../../../../../', import.meta.url)
+);
+
+export default defineConfig({
+ root: directory,
+ cacheDir: `${directory}/.vite`,
+ plugins: [
+ solidPlugin(),
+ solidSvg({ defaultAsComponent: true }),
+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
+ tailwind(),
+ ],
+ resolve: {
+ dedupe: ['solid-js'],
+ alias: {
+ '@ui': fileURLToPath(new URL('./ui-shim.ts', import.meta.url)),
+ },
+ },
+ server: {
+ host: '127.0.0.1',
+ port: 3018,
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+ build: {
+ target: 'esnext',
+ outDir: `${directory}/.dist`,
+ emptyOutDir: true,
+ },
+});
diff --git a/apps/web/src/features/email-compose/components/date-selector.tsx b/apps/web/src/features/email-compose/components/date-selector.tsx
index 914c6c8792..f78046a2ee 100644
--- a/apps/web/src/features/email-compose/components/date-selector.tsx
+++ b/apps/web/src/features/email-compose/components/date-selector.tsx
@@ -5,7 +5,7 @@ import {
type ComboboxRootItemComponentProps,
} from '@kobalte/core/combobox';
import SearchIcon from '@phosphor/magnifying-glass.svg';
-import { useSearchInputFocus } from '@property/utils';
+import { useSearchInputFocus } from '@property/utils/focus';
import { Surface } from '@ui';
import { format, setHours, setMinutes, startOfDay } from 'date-fns';
import {
@@ -35,7 +35,10 @@ type DateSelectorProps = {
open?: boolean;
onClose?: VoidFunction;
selectedDate?: Date | null;
- onSelectDate?: (date: Date | null) => void;
+ /** Return false (or reject) to leave the confirmed selection unchanged. */
+ onSelectDate?: (
+ date: Date | null
+ ) => void | boolean | Promise<void | boolean>;
placeholder?: string;
disablePriorToDate?: Date;
disableAfterDate?: Date;
@@ -43,6 +46,14 @@ type DateSelectorProps = {
/** Render content inline instead of in a portal (avoids keyboard positioning issues on mobile) */
disablePortal?: boolean;
disabled?: boolean;
+ triggerClass?: string;
+ triggerLabel?: string;
+ clearLabel?: string;
+ currentLabel?: string;
+ /** Show the selected date in the menu above its clear action. */
+ showCurrentValue?: boolean;
+ clearable?: boolean;
+ footer?: JSX.Element;
trigger?:
| JSX.Element
| ((props: { selectedDate: Date | null }) => JSX.Element);
@@ -122,11 +133,15 @@ export const DateSelector = (props: DateSelectorProps) => {
switch (e.key) {
case 'Delete':
case 'Backspace': {
- if (isNonComboboxInput || searchQuery().trim()) {
+ if (
+ props.clearable === false ||
+ isNonComboboxInput ||
+ searchQuery().trim()
+ ) {
return;
}
e.preventDefault();
- onChange(null);
+ void onChange(null);
break;
}
@@ -175,23 +190,20 @@ export const DateSelector = (props: DateSelectorProps) => {
}
};
- const onChange = (option: DateSelectorOption | null) => {
+ const onChange = async (option: DateSelectorOption | null) => {
if (option?.type === 'select-custom') {
setMode('calendar');
return;
}
- setSelectedOption(option);
- if (!option) {
- props.onSelectDate?.(null);
- onOpenChange(false);
- return;
- }
-
- const dateValue = option.date;
-
- props.onSelectDate?.(dateValue);
onOpenChange(false);
+ const dateValue = option?.date ?? null;
+ try {
+ const accepted = await props.onSelectDate?.(dateValue);
+ if (accepted !== false) setSelectedOption(option);
+ } catch {
+ // The caller owns request feedback. Keep showing the last confirmed value.
+ }
};
const options = createMemo(() => {
@@ -239,7 +251,7 @@ export const DateSelector = (props: DateSelectorProps) => {
if (!value || !value.trim().length) {
const currentDate = selectedDate() ?? new Date();
- onChange({
+ void onChange({
type: 'custom',
date: startOfDay(currentDate),
});
@@ -259,7 +271,7 @@ export const DateSelector = (props: DateSelectorProps) => {
currentDate = setHours(currentDate, Number(hours));
currentDate = setMinutes(currentDate, Number(mins));
- onChange({ type: 'custom', date: currentDate });
+ void onChange({ type: 'custom', date: currentDate });
};
return (
@@ -286,7 +298,8 @@ export const DateSelector = (props: DateSelectorProps) => {
<Show when={typeof props.trigger !== 'undefined'}>
<Combobox.Control>
<Combobox.Trigger
- class="flex group/date-selector-trigger"
+ class={props.triggerClass ?? 'flex group/date-selector-trigger'}
+ aria-label={props.triggerLabel}
tabIndex={0}
onKeyDown={(e: KeyboardEvent) => {
if (e.key === 'Enter') {
@@ -315,7 +328,7 @@ export const DateSelector = (props: DateSelectorProps) => {
disableAfterDate={props.disableAfterDate}
mode={mode()}
onSelectDate={(date) => {
- onChange({ type: 'custom', date });
+ void onChange({ type: 'custom', date });
setInternalOpen(false);
}}
>
@@ -328,15 +341,25 @@ export const DateSelector = (props: DateSelectorProps) => {
/>
</div>
- <Show when={selectedOption()}>
- {(option) => (
- <CurrentValueDisplay
- selectedOption={option()}
- onClear={() => {
- onChange(null);
- }}
- />
- )}
+ <Show
+ when={
+ props.showCurrentValue !== false || props.clearable !== false
+ }
+ >
+ <Show when={selectedOption()}>
+ {(option) => (
+ <CurrentValueDisplay
+ selectedOption={option()}
+ clearLabel={props.clearLabel}
+ currentLabel={props.currentLabel}
+ showValue={props.showCurrentValue !== false}
+ clearable={props.clearable !== false}
+ onClear={() => {
+ void onChange(null);
+ }}
+ />
+ )}
+ </Show>
</Show>
<div class="p-1.5">
<div class="max-h-56 overflow-y-auto overflow-x-hidden scrollbar-hidden">
@@ -382,6 +405,9 @@ export const DateSelector = (props: DateSelectorProps) => {
<code class="bg-active px-1">tomorrow</code>
</div>
</div>
+ <Show when={props.footer}>
+ <div class="border-t border-edge-muted p-1.5">{props.footer}</div>
+ </Show>
</WithCustomDateMode>
</Combobox.Content>
</DateSelectorPortalWrapper>
@@ -392,6 +418,10 @@ export const DateSelector = (props: DateSelectorProps) => {
interface CurrentValueDisplayProps {
selectedOption: DateSelectorOption;
onClear: VoidFunction;
+ clearLabel?: string;
+ currentLabel?: string;
+ showValue: boolean;
+ clearable: boolean;
}
const CurrentValueDisplay = (props: CurrentValueDisplayProps) => {
@@ -405,19 +435,28 @@ const CurrentValueDisplay = (props: CurrentValueDisplayProps) => {
});
return (
- <div class="px-3 py-2 border-b border-edge-muted">
- <div class="flex items-center justify-between">
- <div class="flex items-center gap-2">
- <span class="text-xs text-ink-muted">Current:</span>
- <span class="text-xs font-medium">{currentDateDisplay()}</span>
- </div>
- <button
- onPointerDown={(e: PointerEvent) => e.preventDefault()}
- onClick={props.onClear}
- class="text-xs text-ink-muted hover:text-ink underline"
- >
- Clear
- </button>
+ <div class="border-b border-edge-muted p-1.5">
+ <div class="flex items-center justify-between gap-3">
+ <Show when={props.showValue}>
+ <div class="flex min-w-0 flex-1 items-center gap-2 px-1.5">
+ <span class="shrink-0 text-xs text-ink-muted">
+ {props.currentLabel ?? 'Current:'}
+ </span>
+ <span class="min-w-0 truncate text-xs font-medium">
+ {currentDateDisplay()}
+ </span>
+ </div>
+ </Show>
+ <Show when={props.clearable}>
+ <button
+ onPointerDown={(e: PointerEvent) => e.preventDefault()}
+ onClick={props.onClear}
+ class="min-h-10 shrink-0 rounded-lg px-3 text-xs text-ink-muted underline hover:bg-hover hover:text-ink"
+ classList={{ 'w-full text-left': !props.showValue }}
+ >
+ {props.clearLabel ?? 'Clear'}
+ </button>
+ </Show>
</div>
</div>
);
diff --git a/apps/web/src/features/email-compose/components/email-date-selector.test.tsx b/apps/web/src/features/email-compose/components/email-date-selector.test.tsx
new file mode 100644
index 0000000000..d86fc75f37
--- /dev/null
+++ b/apps/web/src/features/email-compose/components/email-date-selector.test.tsx
@@ -0,0 +1,108 @@
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import type { ComponentProps, JSX, ParentProps } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { EmailDateSelector } from './email-date-selector';
+
+vi.mock('@ui', () => ({
+ buttonClasses: () => 'button-base',
+ cn: (...values: Array<string | false | null | undefined>) =>
+ values.filter(Boolean).join(' '),
+ Tooltip: (props: ParentProps) => <>{props.children}</>,
+ Surface: (props: ComponentProps<'div'>) => <div {...props} />,
+}));
+vi.mock('./date-selector', () => ({
+ DateSelector: (props: {
+ selectedDate?: Date | null;
+ triggerClass?: string;
+ triggerLabel?: string;
+ showCurrentValue?: boolean;
+ trigger: (state: { selectedDate: Date | null }) => JSX.Element;
+ }) => (
+ <button
+ class={props.triggerClass}
+ aria-label={props.triggerLabel}
+ data-show-current-value={String(props.showCurrentValue)}
+ >
+ {props.trigger({ selectedDate: props.selectedDate ?? null })}
+ </button>
+ ),
+}));
+
+afterEach(cleanup);
+
+describe('EmailDateSelector', () => {
+ it('puts the confirmed scheduled label on a flexible, truncating trigger', () => {
+ render(() => (
+ <div style={{ width: '150px' }}>
+ <EmailDateSelector
+ mobile={false}
+ state={{
+ type: 'scheduled',
+ confirmedTime: new Date('2026-12-31T23:59:00Z'),
+ }}
+ selectedTime={new Date('2026-12-31T23:59:00Z')}
+ onSelectTime={vi.fn()}
+ operation="idle"
+ disablePortal
+ />
+ </div>
+ ));
+
+ const trigger = screen.getByRole('button', {
+ name: /Scheduled for .* Open to propose a new time\./,
+ });
+ expect(trigger.className).toContain('not-touch:w-auto!');
+ expect(trigger.className).toContain('aspect-auto!');
+ expect(trigger.className).toContain('min-w-0');
+ expect(trigger.className).toContain('max-w-full');
+ expect(trigger.className).toContain('shrink');
+ expect(trigger.querySelector('.truncate')).not.toBeNull();
+ expect(trigger.querySelector('button')).toBeNull();
+ });
+
+ it('uses an icon-sized trigger on mobile', () => {
+ render(() => (
+ <EmailDateSelector
+ mobile
+ state={{
+ type: 'scheduled',
+ confirmedTime: new Date('2026-12-31T23:59:00Z'),
+ }}
+ selectedTime={new Date('2026-12-31T23:59:00Z')}
+ onSelectTime={vi.fn()}
+ operation="idle"
+ disablePortal
+ />
+ ));
+
+ const trigger = screen.getByRole('button', {
+ name: /Scheduled for .* Open to propose a new time or cancel/,
+ });
+ expect(trigger.className).not.toContain('not-touch:w-auto!');
+ expect(trigger.querySelector('.truncate')).toBeNull();
+ });
+
+ it('does not repeat an unconfirmed time inside the picker menu', () => {
+ render(() => (
+ <EmailDateSelector
+ mobile={false}
+ state={{
+ type: 'editing',
+ intent: {
+ type: 'later',
+ sendTime: new Date('2026-12-31T23:59:00Z'),
+ },
+ }}
+ selectedTime={new Date('2026-12-31T23:59:00Z')}
+ onSelectTime={vi.fn()}
+ operation="idle"
+ disablePortal
+ />
+ ));
+
+ const trigger = screen.getByRole('button', {
+ name: /Send time set to .* Open to change it/,
+ });
+ expect(trigger.dataset.showCurrentValue).toBe('false');
+ });
+});
diff --git a/apps/web/src/features/email-compose/components/email-date-selector.tsx b/apps/web/src/features/email-compose/components/email-date-selector.tsx
index 2b68a33209..81046998dc 100644
--- a/apps/web/src/features/email-compose/components/email-date-selector.tsx
+++ b/apps/web/src/features/email-compose/components/email-date-selector.tsx
@@ -1,93 +1,134 @@
+import type { EmailScheduleState } from '@app/features/email-compose/primitives/email-send-schedule';
import ClockIcon from '@phosphor/clock.svg';
-import IconX from '@phosphor/x.svg';
-import { Button, Tooltip } from '@ui';
+import { buttonClasses, cn, Tooltip } from '@ui';
import { addYears } from 'date-fns/addYears';
import { format } from 'date-fns/format';
import { type JSX, Show, type VoidComponent } from 'solid-js';
import { DateSelector } from './date-selector';
interface EmailDateSelectorProps {
- sendTime?: Date | null;
+ state: EmailScheduleState;
+ selectedTime?: Date;
mobile: boolean;
- onSendTimeChange?: (date: Date | null) => void;
- /** Only show the clock icon, no date text or clear button */
+ onSelectTime?: (date: Date | null) => void | boolean;
+ onCancelSchedule?: () => Promise<boolean>;
+ operation?: 'idle' | 'committing' | 'updating' | 'cancelling';
+ /** Only show the clock icon, no date text. */
compact?: boolean;
- /** Render content inline instead of in a portal */
+ /** Render content inline instead of in a portal. */
disablePortal?: boolean;
- /** Disable the schedule button */
disabled?: boolean;
trigger?: (state: {
selectedDate: Date | null;
formattedDate: string | undefined;
}) => JSX.Element;
}
+
export const EmailDateSelector: VoidComponent<EmailDateSelectorProps> = (
props
) => {
const isCompact = () => props.compact || props.mobile;
+ const formattedDate = () =>
+ props.selectedTime
+ ? format(props.selectedTime, 'MMM d, yyyy h:mm a')
+ : undefined;
+ const isConfirmed = () => props.state.type === 'scheduled';
+ const hasProposal = () =>
+ props.state.type === 'scheduled' && !!props.state.proposedTime;
+ const accessibleLabel = () => {
+ const label = formattedDate();
+ if (!label) return 'Choose send time';
+ if (!isConfirmed()) return `Send time set to ${label}. Open to change it.`;
+ if (hasProposal()) {
+ const confirmed = (
+ props.state as Extract<EmailScheduleState, { type: 'scheduled' }>
+ ).confirmedTime;
+ return `Proposed send time ${label}. The email remains scheduled for ${format(confirmed, 'MMM d, yyyy h:mm a')} until you choose Update schedule.`;
+ }
+ return props.mobile
+ ? `Scheduled for ${label}. Open to propose a new time or cancel the schedule.`
+ : `Scheduled for ${label}. Open to propose a new time.`;
+ };
+ const clearable = () =>
+ (props.state.type === 'editing' && props.state.intent.type === 'later') ||
+ hasProposal();
return (
- <DateSelector
- selectedDate={props.sendTime}
- onSelectDate={props.onSendTimeChange}
- disabled={props.disabled}
- disablePriorToDate={new Date()}
- disableAfterDate={addYears(new Date(), 1)}
- disablePortal={props.disablePortal}
- trigger={(state) => {
- const formattedDate = () =>
- state.selectedDate
- ? format(state.selectedDate, 'MMM d, yyyy h:mm a')
- : undefined;
- const showExpanded = () => !isCompact() && !!formattedDate();
-
- if (props.trigger) {
- return props.trigger({
- selectedDate: state.selectedDate,
- formattedDate: formattedDate(),
- });
- }
+ <Tooltip label="Schedule send time" class="min-w-0 max-w-full">
+ <div class="min-w-0 max-w-full">
+ <DateSelector
+ selectedDate={props.selectedTime}
+ onSelectDate={props.onSelectTime}
+ disabled={props.disabled}
+ disablePriorToDate={new Date()}
+ disableAfterDate={addYears(new Date(), 1)}
+ disablePortal={props.disablePortal}
+ triggerLabel={accessibleLabel()}
+ clearable={props.mobile && clearable()}
+ clearLabel={hasProposal() ? 'Discard proposed time' : 'Clear time'}
+ showCurrentValue={props.mobile && isConfirmed()}
+ currentLabel={
+ hasProposal()
+ ? 'Proposed:'
+ : isConfirmed()
+ ? 'Scheduled:'
+ : undefined
+ }
+ footer={
+ <Show when={props.mobile && isConfirmed()}>
+ <div class="flex flex-col gap-2">
+ <p class="px-1 text-xs text-ink-muted">
+ {hasProposal()
+ ? 'The original schedule stays active until Update schedule succeeds.'
+ : 'Cancel the schedule before editing the message.'}
+ </p>
+ <button
+ type="button"
+ class="rounded-lg px-2 py-1.5 text-left text-sm text-failure hover:bg-hover disabled:text-ink-extra-muted"
+ disabled={props.operation !== 'idle'}
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={() => void props.onCancelSchedule?.()}
+ >
+ {props.operation === 'cancelling'
+ ? 'Cancelling schedule…'
+ : 'Cancel schedule'}
+ </button>
+ </div>
+ </Show>
+ }
+ triggerClass={cn(
+ buttonClasses({ size: 'icon-composer' }),
+ props.selectedTime &&
+ !isCompact() &&
+ 'min-w-0 max-w-full shrink gap-1 aspect-auto! bg-accent/20 text-accent hover:bg-accent/15! hover:text-accent! not-touch:min-w-[33.75px] not-touch:w-auto! not-touch:px-2'
+ )}
+ trigger={(state) => {
+ // The form-owned value is authoritative. Reading the selector's
+ // internal value here can leave the clock accented for one render
+ // after the summary's Cancel action clears the time.
+ const selectedLabel = formattedDate;
+ const showExpanded = () => !isCompact() && !!selectedLabel();
- return (
- <Show
- when={showExpanded()}
- fallback={
- <Tooltip
- label={
- state.selectedDate
- ? `Scheduled for ${formattedDate()}`
- : 'Schedule this email'
- }
- >
- <Button size="icon-composer" disabled={props.disabled}>
- <ClockIcon class={state.selectedDate ? 'text-accent' : ''} />
- </Button>
- </Tooltip>
+ if (props.trigger) {
+ return props.trigger({
+ selectedDate: state.selectedDate,
+ formattedDate: selectedLabel(),
+ });
}
- >
- <Button
- size="icon-composer"
- disabled={props.disabled}
- class="size-auto gap-1 bg-accent/20 text-accent hover:bg-accent/15! hover:text-accent!"
- >
- <ClockIcon />
- <span class="text-sm">{formattedDate()}</span>
- <Tooltip label="Clear">
- <div
- tabIndex={0}
- class="hover:bg-accent/30"
- onPointerDown={(e) => {
- e.stopPropagation();
- }}
- onClick={() => props.onSendTimeChange?.(null)}
- >
- <IconX class="size-5" />
- </div>
- </Tooltip>
- </Button>
- </Show>
- );
- }}
- />
+
+ return (
+ <div class="flex min-w-0 items-center gap-1">
+ <ClockIcon class={props.selectedTime ? 'text-accent' : ''} />
+ <Show when={showExpanded()}>
+ <span class="min-w-0 truncate text-sm">
+ {selectedLabel()}
+ </span>
+ </Show>
+ </div>
+ );
+ }}
+ />
+ </div>
+ </Tooltip>
);
};
diff --git a/apps/web/src/features/email-compose/components/email-schedule-summary.tsx b/apps/web/src/features/email-compose/components/email-schedule-summary.tsx
new file mode 100644
index 0000000000..f0654979c2
--- /dev/null
+++ b/apps/web/src/features/email-compose/components/email-schedule-summary.tsx
@@ -0,0 +1,153 @@
+import type { EmailScheduleState } from '@app/features/email-compose/primitives/email-send-schedule';
+import { formatTimeZoneAbbreviation } from '@core/util/date';
+import ClockIcon from '@phosphor/clock.svg';
+import { Button, cn } from '@ui';
+import { format } from 'date-fns/format';
+import { Show, type VoidComponent } from 'solid-js';
+
+interface EmailScheduleSummaryProps {
+ state: EmailScheduleState;
+ operation: 'idle' | 'committing' | 'updating' | 'cancelling';
+ onSelectTime: (date: Date | null) => void | boolean;
+ onCancelSchedule: () => Promise<boolean>;
+}
+
+type ScheduleSummary = {
+ label: string;
+ detail: string | undefined;
+ actionLabel: string;
+ accessibleActionLabel: string;
+ action: () => void;
+};
+
+/** A send time with its zone, since the viewer's zone may not be the recipient's. */
+function sendTimeLabel(time: Date): string {
+ const zone = formatTimeZoneAbbreviation(time);
+ const label = format(time, "MMM d 'at' h:mm a");
+ return zone ? `${label} ${zone}` : label;
+}
+
+function describeSchedule(
+ props: EmailScheduleSummaryProps
+): ScheduleSummary | undefined {
+ const state = props.state;
+ if (state.type === 'editing') {
+ if (state.intent.type === 'immediate') return undefined;
+ return {
+ label: `Scheduled send: ${sendTimeLabel(state.intent.sendTime)}`,
+ detail: undefined,
+ actionLabel: 'Cancel',
+ accessibleActionLabel: 'Clear send time',
+ action: () => props.onSelectTime(null),
+ };
+ }
+ if (state.proposedTime) {
+ return {
+ label: `Scheduled for ${sendTimeLabel(state.confirmedTime)}`,
+ detail: `Update to ${sendTimeLabel(state.proposedTime)}; original remains active until Update succeeds`,
+ actionLabel: 'Cancel change',
+ accessibleActionLabel: 'Cancel schedule change',
+ action: () => props.onSelectTime(null),
+ };
+ }
+ return {
+ label: `Scheduled for ${sendTimeLabel(state.confirmedTime)}`,
+ detail: undefined,
+ actionLabel: 'Cancel',
+ accessibleActionLabel: 'Cancel scheduled send',
+ action: () => void props.onCancelSchedule(),
+ };
+}
+
+function ScheduleSummaryLabel(props: {
+ summary: ScheduleSummary;
+ class?: string;
+}) {
+ return (
+ <div
+ role="status"
+ data-testid="schedule-summary-label"
+ class={cn('min-w-0 leading-tight', props.class)}
+ title={
+ props.summary.detail
+ ? `${props.summary.label}. ${props.summary.detail}`
+ : props.summary.label
+ }
+ >
+ <div class="truncate text-ink-muted">{props.summary.label}</div>
+ <Show when={props.summary.detail}>
+ {(detail) => (
+ <div class="truncate text-ink-extra-muted">{detail()}</div>
+ )}
+ </Show>
+ </div>
+ );
+}
+
+function ScheduleSummaryAction(props: {
+ summary: ScheduleSummary;
+ operation: EmailScheduleSummaryProps['operation'];
+}) {
+ return (
+ <Button
+ variant="accent"
+ size="xs"
+ aria-label={props.summary.accessibleActionLabel}
+ tooltip={props.summary.accessibleActionLabel}
+ disabled={props.operation !== 'idle'}
+ onClick={props.summary.action}
+ >
+ {props.operation === 'cancelling'
+ ? 'Cancelling…'
+ : props.summary.actionLabel}
+ </Button>
+ );
+}
+
+/** The send time and its Cancel together, for toolbars with no room for a bar. */
+export const EmailScheduleSummary: VoidComponent<EmailScheduleSummaryProps> = (
+ props
+) => (
+ <Show when={describeSchedule(props)}>
+ {(summary) => (
+ <div
+ data-testid="schedule-summary"
+ class="mr-auto flex min-w-0 flex-auto items-center gap-1 pr-2 text-xs"
+ >
+ <ScheduleSummaryLabel summary={summary()} />
+ <ScheduleSummaryAction
+ summary={summary()}
+ operation={props.operation}
+ />
+ </div>
+ )}
+ </Show>
+);
+
+/**
+ * A full-width bar under the composer: the send time on the left and its
+ * Cancel at the far edge, so neither competes with the toolbar for room.
+ * `class` supplies the surface the bar attaches to.
+ */
+export const EmailScheduleBar: VoidComponent<
+ EmailScheduleSummaryProps & { class?: string }
+> = (props) => (
+ <Show when={describeSchedule(props)}>
+ {(summary) => (
+ <div
+ data-testid="schedule-summary"
+ class={cn(
+ 'flex min-w-0 items-center gap-2 bg-[color-mix(in_oklch,var(--color-surface-1)_40%,var(--color-surface-2))] text-xs',
+ props.class
+ )}
+ >
+ <ClockIcon class="size-3.5 shrink-0 text-accent" aria-hidden="true" />
+ <ScheduleSummaryLabel summary={summary()} class="flex-1" />
+ <ScheduleSummaryAction
+ summary={summary()}
+ operation={props.operation}
+ />
+ </div>
+ )}
+ </Show>
+);
diff --git a/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx b/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx
index adf9e3adad..2dbb163529 100644
--- a/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx
+++ b/apps/web/src/features/email-compose/components/mobile-reply-toolbar.tsx
@@ -3,7 +3,7 @@ import Paperclip from '@phosphor/paperclip.svg';
import Spinner from '@phosphor/spinner-gap.svg';
import Trash from '@phosphor/trash.svg';
import { Button, type ButtonProps } from '@ui';
-import { Show } from 'solid-js';
+import { type JSX, Show } from 'solid-js';
function ToolbarButton(props: ButtonProps) {
return (
@@ -24,23 +24,37 @@ export function MobileReplyToolbar(props: {
onDiscard: () => void;
attachRef: (element: HTMLButtonElement) => void;
onSend: () => void;
+ sendLabel: string;
sendDisabled: boolean;
sending: boolean;
+ editingDisabled: boolean;
+ scheduleSummary?: JSX.Element;
+ scheduleControl?: JSX.Element;
}) {
return (
<div
data-corvu-no-drag=""
- class="sticky top-0 inset-x-0 z-10 flex shrink-0 items-center justify-between bg-surface p-3 pt-0"
+ class="sticky top-0 inset-x-0 z-10 flex shrink-0 flex-wrap items-center justify-between gap-y-2 bg-surface p-3 pt-0"
>
- <ToolbarButton label={props.discardLabel} onClick={props.onDiscard}>
+ <ToolbarButton
+ label={props.discardLabel}
+ onClick={props.onDiscard}
+ disabled={props.editingDisabled}
+ >
<Trash class="size-(--mobile-chrome-icon-size)" />
</ToolbarButton>
+ {props.scheduleSummary}
<div class="ml-auto flex items-center gap-2">
- <ToolbarButton label="Attach" ref={props.attachRef}>
+ {props.scheduleControl}
+ <ToolbarButton
+ label="Attach"
+ ref={props.attachRef}
+ disabled={props.editingDisabled}
+ >
<Paperclip class="size-(--mobile-chrome-icon-size)" />
</ToolbarButton>
<ToolbarButton
- label="Send email"
+ label={props.sendLabel}
disabled={props.sendDisabled}
onClick={props.onSend}
>
diff --git a/apps/web/src/features/email-compose/components/signature-preview.tsx b/apps/web/src/features/email-compose/components/signature-preview.tsx
index 90b682b378..2aac27d5ca 100644
--- a/apps/web/src/features/email-compose/components/signature-preview.tsx
+++ b/apps/web/src/features/email-compose/components/signature-preview.tsx
@@ -36,6 +36,7 @@ export function SignaturePreview(props: {
mobile: boolean;
prepareLinks?: (root: ShadowRoot) => void;
onDismiss: () => void;
+ dismissable?: boolean;
}) {
let mountEl!: HTMLDivElement;
// Always starts collapsed to just the bar; the user expands to preview it.
@@ -84,16 +85,18 @@ export function SignaturePreview(props: {
</Tooltip>
</Show>
</div>
- <Tooltip label="Don't include signature" as="span">
- <button
- type="button"
- class="-m-1 rounded-md p-1 text-ink-muted hover:bg-hover hover:text-ink"
- aria-label="Don't include signature"
- onClick={() => props.onDismiss()}
- >
- <XIcon class="size-3.5" />
- </button>
- </Tooltip>
+ <Show when={props.dismissable !== false}>
+ <Tooltip label="Don't include signature" as="span">
+ <button
+ type="button"
+ class="-m-1 rounded-md p-1 text-ink-muted hover:bg-hover hover:text-ink"
+ aria-label="Don't include signature"
+ onClick={() => props.onDismiss()}
+ >
+ <XIcon class="size-3.5" />
+ </button>
+ </Tooltip>
+ </Show>
</div>
<div
ref={mountEl}
diff --git a/apps/web/src/features/email-compose/compose-adapter.ts b/apps/web/src/features/email-compose/compose-adapter.ts
index c3d65cfd85..39bb50f7e0 100644
--- a/apps/web/src/features/email-compose/compose-adapter.ts
+++ b/apps/web/src/features/email-compose/compose-adapter.ts
@@ -23,6 +23,7 @@ import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
import { handleFileFolderDrop } from '@core/util/upload';
import { Telemetry } from '@macro-inc/observability';
import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-clockwise.svg?component-solid';
+import ArrowSquareOut from '@phosphor-icons/core/regular/arrow-square-out.svg?component-solid';
import { queryClient } from '@queries/client';
import {
useAddForwardedAttachmentsMutation,
@@ -77,6 +78,10 @@ import { decodeBase64Utf8 } from './core/decode-base64';
import type { EmailDraft } from './core/email-draft';
import { readDroppedEmailFiles } from './editor-adapter';
import { makeAttachmentPublic } from './make-attachment-public';
+import {
+ emailDraftLifecycleSource,
+ publishDraftLifecycleChange,
+} from './queries/draft-lifecycle';
import { createEmailInboxSource } from './queries/inbox-source';
import { restoreDraftBodyAfterUndo, runUndoSend } from './undo-send';
@@ -113,9 +118,9 @@ export function createEmailComposeContext(
const { users } = useCombinedRecipients();
const notice = (options?: ComposeNoticeOptions) => ({
...options,
- actions: options?.actions?.map((action) => ({
+ actions: options?.actions?.map(({ kind, ...action }) => ({
...action,
- icon: ArrowCounterClockwise,
+ icon: kind === 'open' ? ArrowSquareOut : ArrowCounterClockwise,
})),
});
const reportError = (error: unknown) =>
@@ -169,6 +174,7 @@ export function createEmailComposeContext(
});
return {
+ draftLifecycle: emailDraftLifecycleSource,
recipientName: (id) => getDisplayName(tryMacroId(id)),
recordMention: (sourceId, targetId) => {
void trackMention(sourceId, 'document', targetId).catch(reportError);
@@ -298,6 +304,7 @@ export function createEmailComposeContext(
skipSoupRefetch: completingThread,
});
try {
+ publishDraftLifecycleChange(input.draftId, inboxId);
if (input.threadId) markThreadDraftSaved(input.threadId);
} catch (error) {
reportError(error);
@@ -336,6 +343,11 @@ export function createEmailComposeContext(
skipSoupRefetch: completingThread,
});
try {
+ if (result.message.db_id)
+ publishDraftLifecycleChange(
+ result.message.db_id,
+ result.message.link_id
+ );
if (result.message.thread_db_id)
markThreadDraftSaved(result.message.thread_db_id);
} catch (error) {
@@ -353,16 +365,33 @@ export function createEmailComposeContext(
linkId: headerId(inboxId),
});
try {
+ publishDraftLifecycleChange(draftId, inboxId);
invalidateSoupEntity(draftId);
} catch (error) {
reportError(error);
}
},
- schedule: async ({ draftId, sendTime }, inboxId) => {
+ schedule: async ({ draftId, sendTime, includeSignature }, inboxId) => {
await scheduleEmailMessage(
- { draftID: draftId, send_time: sendTime },
+ {
+ draftID: draftId,
+ send_time: sendTime,
+ include_signature: includeSignature,
+ },
headerId(inboxId)
);
+ try {
+ publishDraftLifecycleChange(draftId, inboxId);
+ void queryClient
+ .invalidateQueries({
+ queryKey: emailKeys.scheduledMessages._def,
+ })
+ .catch(reportError);
+ } catch (error) {
+ // Cache and cross-tab notifications are post-commit UI work. A
+ // failure here must not make a successful schedule retryable.
+ reportError(error);
+ }
},
archive: async ({ threadId, value }, inboxId) => {
await archiveEmailThread({ id: threadId, value }, headerId(inboxId));
diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.ts
index 6a4a3fbd82..1cdc19deb4 100644
--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts
+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts
@@ -66,7 +66,6 @@ export interface DraftClientHandles {
export interface SaveEmailDraft {
draft: EmailDraft;
clientHandles?: DraftClientHandles;
- sendTime?: Date | null;
previousThreadId?: string;
inboxId?: string;
completingThread?: boolean;
@@ -122,7 +121,11 @@ export interface EmailDelivery {
sendMessage(input: SendEmailDraft): Promise<PersistedEmailIdentity>;
unschedule(input: { draftId: string; inboxId?: string }): Promise<void>;
schedule(
- input: { draftId: string; sendTime: string },
+ input: {
+ draftId: string;
+ sendTime: string;
+ includeSignature?: boolean;
+ },
inboxId?: string
): Promise<void>;
archive(
@@ -137,6 +140,55 @@ export interface EmailDelivery {
}): Promise<void>;
}
+export type EmailDraftLifecycleState =
+ | {
+ type: 'editing';
+ draftId: string;
+ threadId: string;
+ inboxId: string;
+ observedAt: number;
+ }
+ | {
+ type: 'scheduled';
+ draftId: string;
+ threadId: string;
+ inboxId: string;
+ sendTime: string;
+ observedAt: number;
+ }
+ | {
+ type: 'sent';
+ draftId: string;
+ threadId: string;
+ inboxId: string;
+ observedAt: number;
+ }
+ | {
+ type: 'missing';
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+ observedAt: number;
+ };
+
+export interface EmailDraftLifecycleSource {
+ observe(input: {
+ draftId: Accessor<string | null | undefined>;
+ threadId: Accessor<string | null | undefined>;
+ inboxId: Accessor<string | undefined>;
+ }): {
+ state: Accessor<EmailDraftLifecycleState | undefined>;
+ /** Prior observations stay invalid after failure until a fresh read succeeds. */
+ refresh(): Promise<EmailDraftLifecycleState | undefined>;
+ /** Read one captured identity even if the observing composer has navigated away. */
+ refreshIdentity?(input: {
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+ }): Promise<EmailDraftLifecycleState | undefined>;
+ };
+}
+
export interface EmailComposeFeedback {
feedback: {
success(
@@ -193,6 +245,7 @@ export interface EmailComposeContext {
drafts: EmailDraftStorage;
attachmentStorage: EmailAttachmentStorage;
delivery: EmailDelivery;
+ draftLifecycle: EmailDraftLifecycleSource;
notices: EmailComposeFeedback;
accounts: EmailComposeAccounts;
connectivity: EmailConnectivity;
@@ -208,7 +261,8 @@ export interface EmailComposeContext {
export interface ComposeNoticeOptions {
subtext?: string;
duration?: number;
- actions?: { label: string; onClick: () => void }[];
+ /** `kind` picks the action's icon; actions default to undo. */
+ actions?: { label: string; onClick: () => void; kind?: 'undo' | 'open' }[];
}
export interface EmailComposeHost {
focusSibling?: (direction: 'next' | 'prev') => boolean | void;
diff --git a/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts b/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts
index 91c09b6c74..f207ba0345 100644
--- a/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts
+++ b/apps/web/src/features/email-compose/primitives/attachment-persistence.test.ts
@@ -1,4 +1,4 @@
-import { createRoot } from 'solid-js';
+import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { UploadEmailAttachments } from '../context/compose-capabilities';
import { createAttachmentPersistence } from './attachment-persistence';
@@ -18,16 +18,18 @@ function setup(
});
const services = {
uploadAttachments: vi.fn(uploadAttachments),
+ addForwardedAttachments: vi.fn(async () => {}),
removeAttachment: vi.fn(async () => {}),
removeForwardedAttachment: vi.fn(async () => {}),
};
+ const [draftId, setDraftId] = createSignal('draft');
const persistence = createAttachmentPersistence({
services,
attachments: form.attachments,
- draftId: () => 'draft',
+ draftId,
inboxId: () => 'secondary-inbox',
});
- return { form, services, persistence };
+ return { form, services, persistence, setDraftId };
});
}
@@ -110,4 +112,35 @@ describe('draft attachment persistence', () => {
});
await Promise.resolve();
});
+
+ it('re-uploads files after detach and ignores late callbacks from the obsolete upload', async () => {
+ const pending = Promise.withResolvers<void>();
+ const file = new File(['content'], 'notes.txt');
+ let oldInput: UploadEmailAttachments | undefined;
+ const state = setup(async (input) => {
+ input.onAttachmentAdded?.(file, 'replacement-attachment');
+ });
+ state.services.uploadAttachments.mockImplementationOnce(async (input) => {
+ oldInput = input;
+ input.onAttachmentAdded?.(file, 'old-attachment');
+ await pending.promise;
+ });
+ state.form.attachments.add({ type: 'local', file });
+ const oldUpload = state.persistence.upload('draft');
+ state.persistence.detach();
+ state.setDraftId('replacement');
+ expect(state.form.attachments.list()[0].attachmentId).toBeUndefined();
+ const newUpload = state.persistence.upload('replacement');
+ oldInput?.onAttachmentAdded?.(file, 'late-old-id');
+ oldInput?.onAttachmentUploadFailed?.(file);
+ expect(state.form.attachments.list()[0].attachmentId).toBe(
+ 'replacement-attachment'
+ );
+ pending.resolve();
+ await Promise.all([oldUpload, newUpload]);
+ expect(state.services.uploadAttachments).toHaveBeenCalledTimes(2);
+ expect(state.form.attachments.list()[0].attachmentId).toBe(
+ 'replacement-attachment'
+ );
+ });
});
diff --git a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
index 1e21baa647..1fa3d2fbbe 100644
--- a/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/attachment-persistence.ts
@@ -41,17 +41,38 @@ export function createAttachmentPersistence(options: {
inboxId: Accessor<string | undefined>;
services: Pick<
EmailAttachmentStorage,
- 'uploadAttachments' | 'removeAttachment' | 'removeForwardedAttachment'
+ | 'uploadAttachments'
+ | 'addForwardedAttachments'
+ | 'removeAttachment'
+ | 'removeForwardedAttachment'
>;
}) {
// An assigned ID only proves that the attachment record exists. Every save
// must also wait for content uploads started by earlier concurrent saves.
const inFlight = new Set<Promise<void>>();
const [uploading, setUploading] = createSignal(false);
+ let generation = 0;
return {
uploading,
+ /** Local files can be uploaded again; remote-only draft files cannot be cloned. */
+ detach() {
+ generation += 1;
+ let removed = 0;
+ for (const attachment of options.attachments.list()) {
+ if (attachment.type === 'local') {
+ options.attachments.clearAttachmentId(attachment.file);
+ } else if (attachment.type === 'remote') {
+ options.attachments.removeById(attachment.attachmentId);
+ removed += 1;
+ }
+ }
+ return removed;
+ },
async upload(draftId: string, inbox = { inboxId: options.inboxId() }) {
+ const uploadGeneration = generation;
+ const stillCurrent = () =>
+ uploadGeneration === generation && options.draftId() === draftId;
const attachments = options.attachments
.list()
.filter(
@@ -66,8 +87,13 @@ export function createAttachmentPersistence(options: {
draftId: draftId,
attachments: attachments.map((attachment) => attachment.file),
inboxId: inbox.inboxId,
- onAttachmentAdded: options.attachments.assignAttachmentId,
- onAttachmentUploadFailed: options.attachments.clearAttachmentId,
+ onAttachmentAdded: (file, id) => {
+ if (stillCurrent())
+ options.attachments.assignAttachmentId(file, id);
+ },
+ onAttachmentUploadFailed: (file) => {
+ if (stillCurrent()) options.attachments.clearAttachmentId(file);
+ },
});
const settled = run.then(
() => undefined,
@@ -83,6 +109,17 @@ export function createAttachmentPersistence(options: {
while (inFlight.size) await Promise.all([...inFlight]);
// All work has settled; rethrow this save's own upload failure.
if (run) await run;
+ if (!stillCurrent()) return;
+ const forwarded = options.attachments
+ .list()
+ .filter((attachment) => attachment.type === 'forwarded');
+ if (forwarded.length) {
+ await options.services.addForwardedAttachments({
+ draftId,
+ inboxId: inbox.inboxId,
+ attachments: forwarded.map(({ attachmentId }) => ({ attachmentId })),
+ });
+ }
},
remove(attachment: DraftFormAttachment) {
const state = options.attachments;
diff --git a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts b/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts
index 3f4ab9b7a2..dfb0589d18 100644
--- a/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts
+++ b/apps/web/src/features/email-compose/primitives/compose-persistence.test.ts
@@ -228,7 +228,7 @@ it('rejects sender/schedule changes and repeated discard while a deletion is pen
const discard = root.state.deleteDraftAndReset();
expect(await root.state.deleteDraftAndReset()).toBe(false);
root.state.context.onSelectInbox?.('other-inbox');
- await root.state.context.onSendTimeChange?.(new Date('2026-12-01T12:00:00Z'));
+ root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));
expect(root.state.context.selectedInboxId?.()).toBe('inbox');
expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
@@ -248,7 +248,7 @@ it('rejects sender and scheduling changes after send dispatch', async () => {
root.state.context.onSend();
await vi.advanceTimersByTimeAsync(1);
root.state.context.onSelectInbox?.('other-inbox');
- await root.state.context.onSendTimeChange?.(new Date('2026-12-01T12:00:00Z'));
+ root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));
expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
expect(root.state.context.selectedInboxId?.()).toBe('inbox');
@@ -289,43 +289,453 @@ it('uses the captured inbox for attachment upload when a sender switch queues be
root.dispose();
});
-it('retains the thread identity when undo reopens a standalone draft from its snapshot', async () => {
- const context = createComposeContext();
- vi.mocked(context.delivery.sendMessage).mockResolvedValue(response);
- vi.mocked(context.drafts.saveDraft).mockResolvedValue(response);
- vi.mocked(context.delivery.undoSend).mockImplementation(async (input) => {
- await input.onUndone();
- });
- let reopened: ReturnType<typeof mountEmailComposer> | undefined;
- const root = mountEmailComposer(context, {
- showDraft: (draftId) => {
- reopened = mountEmailComposer(context, undefined, { draftId });
+it('keeps a selected or cleared time inert while ordinary autosave continues', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ const selected = new Date('2026-12-01T12:00:00Z');
+ root.edit('Autosave this scheduled-send preparation');
+ expect(root.state.context.schedule.onSelect(selected)).toBe(true);
+ await vi.advanceTimersByTimeAsync(600);
+
+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
+ expect(
+ vi.mocked(composeContext.drafts.saveDraft).mock.calls[0][0]
+ ).not.toHaveProperty('sendTime');
+ expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
+ expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
+ expect(composeContext.delivery.archive).not.toHaveBeenCalled();
+
+ expect(root.state.context.schedule.onSelect(null)).toBe(true);
+ expect(root.state.context.schedule.selectedTime()).toBeUndefined();
+ expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
+ root.dispose();
+});
+
+it('only commits a selected time through the primary action', async () => {
+ const composeContext = createComposeContext();
+ const host = { showThread: vi.fn(), showDraft: vi.fn() };
+ const root = mountEmailComposer(composeContext, host);
+ root.edit('Schedule this');
+ const firstTime = new Date('2026-12-01T12:00:00Z');
+ expect(root.state.context.schedule.onSelect(firstTime)).toBe(true);
+ expect(root.state.context.schedule.selectedTime()).toEqual(firstTime);
+ expect(root.state.context.deliveryState?.()).toBe('draft');
+ expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
+ expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
+ expect(composeContext.notices.feedback.success).not.toHaveBeenCalled();
+
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
+ expect(composeContext.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
+ {
+ draftId: 'draft',
+ sendTime: firstTime.toISOString(),
+ includeSignature: undefined,
},
+ 'inbox'
+ );
+ expect(root.state.context.schedule.confirmedTime()).toEqual(firstTime);
+ expect(root.state.context.deliveryState?.()).toBe('scheduled');
+ expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
+ 'Email scheduled',
+ expect.objectContaining({
+ // The year appears only when the send is not this year.
+ subtext: expect.stringMatching(/^Sends Tue, Dec 1(, 2026)? at 12:00 PM$/),
+ actions: [
+ expect.objectContaining({ label: 'Undo' }),
+ expect.objectContaining({ label: 'View message', kind: 'open' }),
+ ],
+ duration: 8_000,
+ })
+ );
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.schedule).toHaveBeenCalledOnce();
+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
+
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([message]) => message === 'Email scheduled');
+ host.showThread.mockClear();
+ scheduledNotice?.[1]?.actions?.[1].onClick();
+ expect(host.showThread).toHaveBeenCalledExactlyOnceWith('thread');
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.unschedule).toHaveBeenCalledExactlyOnceWith({
+ draftId: 'draft',
+ inboxId: 'inbox',
});
- try {
- root.edit('Restore this draft');
+ expect(root.state.context.schedule.state()).toEqual({
+ type: 'editing',
+ intent: { type: 'immediate' },
+ });
+ root.dispose();
+});
+
+it('preserves local intent on schedule failure without falling back to send', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Schedule carefully');
+ const sendTime = new Date('2026-12-01T12:00:00Z');
+ vi.mocked(composeContext.delivery.schedule).mockRejectedValueOnce(
+ new Error('schedule offline')
+ );
+
+ expect(root.state.context.schedule.onSelect(sendTime)).toBe(true);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(root.state.context.schedule.selectedTime()).toEqual(sendTime);
+ expect(root.state.context.schedule.state().type).toBe('editing');
+ expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Failed to schedule email'
+ );
+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
+ root.dispose();
+});
+
+it('stops an open scheduled composer when delivery is observed', async () => {
+ const composeContext = createComposeContext();
+ const showThread = vi.fn();
+ const root = mountEmailComposer(composeContext, { showThread });
+ root.edit('Deliver this');
+ root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'));
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ showThread.mockClear();
+
+ composeContext.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(root.state.context.deliveryState?.()).toBe('sent');
+ expect(root.state.context.disabled()).toBe(true);
+ expect(showThread).toHaveBeenCalledExactlyOnceWith('thread');
+ expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
+ 'Scheduled email sent'
+ );
+ root.state.context.onSend();
+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
+ root.dispose();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(composeContext.drafts.deleteDraft).not.toHaveBeenCalled();
+});
+
+it('reconciles an external schedule and cancellation while the composer is open', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Coordinate this draft');
+ await vi.advanceTimersByTimeAsync(600);
+ const sendTime = '2026-12-01T12:00:00Z';
+
+ composeContext.setDraftLifecycle({
+ type: 'scheduled',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime,
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.schedule.confirmedTime()).toEqual(
+ new Date(sendTime)
+ );
+ expect(root.state.context.disabled()).toBe(true);
+
+ composeContext.setDraftLifecycle({
+ type: 'editing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.schedule.confirmedTime()).toBeUndefined();
+ expect(root.state.context.disabled()).toBe(false);
+ expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
+ 'Schedule cancelled. This email is editable again.'
+ );
+ root.dispose();
+});
+
+it('keeps the confirmed time authoritative until update or cancellation succeeds', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Manage this schedule');
+ await vi.advanceTimersByTimeAsync(600);
+ const original = new Date('2026-12-01T12:00:00Z');
+ const replacement = new Date('2026-12-02T14:30:00Z');
+ composeContext.setDraftLifecycle({
+ type: 'scheduled',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime: original.toISOString(),
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(root.state.context.schedule.onSelect(replacement)).toBe(true);
+ expect(root.state.context.schedule.confirmedTime()).toEqual(original);
+ expect(root.state.context.schedule.selectedTime()).toEqual(replacement);
+ expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
+ expect(root.state.context.schedule.onSelect(null)).toBe(true);
+ expect(root.state.context.schedule.confirmedTime()).toEqual(original);
+ expect(composeContext.delivery.unschedule).not.toHaveBeenCalled();
+
+ root.state.context.schedule.onSelect(replacement);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ draftId: 'draft',
+ sendTime: replacement.toISOString(),
+ }),
+ 'inbox'
+ );
+ expect(root.state.context.schedule.confirmedTime()).toEqual(replacement);
+ composeContext.setDraftLifecycle({
+ type: 'scheduled',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime: replacement.toISOString(),
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ vi.mocked(composeContext.delivery.unschedule).mockRejectedValueOnce(
+ new Error('cancel offline')
+ );
+ expect(await root.state.context.schedule.onCancel()).toBe(false);
+ expect(root.state.context.schedule.confirmedTime()).toEqual(replacement);
+ expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Failed to cancel schedule'
+ );
+
+ expect(await root.state.context.schedule.onCancel()).toBe(true);
+ expect(root.state.context.schedule.state().type).toBe('editing');
+ expect(root.state.context.disabled()).toBe(false);
+ root.dispose();
+});
+
+it('unlocks a composer that stays mounted after its schedule is cancelled', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Schedule, then change my mind');
+ expect(
+ root.state.context.schedule.onSelect(new Date('2026-12-01T12:00:00Z'))
+ ).toBe(true);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(composeContext.delivery.schedule).toHaveBeenCalledOnce();
+ expect(root.state.context.disabled()).toBe(true);
+
+ expect(await root.state.context.schedule.onCancel()).toBe(true);
+ expect(root.state.context.schedule.state().type).toBe('editing');
+ expect(root.state.context.disabled()).toBe(false);
+ expect(root.state.context.primaryActionDisabled()).toBe(false);
+ root.dispose();
+});
+
+it('blocks a past local time at submission without sending immediately', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Do not send early');
+ const past = new Date(Date.now() - 1_000);
+ expect(root.state.context.schedule.onSelect(past)).toBe(true);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
+ expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
+ 'That send time has passed. Choose a future time.'
+ );
+ expect(root.state.context.schedule.selectedTime()).toEqual(past);
+ root.dispose();
+});
+
+it('ignores a stale autosave response and preserves a racing edit under a new draft ID', async () => {
+ const composeContext = createComposeContext();
+ const root = mountEmailComposer(composeContext);
+ root.edit('Persisted version');
+ await vi.advanceTimersByTimeAsync(600);
+ const pending = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(composeContext.drafts.saveDraft).mockReturnValueOnce(
+ pending.promise
+ );
+ root.edit('New text that raced delivery');
+ await vi.advanceTimersByTimeAsync(600);
+
+ composeContext.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ pending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(composeContext.drafts.saveDraft).toHaveBeenCalledTimes(3);
+ const preserved = vi.mocked(composeContext.drafts.saveDraft).mock.calls[2][0]
+ .draft;
+ expect(preserved.db_id).toBeUndefined();
+ expect(decodeBase64Utf8(preserved.body_html ?? '')).toContain(
+ 'New text that raced delivery'
+ );
+ expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
+ 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
+ );
+ expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
+ root.dispose();
+});
+
+it('reports delivery specifically when it races draft deletion', async () => {
+ const composeContext = createComposeContext();
+ const showThread = vi.fn();
+ const root = mountEmailComposer(composeContext, { showThread });
+ root.edit('Saved before delete');
+ await vi.advanceTimersByTimeAsync(600);
+ const pending = Promise.withResolvers<void>();
+ vi.mocked(composeContext.drafts.deleteDraft).mockReturnValueOnce(
+ pending.promise
+ );
+
+ const deletion = root.state.deleteDraftAndReset();
+ composeContext.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ pending.reject(new Error('message already sent'));
+ await expect(deletion).rejects.toThrow('message already sent');
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(composeContext.notices.feedback.failure).not.toHaveBeenCalledWith(
+ 'Failed to delete draft'
+ );
+ expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
+ 'This scheduled email was sent. Your composer has been updated.'
+ );
+ expect(showThread).toHaveBeenCalledWith('thread');
+ root.dispose();
+});
+
+it.each([true, false])(
+ 'does not send a recovery draft when pre-send persistence discovers delivery (immediate effect: %s)',
+ async (immediateEffect) => {
+ const context = createComposeContext();
+ const root = mountEmailComposer(context);
+ root.edit('Previously saved');
+ await vi.advanceTimersByTimeAsync(600);
+ const lifecycle = vi.mocked(context.draftLifecycle.observe).mock.results[0]
+ .value;
+ const sent = {
+ type: 'sent' as const,
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ };
+ vi.mocked(lifecycle.refresh).mockImplementationOnce(async () => {
+ if (immediateEffect) context.setDraftLifecycle(sent);
+ return sent;
+ });
+ vi.mocked(context.drafts.saveDraft)
+ .mockRejectedValueOnce(new Error('Message already sent'))
+ .mockResolvedValue({ ...response, draftId: 'recovered' });
+ root.edit('Keep this newer text unsent');
root.state.context.onSend();
await vi.advanceTimersByTimeAsync(0);
+
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
+ if (!immediateEffect) {
+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
+ // The refresh result already stopped Send before Solid applies the state.
+ context.setDraftLifecycle(sent);
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(3);
+ expect(
+ vi.mocked(context.drafts.saveDraft).mock.lastCall?.[0].draft.db_id
+ ).toBeUndefined();
+ expect(root.state.context.disabled()).toBe(false);
root.dispose();
- const notice = vi
- .mocked(context.notices.feedback.success)
- .mock.calls.find(([message]) => message === 'Email sent');
- expect(notice?.[1]?.actions).toHaveLength(1);
- notice?.[1]?.actions?.[0].onClick();
- await vi.advanceTimersByTimeAsync(0);
- expect(reopened).toBeDefined();
- reopened?.edit('Edited after undo');
- await vi.advanceTimersByTimeAsync(600);
- expect(context.drafts.saveDraft).toHaveBeenLastCalledWith(
- expect.objectContaining({
- draft: expect.objectContaining({
- db_id: 'saved-id',
- thread_db_id: 'thread',
- }),
- })
- );
- } finally {
- root.dispose();
- reopened?.dispose();
}
+);
+
+it('recovers local and forwarded attachments without retaining remote-only attachment pills', async () => {
+ const context = createComposeContext();
+ vi.mocked(context.attachmentStorage.uploadAttachments).mockImplementation(
+ async (input) => {
+ for (const file of input.attachments)
+ input.onAttachmentAdded?.(file, `${input.draftId}-attachment`);
+ }
+ );
+ const root = mountEmailComposer(context);
+ const file = new File(['notes'], 'notes.txt');
+ root.edit('Saved with files');
+ root.state.context.onAddAttachments([
+ { type: 'local', file },
+ {
+ type: 'remote',
+ attachmentId: 'remote',
+ url: 'https://example.com/file',
+ fileName: 'remote.txt',
+ contentType: 'text/plain',
+ fileSize: 10,
+ },
+ {
+ type: 'forwarded',
+ attachmentId: 'original-file',
+ fileName: 'forward.txt',
+ mimeType: 'text/plain',
+ fileSize: 10,
+ },
+ ]);
+ await vi.advanceTimersByTimeAsync(600);
+ vi.mocked(context.drafts.saveDraft).mockResolvedValue({
+ ...response,
+ draftId: 'recovered',
+ });
+ root.edit('New text to recover');
+ context.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(context.attachmentStorage.uploadAttachments).toHaveBeenCalledTimes(2);
+ expect(context.attachmentStorage.uploadAttachments).toHaveBeenLastCalledWith(
+ expect.objectContaining({ draftId: 'recovered', attachments: [file] })
+ );
+ expect(
+ context.attachmentStorage.addForwardedAttachments
+ ).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ draftId: 'recovered',
+ attachments: [{ attachmentId: 'original-file' }],
+ })
+ );
+ expect(
+ root.state.context
+ .attachments()
+ .map((attachment) => attachment.attachmentId)
+ ).toEqual(['recovered-attachment', 'original-file']);
+ expect(context.notices.feedback.alert).toHaveBeenCalledWith(
+ 'Previously saved attachments could not be copied to the new draft. Please attach those files again.'
+ );
+ root.dispose();
});
diff --git a/apps/web/src/features/email-compose/primitives/compose-view-state.ts b/apps/web/src/features/email-compose/primitives/compose-view-state.ts
index a02d7160a7..cad3bdfbd2 100644
--- a/apps/web/src/features/email-compose/primitives/compose-view-state.ts
+++ b/apps/web/src/features/email-compose/primitives/compose-view-state.ts
@@ -6,6 +6,7 @@ import type {
EmailRecipient,
} from '../core/email-recipient';
import type { DraftFormAttachment } from './email-form-state';
+import type { EmailScheduleState } from './email-send-schedule';
export type ComposeValidationError = {
type: 'no_recipient' | 'no_message' | 'no_subject' | 'no_link';
@@ -26,7 +27,6 @@ export interface ComposeState {
recipients: () => EmailFormRecipients;
subject: () => string;
attachments: () => DraftFormAttachment[];
- sendTime: () => Date | null | undefined;
initialHtml: () => string | undefined;
initialMarkdown?: () => string | undefined;
@@ -47,13 +47,25 @@ export interface ComposeState {
// Actions
onSend: () => void;
onDelete?: () => void;
- onSendTimeChange?: (date: Date | null) => void;
+ schedule: {
+ state: Accessor<EmailScheduleState>;
+ selectedTime: Accessor<Date | undefined>;
+ confirmedTime: Accessor<Date | undefined>;
+ actionLabel: Accessor<string>;
+ operation: Accessor<'idle' | 'committing' | 'updating' | 'cancelling'>;
+ onSelect(date: Date | null): boolean;
+ onCancel(): Promise<boolean>;
+ pickerDisabled: Accessor<boolean>;
+ };
// Status
disabled: Accessor<boolean>;
+ primaryActionDisabled: Accessor<boolean>;
isSending: Accessor<boolean>;
isSavingDraft?: Accessor<boolean>;
hasDraft: Accessor<boolean>;
+ sendUnavailableReason?: Accessor<string | undefined>;
+ deliveryState?: Accessor<'draft' | 'scheduled' | 'sent' | 'missing'>;
// Validation
validationError: (
@@ -66,9 +78,6 @@ export interface ComposeState {
includeSelf?: boolean;
hideAttachments?: boolean;
- // Schedule send
- scheduleSendDisabled?: Accessor<boolean>;
-
// Display
fromAddress?: Accessor<string | undefined>;
// From-inbox selection: the inboxes the user can send from, the active one,
diff --git a/apps/web/src/features/email-compose/primitives/draft-persistence.ts b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
index 5de2377690..9c9cdbed51 100644
--- a/apps/web/src/features/email-compose/primitives/draft-persistence.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-persistence.ts
@@ -140,7 +140,7 @@ export function createDraftPersistence(options: {
if (session.isStale(epoch)) return;
session.dispatch({ type: 'saved', epoch, identity: saved });
if (!saved.draftId) return;
- const inbox = { inboxId: input.inboxId };
+ const inbox = { inboxId: saved.inboxId };
if (saved.persistence === 'queued') {
// REST cannot resolve client handles. Keep local files for the next
// committed save, which also waits for all uploads before sending.
diff --git a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
index 9472f22a74..9d2de0c7bd 100644
--- a/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-session-scenarios.test.ts
@@ -344,6 +344,8 @@ describe.each(['reply', 'compose'] as const)(
...root,
send: root.sendEmail,
schedule: root.handleSendTimeChange,
+ cancelSchedule: root.cancelSchedule,
+ addAttachment: (file: File) => root.handleAddAttachments([file]),
};
}
const root = mountEmailComposer(context);
@@ -353,10 +355,80 @@ describe.each(['reply', 'compose'] as const)(
root.state.context.onSend();
await vi.advanceTimersByTimeAsync(0);
},
- schedule: root.state.context.onSendTimeChange,
+ schedule: root.state.context.schedule.onSelect,
+ cancelSchedule: root.state.context.schedule.onCancel,
+ addAttachment: (file: File) =>
+ root.state.context.onAddAttachments([{ type: 'local', file }]),
};
};
+ it('commits local schedule intent only after queued handles become server-confirmed', async () => {
+ const context = createComposeContext();
+ vi.mocked(context.drafts.saveDraft).mockImplementation(async (input) =>
+ queued(input)
+ );
+ vi.mocked(context.attachmentStorage.uploadAttachments).mockImplementation(
+ async ({ attachments, onAttachmentAdded }) => {
+ for (const file of attachments) onAttachmentAdded?.(file, 'uploaded');
+ }
+ );
+ const root = mount(context);
+ try {
+ root.edit('Schedule once synced');
+ await root.addAttachment(new File(['bytes'], 'notes.txt'));
+ root.schedule(new Date('2027-01-01T12:00:00Z'));
+ await vi.advanceTimersByTimeAsync(600);
+ await root.send();
+ expect(context.delivery.schedule).not.toHaveBeenCalled();
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(
+ 'Failed to schedule email',
+ {
+ subtext:
+ 'Draft is not ready to schedule. Resolve any save or connection errors and try again',
+ }
+ );
+ expect(
+ context.attachmentStorage.uploadAttachments
+ ).not.toHaveBeenCalled();
+ const observer = vi.mocked(context.draftLifecycle.observe).mock
+ .calls[0][0];
+ expect(observer.draftId()).toBeUndefined();
+ const [first, second] = savedInputs(context);
+ expect(first.clientHandles?.draftId).toBeTruthy();
+ expect(second.clientHandles).toEqual(first.clientHandles);
+ expect(first.draft).not.toHaveProperty('send_time');
+ expect(second.draft).not.toHaveProperty('send_time');
+
+ vi.mocked(context.drafts.saveDraft).mockResolvedValue(
+ committed('scheduled-server')
+ );
+ await root.send();
+ expect(savedInputs(context)[2].clientHandles).toEqual(
+ first.clientHandles
+ );
+ expect(
+ context.attachmentStorage.uploadAttachments
+ ).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({
+ draftId: 'scheduled-server',
+ inboxId: 'inbox',
+ })
+ );
+ expect(context.delivery.schedule).toHaveBeenCalledExactlyOnceWith(
+ {
+ draftId: 'scheduled-server',
+ sendTime: '2027-01-01T12:00:00.000Z',
+ includeSignature: undefined,
+ },
+ 'inbox'
+ );
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
+ } finally {
+ root.dispose();
+ }
+ });
+
it('does not send or schedule over a queued update to an existing server draft', async () => {
const context = createComposeContext();
vi.mocked(context.drafts.saveDraft)
@@ -374,10 +446,19 @@ describe.each(['reply', 'compose'] as const)(
{ subtext: 'Draft still syncing, try again' }
);
await root.schedule?.(new Date('2027-01-01T12:00:00Z'));
+ await root.send();
expect(context.delivery.schedule).not.toHaveBeenCalled();
+ expect(context.notices.feedback.failure).toHaveBeenLastCalledWith(
+ 'Failed to schedule email',
+ {
+ subtext:
+ 'Draft is not ready to schedule. Resolve any save or connection errors and try again',
+ }
+ );
vi.mocked(context.drafts.saveDraft).mockResolvedValue(
committed('existing')
);
+ await root.schedule?.(null);
await root.send();
expect(context.delivery.sendMessage).toHaveBeenCalledOnce();
} finally {
@@ -385,6 +466,40 @@ describe.each(['reply', 'compose'] as const)(
}
});
+ it('resumes saving after a schedule-locked rejection is explicitly cancelled', async () => {
+ const context = createComposeContext();
+ vi.mocked(context.drafts.saveDraft).mockResolvedValue(
+ committed('existing')
+ );
+ const root = mount(context);
+ try {
+ root.edit('Saved content');
+ await vi.advanceTimersByTimeAsync(600);
+ root.schedule(new Date('2027-01-01T12:00:00Z'));
+ vi.mocked(context.drafts.saveDraft).mockImplementationOnce(async () => {
+ context.setDraftLifecycle({
+ type: 'scheduled',
+ draftId: 'existing',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime: '2027-01-01T12:00:00Z',
+ observedAt: Date.now(),
+ });
+ throw new DraftPersistRejected('INVALID');
+ });
+ await root.send();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.delivery.schedule).not.toHaveBeenCalled();
+ expect(await root.cancelSchedule()).toBe(true);
+ root.edit('Editable after cancellation');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(3);
+ expect(savedInputs(context)[2].draft.db_id).toBe('existing');
+ } finally {
+ root.dispose();
+ }
+ });
+
it('does not send a known server draft after autosave has been rejected', async () => {
const context = createComposeContext();
vi.mocked(context.drafts.saveDraft)
diff --git a/apps/web/src/features/email-compose/primitives/draft-session.test.ts b/apps/web/src/features/email-compose/primitives/draft-session.test.ts
index 2a5ccacff0..2fbcee9a77 100644
--- a/apps/web/src/features/email-compose/primitives/draft-session.test.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-session.test.ts
@@ -156,7 +156,7 @@ describe('reduceDraftSession', () => {
}
});
- it('nothing but emptied, reset, or already-sent leaves the latch', () => {
+ it('ordinary persistence events cannot clear a rejection latch', () => {
const keepsLatch: DraftSessionEvent[] = [
{ type: 'minted', draftId: 'h-9' },
{
@@ -175,6 +175,59 @@ describe('reduceDraftSession', () => {
expect(reduceDraftSession(latched, event).policy.kind).toBe('latched');
}
});
+
+ it('adopts inbox, message, and thread atomically only after migration commits', () => {
+ const before = initialDraftSession({
+ draftId: 'draft-a',
+ threadId: 'thread-a',
+ inboxId: 'inbox-a',
+ });
+ const queued = reduceDraftSession(before, {
+ type: 'saved',
+ epoch: before.epoch,
+ identity: {
+ draftId: 'draft-b',
+ threadId: 'thread-b',
+ inboxId: 'inbox-b',
+ persistence: 'queued',
+ },
+ });
+ expect(queued.identity).toEqual({ ...before.identity, queued: true });
+ const committed = reduceDraftSession(queued, {
+ type: 'saved',
+ epoch: queued.epoch,
+ identity: {
+ draftId: 'draft-b',
+ threadId: 'thread-b',
+ inboxId: 'inbox-b',
+ persistence: 'committed',
+ },
+ });
+ expect(committed.identity).toEqual({
+ kind: 'server',
+ draftId: 'draft-b',
+ threadId: 'thread-b',
+ inboxId: 'inbox-b',
+ queued: false,
+ });
+ });
+
+ it('authoritative cancellation clears a schedule rejection without changing identity', () => {
+ const rejected: DraftSessionState = { ...seeded, policy: latched.policy };
+ const resumed = reduceDraftSession(rejected, {
+ type: 'schedule-cancelled',
+ });
+ expect(resumed.identity).toBe(rejected.identity);
+ expect(resumed.policy.kind).toBe('autosaving');
+ expect(resumed.epoch).toBe(rejected.epoch + 1);
+ const unauthorized: DraftSessionState = {
+ ...rejected,
+ policy: { kind: 'latched', code: 'UNAUTHORIZED' },
+ };
+ expect(
+ reduceDraftSession(unauthorized, { type: 'schedule-cancelled' })
+ ).toBe(unauthorized);
+ });
});
describe('createDraftSession', () => {
diff --git a/apps/web/src/features/email-compose/primitives/draft-session.ts b/apps/web/src/features/email-compose/primitives/draft-session.ts
index f3f0cf4194..f9848cf8d0 100644
--- a/apps/web/src/features/email-compose/primitives/draft-session.ts
+++ b/apps/web/src/features/email-compose/primitives/draft-session.ts
@@ -15,8 +15,20 @@ import type {
*/
export type DraftIdentity =
| { kind: 'none' }
- | { kind: 'handle'; draftId: string; threadId?: string; queued: boolean }
- | { kind: 'server'; draftId: string; threadId?: string; queued: boolean };
+ | {
+ kind: 'handle';
+ draftId: string;
+ threadId?: string;
+ inboxId?: string;
+ queued: boolean;
+ }
+ | {
+ kind: 'server';
+ draftId: string;
+ threadId?: string;
+ inboxId?: string;
+ queued: boolean;
+ };
/**
* Whether edits may autosave. A deterministic server rejection latches the
@@ -42,17 +54,27 @@ export type DraftSessionState = {
export type DraftSessionEvent =
/** Mounted on (or restored to) a draft the server already holds. */
- | { type: 'seeded'; draftId?: string | null; threadId?: string | null }
+ | {
+ type: 'seeded';
+ draftId?: string | null;
+ threadId?: string | null;
+ inboxId?: string;
+ }
/** Client handles minted before the first dispatch of a new draft. */
| { type: 'minted'; draftId: string; threadId?: string }
/** A save resolved; `epoch` is the value captured before dispatch. */
| {
type: 'saved';
epoch: number;
- identity: Pick<DraftSaveResult, 'draftId' | 'threadId' | 'persistence'>;
+ identity: Pick<
+ DraftSaveResult,
+ 'draftId' | 'threadId' | 'persistence'
+ > & { inboxId?: string };
}
/** The server rejected a save or delete deterministically. */
| { type: 'rejected'; epoch: number; code: DraftPersistFailureCode }
+ /** An authoritative cancellation makes a schedule-locked draft editable. */
+ | { type: 'schedule-cancelled' }
/** The draft has no content left; its row was (or is being) deleted. */
| { type: 'emptied' }
/** The composer dropped its draft: sent, discarded, or superseded. */
@@ -66,6 +88,7 @@ const FRESH: Omit<DraftSessionState, 'epoch'> = {
export function initialDraftSession(seed?: {
draftId?: string | null;
threadId?: string | null;
+ inboxId?: string;
}): DraftSessionState {
return reduceDraftSession(
{ ...FRESH, epoch: 0 },
@@ -89,6 +112,7 @@ export function reduceDraftSession(
queued: false,
draftId: event.draftId,
threadId: event.threadId ?? undefined,
+ inboxId: event.inboxId,
}
: { kind: 'none' },
policy: { kind: 'autosaving' },
@@ -112,6 +136,9 @@ export function reduceDraftSession(
const draftId = event.identity.draftId ?? currentDraftId(state);
if (!draftId) return state;
const threadId = event.identity.threadId ?? currentThreadId(state);
+ const inboxId =
+ event.identity.inboxId ??
+ (state.identity.kind === 'none' ? undefined : state.identity.inboxId);
if (event.identity.persistence === 'queued') {
// Durable locally under the caller's handles; the server has not
// confirmed them. A server id stays a server id.
@@ -119,12 +146,18 @@ export function reduceDraftSession(
? { ...state, identity: { ...state.identity, queued: true } }
: {
...state,
- identity: { kind: 'handle', draftId, threadId, queued: true },
+ identity: {
+ kind: 'handle',
+ draftId,
+ threadId,
+ inboxId,
+ queued: true,
+ },
};
}
return {
...state,
- identity: { kind: 'server', draftId, threadId, queued: false },
+ identity: { kind: 'server', draftId, threadId, inboxId, queued: false },
};
})
.with({ type: 'rejected' }, (event) => {
@@ -136,6 +169,15 @@ export function reduceDraftSession(
}
return { ...state, policy: { kind: 'latched', code: event.code } };
})
+ .with({ type: 'schedule-cancelled' }, () => {
+ if (state.policy.kind !== 'latched' || state.policy.code !== 'INVALID')
+ return state;
+ return {
+ ...state,
+ policy: { kind: 'autosaving' },
+ epoch: state.epoch + 1,
+ };
+ })
.with({ type: 'emptied' }, { type: 'reset' }, () => {
// A fresh draft: nothing in flight belongs to it, and a rejection
// latched against the previous content must not keep it from saving.
@@ -157,6 +199,7 @@ export type DraftSession = ReturnType<typeof createDraftSession>;
export function createDraftSession(seed?: {
draftId?: string | null;
threadId?: string | null;
+ inboxId?: string;
}) {
const [state, setState] = createSignal(initialDraftSession(seed));
return {
@@ -170,6 +213,10 @@ export function createDraftSession(seed?: {
identity: () => state().identity,
draftId: () => currentDraftId(state()),
threadId: () => currentThreadId(state()),
+ inboxId: () => {
+ const identity = state().identity;
+ return identity.kind === 'none' ? undefined : identity.inboxId;
+ },
/** The server holds the draft under these ids, so any transport can address it. */
serverConfirmed: () => {
const identity = state().identity;
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.test.ts b/apps/web/src/features/email-compose/primitives/email-composer.test.ts
index 7e388b1e95..1658d8fd79 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.test.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.test.ts
@@ -50,7 +50,7 @@ describe('standalone compose controller', () => {
}
});
- it('reports scheduling failure without adopting an unconfirmed time, and keeps a confirmed schedule when archive fails', async () => {
+ it('keeps a picked time local and preserves it when explicit scheduling fails', async () => {
const context = createComposeContext();
const root = mountEmailComposer(context);
try {
@@ -59,16 +59,22 @@ describe('standalone compose controller', () => {
vi.mocked(context.delivery.schedule).mockRejectedValueOnce(
new Error('offline')
);
- await root.state.context.onSendTimeChange?.(requested);
- expect(root.state.context.sendTime()).toBeFalsy();
+ expect(root.state.context.schedule.onSelect(requested)).toBe(true);
+ expect(root.state.context.schedule.selectedTime()).toEqual(requested);
+ expect(context.delivery.schedule).not.toHaveBeenCalled();
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.schedule.selectedTime()).toEqual(requested);
+ expect(root.state.context.schedule.state().type).toBe('editing');
expect(context.notices.feedback.failure).toHaveBeenCalledWith(
- 'Failed to schedule message'
+ 'Failed to schedule email'
);
vi.mocked(context.delivery.archive).mockRejectedValueOnce(
new Error('archive offline')
);
- await root.state.context.onSendTimeChange?.(requested);
- expect(root.state.context.sendTime()).toEqual(requested);
+ root.state.context.onSend();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.schedule.confirmedTime()).toEqual(requested);
expect(context.notices.feedback.failure).toHaveBeenCalledWith(
'Email scheduled, but unable to mark thread done'
);
@@ -84,21 +90,23 @@ describe('standalone compose controller', () => {
const root = mountEmailComposer(context);
try {
root.edit('Schedule this reply', 'Schedule review');
- const request = root.state.context.onSendTimeChange?.(
- new Date('2026-10-01T12:00:00Z')
- );
+ root.state.context.schedule.onSelect(new Date('2026-10-01T12:00:00Z'));
+ root.state.context.onSend();
await vi.advanceTimersByTimeAsync(0);
expect(context.delivery.schedule).toHaveBeenCalledOnce();
expect(root.state.context.disabled()).toBe(true);
root.state.context.onSend();
- await root.state.context.onSendTimeChange?.(
- new Date('2026-10-02T12:00:00Z')
- );
+ expect(
+ root.state.context.schedule.onSelect(new Date('2026-10-02T12:00:00Z'))
+ ).toBe(false);
expect(context.delivery.sendMessage).not.toHaveBeenCalled();
expect(context.delivery.schedule).toHaveBeenCalledOnce();
pending.resolve();
- await request;
- expect(root.state.context.disabled()).toBe(false);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(root.state.context.disabled()).toBe(true);
+ expect(root.state.context.sendUnavailableReason?.()).toContain(
+ 'Scheduled for'
+ );
expect(root.state.draftDirty()).toBe(true);
} finally {
pending.resolve();
diff --git a/apps/web/src/features/email-compose/primitives/email-composer.ts b/apps/web/src/features/email-compose/primitives/email-composer.ts
index d16970233c..089a97a578 100644
--- a/apps/web/src/features/email-compose/primitives/email-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/email-composer.ts
@@ -6,7 +6,13 @@ import {
} from '@macro-inc/lexical-core';
import * as EmailValidator from 'email-validator';
import type { LexicalEditor } from 'lexical';
-import { type Accessor, createMemo, createSignal } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+} from 'solid-js';
import { unwrap } from 'solid-js/store';
import type {
EmailContact,
@@ -19,6 +25,7 @@ import type {
EmailComposeHost,
EmailConnectivity,
EmailDelivery,
+ EmailDraftLifecycleSource,
EmailDraftStorage,
PersistedEmailIdentity,
} from '../context/compose-capabilities';
@@ -76,6 +83,7 @@ export type EmailComposerOptions = {
drafts: EmailDraftStorage;
attachmentStorage: EmailAttachmentStorage;
delivery: EmailDelivery;
+ draftLifecycle: EmailDraftLifecycleSource;
notices: EmailComposeFeedback;
accounts: EmailComposeAccounts;
connectivity: EmailConnectivity;
@@ -95,6 +103,9 @@ export type EmailComposerOptions = {
export function createEmailComposer(props: EmailComposerOptions) {
const initialDraftId = props.draft?.db_id ?? props.draftId;
+ const restoredSnapshot = initialDraftId
+ ? composeUndo.take(initialDraftId)
+ : undefined;
const hasPaidAccess = props.hasPaidAccess;
const form = createEmailFormState(
@@ -144,36 +155,44 @@ export function createEmailComposer(props: EmailComposerOptions) {
const [editor, setEditor] = createSignal<LexicalEditor | undefined>();
const [content, setContent] = createSignal('');
- // The draft's persisted identity — and whether the server has confirmed
- // it, which the REST-only send and schedule depend on. The thread it lives
- // under is part of it: switching the sending inbox re-homes the draft
- // server-side, so the previous thread's soup row must be dropped after
- // the save.
+ // The selected sender can change before the server migrates the draft.
+ // Lifecycle reads always use one complete persisted identity.
const session = createDraftSession(
initialDraftId
- ? { draftId: initialDraftId, threadId: props.draft?.thread_db_id }
+ ? {
+ draftId: initialDraftId,
+ threadId: restoredSnapshot?.threadId ?? props.draft?.thread_db_id,
+ inboxId: restoredSnapshot?.inboxId ?? props.draft?.link_id,
+ }
: undefined
);
const currentDraftId = session.draftId;
const currentThreadId = session.threadId;
+ const persistedInboxId = session.inboxId;
+ const [movingInbox, setMovingInbox] = createSignal(false);
+ let identityVersion = 0;
+ let editVersion = 0;
+ let persistedEditVersion = 0;
+ const lifecycle = props.draftLifecycle.observe({
+ draftId: () => (session.serverConfirmed() ? currentDraftId() : undefined),
+ threadId: currentThreadId,
+ inboxId: persistedInboxId,
+ });
const attachmentPersistence = createAttachmentPersistence({
services: props.attachmentStorage,
attachments: form.attachments,
- draftId: currentDraftId,
- inboxId: activeInboxId,
+ draftId: () => (session.serverConfirmed() ? currentDraftId() : undefined),
+ inboxId: persistedInboxId,
});
// Restore form state from undo-send snapshot if available
- const restoredSnapshot = initialDraftId
- ? composeUndo.take(initialDraftId)
- : undefined;
-
if (restoredSnapshot) {
session.dispatch({
type: 'seeded',
draftId: restoredSnapshot.draftId,
threadId: restoredSnapshot.threadId,
+ inboxId: restoredSnapshot.inboxId,
});
form.setSelectedInbox(restoredSnapshot.inboxId);
form.setRecipients('to', restoredSnapshot.recipients.to);
@@ -203,8 +222,8 @@ export function createEmailComposer(props: EmailComposerOptions) {
// --- Draft persistence ---
- function collectDraft() {
- $removeAllWatermarkNodes(editor());
+ function collectDraft(forDelivery = false) {
+ if (!forDelivery) $removeAllWatermarkNodes(editor());
const prepared = prepareEmailBody(editor());
if (!prepared) {
props.notices.reportError(
@@ -230,37 +249,90 @@ export function createEmailComposer(props: EmailComposerOptions) {
cc: form.recipients().cc.map(convertEmailRecipientToContactInfo),
subject: form.subject(),
to: form.recipients().to.map(convertEmailRecipientToContactInfo),
+ include_signature: includeSignature() ? undefined : false,
};
}
+ async function reportPersistenceFailure(
+ error: unknown,
+ operation: 'save' | 'delete'
+ ) {
+ props.notices.reportError(error);
+ if (!session.serverConfirmed()) {
+ if (schedule?.pending()) {
+ props.notices.feedback.failure(`Failed to ${operation} draft`);
+ }
+ return;
+ }
+ let state;
+ try {
+ state = await lifecycle.refresh();
+ } catch (refreshError) {
+ props.notices.reportError(refreshError);
+ }
+ if (
+ state &&
+ state.draftId === currentDraftId() &&
+ state.threadId === currentThreadId() &&
+ state.inboxId === persistedInboxId()
+ ) {
+ if (state.type !== 'editing') {
+ // Abort an awaiting Send directly. The reactive lifecycle effect may
+ // apply this observation after the save rejection resumes.
+ identityVersion += 1;
+ }
+ if (state.type === 'sent') {
+ props.notices.feedback.alert(
+ 'This scheduled email was sent. Your composer has been updated.'
+ );
+ return;
+ }
+ }
+ props.notices.feedback.failure(`Failed to ${operation} draft`);
+ }
+
const persistence = createDraftPersistence({
session,
drafts: props.drafts,
attachments: attachmentPersistence,
mintThreadHandle: true,
onAlreadySent: () => {
- props.notices.feedback.alert('This email was already sent');
- // Discarding pauses the save that clearing schedules.
- setDiscarding(true);
+ identityVersion += 1;
autosave.cancel();
- try {
- resetState();
- } finally {
- setDiscarding(false);
- }
+ props.notices.feedback.alert('This email was already sent');
+ resetState();
},
});
- async function persistDraft(
- draft: ReturnType<typeof collectDraft>,
- inboxId: string | undefined
- ) {
- if (!draft) {
- await persistence.remove({ inboxId });
- return;
+ async function persistDraft({
+ draft: draftToSave,
+ inboxId,
+ generation,
+ revision,
+ }: {
+ draft: ReturnType<typeof collectDraft>;
+ inboxId: string | undefined;
+ generation: number;
+ revision: number;
+ }) {
+ if (generation !== identityVersion) return;
+ try {
+ if (!draftToSave) {
+ await persistence.remove({ inboxId });
+ if (generation === identityVersion)
+ persistedEditVersion = Math.max(persistedEditVersion, revision);
+ return;
+ }
+ const saved = await persistence.save({ draft: draftToSave, inboxId });
+ if (generation !== identityVersion || !saved) return;
+ if (saved.persistence !== 'queued')
+ persistedEditVersion = Math.max(persistedEditVersion, revision);
+ return saved.draftId;
+ } catch (error) {
+ if (generation === identityVersion)
+ await reportPersistenceFailure(error, draftToSave ? 'save' : 'delete');
+ throw error;
}
- const saved = await persistence.save({ draft, inboxId });
- return saved?.draftId;
}
// Edits since the composer opened; an untouched existing draft can be
@@ -271,18 +343,88 @@ export function createEmailComposer(props: EmailComposerOptions) {
'idle' | 'preparing' | 'sending'
>('idle');
const submitting = () => sendPhase() !== 'idle';
- const sending = () => sendPhase() === 'sending';
const [discarding, setDiscarding] = createSignal(false);
- let completed = false;
- const persistencePaused = () => submitting() || discarding() || completed;
+ const [completed, setCompleted] = createSignal(false);
+ const [terminalState, setTerminalState] = createSignal<
+ 'sent' | 'missing' | undefined
+ >();
+ let schedule: ReturnType<typeof createEmailSendSchedule>;
+ const persistencePaused = () =>
+ submitting() ||
+ discarding() ||
+ movingInbox() ||
+ completed() ||
+ schedule?.pending() ||
+ schedule?.state().type === 'scheduled';
const autosave = createDraftAutosave({
- capture: () => ({ draft: collectDraft(), inboxId: activeInboxId() }),
- persist: ({ draft, inboxId }) => persistDraft(draft, inboxId),
+ capture: () => ({
+ draft: collectDraft(),
+ inboxId: activeInboxId(),
+ generation: identityVersion,
+ revision: editVersion,
+ }),
+ persist: persistDraft,
paused: persistencePaused,
});
+
+ const saveForSchedule = async () => {
+ const currentEditor = editor();
+ const cleanupWatermark = $appendWatermarkNodeToLast(
+ currentEditor,
+ !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
+ );
+ try {
+ return persistence.confirmed(
+ await autosave.save({
+ draft: collectDraft(true),
+ inboxId: activeInboxId(),
+ generation: identityVersion,
+ revision: editVersion,
+ })
+ );
+ } finally {
+ cleanupWatermark();
+ }
+ };
+
+ schedule = createEmailSendSchedule({
+ delivery: props.delivery,
+ notices: props.notices,
+ initialScheduledTime: props.draft?.scheduled_send_time
+ ? new Date(props.draft.scheduled_send_time)
+ : undefined,
+ draftId: currentDraftId,
+ saveDraft: saveForSchedule,
+ threadId: currentThreadId,
+ inboxId: activeInboxId,
+ includeSignature: () => (includeSignature() ? undefined : false),
+ generation: () =>
+ `${identityVersion}:${editVersion}:${activeInboxId() ?? ''}`,
+ lifecycleState: lifecycle.state,
+ reconcile: lifecycle.refresh,
+ reconcileIdentity: lifecycle.refreshIdentity,
+ onScheduleUndone: ({ draftId }) => {
+ session.dispatch({ type: 'schedule-cancelled' });
+ setCompleted(false);
+ props.host?.showDraft?.(draftId);
+ },
+ onViewScheduled: ({ draftId, threadId }) => {
+ if (threadId) props.host?.showThread?.(threadId);
+ else props.host?.showDraft?.(draftId);
+ },
+ });
+ const cancelSchedule = async () => {
+ if (!(await schedule.cancel())) return false;
+ session.dispatch({ type: 'schedule-cancelled' });
+ // An in-place schedule marked the composer complete; a host that keeps it
+ // mounted must get an editable draft back, as Undo does.
+ setCompleted(false);
+ return true;
+ };
const markDirtyAndScheduleSave = () => {
if (persistencePaused()) return;
+ editVersion += 1;
setDraftDirty(true);
autosave.schedule();
};
@@ -290,6 +432,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
// --- Attachment handling ---
const handleAddAttachments = async (attachments: DraftFormAttachment[]) => {
+ if (persistencePaused()) return;
if (await refuseAttachmentsOffline(props.connectivity, props.notices))
return;
for (const attachment of attachments) {
@@ -299,6 +442,8 @@ export function createEmailComposer(props: EmailComposerOptions) {
};
const handleRemoveAttachment = (attachment: DraftFormAttachment) => {
+ if (persistencePaused()) return;
+ editVersion += 1;
setDraftDirty(true);
attachmentPersistence.remove(attachment);
};
@@ -398,7 +543,15 @@ export function createEmailComposer(props: EmailComposerOptions) {
};
const onSubmit = async () => {
- if (scheduling() || persistencePaused()) return;
+ if (
+ schedule.pending() ||
+ submitting() ||
+ discarding() ||
+ movingInbox() ||
+ completed() ||
+ terminalState()
+ )
+ return;
setValidationError(null);
const currentEditor = editor();
@@ -437,15 +590,31 @@ export function createEmailComposer(props: EmailComposerOptions) {
return;
}
- // Failsafe: don't send if a scheduled send time is set
- if (form.sendTime()) {
- return;
- }
-
const offline = sendRefusalBeforeSave(props.connectivity);
if (offline) return refuseSend(props.notices, offline);
+ const scheduleAction = schedule.action();
+ if (scheduleAction === 'unavailable') {
+ props.notices.feedback.alert(
+ `This email is scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`
+ );
+ return;
+ }
+ if (scheduleAction === 'schedule' || scheduleAction === 'update') {
+ const result = await schedule.submit();
+ if (result === 'scheduled') {
+ setCompleted(true);
+ const threadId = currentThreadId();
+ try {
+ if (threadId) props.host?.showThread?.(threadId);
+ } catch (error) {
+ props.notices.reportError(error);
+ }
+ }
+ return;
+ }
setSendPhase('preparing');
+ const sendGeneration = identityVersion;
try {
// Ensure the draft is saved before sending so undo-send always has a
// draft id to snapshot and restore (the send reuses the draft's db_id).
@@ -468,8 +637,14 @@ export function createEmailComposer(props: EmailComposerOptions) {
});
if (refusal) return refuseSend(props.notices, refusal);
- // Scheduling may have started while the draft save was pending.
- if (scheduling() || form.sendTime()) return;
+ if (
+ sendGeneration !== identityVersion ||
+ completed() ||
+ terminalState() ||
+ schedule.pending() ||
+ schedule.action() !== 'send'
+ )
+ return;
const draftId = identity.kind === 'server' ? identity.draftId : undefined;
// Snapshot editor state before watermark so undo-send can restore it
@@ -531,8 +706,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
inboxId: activeInboxId(),
});
- completed = true;
- // The draft is sent: nothing still on the wire belongs to it.
+ setCompleted(true);
session.dispatch({ type: 'reset' });
afterSend(result, currentLink.id);
} finally {
@@ -540,37 +714,18 @@ export function createEmailComposer(props: EmailComposerOptions) {
}
} catch (error) {
props.notices.reportError(error);
- if (!completed) props.notices.feedback.failure('Failed to send email');
+ if (!completed()) props.notices.feedback.failure('Failed to send email');
} finally {
setSendPhase('idle');
}
};
- // --- Schedule ---
-
- const totalRecipientCount = () => {
- const recipients = form.recipients();
- return recipients.to.length + recipients.cc.length + recipients.bcc.length;
- };
- const schedule = createEmailSendSchedule({
- delivery: props.delivery,
- notices: props.notices,
- draftId: currentDraftId,
- saveDraft: async () => persistence.confirmed(await autosave.save()),
- threadId: currentThreadId,
- inboxId: activeInboxId,
- sendTime: form.sendTime,
- setSendTime: (date) => {
- form.setSendTime(date);
- setDraftDirty(true);
- },
- recipientCount: totalRecipientCount,
- });
const scheduling = schedule.pending;
- const scheduleBlocked = () => sending() || discarding() || completed;
+ const scheduleBlocked = () =>
+ submitting() || discarding() || movingInbox() || completed();
const handleSendTimeChange = (date: Date | null) => {
- if (scheduleBlocked()) return Promise.resolve();
- return schedule.change(date);
+ if (scheduleBlocked()) return false;
+ return schedule.select(date);
};
// --- Reset / delete ---
@@ -580,9 +735,17 @@ export function createEmailComposer(props: EmailComposerOptions) {
setContent('');
session.dispatch({ type: 'reset' });
form.clear();
+ schedule.reset();
+ setTerminalState(undefined);
};
const deleteDraftAndReset = async () => {
+ if (schedule.state().type === 'scheduled') {
+ props.notices.feedback.alert(
+ 'Cancel the schedule before deleting this draft.'
+ );
+ return false;
+ }
if (persistencePaused() || scheduling()) return false;
setDiscarding(true);
autosave.cancel();
@@ -592,13 +755,25 @@ export function createEmailComposer(props: EmailComposerOptions) {
await autosave.settled().catch(() => {});
const draftId = currentDraftId();
if (draftId) {
- await deleteDraftForDiscard(
- props.drafts,
- { draftId, threadId: currentThreadId(), inboxId: activeInboxId() },
- props.notices,
- 'This email was already sent'
- );
+ try {
+ await deleteDraftForDiscard(
+ props.drafts,
+ {
+ draftId,
+ threadId: currentThreadId(),
+ inboxId: activeInboxId(),
+ },
+ props.notices,
+ 'This email was already sent'
+ );
+ } catch (error) {
+ await reportPersistenceFailure(error, 'delete');
+ setDiscarding(false);
+ void lifecycle.refresh().catch(props.notices.reportError);
+ throw error;
+ }
}
+ identityVersion += 1;
resetState();
return true;
} finally {
@@ -606,6 +781,124 @@ export function createEmailComposer(props: EmailComposerOptions) {
}
};
+ const detachFromObsoleteDraft = (message: string) => {
+ identityVersion += 1;
+ autosave.cancel();
+ session.dispatch({ type: 'reset' });
+ const omittedAttachments = attachmentPersistence.detach();
+ schedule.detach();
+ setCompleted(false);
+ setTerminalState(undefined);
+ persistedEditVersion = 0;
+ props.notices.feedback.alert(message);
+ if (omittedAttachments) {
+ props.notices.feedback.alert(
+ 'Previously saved attachments could not be copied to the new draft. Please attach those files again.'
+ );
+ }
+ void autosave.save().catch(() => {});
+ };
+
+ let lastScheduledTime = schedule.confirmedTime()?.toISOString();
+ let handledTerminalIdentity: string | undefined;
+ createEffect(
+ on([lifecycle.state, scheduling, movingInbox], ([state, , moving]) => {
+ if (
+ !state ||
+ !session.serverConfirmed() ||
+ state.draftId !== currentDraftId() ||
+ state.threadId !== currentThreadId() ||
+ (state.inboxId !== undefined && state.inboxId !== persistedInboxId()) ||
+ moving ||
+ discarding()
+ )
+ return;
+
+ if (state.type === 'scheduled') {
+ if (editVersion > persistedEditVersion) {
+ detachFromObsoleteDraft(
+ 'This email was scheduled in another tab. Your newer text was kept as a new draft.'
+ );
+ return;
+ }
+ const nextTime = new Date(state.sendTime);
+ const changedElsewhere =
+ !schedule.confirmedTime() ||
+ schedule.confirmedTime()?.getTime() !== nextTime.getTime();
+ schedule.observe(state);
+ if (changedElsewhere && lastScheduledTime !== state.sendTime) {
+ props.notices.feedback.alert(
+ `Email scheduled for ${nextTime.toLocaleString()}. Cancel the schedule to edit.`
+ );
+ }
+ lastScheduledTime = state.sendTime;
+ return;
+ }
+
+ if (state.type === 'editing') {
+ const wasScheduled = schedule.state().type === 'scheduled';
+ schedule.observe(state);
+ if (wasScheduled && schedule.state().type === 'editing') {
+ session.dispatch({ type: 'schedule-cancelled' });
+ lastScheduledTime = undefined;
+ props.notices.feedback.success(
+ 'Schedule cancelled. This email is editable again.'
+ );
+ }
+ return;
+ }
+
+ if (handledTerminalIdentity === `${state.draftId}:${state.type}`) return;
+ handledTerminalIdentity = `${state.draftId}:${state.type}`;
+ if (editVersion > persistedEditVersion) {
+ detachFromObsoleteDraft(
+ state.type === 'sent'
+ ? 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
+ : 'The draft changed elsewhere. Your newer text was kept as a new draft.'
+ );
+ return;
+ }
+
+ identityVersion += 1;
+ autosave.cancel();
+ session.dispatch({ type: 'reset' });
+ schedule.detach();
+ setCompleted(true);
+ setTerminalState(state.type);
+ if (state.type === 'sent') {
+ props.notices.feedback.success('Scheduled email sent');
+ props.host?.showThread?.(state.threadId);
+ } else {
+ props.notices.feedback.alert('This draft is no longer available.');
+ props.host?.goBack?.();
+ }
+ })
+ );
+
+ const selectInbox = async (inboxId: string) => {
+ if (
+ submitting() ||
+ discarding() ||
+ movingInbox() ||
+ completed() ||
+ schedule.state().type === 'scheduled' ||
+ scheduling()
+ )
+ return;
+ setMovingInbox(true);
+ try {
+ form.setSelectedInbox(inboxId);
+ editVersion += 1;
+ setDraftDirty(true);
+ autosave.cancel();
+ await autosave.save();
+ } catch {
+ // Persistence reports failures; replay lifecycle after the move settles.
+ } finally {
+ setMovingInbox(false);
+ }
+ };
+
// --- Derived state ---
const initialHtml = () => {
@@ -670,15 +963,16 @@ export function createEmailComposer(props: EmailComposerOptions) {
recipients: form.recipients,
subject: form.subject,
attachments: form.attachments.list,
- sendTime: form.sendTime,
initialHtml,
// Form state (write)
setRecipients: (field, value) => {
+ if (persistencePaused() || scheduling()) return;
form.setRecipients(field, value);
markDirtyAndScheduleSave();
},
setSubject: (value) => {
+ if (persistencePaused() || scheduling()) return;
form.setSubject(value);
markDirtyAndScheduleSave();
},
@@ -692,12 +986,54 @@ export function createEmailComposer(props: EmailComposerOptions) {
// Actions
onSend: () => void onSubmit(),
onDelete: () => void deleteDraftAndReset().catch(() => {}),
- onSendTimeChange: handleSendTimeChange,
+ schedule: {
+ state: schedule.state,
+ selectedTime: schedule.selectedTime,
+ confirmedTime: schedule.confirmedTime,
+ actionLabel: schedule.actionLabel,
+ operation: schedule.operation,
+ onSelect: handleSendTimeChange,
+ onCancel: cancelSchedule,
+ pickerDisabled: () => scheduleBlocked() || scheduling(),
+ },
// Status
- disabled: () => hasInboxError() || persistencePaused() || scheduling(),
- isSending: submitting,
+ disabled: () =>
+ hasInboxError() ||
+ submitting() ||
+ discarding() ||
+ movingInbox() ||
+ completed() ||
+ terminalState() !== undefined ||
+ scheduling() ||
+ schedule.state().type === 'scheduled',
+ primaryActionDisabled: () =>
+ hasInboxError() ||
+ submitting() ||
+ discarding() ||
+ movingInbox() ||
+ completed() ||
+ terminalState() !== undefined ||
+ scheduling() ||
+ schedule.action() === 'unavailable',
+ isSending: () => submitting() || scheduling(),
hasDraft: () => currentDraftId() != null,
+ deliveryState: () =>
+ terminalState() ??
+ (schedule.state().type === 'scheduled' ? 'scheduled' : 'draft'),
+ sendUnavailableReason: () => {
+ if (terminalState() === 'sent')
+ return 'This email has already been sent.';
+ if (terminalState() === 'missing')
+ return 'This draft is no longer available.';
+ if (schedule.operation() === 'committing') return 'Scheduling email…';
+ if (schedule.operation() === 'updating') return 'Updating schedule…';
+ if (schedule.operation() === 'cancelling') return 'Cancelling schedule…';
+ if (submitting()) return 'Sending…';
+ if (schedule.action() === 'unavailable')
+ return `Scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`;
+ return undefined;
+ },
// Validation
validationError: (type) => {
@@ -710,10 +1046,6 @@ export function createEmailComposer(props: EmailComposerOptions) {
recipientOptions: getRecipientOptions,
focusRecipientsOnMount: !hasInboxError(),
- // Schedule send
- scheduleSendDisabled: () =>
- totalRecipientCount() === 0 || scheduling() || persistencePaused(),
-
// Display
fromAddress: () => link()?.email_address,
fromInboxes: () => props.accounts.inboxes() ?? [],
@@ -721,11 +1053,7 @@ export function createEmailComposer(props: EmailComposerOptions) {
// Persist immediately on a sender switch so the draft moves to the new
// inbox even without a text edit.
onSelectInbox: (inboxId) => {
- if (persistencePaused() || scheduling()) return;
- form.setSelectedInbox(inboxId);
- setDraftDirty(true);
- autosave.cancel();
- void autosave.save().catch(() => {});
+ void selectInbox(inboxId);
},
hasPaidAccess,
};
diff --git a/apps/web/src/features/email-compose/primitives/email-form-state.ts b/apps/web/src/features/email-compose/primitives/email-form-state.ts
index 83791f2947..8dd93817b5 100644
--- a/apps/web/src/features/email-compose/primitives/email-form-state.ts
+++ b/apps/web/src/features/email-compose/primitives/email-form-state.ts
@@ -50,7 +50,6 @@ type EmailFormState = {
replyType: ReplyType;
withQuotedText: boolean;
subject: string;
- sendTime?: Date;
};
const EMPTY_FORM_STATE: EmailFormState = {
@@ -153,9 +152,6 @@ export function createEmailFormState(
replyType,
withQuotedText: draftContainsAppendedReply(),
subject: initialSubject,
- sendTime: draft?.scheduled_send_time
- ? new Date(draft.scheduled_send_time)
- : undefined,
} satisfies EmailFormState;
};
@@ -253,10 +249,6 @@ export function createEmailFormState(
setRecipients('bcc', recalculated.bcc);
};
- const setSendTime = (date: Date | null) => {
- setState('sendTime', date ?? undefined);
- };
-
const callDirty = () => {
setEditRevision((revision) => revision + 1);
};
@@ -285,8 +277,6 @@ export function createEmailFormState(
selectedInboxId,
setSelectedInbox,
editRevision,
- sendTime: () => state.sendTime,
- setSendTime,
reset: () => reset(getInitialState()),
clear: () => reset({ ...EMPTY_FORM_STATE }),
attachments: {
diff --git a/apps/web/src/features/email-compose/primitives/email-send-schedule.ts b/apps/web/src/features/email-compose/primitives/email-send-schedule.ts
index b3c2f44b23..e5bc17d9bf 100644
--- a/apps/web/src/features/email-compose/primitives/email-send-schedule.ts
+++ b/apps/web/src/features/email-compose/primitives/email-send-schedule.ts
@@ -1,69 +1,331 @@
-import { type Accessor, createEffect, createSignal, on } from 'solid-js';
+import { format } from 'date-fns/format';
+import { isThisYear } from 'date-fns/isThisYear';
+import { type Accessor, createSignal } from 'solid-js';
import type {
EmailComposeFeedback,
EmailDelivery,
+ EmailDraftLifecycleState,
} from '../context/compose-capabilities';
+export type EmailDeliveryIntent =
+ | { type: 'immediate' }
+ | { type: 'later'; sendTime: Date };
+
+export type EmailScheduleState =
+ | { type: 'editing'; intent: EmailDeliveryIntent }
+ | { type: 'scheduled'; confirmedTime: Date; proposedTime?: Date };
+
+export type EmailScheduleAction =
+ | 'send'
+ | 'schedule'
+ | 'update'
+ | 'unavailable';
+
+export function getScheduleSelection(state: EmailScheduleState) {
+ if (state.type === 'editing') {
+ return state.intent.type === 'later' ? state.intent.sendTime : undefined;
+ }
+ return state.proposedTime ?? state.confirmedTime;
+}
+
+export function getScheduleAction(
+ state: EmailScheduleState
+): EmailScheduleAction {
+ if (state.type === 'editing') {
+ return state.intent.type === 'later' ? 'schedule' : 'send';
+ }
+ return state.proposedTime ? 'update' : 'unavailable';
+}
+
+export function getScheduleActionLabel(state: EmailScheduleState) {
+ switch (getScheduleAction(state)) {
+ case 'schedule':
+ return 'Schedule send';
+ case 'update':
+ return 'Update schedule';
+ default:
+ return 'Send email';
+ }
+}
+
+const sameTime = (left: Date, right: Date) =>
+ left.getTime() === right.getTime();
+
export function createEmailSendSchedule(options: {
delivery: Pick<EmailDelivery, 'schedule' | 'unschedule' | 'archive'>;
notices: EmailComposeFeedback;
+ initialScheduledTime?: Date;
draftId: Accessor<string | null | undefined>;
saveDraft: () => Promise<string | undefined>;
threadId: Accessor<string | null | undefined>;
inboxId: Accessor<string | undefined>;
- sendTime: Accessor<Date | null | undefined>;
- setSendTime: (date: Date | null) => void;
- recipientCount: Accessor<number>;
+ includeSignature: Accessor<boolean | undefined>;
+ /** Changes whenever the persisted draft identity or editable content changes. */
+ generation: Accessor<string>;
+ lifecycleState?: Accessor<EmailDraftLifecycleState | undefined>;
+ reconcile?: () => Promise<EmailDraftLifecycleState | undefined>;
+ reconcileIdentity?: (input: {
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+ }) => Promise<EmailDraftLifecycleState | undefined>;
+ onScheduleUndone?: (input: {
+ draftId: string;
+ threadId: string | undefined;
+ inboxId: string | undefined;
+ sendTime: Date;
+ }) => Promise<void> | void;
+ /** Opens the scheduled message; the success notice offers it when present. */
+ onViewScheduled?: (input: {
+ draftId: string;
+ threadId: string | undefined;
+ inboxId: string | undefined;
+ }) => void;
}) {
const { delivery, notices } = options;
- const [pending, setPending] = createSignal(false);
+ const [state, setState] = createSignal<EmailScheduleState>(
+ options.initialScheduledTime
+ ? {
+ type: 'scheduled',
+ confirmedTime: options.initialScheduledTime,
+ }
+ : { type: 'editing', intent: { type: 'immediate' } }
+ );
+ const [operation, setOperation] = createSignal<
+ 'idle' | 'committing' | 'updating' | 'cancelling'
+ >('idle');
+ let selectionRevision = 0;
+ let ignoredLifecycleObservation: EmailDraftLifecycleState | undefined;
+ let deferredLifecycleObservation: EmailDraftLifecycleState | undefined;
- const change = async (date: Date | null) => {
- if (pending()) return;
- const inboxId = options.inboxId();
- setPending(true);
+ const pending = () => operation() !== 'idle';
+ const selectedTime = () => getScheduleSelection(state());
+ const confirmedTime = () => {
+ const current = state();
+ return current.type === 'scheduled' ? current.confirmedTime : undefined;
+ };
+
+ /** Picker changes are deliberately local. They never mutate delivery state. */
+ const select = (date: Date | null): boolean => {
+ if (pending()) return false;
+ selectionRevision += 1;
+ setState((current) => {
+ if (current.type === 'editing') {
+ return date
+ ? { type: 'editing', intent: { type: 'later', sendTime: date } }
+ : { type: 'editing', intent: { type: 'immediate' } };
+ }
+
+ if (!date || sameTime(date, current.confirmedTime)) {
+ return { type: 'scheduled', confirmedTime: current.confirmedTime };
+ }
+ return {
+ type: 'scheduled',
+ confirmedTime: current.confirmedTime,
+ proposedTime: date,
+ };
+ });
+ return true;
+ };
+
+ const applyScheduled = (sendTime: Date, replaceProposal = false) => {
+ const current = state();
+ if (
+ !replaceProposal &&
+ current.type === 'scheduled' &&
+ sameTime(current.confirmedTime, sendTime) &&
+ current.proposedTime
+ ) {
+ return;
+ }
+ selectionRevision += 1;
+ setState({ type: 'scheduled', confirmedTime: sendTime });
+ };
+
+ const applyEditing = () => {
+ if (state().type !== 'scheduled') return;
+ selectionRevision += 1;
+ setState({ type: 'editing', intent: { type: 'immediate' } });
+ };
+
+ /**
+ * Apply only authoritative server lifecycle. An ordinary editing observation
+ * intentionally leaves a local, unconfirmed time choice intact.
+ */
+ const observe = (next: EmailDraftLifecycleState) => {
+ if (pending()) {
+ deferredLifecycleObservation = next;
+ return;
+ }
+ if (next === ignoredLifecycleObservation) return;
+ if (next.type === 'scheduled') {
+ applyScheduled(new Date(next.sendTime));
+ return;
+ }
+ if (next.type === 'editing') applyEditing();
+ };
+
+ const reconcileScheduleFailure = async (requested: Date) => {
try {
- const previous = options.sendTime();
- const currentDraft = options.draftId();
- if (!date && previous && currentDraft) {
- try {
- await delivery.unschedule({
- draftId: currentDraft,
- inboxId,
- });
- } catch (error) {
- notices.reportError(error);
- notices.feedback.failure('Failed to unschedule email');
+ const authoritative = await options.reconcile?.();
+ if (
+ authoritative?.type === 'scheduled' &&
+ new Date(authoritative.sendTime).getTime() === requested.getTime()
+ ) {
+ return true;
+ }
+ } catch (error) {
+ notices.reportError(error);
+ }
+ return false;
+ };
+
+ const undoInitialSchedule = async (input: {
+ draftId: string;
+ threadId: string | undefined;
+ inboxId: string | undefined;
+ sendTime: Date;
+ }) => {
+ try {
+ await delivery.unschedule({
+ draftId: input.draftId,
+ inboxId: input.inboxId,
+ });
+ } catch (error) {
+ notices.reportError(error);
+ try {
+ const authoritative =
+ input.threadId && options.reconcileIdentity
+ ? await options.reconcileIdentity({
+ draftId: input.draftId,
+ threadId: input.threadId,
+ inboxId: input.inboxId,
+ })
+ : await options.reconcile?.();
+ const matchesCapturedIdentity =
+ authoritative?.draftId === input.draftId &&
+ (input.threadId === undefined ||
+ authoritative.threadId === input.threadId) &&
+ (input.inboxId === undefined ||
+ authoritative.inboxId === input.inboxId);
+ if (matchesCapturedIdentity && authoritative?.type === 'editing') {
+ // A lost cancellation response is still a successful undo.
+ } else if (matchesCapturedIdentity && authoritative?.type === 'sent') {
+ notices.feedback.alert(
+ 'This email was already sent and can no longer be unscheduled.'
+ );
+ return;
+ } else {
+ notices.feedback.failure('Failed to undo scheduled send');
return;
}
- options.setSendTime(null);
- notices.feedback.success('Email unscheduled');
- return;
- }
- if (!date) {
- options.setSendTime(null);
+ } catch (refreshError) {
+ notices.reportError(refreshError);
+ notices.feedback.failure('Failed to undo scheduled send');
return;
}
- // Persistence owns its failure notice; a failed save is not a failed schedule request.
+ }
+
+ if (options.draftId() === input.draftId) applyEditing();
+ try {
+ await options.onScheduleUndone?.(input);
+ notices.feedback.success('Schedule cancelled.');
+ } catch (error) {
+ notices.reportError(error);
+ notices.feedback.alert(
+ 'Schedule cancelled, but the draft could not be reopened. Check Drafts.'
+ );
+ }
+ };
+
+ const submit = async (): Promise<'scheduled' | 'updated' | false> => {
+ const before = state();
+ const action = getScheduleAction(before);
+ if (action !== 'schedule' && action !== 'update') return false;
+ if (pending()) return false;
+
+ const requested = getScheduleSelection(before);
+ if (!requested || !Number.isFinite(requested.getTime())) {
+ notices.feedback.alert('Choose a valid send time.');
+ return false;
+ }
+ if (requested.getTime() <= Date.now()) {
+ notices.feedback.alert(
+ 'That send time has passed. Choose a future time.'
+ );
+ return false;
+ }
+
+ const revision = selectionRevision;
+ const generation = options.generation();
+ const inboxId = options.inboxId();
+ deferredLifecycleObservation = undefined;
+ setOperation(action === 'update' ? 'updating' : 'committing');
+ try {
let draftId: string | undefined;
- try {
- draftId = await options.saveDraft();
- } catch (error) {
- notices.reportError(error);
- return;
+ if (action === 'schedule') {
+ try {
+ draftId = await options.saveDraft();
+ } catch {
+ // Persistence owns its specific feedback. Never fall through to Send.
+ return false;
+ }
+ } else {
+ // A confirmed schedule is content-locked; updating its time must not
+ // rewrite the draft body through the ordinary autosave endpoint.
+ draftId = options.draftId() ?? undefined;
+ }
+ if (
+ revision !== selectionRevision ||
+ generation !== options.generation() ||
+ inboxId !== options.inboxId()
+ ) {
+ return false;
}
+ if (!draftId) {
+ notices.feedback.failure(
+ action === 'update'
+ ? 'Failed to update schedule'
+ : 'Failed to schedule email',
+ {
+ subtext:
+ 'Draft is not ready to schedule. Resolve any save or connection errors and try again',
+ }
+ );
+ return false;
+ }
+
try {
- if (!draftId) throw new Error('Draft required');
await delivery.schedule(
- { draftId, sendTime: date.toISOString() },
+ {
+ draftId,
+ sendTime: requested.toISOString(),
+ includeSignature: options.includeSignature(),
+ },
inboxId
);
} catch (error) {
notices.reportError(error);
- notices.feedback.failure('Failed to schedule message');
- return;
+ if (!(await reconcileScheduleFailure(requested))) {
+ notices.feedback.failure(
+ action === 'update'
+ ? 'Failed to update schedule'
+ : 'Failed to schedule email'
+ );
+ return false;
+ }
+ }
+
+ if (
+ revision !== selectionRevision ||
+ generation !== options.generation() ||
+ inboxId !== options.inboxId()
+ ) {
+ await options.reconcile?.().catch(notices.reportError);
+ return false;
}
- options.setSendTime(date);
+
+ applyScheduled(requested, true);
const threadId = options.threadId();
if (threadId) {
try {
@@ -75,22 +337,147 @@ export function createEmailSendSchedule(options: {
);
}
}
- } catch (error) {
- // Presentation failures do not change a successful schedule/unschedule.
- notices.reportError(error);
+ try {
+ // The title stays terse so it never truncates; the time is the subtext.
+ let toastId: number | undefined;
+ let undoStarted = false;
+ const onViewScheduled = options.onViewScheduled;
+ const viewAction = onViewScheduled
+ ? [
+ {
+ label: 'View message',
+ kind: 'open' as const,
+ onClick: () => {
+ if (toastId != null) notices.feedback.dismiss(toastId);
+ onViewScheduled({
+ draftId,
+ threadId: threadId ?? undefined,
+ inboxId,
+ });
+ },
+ },
+ ]
+ : [];
+ const undoAction =
+ action === 'schedule'
+ ? [
+ {
+ label: 'Undo',
+ onClick: () => {
+ if (undoStarted) return;
+ undoStarted = true;
+ if (toastId != null) notices.feedback.dismiss(toastId);
+ void undoInitialSchedule({
+ draftId,
+ threadId: threadId ?? undefined,
+ inboxId,
+ sendTime: requested,
+ });
+ },
+ },
+ ]
+ : [];
+ const actions = [...undoAction, ...viewAction];
+ toastId = notices.feedback.success(
+ action === 'update' ? 'Email rescheduled' : 'Email scheduled',
+ {
+ subtext: `Sends ${format(
+ requested,
+ isThisYear(requested)
+ ? "EEE, MMM d 'at' h:mm a"
+ : "EEE, MMM d, yyyy 'at' h:mm a"
+ )}`,
+ ...(actions.length > 0 ? { actions, duration: 8_000 } : {}),
+ }
+ );
+ } catch (error) {
+ // Toast rendering is post-commit UI and cannot make a successful
+ // schedule retryable.
+ notices.reportError(error);
+ }
+ ignoredLifecycleObservation =
+ deferredLifecycleObservation ?? options.lifecycleState?.();
+ return action === 'update' ? 'updated' : 'scheduled';
} finally {
- setPending(false);
+ setOperation('idle');
}
};
- createEffect(
- on(
- options.recipientCount,
- (count) => {
- if (count === 0 && options.sendTime()) void change(null);
- },
- { defer: true }
- )
- );
- return { pending, change };
+ const cancel = async (): Promise<boolean> => {
+ const before = state();
+ if (before.type !== 'scheduled' || pending()) return false;
+ const draftId = options.draftId();
+ if (!draftId) return false;
+ const generation = options.generation();
+ const inboxId = options.inboxId();
+ deferredLifecycleObservation = undefined;
+ setOperation('cancelling');
+ try {
+ try {
+ await delivery.unschedule({ draftId, inboxId });
+ } catch (error) {
+ notices.reportError(error);
+ try {
+ const authoritative = await options.reconcile?.();
+ if (authoritative?.type !== 'editing') {
+ notices.feedback.failure('Failed to cancel schedule');
+ return false;
+ }
+ } catch (refreshError) {
+ notices.reportError(refreshError);
+ notices.feedback.failure('Failed to cancel schedule');
+ return false;
+ }
+ }
+ if (
+ generation !== options.generation() ||
+ inboxId !== options.inboxId()
+ ) {
+ await options.reconcile?.().catch(notices.reportError);
+ return false;
+ }
+ ignoredLifecycleObservation =
+ deferredLifecycleObservation ?? options.lifecycleState?.();
+ applyEditing();
+ notices.feedback.success(
+ 'Schedule cancelled. This email is editable again.'
+ );
+ return true;
+ } finally {
+ setOperation('idle');
+ }
+ };
+
+ /** Preserve a proposed replacement as inert local intent after detaching. */
+ const detach = () => {
+ const current = state();
+ if (current.type === 'editing') return;
+ const proposed =
+ current.type === 'scheduled' ? current.proposedTime : undefined;
+ selectionRevision += 1;
+ setState(
+ proposed
+ ? { type: 'editing', intent: { type: 'later', sendTime: proposed } }
+ : { type: 'editing', intent: { type: 'immediate' } }
+ );
+ };
+
+ return {
+ state,
+ operation,
+ pending,
+ selectedTime,
+ confirmedTime,
+ action: () => getScheduleAction(state()),
+ actionLabel: () => getScheduleActionLabel(state()),
+ select,
+ submit,
+ cancel,
+ observe,
+ detach,
+ reset: () => {
+ selectionRevision += 1;
+ setState({ type: 'editing', intent: { type: 'immediate' } });
+ },
+ };
}
diff --git a/apps/web/src/features/email-compose/primitives/reply-composer.ts b/apps/web/src/features/email-compose/primitives/reply-composer.ts
index 3cbe831ae7..96f8ff609f 100644
--- a/apps/web/src/features/email-compose/primitives/reply-composer.ts
+++ b/apps/web/src/features/email-compose/primitives/reply-composer.ts
@@ -28,8 +28,10 @@ import type {
EmailAttachmentStorage,
EmailComposeAccounts,
EmailComposeFeedback,
+ EmailComposeHost,
EmailConnectivity,
EmailDelivery,
+ EmailDraftLifecycleSource,
EmailDraftStorage,
EmailUndoHandle,
} from '../context/compose-capabilities';
@@ -93,6 +95,7 @@ export type ReplyComposerOptions = {
drafts: EmailDraftStorage;
attachmentStorage: EmailAttachmentStorage;
delivery: EmailDelivery;
+ draftLifecycle: EmailDraftLifecycleSource;
notices: EmailComposeFeedback;
accounts: EmailComposeAccounts;
connectivity: EmailConnectivity;
@@ -123,6 +126,8 @@ export type ReplyComposerOptions = {
navigate?: boolean;
}) => void;
setShowReply?: Setter<boolean>;
+ /** Reopens this reply's thread when the composer is no longer on screen. */
+ host?: Pick<EmailComposeHost, 'showThread'>;
};
export function createReplyComposer(
@@ -201,6 +206,10 @@ export function createReplyComposer(
// Gmail-style sizing: the composer opens compact and grows to the full cap
// once the user scrolls the content
const [composerExpanded, setComposerExpanded] = createSignal(false);
+ const [terminalState, setTerminalState] = createSignal<
+ 'sent' | 'missing' | undefined
+ >();
+ let schedule: ReturnType<typeof createEmailSendSchedule>;
// Appended quoted thread starts hidden behind a "⋯" pill (desktop). A
// draft reloaded with the quote already appended opens expanded instead —
// that's how the composer looked when the draft was saved.
@@ -212,7 +221,13 @@ export function createReplyComposer(
setValues: form.setRecipients,
onChange: scheduleDraftSave,
container: dom.container,
- disabled: () => submitting() || pendingDeletion() || scheduling(),
+ disabled: () =>
+ submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
+ schedule?.pending() ||
+ schedule?.state().type === 'scheduled' ||
+ terminalState() !== undefined,
});
const focus = createReplyComposerFocus({
editor,
@@ -226,22 +241,35 @@ export function createReplyComposer(
// remount case). It carries a just-undone send. Consumed below.
const restoredSnapshot = replyUndo.takePending(undoKey);
- // Switching inboxes can move a draft out of the displayed thread. The
- // session keeps the draft's persisted identity together for subsequent
- // saves, discard, schedule and undo — and whether the server has confirmed
- // it, which the REST-only send and schedule depend on.
+ // Switching inboxes can move a draft out of the displayed thread. Keep its
+ // persisted identity together for subsequent saves, discard, schedule and undo.
const session = createDraftSession(
restoredSnapshot
? {
draftId: restoredSnapshot.draftId,
threadId: restoredSnapshot.threadId,
+ inboxId: restoredSnapshot.inboxId,
}
: draftSeed?.db_id
- ? { draftId: draftSeed.db_id, threadId: draftSeed.thread_db_id }
+ ? {
+ draftId: draftSeed.db_id,
+ threadId: draftSeed.thread_db_id,
+ inboxId: draftSeed.link_id,
+ }
: undefined
);
const savedDraftId = session.draftId;
const savedDraftThreadId = session.threadId;
+ const persistedInboxId = session.inboxId;
+ const [movingInbox, setMovingInbox] = createSignal(false);
+ let identityVersion = 0;
+ let editVersion = 0;
+ let persistedEditVersion = 0;
+ const lifecycle = props.draftLifecycle.observe({
+ draftId: () => (session.serverConfirmed() ? savedDraftId() : undefined),
+ threadId: savedDraftThreadId,
+ inboxId: persistedInboxId,
+ });
// Consume the undo-send snapshot so a later composer mount doesn't restore
// it again. Use bodyHtml as initialHtml for the editor, restore attachments
@@ -275,10 +303,28 @@ export function createReplyComposer(
// Register a callback so stale undoSend closures from a previous mount can
// restore state into this (the live) component instance.
+ let hasLocalChanges = false;
const restoreMountedReply = (snapshot: UndoReplySnapshot) => {
+ const currentDraftId = savedDraftId();
+ if (
+ hasLocalChanges ||
+ (currentDraftId !== undefined && currentDraftId !== snapshot.draftId)
+ ) {
+ props.notices.feedback.alert(
+ 'Your newer reply was kept. The earlier message was not reopened.'
+ );
+ props.setShowReply?.(true);
+ return;
+ }
const draftId = snapshot.draftId;
+ hasLocalChanges = false;
props.onEngaged?.();
- session.dispatch({ type: 'seeded', draftId, threadId: snapshot.threadId });
+ session.dispatch({
+ type: 'seeded',
+ draftId,
+ threadId: snapshot.threadId,
+ inboxId: snapshot.inboxId,
+ });
restoreEnvelope(snapshot);
const currentEditor = editor();
if (currentEditor && snapshot.bodyHtml) {
@@ -323,7 +369,7 @@ export function createReplyComposer(
sentThreadId: string | undefined,
inboxId: string | undefined
) => {
- const snapshot = replyUndo.take(draftId);
+ const snapshot = replyUndo.peek(draftId);
// Reconcile the actual message thread, which can differ from the host when
// replying from another inbox. The host's undoKey still owns local recovery.
@@ -337,6 +383,9 @@ export function createReplyComposer(
});
if (snapshot) {
+ // Keep the recovery snapshot available if restoring the server draft
+ // fails. Consume it only after the authoritative restore succeeds.
+ replyUndo.take(draftId);
// Resolve the live registration after cache updates and unmounts settle.
setTimeout(() => replyUndo.restore(undoKey, snapshot), 0);
props.setShowReply?.(true);
@@ -346,8 +395,8 @@ export function createReplyComposer(
const attachmentPersistence = createAttachmentPersistence({
services: props.attachmentStorage,
attachments: form.attachments,
- draftId: savedDraftId,
- inboxId: activeInboxId,
+ draftId: () => (session.serverConfirmed() ? savedDraftId() : undefined),
+ inboxId: persistedInboxId,
});
createEffect(
@@ -392,12 +441,19 @@ export function createReplyComposer(
'idle' | 'preparing' | 'sending'
>('idle');
const submitting = () => sendPhase() !== 'idle';
- const sending = () => sendPhase() === 'sending';
const [pendingDeletion, setPendingDeletion] = createSignal(false);
- function collectDraft() {
- $removeAllWatermarkNodes(editor());
- const prepared = prepareEmailBody(editor());
+ function collectDraft(forDelivery = false) {
+ if (!forDelivery) $removeAllWatermarkNodes(editor());
+ const prepared = prepareEmailBody(
+ editor(),
+ forDelivery && replyTarget
+ ? {
+ replyType: form.replyType(),
+ replyingTo: replyTarget,
+ }
+ : undefined
+ );
if (!prepared) {
props.notices.reportError(
new Error('Unable to prepare email body for draft collection.')
@@ -422,17 +478,52 @@ export function createReplyComposer(
replying_to_id: replyTarget?.db_id,
subject: form.subject(),
to: form.recipients().to.map(convertEmailRecipientToContactInfo),
+ body_macro: forDelivery ? prepareMacroBody(bodyMacro()) : undefined,
+ include_signature: includeSignature() ? undefined : false,
};
}
- const captureSave = (completingThread = false) => ({
- draft: collectDraft(),
+ const captureSave = (completingThread = false, forDelivery = false) => ({
+ draft: collectDraft(forDelivery),
thread: thread(),
inboxId: activeInboxId(),
completingThread,
+ generation: identityVersion,
+ revision: editVersion,
});
- // Block the save that resetting schedules; restore on a timeout so a
- // stay-mounted input can autosave again afterwards.
+
+ async function reportPersistenceFailure(
+ error: unknown,
+ operation: 'save' | 'delete'
+ ) {
+ props.notices.reportError(error);
+ if (!session.serverConfirmed()) {
+ if (schedule?.pending()) {
+ props.notices.feedback.failure(`Failed to ${operation} draft`);
+ }
+ return;
+ }
+ let state;
+ try {
+ state = await lifecycle.refresh();
+ } catch (refreshError) {
+ props.notices.reportError(refreshError);
+ }
+ if (
+ state?.type === 'sent' &&
+ state.draftId === savedDraftId() &&
+ state.threadId === savedDraftThreadId() &&
+ state.inboxId === persistedInboxId()
+ ) {
+ props.notices.feedback.alert(
+ 'This scheduled email was sent. Your composer has been updated.'
+ );
+ return;
+ }
+ props.notices.feedback.failure(`Failed to ${operation} draft`);
+ }
+
+ // Reset notifications must not autosave the draft that was just discarded.
const withDeletionGuard = async (run: () => Promise<void> | void) => {
setPendingDeletion(true);
autosave.cancel();
@@ -451,6 +542,7 @@ export function createReplyComposer(
attachments: attachmentPersistence,
mintThreadHandle: false,
onAlreadySent: () => {
+ identityVersion += 1;
props.notices.feedback.alert('This reply was already sent');
void withDeletionGuard(() => {
resetState();
@@ -464,59 +556,69 @@ export function createReplyComposer(
thread: currentThread,
inboxId,
completingThread,
+ generation,
+ revision,
}: ReturnType<typeof captureSave>) {
- if (!draft) {
- await persistence.remove({ inboxId, completingThread });
- return;
- }
- if (!currentThread) {
- props.notices.reportError(
- new Error('Failed to save draft: thread not found')
- );
- return;
- }
- const saved = await persistence.save({
- draft: {
- ...draft,
- provider_thread_id: currentThread.provider_id,
- thread_db_id: currentThread.db_id,
- },
- inboxId,
- completingThread,
- });
- if (!saved?.draftId) return;
- // Forwarded attachments wait for a committed save.
- if (saved.persistence !== 'queued') {
- await syncForwardedAttachments(saved.draftId, inboxId);
+ if (generation !== identityVersion) return;
+ try {
+ if (!draft) {
+ await persistence.remove({ inboxId, completingThread });
+ if (generation === identityVersion)
+ persistedEditVersion = Math.max(persistedEditVersion, revision);
+ return;
+ }
+ if (!currentThread) {
+ props.notices.reportError(
+ new Error('Failed to save draft: thread not found')
+ );
+ return;
+ }
+ const saved = await persistence.save({
+ draft: {
+ ...draft,
+ provider_thread_id: currentThread.provider_id,
+ thread_db_id: currentThread.db_id,
+ },
+ inboxId,
+ completingThread,
+ });
+ if (generation !== identityVersion || !saved) return;
+ if (saved.persistence !== 'queued')
+ persistedEditVersion = Math.max(persistedEditVersion, revision);
+ return saved.draftId;
+ } catch (error) {
+ if (generation === identityVersion)
+ await reportPersistenceFailure(error, draft ? 'save' : 'delete');
+ throw error;
}
- return saved.draftId;
- }
-
- async function syncForwardedAttachments(
- draftId: string,
- inboxId: string | undefined
- ) {
- const forwarded = form.attachments
- .list()
- .filter((attachment) => attachment.type === 'forwarded');
- if (!forwarded.length) return;
- await props.attachmentStorage.addForwardedAttachments({
- draftId,
- attachments: forwarded.map((a) => ({ attachmentId: a.attachmentId })),
- inboxId,
- });
}
const autosave = createDraftAutosave({
capture: captureSave,
persist: persistDraft,
- paused: () => submitting() || pendingDeletion(),
+ paused: () =>
+ submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
+ schedule?.pending() ||
+ schedule?.state().type === 'scheduled' ||
+ terminalState() !== undefined,
});
function executeSaveDraft(completingThread = false) {
return autosave.save(captureSave(completingThread));
}
function scheduleDraftSave() {
- if (submitting() || pendingDeletion()) return;
+ if (
+ submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
+ schedule.pending() ||
+ schedule.state().type === 'scheduled' ||
+ terminalState()
+ )
+ return;
+ hasLocalChanges = true;
+ editVersion += 1;
props.onEngaged?.();
autosave.schedule();
}
@@ -524,12 +626,81 @@ export function createReplyComposer(
// 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 saveSelectedInbox = async (inboxId: string) => {
+ if (
+ submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
+ schedule.pending() ||
+ schedule.state().type === 'scheduled' ||
+ terminalState()
+ )
+ return;
+ hasLocalChanges = true;
+ setMovingInbox(true);
+ try {
+ editVersion += 1;
+ props.onEngaged?.();
+ form.setSelectedInbox(inboxId);
+ autosave.cancel();
+ await executeSaveDraft();
+ } catch {
+ // Persistence reports failures; replay lifecycle after the move settles.
+ } finally {
+ setMovingInbox(false);
+ }
+ };
const persistDraftOnSenderSwitch = (inboxId: string) => {
- if (submitting() || pendingDeletion() || scheduling()) return;
- props.onEngaged?.();
- form.setSelectedInbox(inboxId);
- autosave.cancel();
- void executeSaveDraft().catch(() => {});
+ void saveSelectedInbox(inboxId);
+ };
+
+ const saveForSchedule = async () => {
+ const currentEditor = editor();
+ const cleanupWatermark = $appendWatermarkNodeToLast(
+ currentEditor,
+ !hasPaidAccess() ? MACRO_EMAIL_SIGNATURE : undefined
+ );
+ try {
+ return persistence.confirmed(
+ await autosave.save(captureSave(false, true))
+ );
+ } finally {
+ cleanupWatermark();
+ }
+ };
+
+ schedule = createEmailSendSchedule({
+ delivery: props.delivery,
+ notices: props.notices,
+ initialScheduledTime: draftSeed?.scheduled_send_time
+ ? new Date(draftSeed.scheduled_send_time)
+ : undefined,
+ draftId: savedDraftId,
+ saveDraft: saveForSchedule,
+ threadId: savedDraftThreadId,
+ inboxId: activeInboxId,
+ includeSignature: () => (includeSignature() ? undefined : false),
+ generation: () =>
+ `${identityVersion}:${editVersion}:${activeInboxId() ?? ''}`,
+ lifecycleState: lifecycle.state,
+ reconcile: lifecycle.refresh,
+ reconcileIdentity: lifecycle.refreshIdentity,
+ onScheduleUndone: ({ draftId, threadId, inboxId }) =>
+ restoreAfterUndoSend(draftId, threadId, inboxId),
+ // The scheduled reply stays in its thread, locked; bring it back into view.
+ onViewScheduled: ({ threadId }) => {
+ const container = dom.container();
+ if (container?.isConnected) {
+ container.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ return;
+ }
+ if (threadId) props.host?.showThread?.(threadId);
+ },
+ });
+ const cancelSchedule = async () => {
+ if (!(await schedule.cancel())) return false;
+ session.dispatch({ type: 'schedule-cancelled' });
+ return true;
};
createEffect(() => {
@@ -565,9 +736,8 @@ export function createReplyComposer(
const hasPaidAccess = props.hasPaidAccess;
const sendEmail = async (markDone = false) => {
- if (scheduling()) return;
- if (submitting() || pendingDeletion() || attachmentPersistence.uploading())
- return;
+ if (scheduling() || movingInbox() || terminalState()) return;
+ if (submitting() || pendingDeletion()) return;
const to = form.recipients().to.map(convertEmailRecipientToContactInfo);
const cc = form.recipients().cc.map(convertEmailRecipientToContactInfo);
@@ -615,17 +785,71 @@ export function createReplyComposer(
inboxId = primaryInboxId() ?? inboxes[0].id;
}
+ const offline = sendRefusalBeforeSave(props.connectivity);
+ if (offline) return refuseSend(props.notices, offline);
const currentEditor = editor();
+ const rememberCurrentReply = () => {
+ if (!currentEditor) return;
+ const snapshotDraftId = savedDraftId();
+ const snapshotThreadId = savedDraftThreadId();
+ if (!snapshotDraftId || !snapshotThreadId) return;
+ const snapshotHtml = currentEditor.read(() =>
+ $generateHtmlFromNodes(currentEditor)
+ );
+ replyUndo.remember({
+ threadId: snapshotThreadId,
+ inboxId,
+ draftId: snapshotDraftId,
+ bodyHtml: snapshotHtml,
+ attachments: [...form.attachments.list()],
+ includeSignature: includeSignature(),
+ replyAppended: form.replyAppended(),
+ draftRestore: {
+ bcc,
+ cc,
+ db_id: snapshotDraftId,
+ provider_id: draftSeed?.provider_id,
+ provider_thread_id: currentThread.provider_id,
+ replying_to_id: replyTarget?.db_id,
+ subject: form.subject(),
+ thread_db_id: snapshotThreadId,
+ to,
+ },
+ });
+ };
+ const scheduleAction = schedule.action();
+ if (scheduleAction === 'unavailable') {
+ props.notices.feedback.alert(
+ `This email is scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`
+ );
+ return;
+ }
+ if (scheduleAction === 'schedule' || scheduleAction === 'update') {
+ const result = await schedule.submit();
+ if (result === 'scheduled') {
+ const scheduledDraftId = savedDraftId();
+ rememberCurrentReply();
+ try {
+ resetState();
+ clearDraftState();
+ } catch (error) {
+ props.notices.reportError(error);
+ }
+ void Promise.resolve(
+ props.sideEffectOnSend?.(scheduledDraftId ?? null)
+ ).catch(props.notices.reportError);
+ }
+ return;
+ }
+ if (attachmentPersistence.uploading()) return;
// Sending a reply marks the thread done. Gated on inbox_visible because
// onMarkDone (archiveThread) toggles: an already-archived thread (e.g.
// replying from search or the sent view) would be unarchived.
const willMarkDone = markDone || currentThread.inbox_visible;
- const offline = sendRefusalBeforeSave(props.connectivity);
- if (offline) return refuseSend(props.notices, offline);
-
setSendPhase('preparing');
+ const sendGeneration = identityVersion;
try {
// Ensure draft is saved before sending so undo-send always has a draft to restore
autosave.cancel();
@@ -633,12 +857,16 @@ export function createReplyComposer(
try {
await executeSaveDraft(willMarkDone);
} catch (error) {
- // A draft the server may not have must not be sent.
props.notices.reportError(error);
+ if (session.isStale(epochBeforeSave)) return;
return refuseSend(props.notices, 'draft-not-saved');
}
- // Already sent from another device: the composer was reset mid-save.
- if (session.isStale(epochBeforeSave)) return;
+ if (
+ sendGeneration !== identityVersion ||
+ session.isStale(epochBeforeSave) ||
+ terminalState()
+ )
+ return;
const refusal = sendRefusalAfterSave({
identity: session.identity(),
autosaveAllowed: session.autosaveAllowed(),
@@ -649,38 +877,9 @@ export function createReplyComposer(
// Snapshot editor state before watermark so undo-send can restore it.
// Remember by draft so sends in separate composers cannot replace each other.
- if (currentEditor) {
- const snapshotHtml = currentEditor.read(() =>
- $generateHtmlFromNodes(currentEditor)
- );
- const snapshotDraftId = savedDraftId();
- const snapshotThreadId = savedDraftThreadId();
- if (snapshotDraftId && snapshotThreadId) {
- replyUndo.remember({
- threadId: snapshotThreadId,
- inboxId,
- draftId: snapshotDraftId,
- bodyHtml: snapshotHtml,
- attachments: [...form.attachments.list()],
- includeSignature: includeSignature(),
- replyAppended: form.replyAppended(),
- draftRestore: {
- bcc,
- cc,
- db_id: snapshotDraftId,
- provider_id: draftSeed?.provider_id,
- provider_thread_id: currentThread.provider_id,
- replying_to_id: replyTarget?.db_id,
- subject: form.subject(),
- thread_db_id: snapshotThreadId,
- to,
- },
- });
- }
- }
+ rememberCurrentReply();
- // Scheduling may have started while the draft save was pending.
- if (scheduling() || form.sendTime()) {
+ if (scheduling() || schedule.action() !== 'send') {
return;
}
@@ -842,6 +1041,9 @@ export function createReplyComposer(
setBodyMacro('');
session.dispatch({ type: 'reset' });
form.reset();
+ schedule.reset();
+ setTerminalState(undefined);
+ hasLocalChanges = false;
};
const clearDraftState = () => {
@@ -850,23 +1052,49 @@ export function createReplyComposer(
};
const deleteDraftAndReset = async () => {
- if (submitting() || pendingDeletion() || scheduling()) return;
- await withDeletionGuard(async () => {
- // A first save may still be creating the draft; delete its returned id.
+ if (schedule.state().type === 'scheduled') {
+ props.notices.feedback.alert(
+ 'Cancel the schedule before deleting this draft.'
+ );
+ return;
+ }
+ if (submitting() || pendingDeletion() || movingInbox() || scheduling())
+ return;
+ // Keep Lexical's deferred reset notification from recreating a discarded draft.
+ setPendingDeletion(true);
+ autosave.cancel();
+ try {
await autosave.settled().catch(() => {});
const draftId = savedDraftId();
if (draftId) {
- await deleteDraftForDiscard(
- props.drafts,
- { draftId, threadId: savedDraftThreadId(), inboxId: activeInboxId() },
- props.notices,
- 'This reply was already sent'
- );
+ try {
+ await deleteDraftForDiscard(
+ props.drafts,
+ {
+ draftId,
+ threadId: savedDraftThreadId(),
+ inboxId: activeInboxId(),
+ },
+ props.notices,
+ 'This reply was already sent'
+ );
+ } catch (error) {
+ await reportPersistenceFailure(error, 'delete');
+ setPendingDeletion(false);
+ void lifecycle.refresh().catch(props.notices.reportError);
+ throw error;
+ }
}
+ identityVersion += 1;
resetState();
form.setReplyAppended(false);
clearDraftState();
- });
+ } finally {
+ setTimeout(() => {
+ autosave.cancel();
+ setPendingDeletion(false);
+ }, 0);
+ }
};
const handleUserMention = (mention: UserMentionRecord) => {
@@ -885,6 +1113,15 @@ export function createReplyComposer(
};
const handleAddAttachments = async (files: File[]) => {
+ if (
+ submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
+ scheduling() ||
+ schedule.state().type === 'scheduled' ||
+ terminalState()
+ )
+ return;
if (await refuseAttachmentsOffline(props.connectivity, props.notices))
return;
const currentAttachments = form.attachments.list();
@@ -923,43 +1160,150 @@ export function createReplyComposer(
scheduleDraftSave();
};
- const handleRemoveAttachment = attachmentPersistence.remove;
+ const handleRemoveAttachment = (attachment: DraftFormAttachment) => {
+ if (
+ submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
+ scheduling() ||
+ schedule.state().type === 'scheduled' ||
+ terminalState()
+ )
+ return;
+ hasLocalChanges = true;
+ editVersion += 1;
+ attachmentPersistence.remove(attachment);
+ };
- const schedule = createEmailSendSchedule({
- delivery: props.delivery,
- notices: props.notices,
- draftId: savedDraftId,
- saveDraft: async () => persistence.confirmed(await executeSaveDraft()),
- threadId: savedDraftThreadId,
- inboxId: activeInboxId,
- sendTime: form.sendTime,
- setSendTime: form.setSendTime,
- recipientCount: () => {
- const recipients = form.recipients();
- return (
- recipients.to.length + recipients.cc.length + recipients.bcc.length
- );
- },
- });
const scheduling = schedule.pending;
- const scheduleBlocked = () => pendingDeletion() || sending();
+ const scheduleBlocked = () =>
+ pendingDeletion() ||
+ movingInbox() ||
+ submitting() ||
+ terminalState() !== undefined;
const handleSendTimeChange = (date: Date | null) =>
- scheduleBlocked() ? Promise.resolve() : schedule.change(date);
+ scheduleBlocked() ? false : schedule.select(date);
+
+ const detachFromObsoleteDraft = (message: string) => {
+ identityVersion += 1;
+ autosave.cancel();
+ session.dispatch({ type: 'reset' });
+ const omittedAttachments = attachmentPersistence.detach();
+ schedule.detach();
+ setTerminalState(undefined);
+ persistedEditVersion = 0;
+ props.notices.feedback.alert(message);
+ if (omittedAttachments) {
+ props.notices.feedback.alert(
+ 'Previously saved attachments could not be copied to the new draft. Please attach those files again.'
+ );
+ }
+ void autosave.save().catch(() => {});
+ };
+
+ let lastScheduledTime = schedule.confirmedTime()?.toISOString();
+ let handledTerminalIdentity: string | undefined;
+ createEffect(
+ on([lifecycle.state, scheduling, movingInbox], ([state, , moving]) => {
+ if (
+ !state ||
+ !session.serverConfirmed() ||
+ state.draftId !== savedDraftId() ||
+ state.threadId !== savedDraftThreadId() ||
+ (state.inboxId !== undefined && state.inboxId !== persistedInboxId()) ||
+ moving ||
+ pendingDeletion()
+ )
+ return;
+
+ if (state.type === 'scheduled') {
+ if (editVersion > persistedEditVersion) {
+ detachFromObsoleteDraft(
+ 'This email was scheduled in another tab. Your newer text was kept as a new draft.'
+ );
+ return;
+ }
+ const nextTime = new Date(state.sendTime);
+ const changedElsewhere =
+ !schedule.confirmedTime() ||
+ schedule.confirmedTime()?.getTime() !== nextTime.getTime();
+ schedule.observe(state);
+ if (changedElsewhere && lastScheduledTime !== state.sendTime) {
+ props.notices.feedback.alert(
+ `Email scheduled for ${nextTime.toLocaleString()}. Cancel the schedule to edit.`
+ );
+ }
+ lastScheduledTime = state.sendTime;
+ return;
+ }
+
+ if (state.type === 'editing') {
+ const wasScheduled = schedule.state().type === 'scheduled';
+ schedule.observe(state);
+ if (wasScheduled && schedule.state().type === 'editing') {
+ session.dispatch({ type: 'schedule-cancelled' });
+ lastScheduledTime = undefined;
+ props.notices.feedback.success(
+ 'Schedule cancelled. This email is editable again.'
+ );
+ }
+ return;
+ }
+
+ if (handledTerminalIdentity === `${state.draftId}:${state.type}`) return;
+ handledTerminalIdentity = `${state.draftId}:${state.type}`;
+ if (editVersion > persistedEditVersion) {
+ detachFromObsoleteDraft(
+ state.type === 'sent'
+ ? 'The scheduled email was sent while you were editing. Your newer text was kept as a new draft and was not sent.'
+ : 'The draft changed elsewhere. Your newer text was kept as a new draft.'
+ );
+ return;
+ }
+
+ identityVersion += 1;
+ autosave.cancel();
+ resetState();
+ setTerminalState(state.type);
+ clearDraftState();
+ if (state.type === 'sent') {
+ props.notices.feedback.success('Scheduled email sent');
+ } else {
+ props.notices.feedback.alert('This draft is no longer available.');
+ }
+ })
+ );
const hasBodyText = () => bodyMacro().trim().length > 0;
- const sendActionDisabled = () =>
+ const editingDisabled = () =>
+ submitting() ||
pendingDeletion() ||
+ movingInbox() ||
+ scheduling() ||
+ schedule.state().type === 'scheduled' ||
+ terminalState() !== undefined;
+ const sendUnavailableReason = () => {
+ if (terminalState() === 'sent') return 'This email has already been sent.';
+ if (terminalState() === 'missing')
+ return 'This draft is no longer available.';
+ if (schedule.operation() === 'committing') return 'Scheduling email…';
+ if (schedule.operation() === 'updating') return 'Updating schedule…';
+ if (schedule.operation() === 'cancelling') return 'Cancelling schedule…';
+ if (submitting()) return 'Sending…';
+ if (schedule.action() === 'unavailable')
+ return `Scheduled for ${schedule.confirmedTime()?.toLocaleString()}. Choose a new time to update it, or cancel the schedule to edit.`;
+ return undefined;
+ };
+ const sendActionDisabled = () =>
submitting() ||
+ pendingDeletion() ||
+ movingInbox() ||
scheduling() ||
+ terminalState() !== undefined ||
attachmentPersistence.uploading() ||
- !!form.sendTime();
- const scheduleSendDisabled = () =>
- scheduleBlocked() ||
- scheduling() ||
- (form.recipients().to.length === 0 &&
- form.recipients().cc.length === 0 &&
- form.recipients().bcc.length === 0);
+ schedule.action() === 'unavailable';
const toggleQuotedText = () => {
+ if (editingDisabled()) return;
const replyingTo = replyTarget;
if (!replyingTo) return;
@@ -997,7 +1341,7 @@ export function createReplyComposer(
setQuoteCollapsed,
savedDraftId,
handleEditorConnect,
- isSending: submitting,
+ isSending: () => submitting() || scheduling(),
recipients,
collectDraft,
scheduleDraftSave,
@@ -1008,9 +1352,17 @@ export function createReplyComposer(
handleAddAttachments,
handleRemoveAttachment,
handleSendTimeChange,
+ scheduleState: schedule.state,
+ selectedSendTime: schedule.selectedTime,
+ confirmedSendTime: schedule.confirmedTime,
+ scheduleActionLabel: schedule.actionLabel,
+ scheduleOperation: schedule.operation,
+ cancelSchedule,
+ schedulePickerDisabled: () => scheduleBlocked() || scheduling(),
+ editingDisabled,
+ sendUnavailableReason,
hasBodyText,
sendActionDisabled,
- scheduleSendDisabled,
toggleQuotedText,
};
}
diff --git a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
index ffdb8d091c..00e75d0971 100644
--- a/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
+++ b/apps/web/src/features/email-compose/primitives/send-schedule.test.ts
@@ -1,4 +1,6 @@
-import { createSignal } from 'solid-js';
+import { emailKeys } from '@queries/email/keys';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createComponent, createRoot, createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { message } from '../../email-message/tests/messages';
import type {
@@ -6,10 +8,19 @@ import type {
PersistedEmailIdentity,
} from '../context/compose-capabilities';
import { decodeBase64Utf8 } from '../core/decode-base64';
+import { emailDraftLifecycleSource } from '../queries/draft-lifecycle';
import { createComposeContext } from '../tests/capabilities';
import { mountEmailComposer } from '../tests/composer';
import { mountReplyComposer } from '../tests/reply';
+const fetchLifecycleThread = vi.hoisted(() => vi.fn());
+vi.mock('@queries/email/thread', () => ({
+ fetchFreshEmailThread: fetchLifecycleThread,
+}));
+vi.mock('@core/cross-tab/cross-tab-bus', () => ({
+ createCrossTabBus: () => ({ publish() {}, subscribe: () => () => {} }),
+}));
+
function composer(
kind: 'standalone' | 'reply',
composeContext: EmailComposeContext
@@ -18,29 +29,362 @@ function composer(
const state = mountReplyComposer(composeContext);
return {
dispose: state.dispose,
+ edit: state.edit,
+ switchInbox: state.persistDraftOnSenderSwitch,
+ selectedInbox: state.activeInboxId,
+ disabled: state.editingDisabled,
+ selectedTime: state.selectedSendTime,
+ confirmedTime: state.confirmedSendTime,
+ scheduleState: state.scheduleState,
send: () => state.sendEmail(),
- schedule: state.handleSendTimeChange,
+ selectTime: state.handleSendTimeChange,
+ cancelSchedule: state.cancelSchedule,
};
}
const root = mountEmailComposer(composeContext);
root.edit('Ready to send');
return {
dispose: root.dispose,
+ edit: root.edit,
+ switchInbox: root.state.context.onSelectInbox!,
+ selectedInbox: () => root.state.context.selectedInboxId?.(),
+ disabled: root.state.context.disabled,
+ selectedTime: root.state.context.schedule.selectedTime,
+ confirmedTime: root.state.context.schedule.confirmedTime,
+ scheduleState: root.state.context.schedule.state,
send: root.state.context.onSend,
- schedule: root.state.context.onSendTimeChange!,
+ selectTime: root.state.context.schedule.onSelect,
+ cancelSchedule: root.state.context.schedule.onCancel,
+ };
+}
+
+function composerWithLifecycleQuery(
+ kind: 'standalone' | 'reply',
+ context: EmailComposeContext
+) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },
+ });
+ let state!: ReturnType<typeof composer>;
+ const disposeProvider = createRoot((dispose) => {
+ createComponent(QueryClientProvider, {
+ client,
+ get children() {
+ state = composer(kind, {
+ ...context,
+ draftLifecycle: emailDraftLifecycleSource,
+ });
+ return null;
+ },
+ });
+ return dispose;
+ });
+ return {
+ ...state,
+ client,
+ dispose() {
+ state.dispose();
+ disposeProvider();
+ client.clear();
+ },
};
}
describe('send and schedule ordering', () => {
+ it.each(['standalone', 'reply'] as const)(
+ '%s does not report a syncing failure after delivery invalidates a pending schedule save',
+ async (kind) => {
+ const context = createComposeContext();
+ const state = composer(kind, context);
+ const pending = Promise.withResolvers<PersistedEmailIdentity>();
+ try {
+ state.edit('Previously saved');
+ await vi.advanceTimersByTimeAsync(600);
+ vi.mocked(context.drafts.saveDraft).mockReturnValueOnce(
+ pending.promise
+ );
+ state.selectTime(new Date('2026-12-01T12:00:00Z'));
+ state.send();
+ await vi.advanceTimersByTimeAsync(0);
+ context.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.notices.feedback.success).toHaveBeenCalledWith(
+ 'Scheduled email sent'
+ );
+ pending.resolve({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.delivery.schedule).not.toHaveBeenCalled();
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
+ expect(context.notices.feedback.failure).not.toHaveBeenCalled();
+ } finally {
+ pending.resolve({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ });
+ state.dispose();
+ }
+ }
+ );
+
+ it.each(['standalone', 'reply'] as const)(
+ '%s keeps an unconfirmed time local across an editing refresh',
+ async (kind) => {
+ const context = createComposeContext();
+ const state = composer(kind, context);
+ const selected = new Date('2026-12-01T12:00:00Z');
+ try {
+ expect(state.selectTime(selected)).toBe(true);
+ context.setDraftLifecycle({
+ type: 'editing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(state.selectedTime()).toEqual(selected);
+ expect(state.scheduleState().type).toBe('editing');
+ expect(state.disabled()).toBe(false);
+ expect(context.delivery.schedule).not.toHaveBeenCalled();
+ expect(context.delivery.unschedule).not.toHaveBeenCalled();
+ expect(context.delivery.archive).not.toHaveBeenCalled();
+ } finally {
+ state.dispose();
+ }
+ }
+ );
+
+ it.each(['standalone', 'reply'] as const)(
+ '%s discards deferred missing state when migration and its refresh fail',
+ async (kind) => {
+ const context = createComposeContext();
+ context.accounts.inboxes = () => [
+ { id: 'inbox', email_address: '[email protected]', settings: {} },
+ { id: 'other', email_address: '[email protected]', settings: {} },
+ ];
+ fetchLifecycleThread.mockReset().mockResolvedValueOnce({
+ messages: [message('draft', { is_draft: true })],
+ });
+ const state = composerWithLifecycleQuery(kind, context);
+ const notifications: VoidFunction[] = [];
+ let queueNotification: ReturnType<typeof vi.spyOn> | undefined;
+ try {
+ state.edit('Keep this draft');
+ await vi.advanceTimersByTimeAsync(600);
+ const moving = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(context.drafts.saveDraft).mockReturnValueOnce(moving.promise);
+ state.switchInbox('other');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(state.disabled()).toBe(true);
+
+ // A read during migration cannot establish the final draft state.
+ fetchLifecycleThread.mockResolvedValueOnce({ messages: [] });
+ await state.client.invalidateQueries({
+ queryKey: emailKeys.composeDraftState._def,
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.notices.feedback.alert).not.toHaveBeenCalled();
+
+ const failure = new Error('Lifecycle unavailable');
+ fetchLifecycleThread.mockRejectedValueOnce(failure);
+ queueNotification = vi
+ .spyOn(globalThis, 'queueMicrotask')
+ .mockImplementation((callback) => notifications.push(callback));
+ moving.reject(new Error('Move failed'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.notices.reportError).toHaveBeenCalledWith(failure);
+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
+ expect(context.notices.feedback.alert).not.toHaveBeenCalled();
+ expect(state.disabled()).toBe(false);
+
+ queueNotification.mockRestore();
+ for (const notify of notifications.splice(0)) notify();
+ fetchLifecycleThread.mockResolvedValueOnce({
+ messages: [message('draft', { is_draft: true })],
+ });
+ await state.client.invalidateQueries({
+ queryKey: emailKeys.composeDraftState._def,
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
+ expect(context.notices.feedback.alert).not.toHaveBeenCalled();
+ } finally {
+ queueNotification?.mockRestore();
+ for (const notify of notifications) notify();
+ state.dispose();
+ }
+ }
+ );
+
+ it('does not send a reply when delivery overtakes its pre-send save', async () => {
+ const context = createComposeContext();
+ const state = mountReplyComposer(context);
+ state.edit('Previously saved');
+ await vi.advanceTimersByTimeAsync(600);
+ const pending = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(context.drafts.saveDraft)
+ .mockReturnValueOnce(pending.promise)
+ .mockResolvedValue({
+ draftId: 'recovered',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ });
+ state.edit('Keep this newer reply unsent');
+ const sending = state.sendEmail();
+ await vi.advanceTimersByTimeAsync(0);
+ context.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ pending.resolve({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
+ await sending;
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
+ expect(state.savedDraftId()).toBe('recovered');
+ expect(decodeBase64Utf8(state.collectDraft()?.body_html ?? '')).toContain(
+ 'Keep this newer reply unsent'
+ );
+ state.dispose();
+ });
+
+ it.each(['standalone', 'reply'] as const)(
+ '%s observes the persisted inbox and ignores missing responses during migration',
+ async (kind) => {
+ const context = createComposeContext();
+ context.accounts = {
+ ...context.accounts,
+ inboxes: () => [
+ { id: 'inbox', email_address: '[email protected]', settings: {} },
+ { id: 'other', email_address: '[email protected]', settings: {} },
+ { id: 'third', email_address: '[email protected]', settings: {} },
+ ],
+ };
+ const state = composer(kind, context);
+ state.edit('Move this draft');
+ await vi.advanceTimersByTimeAsync(600);
+ const identity = vi.mocked(context.draftLifecycle.observe).mock
+ .calls[0][0];
+ const pending = Promise.withResolvers<PersistedEmailIdentity>();
+ vi.mocked(context.drafts.saveDraft).mockReturnValueOnce(pending.promise);
+ state.switchInbox('other');
+ await vi.advanceTimersByTimeAsync(0);
+ state.switchInbox('third');
+ expect(state.selectedInbox()).toBe('other');
+ expect(identity.inboxId()).toBe('inbox');
+ expect(identity.draftId()).toBe('draft');
+ context.setDraftLifecycle({
+ type: 'missing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'other',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ // The server deletes the old inbox's draft before the migration response.
+ context.setDraftLifecycle({
+ type: 'missing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(context.notices.feedback.alert).not.toHaveBeenCalled();
+ pending.resolve({
+ draftId: 'moved',
+ threadId: 'moved-thread',
+ inboxId: 'other',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect([
+ identity.draftId(),
+ identity.threadId(),
+ identity.inboxId(),
+ ]).toEqual(['moved', 'moved-thread', 'other']);
+ expect(context.drafts.saveDraft).toHaveBeenCalledTimes(2);
+ expect(state.selectedInbox()).toBe('other');
+ expect(context.notices.feedback.alert).not.toHaveBeenCalled();
+ expect(state.disabled()).toBe(false);
+ state.dispose();
+ }
+ );
+
+ it.each(['standalone', 'reply'] as const)(
+ '%s defers stale observations until schedule reconciliation completes',
+ async (kind) => {
+ const context = createComposeContext();
+ const state = composer(kind, context);
+ const pending = Promise.withResolvers<void>();
+ vi.mocked(context.delivery.archive).mockReturnValueOnce(pending.promise);
+ const lifecycle = vi.mocked(context.draftLifecycle.observe).mock
+ .results[0].value;
+ const scheduled = {
+ type: 'scheduled' as const,
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime: '2026-12-01T12:00:00Z',
+ observedAt: Date.now(),
+ };
+ vi.mocked(lifecycle.refresh).mockImplementationOnce(async () => {
+ context.setDraftLifecycle(scheduled);
+ return scheduled;
+ });
+ state.selectTime(new Date(scheduled.sendTime));
+ const scheduling = state.send();
+ await vi.advanceTimersByTimeAsync(0);
+ context.setDraftLifecycle({
+ type: 'editing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(state.selectedTime()).toEqual(new Date(scheduled.sendTime));
+ pending.resolve();
+ await scheduling;
+ if (kind === 'standalone') {
+ expect(state.confirmedTime()).toEqual(new Date(scheduled.sendTime));
+ expect(state.disabled()).toBe(true);
+ } else {
+ // Inline reply follows its normal successful-submit convention and
+ // collapses; a stale editing observation must not surface a cancel.
+ expect(state.scheduleState().type).toBe('editing');
+ }
+ expect(context.notices.feedback.success).not.toHaveBeenCalledWith(
+ 'Schedule cancelled. This email is editable again.'
+ );
+ state.dispose();
+ }
+ );
it('keeps reply recipients unchanged while a schedule is pending', async () => {
const context = createComposeContext();
const pending = Promise.withResolvers<void>();
vi.mocked(context.delivery.schedule).mockReturnValueOnce(pending.promise);
const state = mountReplyComposer(context);
const originalTo = [...state.form.recipients().to];
- const schedule = state.handleSendTimeChange(
- new Date('2026-12-01T12:00:00Z')
+ expect(state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'))).toBe(
+ true
);
+ expect(context.delivery.schedule).not.toHaveBeenCalled();
+ const scheduling = state.sendEmail();
try {
await vi.advanceTimersByTimeAsync(0);
expect(context.delivery.schedule).toHaveBeenCalledOnce();
@@ -50,15 +394,53 @@ describe('send and schedule ordering', () => {
expect(state.form.recipients().to).toEqual(originalTo);
expect(state.form.recipients().cc).toEqual([]);
pending.resolve();
- await schedule;
- state.recipients.setRecipients('to', []);
- await vi.advanceTimersByTimeAsync(0);
- expect(context.delivery.unschedule).toHaveBeenCalledOnce();
- expect(state.form.sendTime()).toBeUndefined();
- expect(state.sendActionDisabled()).toBe(false);
+ await scheduling;
+ expect(context.delivery.unschedule).not.toHaveBeenCalled();
+ expect(context.delivery.sendMessage).not.toHaveBeenCalled();
} finally {
pending.resolve();
- await schedule;
+ await scheduling;
+ state.dispose();
+ }
+ });
+
+ it('ignores confirmed-schedule edits and quoted-text toggles', async () => {
+ const context = createComposeContext();
+ const state = mountReplyComposer(context);
+ try {
+ state.edit('Persist before scheduling elsewhere');
+ await vi.advanceTimersByTimeAsync(600);
+ context.setDraftLifecycle({
+ type: 'scheduled',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ sendTime: '2026-12-01T12:00:00Z',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(state.confirmedSendTime()).toEqual(
+ new Date('2026-12-01T12:00:00Z')
+ );
+
+ state.scheduleDraftSave();
+ state.toggleQuotedText();
+ expect(state.form.replyAppended()).toBe(false);
+
+ context.setDraftLifecycle({
+ type: 'sent',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(context.drafts.saveDraft).toHaveBeenCalledOnce();
+ expect(context.notices.feedback.success).toHaveBeenCalledWith(
+ 'Scheduled email sent'
+ );
+ } finally {
state.dispose();
}
});
@@ -112,6 +494,44 @@ describe('send and schedule ordering', () => {
}
});
+ it('keeps a newer reply when undoing an immediate send without schedule wording', async () => {
+ const context = createComposeContext();
+ vi.mocked(context.delivery.sendMessage).mockResolvedValueOnce({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ });
+ vi.mocked(context.delivery.undoSend).mockImplementation(
+ async ({ onUndone }) => {
+ await onUndone();
+ }
+ );
+ const state = mountReplyComposer(context);
+ try {
+ state.edit('Earlier reply');
+ await state.sendEmail();
+ const sentNotice = vi
+ .mocked(context.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email sent');
+
+ state.edit('Newer reply that must survive');
+ sentNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(decodeBase64Utf8(state.collectDraft()?.body_html ?? '')).toContain(
+ 'Newer reply that must survive'
+ );
+ expect(context.notices.feedback.alert).toHaveBeenCalledWith(
+ 'Your newer reply was kept. The earlier message was not reopened.'
+ );
+ expect(context.notices.feedback.alert).not.toHaveBeenCalledWith(
+ expect.stringContaining('Schedule cancelled')
+ );
+ } finally {
+ state.dispose();
+ }
+ });
+
it('undoes mark-done while the post-send refresh is still pending', async () => {
const composeContext = createComposeContext();
const { promise: refresh, resolve: finish } = Promise.withResolvers<void>();
@@ -162,15 +582,13 @@ describe('send and schedule ordering', () => {
it('does not add a scheduling notice after persistence already failed', async () => {
const composeContext = createComposeContext();
const failure = new Error('Draft save failed');
- vi.mocked(composeContext.drafts.saveDraft).mockImplementationOnce(
- async () => {
- composeContext.notices.feedback.failure('Failed to save draft');
- throw failure;
- }
- );
+ vi.mocked(composeContext.drafts.saveDraft).mockRejectedValueOnce(failure);
const state = mountReplyComposer(composeContext);
try {
- await state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ expect(state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'))).toBe(
+ true
+ );
+ await state.sendEmail();
expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
expect(
composeContext.notices.feedback.failure
@@ -181,6 +599,179 @@ describe('send and schedule ordering', () => {
}
});
+ it('undoes a scheduled reply with its saved body, envelope, and attachments', async () => {
+ const composeContext = createComposeContext();
+ const state = mountReplyComposer(composeContext);
+ try {
+ state.form.setSubject('Scheduled reply subject');
+ state.form.attachments.add({
+ type: 'forwarded',
+ attachmentId: 'source-file',
+ fileName: 'review.txt',
+ mimeType: 'text/plain',
+ fileSize: 10,
+ });
+ state.edit('Restore this scheduled reply');
+ state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ await state.sendEmail();
+
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(composeContext.delivery.unschedule).toHaveBeenCalledWith({
+ draftId: 'draft',
+ inboxId: 'inbox',
+ });
+ expect(composeContext.drafts.restoreDraft).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ draft: expect.objectContaining({
+ db_id: 'draft',
+ subject: 'Scheduled reply subject',
+ }),
+ })
+ );
+ expect(decodeBase64Utf8(state.collectDraft()?.body_html ?? '')).toContain(
+ 'Restore this scheduled reply'
+ );
+ expect(state.form.attachments.list()).toEqual([
+ expect.objectContaining({ attachmentId: 'source-file' }),
+ ]);
+ } finally {
+ state.dispose();
+ }
+ });
+
+ it('reports a partial undo when the cancelled draft cannot be reopened', async () => {
+ const composeContext = createComposeContext();
+ const restoreFailure = new Error('Draft restore failed');
+ vi.mocked(composeContext.drafts.restoreDraft).mockRejectedValueOnce(
+ restoreFailure
+ );
+ const state = mountReplyComposer(composeContext);
+ try {
+ state.edit('Keep this scheduled reply');
+ state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ await state.sendEmail();
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(composeContext.notices.reportError).toHaveBeenCalledWith(
+ restoreFailure
+ );
+ expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
+ 'Schedule cancelled, but the draft could not be reopened. Check Drafts.'
+ );
+ expect(composeContext.notices.feedback.success).not.toHaveBeenCalledWith(
+ 'Schedule cancelled.'
+ );
+ } finally {
+ state.dispose();
+ }
+ });
+
+ it('keeps a newer reply when undoing an older scheduled reply', async () => {
+ const composeContext = createComposeContext();
+ const state = mountReplyComposer(composeContext);
+ try {
+ state.edit('Older scheduled reply');
+ state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ await state.sendEmail();
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+
+ state.edit('Newer reply that must survive');
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(decodeBase64Utf8(state.collectDraft()?.body_html ?? '')).toContain(
+ 'Newer reply that must survive'
+ );
+ expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
+ 'Your newer reply was kept. The earlier message was not reopened.'
+ );
+ expect(composeContext.notices.feedback.success).toHaveBeenCalledWith(
+ 'Schedule cancelled.'
+ );
+ } finally {
+ state.dispose();
+ }
+ });
+
+ it('keeps a different saved reply mounted after the scheduled reply is closed', async () => {
+ const composeContext = createComposeContext();
+ const parent = () => message('parent');
+ const scheduled = mountReplyComposer(composeContext, parent);
+ scheduled.edit('Older scheduled reply');
+ scheduled.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ await scheduled.sendEmail();
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+ scheduled.dispose();
+
+ const newer = mountReplyComposer(composeContext, parent, {
+ draft: message('newer-draft', {
+ is_draft: true,
+ replying_to_id: 'parent',
+ }),
+ });
+ try {
+ expect(newer.savedDraftId()).toBe('newer-draft');
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(newer.savedDraftId()).toBe('newer-draft');
+ expect(composeContext.notices.feedback.alert).toHaveBeenCalledWith(
+ 'Your newer reply was kept. The earlier message was not reopened.'
+ );
+ } finally {
+ newer.dispose();
+ }
+ });
+
+ it('does not treat another draft as proof that a lost undo response succeeded', async () => {
+ const composeContext = createComposeContext();
+ vi.mocked(composeContext.delivery.unschedule).mockRejectedValueOnce(
+ new Error('response lost')
+ );
+ const state = mountReplyComposer(composeContext);
+ try {
+ state.edit('Scheduled reply');
+ state.handleSendTimeChange(new Date('2026-12-01T12:00:00Z'));
+ await state.sendEmail();
+ composeContext.setDraftLifecycle({
+ type: 'editing',
+ draftId: 'different-draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: Date.now(),
+ });
+ const scheduledNotice = vi
+ .mocked(composeContext.notices.feedback.success)
+ .mock.calls.find(([text]) => text === 'Email scheduled');
+ scheduledNotice?.[1]?.actions?.[0].onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(composeContext.notices.feedback.failure).toHaveBeenCalledWith(
+ 'Failed to undo scheduled send'
+ );
+ expect(composeContext.drafts.restoreDraft).not.toHaveBeenCalled();
+ } finally {
+ state.dispose();
+ }
+ });
+
it('does not overwrite a newly edited reply when an older unmounted send fails', async () => {
const composeContext = createComposeContext();
const { promise: sending, reject } =
@@ -304,11 +895,11 @@ describe('send and schedule ordering', () => {
state.form.setSelectedInbox('secondary');
state.handleAddAttachments([new File(['attachment'], 'review.txt')]);
await vi.advanceTimersByTimeAsync(500);
- const scheduling = state.handleSendTimeChange(
- new Date('2026-10-01T12:00:00Z')
+ expect(state.handleSendTimeChange(new Date('2026-10-01T12:00:00Z'))).toBe(
+ true
);
+ const scheduling = state.sendEmail();
await vi.advanceTimersByTimeAsync(0);
- state.form.setSelectedInbox('inbox');
expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
finish();
await scheduling;
@@ -413,6 +1004,9 @@ describe('send and schedule ordering', () => {
state.edit('Forwarding');
await vi.advanceTimersByTimeAsync(500);
state.handleRemoveAttachment(attachment);
+ expect(
+ composeContext.attachmentStorage.removeForwardedAttachment
+ ).not.toHaveBeenCalled();
finish({ draftId: 'draft', threadId: 'thread', inboxId: 'inbox' });
await vi.advanceTimersByTimeAsync(0);
expect(
@@ -423,6 +1017,31 @@ describe('send and schedule ordering', () => {
}
});
+ it('persists forwarded references once per committed reply save', async () => {
+ const context = createComposeContext();
+ const state = mountReplyComposer(context);
+ try {
+ state.form.attachments.add({
+ type: 'forwarded',
+ attachmentId: 'source-file',
+ fileName: 'review.txt',
+ mimeType: 'text/plain',
+ fileSize: 10,
+ });
+ state.edit('Forwarded content');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(
+ context.attachmentStorage.addForwardedAttachments
+ ).toHaveBeenCalledExactlyOnceWith({
+ draftId: 'draft',
+ inboxId: 'inbox',
+ attachments: [{ attachmentId: 'source-file' }],
+ });
+ } finally {
+ state.dispose();
+ }
+ });
+
it('waits for the first save, sends its returned draft ID once, and does not recreate the sent reply', async () => {
const { promise: saving, resolve: finish } =
Promise.withResolvers<PersistedEmailIdentity>();
@@ -559,9 +1178,10 @@ describe('send and schedule ordering', () => {
state.edit('Moving between inboxes');
await vi.advanceTimersByTimeAsync(500);
state.persistDraftOnSenderSwitch('b');
- state.persistDraftOnSenderSwitch('c');
finish({ draftId: 'draft-a', threadId: 'thread-a', inboxId: 'inbox' });
await vi.advanceTimersByTimeAsync(0);
+ state.persistDraftOnSenderSwitch('c');
+ await vi.advanceTimersByTimeAsync(0);
const inputs = vi
.mocked(composeContext.drafts.saveDraft)
.mock.calls.map(([input]) => input);
@@ -575,7 +1195,8 @@ describe('send and schedule ordering', () => {
'draft-a',
'draft-b',
]);
- await state.handleSendTimeChange(new Date('2026-10-01T12:00:00Z'));
+ state.handleSendTimeChange(new Date('2026-10-01T12:00:00Z'));
+ await state.sendEmail();
expect(composeContext.delivery.archive).toHaveBeenLastCalledWith(
{ threadId: 'thread-c', value: true },
'c'
@@ -586,14 +1207,11 @@ describe('send and schedule ordering', () => {
});
it.each(['standalone', 'reply'] as const)(
- '%s does not dispatch when scheduling starts during the pending draft save',
+ '%s rejects a time change after immediate submission has started',
async (kind) => {
const { promise: saving, resolve: finishSaving } =
Promise.withResolvers<PersistedEmailIdentity>();
- const { promise: scheduled, resolve: finishScheduling } =
- Promise.withResolvers<void>();
const composeContext = createComposeContext();
- vi.mocked(composeContext.delivery.schedule).mockReturnValue(scheduled);
vi.mocked(composeContext.drafts.saveDraft).mockImplementationOnce(
() => saving
);
@@ -602,18 +1220,15 @@ describe('send and schedule ordering', () => {
state.send();
await vi.advanceTimersByTimeAsync(0);
expect(composeContext.drafts.saveDraft).toHaveBeenCalledOnce();
- const scheduling = state.schedule(new Date('2026-10-01T12:00:00Z'));
- await vi.advanceTimersByTimeAsync(0);
+ expect(state.selectTime(new Date('2026-10-01T12:00:00Z'))).toBe(false);
finishSaving({
draftId: 'draft',
threadId: 'thread',
inboxId: 'inbox',
});
await vi.advanceTimersByTimeAsync(0);
- expect(composeContext.delivery.sendMessage).not.toHaveBeenCalled();
- expect(composeContext.delivery.schedule).toHaveBeenCalledOnce();
- finishScheduling();
- await scheduling;
+ expect(composeContext.delivery.sendMessage).toHaveBeenCalledOnce();
+ expect(composeContext.delivery.schedule).not.toHaveBeenCalled();
} finally {
state.dispose();
}
diff --git a/apps/web/src/features/email-compose/queries/draft-lifecycle-source.test.tsx b/apps/web/src/features/email-compose/queries/draft-lifecycle-source.test.tsx
new file mode 100644
index 0000000000..4b1748b1e1
--- /dev/null
+++ b/apps/web/src/features/email-compose/queries/draft-lifecycle-source.test.tsx
@@ -0,0 +1,319 @@
+import { emailKeys } from '@queries/email/keys';
+import type { ApiThread } from '@service-email/generated/schemas';
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type {
+ EmailDraftLifecycleSource,
+ EmailDraftLifecycleState,
+} from '../context/compose-capabilities';
+
+const fetchThread = vi.hoisted(() => vi.fn());
+vi.mock('@queries/email/thread', () => ({
+ fetchFreshEmailThread: fetchThread,
+}));
+vi.mock('@core/cross-tab/cross-tab-bus', () => ({
+ createCrossTabBus: () => ({ publish() {}, subscribe: () => () => {} }),
+}));
+
+import { emailDraftLifecycleSource } from './draft-lifecycle';
+
+const identity = { draftId: 'draft', threadId: 'thread', inboxId: 'inbox' };
+const queryKey = emailKeys.composeDraftState(identity).queryKey;
+const clients: QueryClient[] = [];
+
+function thread(scheduled: boolean): ApiThread {
+ return {
+ access_level: 'owner',
+ created_at: '2026-09-21T00:00:00Z',
+ updated_at: '2026-09-21T00:00:00Z',
+ db_id: 'thread',
+ link_id: 'inbox',
+ inbox_visible: false,
+ is_read: true,
+ messages: [
+ {
+ attachments: [],
+ attachments_draft: [],
+ attachments_forwarded: [],
+ to: [],
+ cc: [],
+ bcc: [],
+ labels: [],
+ created_at: '2026-09-21T00:00:00Z',
+ updated_at: '2026-09-21T00:00:00Z',
+ db_id: 'draft',
+ thread_db_id: 'thread',
+ link_id: 'inbox',
+ has_attachments: false,
+ is_draft: true,
+ is_sent: false,
+ is_read: true,
+ is_starred: false,
+ scheduled_send_time: scheduled ? '2026-12-01T12:00:00Z' : null,
+ },
+ ],
+ };
+}
+
+function createClient() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },
+ });
+ clients.push(client);
+ return client;
+}
+
+function observe(client = createClient()) {
+ const [current, setCurrent] = createSignal(identity);
+ let lifecycle!: ReturnType<EmailDraftLifecycleSource['observe']>;
+ function Probe() {
+ lifecycle = emailDraftLifecycleSource.observe({
+ draftId: () => current().draftId,
+ threadId: () => current().threadId,
+ inboxId: () => current().inboxId,
+ });
+ return null;
+ }
+ const { unmount } = render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+ return { lifecycle, client, setCurrent, unmount };
+}
+
+beforeEach(() => fetchThread.mockReset());
+afterEach(() => {
+ cleanup();
+ for (const client of clients.splice(0)) client.clear();
+ vi.restoreAllMocks();
+});
+
+it('does not republish cached state when a strict refresh rejects', async () => {
+ vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000);
+ const failure = new Error('Lifecycle unavailable');
+ fetchThread
+ .mockResolvedValueOnce(thread(false))
+ .mockRejectedValueOnce(failure)
+ .mockResolvedValueOnce(thread(true));
+ const { lifecycle, client } = observe();
+ await waitFor(() => expect(lifecycle.state()?.type).toBe('editing'));
+
+ const notifications: VoidFunction[] = [];
+ const queueNotification = vi
+ .spyOn(globalThis, 'queueMicrotask')
+ .mockImplementation((callback) => notifications.push(callback));
+ const refreshing = lifecycle.refresh();
+ expect(lifecycle.state()).toBeUndefined();
+ await expect(refreshing).rejects.toBe(failure);
+ // Check synchronously as an awaiting composer releases its mutation gate,
+ // before Solid Query's error notification necessarily reaches its store.
+ expect(lifecycle.state()).toBeUndefined();
+ queueNotification.mockRestore();
+ for (const notify of notifications) notify();
+ await client.invalidateQueries({
+ queryKey: emailKeys.composeDraftState._def,
+ });
+ await waitFor(() => expect(lifecycle.state()?.type).toBe('scheduled'));
+});
+
+it('keeps polling when a failed refresh invalidates an earlier terminal state', async () => {
+ vi.useFakeTimers();
+ try {
+ const missing = thread(false);
+ missing.messages = [];
+ const failure = new Error('Lifecycle unavailable');
+ fetchThread
+ .mockResolvedValueOnce(missing)
+ .mockRejectedValueOnce(failure)
+ .mockResolvedValueOnce(thread(false));
+ const { lifecycle } = observe();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(lifecycle.state()?.type).toBe('missing');
+ await expect(lifecycle.refresh()).rejects.toBe(failure);
+ expect(lifecycle.state()).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(fetchThread).toHaveBeenCalledTimes(3);
+ expect(lifecycle.state()?.type).toBe('editing');
+ } finally {
+ vi.useRealTimers();
+ }
+});
+
+it.each([true, false])(
+ 'starts an independent read after a schedule change (scheduled: %s)',
+ async (scheduled) => {
+ const oldRead = Promise.withResolvers<ApiThread>();
+ const freshRead = Promise.withResolvers<ApiThread>();
+ fetchThread
+ .mockReturnValueOnce(oldRead.promise)
+ .mockReturnValueOnce(freshRead.promise);
+ const { lifecycle, client } = observe();
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledOnce());
+
+ const refreshing = lifecycle.refresh();
+ // A hung initial read must not hold the authoritative read hostage.
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledTimes(2));
+ expect(lifecycle.state()).toBeUndefined();
+ freshRead.resolve(thread(scheduled));
+ await refreshing;
+ const expected = scheduled ? 'scheduled' : 'editing';
+ await waitFor(() => expect(lifecycle.state()?.type).toBe(expected));
+ oldRead.resolve(thread(!scheduled));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(lifecycle.state()?.type).toBe(expected);
+ expect(
+ client
+ .getQueriesData<{ state: EmailDraftLifecycleState }>({ queryKey })
+ .map(([, observation]) => observation?.state.type)
+ ).toEqual([expected]);
+ }
+);
+
+it('ignores a cached sent state while a remounted draft awaits its fresh read', async () => {
+ const sent = thread(false);
+ sent.messages[0].is_sent = true;
+ const freshRead = Promise.withResolvers<ApiThread>();
+ fetchThread
+ .mockResolvedValueOnce(sent)
+ .mockReturnValueOnce(freshRead.promise);
+ const previous = observe();
+ await waitFor(() => expect(previous.lifecycle.state()?.type).toBe('sent'));
+ previous.unmount();
+ const { lifecycle } = observe(previous.client);
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledTimes(2));
+ expect(lifecycle.state()).toBeUndefined();
+ freshRead.resolve(thread(false));
+ await waitFor(() => expect(lifecycle.state()?.type).toBe('editing'));
+});
+
+it('keeps simultaneous observers from cancelling each other or replaying cached editing', async () => {
+ const firstRead = Promise.withResolvers<ApiThread>();
+ const secondRead = Promise.withResolvers<ApiThread>();
+ fetchThread
+ .mockResolvedValueOnce(thread(false))
+ .mockResolvedValueOnce(thread(false))
+ .mockReturnValueOnce(firstRead.promise)
+ .mockReturnValueOnce(secondRead.promise);
+ const first = observe();
+ await waitFor(() => expect(first.lifecycle.state()?.type).toBe('editing'));
+ const second = observe(first.client);
+ await waitFor(() => expect(second.lifecycle.state()?.type).toBe('editing'));
+
+ let firstFinished = false;
+ async function refreshFirst() {
+ const state = await first.lifecycle.refresh();
+ firstFinished = true;
+ return state;
+ }
+ const firstRefresh = refreshFirst();
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledTimes(3));
+ const secondRefresh = second.lifecycle.refresh();
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledTimes(4));
+ expect(firstFinished).toBe(false);
+ expect(first.lifecycle.state()).toBeUndefined();
+ expect(second.lifecycle.state()).toBeUndefined();
+
+ secondRead.resolve(thread(true));
+ expect((await secondRefresh)?.type).toBe('scheduled');
+ await waitFor(() => expect(second.lifecycle.state()?.type).toBe('scheduled'));
+ expect(firstFinished).toBe(false);
+ expect(first.lifecycle.state()).toBeUndefined();
+
+ firstRead.resolve(thread(true));
+ expect((await firstRefresh)?.type).toBe('scheduled');
+ await waitFor(() => expect(first.lifecycle.state()?.type).toBe('scheduled'));
+});
+
+it.each(['scheduled', 'sent'] as const)(
+ 'does not reuse a pending %s read from a previous mount',
+ async (oldState) => {
+ const oldRead = Promise.withResolvers<ApiThread>();
+ const freshRead = Promise.withResolvers<ApiThread>();
+ fetchThread
+ .mockReturnValueOnce(oldRead.promise)
+ .mockReturnValueOnce(freshRead.promise);
+ const previous = observe();
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledOnce());
+ previous.unmount();
+
+ const { lifecycle } = observe(previous.client);
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledTimes(2));
+ expect(lifecycle.state()).toBeUndefined();
+ freshRead.resolve(thread(false));
+ await waitFor(() => expect(lifecycle.state()?.type).toBe('editing'));
+
+ const staleThread = thread(oldState === 'scheduled');
+ staleThread.messages[0].is_sent = oldState === 'sent';
+ oldRead.resolve(staleThread);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(lifecycle.state()?.type).toBe('editing');
+ }
+);
+
+it('refetches every scoped observer through the websocket lifecycle prefix', async () => {
+ fetchThread.mockResolvedValue(thread(false));
+ const first = observe();
+ await waitFor(() => expect(first.lifecycle.state()?.type).toBe('editing'));
+ const second = observe(first.client);
+ await waitFor(() => expect(second.lifecycle.state()?.type).toBe('editing'));
+ expect(fetchThread).toHaveBeenCalledTimes(2);
+ const queries = first.client.getQueryCache().findAll({ queryKey });
+ expect(queries).toHaveLength(2);
+ for (const query of queries) {
+ expect(query.queryKey.slice(0, -1)).toEqual(queryKey);
+ }
+
+ fetchThread.mockResolvedValue(thread(true));
+ await first.client.invalidateQueries({
+ queryKey: emailKeys.composeDraftState._def,
+ });
+ expect(fetchThread).toHaveBeenCalledTimes(4);
+ await waitFor(() => {
+ expect(first.lifecycle.state()?.type).toBe('scheduled');
+ expect(second.lifecycle.state()?.type).toBe('scheduled');
+ });
+});
+
+it('does not let an old identity refresh hide the migrated draft', async () => {
+ const initial = Promise.withResolvers<ApiThread>();
+ const refreshingOldIdentity = Promise.withResolvers<ApiThread>();
+ const movedIdentity = {
+ draftId: 'moved',
+ threadId: 'moved-thread',
+ inboxId: 'other',
+ };
+ const movedThread = thread(false);
+ movedThread.db_id = movedIdentity.threadId;
+ movedThread.link_id = movedIdentity.inboxId;
+ movedThread.messages = movedThread.messages.map((message) => ({
+ ...message,
+ db_id: movedIdentity.draftId,
+ thread_db_id: movedIdentity.threadId,
+ link_id: movedIdentity.inboxId,
+ }));
+ fetchThread
+ .mockReturnValueOnce(initial.promise)
+ .mockReturnValueOnce(refreshingOldIdentity.promise)
+ .mockResolvedValueOnce(movedThread);
+ const { lifecycle, setCurrent } = observe();
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledOnce());
+ const refreshing = lifecycle.refresh();
+ await waitFor(() => expect(fetchThread).toHaveBeenCalledTimes(2));
+ setCurrent(movedIdentity);
+ await waitFor(() =>
+ expect(lifecycle.state()).toMatchObject({
+ ...movedIdentity,
+ type: 'editing',
+ })
+ );
+ initial.resolve(thread(true));
+ refreshingOldIdentity.resolve(thread(true));
+ expect(await refreshing).toBeUndefined();
+ expect(lifecycle.state()).toMatchObject({
+ ...movedIdentity,
+ type: 'editing',
+ });
+});
diff --git a/apps/web/src/features/email-compose/queries/draft-lifecycle.test.ts b/apps/web/src/features/email-compose/queries/draft-lifecycle.test.ts
new file mode 100644
index 0000000000..6f329b460f
--- /dev/null
+++ b/apps/web/src/features/email-compose/queries/draft-lifecycle.test.ts
@@ -0,0 +1,78 @@
+import type { ApiMessage } from '@service-email/generated/schemas';
+import { describe, expect, it } from 'vitest';
+import { message } from '../../email-message/tests/messages';
+import { deriveEmailDraftLifecycle } from './draft-lifecycle';
+
+function draft(overrides: Partial<ApiMessage> = {}): ApiMessage {
+ return {
+ ...(message('draft', {
+ is_draft: true,
+ }) as unknown as ApiMessage),
+ is_sent: false,
+ ...overrides,
+ };
+}
+
+describe('deriveEmailDraftLifecycle', () => {
+ it('tracks an editable draft by its exact message and inbox identity', () => {
+ expect(
+ deriveEmailDraftLifecycle({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ message: draft(),
+ observedAt: 1,
+ })
+ ).toEqual({
+ type: 'editing',
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ observedAt: 1,
+ });
+ });
+
+ it('distinguishes scheduled, sent, and missing states', () => {
+ expect(
+ deriveEmailDraftLifecycle({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ message: draft({ scheduled_send_time: '2026-12-01T12:00:00Z' }),
+ })
+ ).toMatchObject({
+ type: 'scheduled',
+ sendTime: '2026-12-01T12:00:00Z',
+ });
+ expect(
+ deriveEmailDraftLifecycle({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ message: draft({ is_draft: false, is_sent: true }),
+ })
+ ).toMatchObject({ type: 'sent', draftId: 'draft', inboxId: 'inbox' });
+ expect(
+ deriveEmailDraftLifecycle({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'inbox',
+ })
+ ).toMatchObject({ type: 'missing', draftId: 'draft' });
+ });
+
+ it('treats the same message ID from another inbox as missing', () => {
+ expect(
+ deriveEmailDraftLifecycle({
+ draftId: 'draft',
+ threadId: 'thread',
+ inboxId: 'selected-inbox',
+ message: draft({ link_id: 'other-inbox' }),
+ })
+ ).toMatchObject({
+ type: 'missing',
+ draftId: 'draft',
+ inboxId: 'selected-inbox',
+ });
+ });
+});
diff --git a/apps/web/src/features/email-compose/queries/draft-lifecycle.ts b/apps/web/src/features/email-compose/queries/draft-lifecycle.ts
new file mode 100644
index 0000000000..f9f7aa5d35
--- /dev/null
+++ b/apps/web/src/features/email-compose/queries/draft-lifecycle.ts
@@ -0,0 +1,212 @@
+import { thrownResultErrorHasCode } from '@core/util/result';
+import {
+ type DraftLifecycleChange,
+ publishDraftLifecycleChange,
+ subscribeToDraftLifecycleChanges,
+} from '@queries/email/draft-lifecycle-events';
+import { emailKeys } from '@queries/email/keys';
+import { fetchFreshEmailThread } from '@queries/email/thread';
+import type { ApiMessage } from '@service-email/generated/schemas';
+import { useQuery, useQueryClient } from '@tanstack/solid-query';
+import { createSignal, onCleanup } from 'solid-js';
+import type {
+ EmailDraftLifecycleSource,
+ EmailDraftLifecycleState,
+} from '../context/compose-capabilities';
+
+const EDITING_REFRESH_INTERVAL_MS = 15_000;
+const DUE_REFRESH_INTERVAL_MS = 2_000;
+const FAR_SCHEDULE_REFRESH_INTERVAL_MS = 30_000;
+let nextObserverId = 0;
+
+export { publishDraftLifecycleChange };
+
+export function deriveEmailDraftLifecycle(input: {
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+ message?: ApiMessage;
+ observedAt?: number;
+}): EmailDraftLifecycleState {
+ const observedAt = input.observedAt ?? Date.now();
+ const message = input.message;
+ if (!message || (input.inboxId && message.link_id !== input.inboxId)) {
+ return {
+ type: 'missing',
+ draftId: input.draftId,
+ threadId: input.threadId,
+ inboxId: input.inboxId,
+ observedAt,
+ };
+ }
+ const identity = {
+ draftId: input.draftId,
+ threadId: message.thread_db_id,
+ inboxId: message.link_id,
+ observedAt,
+ };
+ if (message.is_sent || !message.is_draft) {
+ return { type: 'sent', ...identity };
+ }
+ if (message.scheduled_send_time) {
+ return {
+ type: 'scheduled',
+ ...identity,
+ sendTime: message.scheduled_send_time,
+ };
+ }
+ return { type: 'editing', ...identity };
+}
+
+async function fetchLifecycle(input: {
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+}): Promise<EmailDraftLifecycleState> {
+ const observedAt = Date.now();
+ try {
+ const thread = await fetchFreshEmailThread(input.threadId, input.draftId);
+ return deriveEmailDraftLifecycle({
+ ...input,
+ observedAt,
+ message: thread.messages.find(
+ (message) => message.db_id === input.draftId
+ ),
+ });
+ } catch (error) {
+ if (thrownResultErrorHasCode(error, 'NOT_FOUND')) {
+ return deriveEmailDraftLifecycle({ ...input, observedAt });
+ }
+ throw error;
+ }
+}
+
+function refreshInterval(state: EmailDraftLifecycleState | undefined) {
+ if (!state || state.type === 'editing') return EDITING_REFRESH_INTERVAL_MS;
+ if (state.type !== 'scheduled') return false;
+ const untilSend = new Date(state.sendTime).getTime() - Date.now();
+ return untilSend > FAR_SCHEDULE_REFRESH_INTERVAL_MS
+ ? FAR_SCHEDULE_REFRESH_INTERVAL_MS
+ : DUE_REFRESH_INTERVAL_MS;
+}
+
+export const emailDraftLifecycleSource: EmailDraftLifecycleSource = {
+ observe(input) {
+ const queryClient = useQueryClient();
+ const observerId = ++nextObserverId;
+ // Keep the shared prefix for websocket invalidation, but never share a
+ // pending read or cancellation with another composer or a previous mount.
+ const observerQueryKey = (
+ draftId: string,
+ threadId: string,
+ inboxId?: string
+ ) =>
+ [
+ ...emailKeys.composeDraftState({ draftId, threadId, inboxId }).queryKey,
+ observerId,
+ ] as const;
+ const [refreshing, setRefreshing] = createSignal<{
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+ }>();
+ let refreshVersion = 0;
+ const [requiredReadVersion, setRequiredReadVersion] = createSignal(0);
+ const read = async (identity: Parameters<typeof fetchLifecycle>[0]) => {
+ const version = refreshVersion;
+ const state = await fetchLifecycle(identity);
+ return { state, version };
+ };
+ const query = useQuery(() => {
+ const draftId = input.draftId() ?? '';
+ const threadId = input.threadId() ?? '';
+ const inboxId = input.inboxId();
+ return {
+ queryKey: observerQueryKey(draftId, threadId, inboxId),
+ enabled: draftId.length > 0 && threadId.length > 0,
+ queryFn: () => read({ draftId, threadId, inboxId }),
+ staleTime: 0,
+ refetchOnWindowFocus: 'always' as const,
+ refetchOnReconnect: 'always' as const,
+ refetchInterval: (stateQuery) =>
+ refreshInterval(
+ stateQuery.state.data?.version === refreshVersion
+ ? stateQuery.state.data.state
+ : undefined
+ ),
+ };
+ });
+
+ const refresh = async () => {
+ const draftId = input.draftId();
+ const threadId = input.threadId();
+ const inboxId = input.inboxId();
+ if (!draftId || !threadId) return undefined;
+
+ const version = ++refreshVersion;
+ // Once a mutation needs reconciliation, no earlier observation is
+ // authoritative again, even if the fresh read fails or query-store
+ // notifications are delayed. A later successful poll can satisfy this
+ // barrier without relying on wall-clock timestamp resolution.
+ setRequiredReadVersion(version);
+ setRefreshing({ draftId, threadId, inboxId });
+ const queryKey = observerQueryKey(draftId, threadId, inboxId);
+ try {
+ // refetch({ cancelRefetch: true }) still shares an initial pending
+ // read. Explicit cancellation prevents its late result from entering
+ // this observer's cache; the REST query below starts independently.
+ await queryClient.cancelQueries({ queryKey, exact: true });
+ const result = await queryClient.fetchQuery({
+ queryKey,
+ queryFn: () => read({ draftId, threadId, inboxId }),
+ staleTime: 0,
+ });
+ return version === refreshVersion &&
+ result.version === version &&
+ draftId === input.draftId() &&
+ threadId === input.threadId() &&
+ inboxId === input.inboxId()
+ ? result.state
+ : undefined;
+ } finally {
+ if (version === refreshVersion) setRefreshing(undefined);
+ }
+ };
+
+ const refreshFromEvent = async (event: DraftLifecycleChange) => {
+ if (event.draftId !== input.draftId()) return;
+ if (event.inboxId && event.inboxId !== input.inboxId()) return;
+ try {
+ await refresh();
+ } catch {
+ // Background failures remain query errors and retry on the next event/poll.
+ }
+ };
+ const unsubscribe = subscribeToDraftLifecycleChanges(
+ (event) => void refreshFromEvent(event)
+ );
+ onCleanup(unsubscribe);
+
+ // A cached terminal state can predate undo-send or a draft migration.
+ // Only a successful read made by this observer can change the composer.
+ const state = () => {
+ const pending = refreshing();
+ if (
+ pending?.draftId === input.draftId() &&
+ pending?.threadId === input.threadId() &&
+ pending?.inboxId === input.inboxId()
+ )
+ return undefined;
+ if (!query.isSuccess || !query.isFetchedAfterMount) return undefined;
+ const observation = query.data;
+ return observation.version === requiredReadVersion()
+ ? observation.state
+ : undefined;
+ };
+ return {
+ state,
+ refresh,
+ refreshIdentity: (identity) => fetchLifecycle(identity),
+ };
+ },
+};
diff --git a/apps/web/src/features/email-compose/tests/capabilities.ts b/apps/web/src/features/email-compose/tests/capabilities.ts
index ff7a587a7e..8bb9b4b976 100644
--- a/apps/web/src/features/email-compose/tests/capabilities.ts
+++ b/apps/web/src/features/email-compose/tests/capabilities.ts
@@ -1,8 +1,40 @@
+import { createSignal } from 'solid-js';
import { vi } from 'vitest';
-import type { EmailComposeContext } from '../context/compose-capabilities';
+import type {
+ EmailComposeContext,
+ EmailDraftLifecycleState,
+} from '../context/compose-capabilities';
/** Fake capabilities: no production modules or app providers are needed by a controller. */
-export function createComposeContext(): EmailComposeContext {
+export function createComposeContext(): EmailComposeContext & {
+ setDraftLifecycle(state: EmailDraftLifecycleState | undefined): void;
+} {
+ const [lifecycleState, setLifecycleState] =
+ createSignal<EmailDraftLifecycleState>();
return {
+ setDraftLifecycle: setLifecycleState,
+ draftLifecycle: {
+ observe: vi.fn(() => ({
+ state: lifecycleState,
+ refresh: vi.fn(async () => {
+ const state = lifecycleState();
+ if (state) setLifecycleState({ ...state, observedAt: Date.now() });
+ return state;
+ }),
+ refreshIdentity: vi.fn(async (identity) => {
+ const state = lifecycleState();
+ if (
+ !state ||
+ state.draftId !== identity.draftId ||
+ state.threadId !== identity.threadId ||
+ (identity.inboxId !== undefined &&
+ state.inboxId !== identity.inboxId)
+ ) {
+ return undefined;
+ }
+ return state;
+ }),
+ })),
+ },
recipientName: (id) => id,
recordMention: vi.fn(),
accounts: {
diff --git a/apps/web/src/features/email-compose/tests/reply.ts b/apps/web/src/features/email-compose/tests/reply.ts
index 6d8176c336..983f51c6b5 100644
--- a/apps/web/src/features/email-compose/tests/reply.ts
+++ b/apps/web/src/features/email-compose/tests/reply.ts
@@ -12,7 +12,10 @@ import { createEmailEditor, setEmailEditorText } from './editor';
export function mountReplyComposer(
composeContext: EmailComposeContext,
replyingTo = () => message('parent'),
- callbacks: Pick<ReplyComposerOptions, 'sideEffectOnSend' | 'onMarkDone'> = {}
+ callbacks: Pick<
+ ReplyComposerOptions,
+ 'draft' | 'sideEffectOnSend' | 'onMarkDone'
+ > = {}
) {
return createRoot((dispose) => {
const editor = createEmailEditor('Ready to send');
diff --git a/apps/web/src/features/email-compose/views/compose-layout.test.tsx b/apps/web/src/features/email-compose/views/compose-layout.test.tsx
index 9335e6067e..353cb8c87a 100644
--- a/apps/web/src/features/email-compose/views/compose-layout.test.tsx
+++ b/apps/web/src/features/email-compose/views/compose-layout.test.tsx
@@ -1,12 +1,17 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { ComposerSurface } from '@ui/components/ComposerSurface';
import { type ComponentProps, createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ComposeLayout } from './compose-layout';
const attachHotkeys = vi.hoisted(() => vi.fn());
+const registerHotkeyMock = vi.hoisted(() => vi.fn());
+const onSend = vi.hoisted(() => vi.fn());
+const composeStatus = vi.hoisted(() => ({
+ disabled: false,
+}));
vi.mock('@core/hotkey/hotkeys', () => ({
- registerHotkey: vi.fn(),
+ registerHotkey: registerHotkeyMock,
useHotkeyDOMScope: () => [attachHotkeys, 'compose-email'],
}));
vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));
@@ -17,7 +22,8 @@ vi.mock('@ui', async () => ({
vi.mock('../context/compose-context', () => ({
useCompose: () => ({
recipients: () => ({ cc: [], bcc: [] }),
- disabled: () => false,
+ disabled: () => composeStatus.disabled,
+ onSend,
isMobile: () => false,
}),
}));
@@ -36,7 +42,12 @@ function DraftSurface(props: ComponentProps<typeof ComposerSurface>) {
return <ComposerSurface {...props} as="div" />;
}
-beforeEach(() => attachHotkeys.mockClear());
+beforeEach(() => {
+ attachHotkeys.mockClear();
+ registerHotkeyMock.mockClear();
+ onSend.mockClear();
+ composeStatus.disabled = false;
+});
afterEach(cleanup);
describe('ComposeLayout root composition', () => {
@@ -70,4 +81,18 @@ describe('ComposeLayout root composition', () => {
expect(attachHotkeys).toHaveBeenCalledTimes(1);
}
);
+
+ it('routes pointer and keyboard submission through the same controller', () => {
+ render(() => (
+ <ComposeLayout toolbar={<button onClick={onSend}>Send email</button>} />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Send email' }));
+
+ composeStatus.disabled = true;
+ const sendHotkey = registerHotkeyMock.mock.calls.find(
+ ([options]) => options.hotkey === 'cmd+enter'
+ )?.[0];
+ expect(sendHotkey?.keyDownHandler()).toBe(true);
+ expect(onSend).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/apps/web/src/features/email-compose/views/compose-layout.tsx b/apps/web/src/features/email-compose/views/compose-layout.tsx
index 6d8ccbac0e..decbdd31bd 100644
--- a/apps/web/src/features/email-compose/views/compose-layout.tsx
+++ b/apps/web/src/features/email-compose/views/compose-layout.tsx
@@ -163,8 +163,8 @@ export function ComposeLayout(props: {
scopeId: composeHotkeyScope,
description: 'Send email',
keyDownHandler: () => {
- if (ctx.disabled()) return false;
- if (ctx.sendTime()) return false;
+ // Pointer and keyboard submission always enter the same controller. It
+ // snapshots whether this is Send, Schedule send, or Update schedule.
ctx.onSend();
return true;
},
diff --git a/apps/web/src/features/email-compose/views/compose-toolbar.tsx b/apps/web/src/features/email-compose/views/compose-toolbar.tsx
index d1f431c756..917eb96756 100644
--- a/apps/web/src/features/email-compose/views/compose-toolbar.tsx
+++ b/apps/web/src/features/email-compose/views/compose-toolbar.tsx
@@ -1,7 +1,10 @@
import { MAX_ATTACHMENTS_BYTES_SIZE } from '@app/features/email-compose/core/constants';
import { FormatButtons } from '@channel/Input/FormatButtons';
import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';
-import { SplitHeaderRight } from '@components/app/split-layout/components/SplitHeader';
+import {
+ SplitHeaderLeft,
+ SplitHeaderRight,
+} from '@components/app/split-layout/components/SplitHeader';
import { defaultSelectionData } from '@core/component/LexicalMarkdown/plugins';
import {
NODE_TRANSFORM,
@@ -12,10 +15,11 @@ import { plural } from '@core/util/string';
import PaperclipIcon from '@phosphor/paperclip.svg?component-solid';
import TextAa from '@phosphor/text-aa.svg';
import Trash from '@phosphor/trash.svg';
-import { Button, SendButton, Tooltip } from '@ui';
+import { Button, SendButton } from '@ui';
import { FORMAT_TEXT_COMMAND, type LexicalEditor } from 'lexical';
import { createSignal, Show } from 'solid-js';
import { EmailDateSelector } from '../components/email-date-selector';
+import { EmailScheduleSummary } from '../components/email-schedule-summary';
import { useCompose } from '../context/compose-context';
export function EmailComposeToolbar(props: {
@@ -23,7 +27,6 @@ export function EmailComposeToolbar(props: {
}) {
const ctx = useCompose();
const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);
-
const handleAddAttachments = (files: File[]) => {
const currentAttachments = ctx.attachments();
@@ -77,62 +80,67 @@ export function EmailComposeToolbar(props: {
/>
</div>
</Show>
- <div class="mt-2 flex items-center justify-end gap-1">
- <Show when={ctx.hasDraft()}>
- <Button
- onClick={ctx.onDelete}
- tooltip="Delete draft"
- size="icon-composer"
- >
- <Trash />
- </Button>
- </Show>
- <Show when={!ctx.hideAttachments}>
+ <div class="mt-2 flex min-w-0 justify-end">
+ <div class="flex shrink-0 items-center gap-1">
+ <Show when={ctx.hasDraft()}>
+ <Button
+ onClick={ctx.onDelete}
+ tooltip="Delete draft"
+ size="icon-composer"
+ disabled={ctx.disabled()}
+ >
+ <Trash />
+ </Button>
+ </Show>
+ <Show when={!ctx.hideAttachments}>
+ <Button
+ ref={(el) =>
+ fileSelector(el, () => ({
+ multiple: true,
+ onSelect: handleAddAttachments,
+ }))
+ }
+ tooltip="Attach"
+ size="icon-composer"
+ disabled={ctx.disabled()}
+ >
+ <PaperclipIcon />
+ </Button>
+ </Show>
<Button
- ref={(el) =>
- fileSelector(el, () => ({
- multiple: true,
- onSelect: handleAddAttachments,
- }))
- }
- tooltip="Attach"
+ tooltip="Format"
size="icon-composer"
disabled={ctx.disabled()}
+ onClick={() => setShowFormatRibbon(!showFormatRibbon())}
>
- <PaperclipIcon />
+ <TextAa />
</Button>
- </Show>
- <Button
- tooltip="Format"
- size="icon-composer"
- disabled={ctx.disabled()}
- onClick={() => setShowFormatRibbon(!showFormatRibbon())}
- >
- <TextAa />
- </Button>
- <Show when={ctx.scheduleEnabled && ctx.onSendTimeChange}>
- <EmailDateSelector
- mobile={false}
- sendTime={ctx.sendTime()}
- onSendTimeChange={ctx.onSendTimeChange}
- disabled={ctx.scheduleSendDisabled?.()}
- />
- </Show>
- <Tooltip label={ctx.sendTime() ? 'Send time is scheduled' : ''}>
+ <Show when={ctx.scheduleEnabled}>
+ <div class="shrink-0">
+ <EmailDateSelector
+ mobile={false}
+ compact
+ state={ctx.schedule.state()}
+ selectedTime={ctx.schedule.selectedTime()}
+ onSelectTime={ctx.schedule.onSelect}
+ onCancelSchedule={ctx.schedule.onCancel}
+ operation={ctx.schedule.operation()}
+ disabled={ctx.schedule.pickerDisabled()}
+ />
+ </div>
+ </Show>
<SendButton
appearance="composer"
onClick={() => ctx.onSend()}
- disabled={
- ctx.isSavingDraft?.() ||
- !!ctx.sendTime() ||
- ctx.isSending() ||
- ctx.disabled()
- }
+ disabled={ctx.isSavingDraft?.() || ctx.primaryActionDisabled()}
pending={ctx.isSending()}
- tooltip="Send email"
+ tooltip={
+ ctx.sendUnavailableReason?.() ?? ctx.schedule.actionLabel()
+ }
+ aria-label={ctx.schedule.actionLabel()}
shortcut="cmd+enter"
/>
- </Tooltip>
+ </div>
</div>
</Show>
);
@@ -142,48 +150,67 @@ function MobileToolbar(props: {
handleAddAttachments: (files: File[]) => void;
}) {
const ctx = useCompose();
+ const hasScheduleSummary = () => {
+ const state = ctx.schedule.state();
+ return state.type === 'scheduled' || state.intent.type === 'later';
+ };
return (
- <SplitHeaderRight>
- <HeaderIsland class="h-(--mobile-chrome-button-size) p-[5px]">
- <Show when={!ctx.hideAttachments}>
- <div class="relative">
- <Button
- ref={(el) =>
- fileSelector(el, () => ({
- multiple: true,
- onSelect: props.handleAddAttachments,
- }))
- }
- size="icon-sm"
- disabled={ctx.disabled()}
- >
- <PaperclipIcon />
- </Button>
- </div>
+ <>
+ <SplitHeaderLeft>
+ <Show when={hasScheduleSummary()}>
+ <HeaderIsland class="max-w-[55cqw] shrink px-2">
+ <EmailScheduleSummary
+ state={ctx.schedule.state()}
+ operation={ctx.schedule.operation()}
+ onSelectTime={ctx.schedule.onSelect}
+ onCancelSchedule={ctx.schedule.onCancel}
+ />
+ </HeaderIsland>
</Show>
+ </SplitHeaderLeft>
+ <SplitHeaderRight>
+ <HeaderIsland class="h-(--mobile-chrome-button-size) p-[5px]">
+ <Show when={!ctx.hideAttachments}>
+ <div class="relative">
+ <Button
+ ref={(el) =>
+ fileSelector(el, () => ({
+ multiple: true,
+ onSelect: props.handleAddAttachments,
+ }))
+ }
+ size="icon-sm"
+ disabled={ctx.disabled()}
+ >
+ <PaperclipIcon />
+ </Button>
+ </div>
+ </Show>
- <Show when={ctx.scheduleEnabled && ctx.onSendTimeChange}>
- <EmailDateSelector
- mobile={ctx.isMobile()}
- sendTime={ctx.sendTime()}
- onSendTimeChange={ctx.onSendTimeChange}
- disabled={ctx.scheduleSendDisabled?.()}
- compact
+ <Show when={ctx.scheduleEnabled}>
+ <EmailDateSelector
+ mobile={ctx.isMobile()}
+ state={ctx.schedule.state()}
+ selectedTime={ctx.schedule.selectedTime()}
+ onSelectTime={ctx.schedule.onSelect}
+ onCancelSchedule={ctx.schedule.onCancel}
+ operation={ctx.schedule.operation()}
+ disabled={ctx.schedule.pickerDisabled()}
+ compact
+ />
+ </Show>
+ <SendButton
+ tooltip={
+ ctx.sendUnavailableReason?.() ?? ctx.schedule.actionLabel()
+ }
+ aria-label={ctx.schedule.actionLabel()}
+ disabled={ctx.isSavingDraft?.() || ctx.primaryActionDisabled()}
+ pending={ctx.isSending()}
+ onClick={() => ctx.onSend()}
/>
- </Show>
- <SendButton
- tooltip="Send email"
- disabled={
- ctx.isSending() ||
- ctx.isSavingDraft?.() ||
- ctx.disabled() ||
- !!ctx.sendTime()
- }
- pending={ctx.isSending()}
- onClick={() => ctx.onSend()}
- />
- </HeaderIsland>
- </SplitHeaderRight>
+ </HeaderIsland>
+ </SplitHeaderRight>
+ </>
);
}
diff --git a/apps/web/src/features/email-compose/views/email-compose.tsx b/apps/web/src/features/email-compose/views/email-compose.tsx
index d450ef831f..9f14232415 100644
--- a/apps/web/src/features/email-compose/views/email-compose.tsx
+++ b/apps/web/src/features/email-compose/views/email-compose.tsx
@@ -10,6 +10,7 @@ import { WrapUnlessMobile } from '@core/mobile/WrapUnlessMobile';
import { ComposerSurface } from '@ui';
import { createSignal, Show } from 'solid-js';
+import { EmailScheduleBar } from '../components/email-schedule-summary';
import { SignaturePreview } from '../components/signature-preview';
import type { EmailComposeContext } from '../context/compose-capabilities';
import { ComposeProvider } from '../context/compose-context';
@@ -35,6 +36,7 @@ export function EmailComposeView(props: EmailComposeViewProps) {
drafts: composeContext.drafts,
attachmentStorage: composeContext.attachmentStorage,
delivery: composeContext.delivery,
+ draftLifecycle: composeContext.draftLifecycle,
notices: composeContext.notices,
accounts: composeContext.accounts,
connectivity: composeContext.connectivity,
@@ -93,6 +95,7 @@ export function EmailComposeView(props: EmailComposeViewProps) {
mobile={composeContext.presentation.isMobile()}
prepareLinks={composeContext.presentation.prepareSignatureLinks}
html={html()}
+ dismissable={!state.context.disabled()}
onDismiss={() => setIncludeSignature(false)}
/>
)}
@@ -100,6 +103,16 @@ export function EmailComposeView(props: EmailComposeViewProps) {
),
};
const [draftBackMenuOpen, setDraftBackMenuOpen] = createSignal(false);
+ const statusLabel = () => ctxValue.deliveryState?.() ?? 'draft';
+ const statusTooltip = () => {
+ const schedule = ctxValue.schedule.state();
+ if (schedule.type === 'scheduled')
+ return `Scheduled for ${schedule.confirmedTime.toLocaleString()}. Use the send-time control to propose an update or cancel.`;
+ if (statusLabel() === 'sent') return 'This email has been sent.';
+ if (statusLabel() === 'missing')
+ return 'This draft is no longer available.';
+ return 'This is a draft email.';
+ };
if (composeContext.presentation.isMobile()) {
// Backing out of a compose that has a draft asks whether to keep it.
@@ -124,7 +137,10 @@ export function EmailComposeView(props: EmailComposeViewProps) {
label={ctxValue.subject() || previewName?.() || 'Draft email'}
iconType="email"
badges={[
- <SplitHeaderBadge text="draft" tooltip="This is a Draft Email" />,
+ <SplitHeaderBadge
+ text={statusLabel()}
+ tooltip={statusTooltip()}
+ />,
]}
/>
</SplitHeaderLeft>
@@ -138,12 +154,23 @@ export function EmailComposeView(props: EmailComposeViewProps) {
wrapper={(children) => (
// The same card as the chat composer and the thread's message
// cards, so a fresh draft reads as one of the app's composers.
- <ComposerSurface
- as="div"
- class="relative size-full min-h-0 overflow-clip touch:rounded-xl touch:border touch:border-edge-muted"
- >
- {children}
- </ComposerSurface>
+ <div class="flex size-full min-h-0 flex-col">
+ <ComposerSurface
+ as="div"
+ class="relative z-10 min-h-0 flex-1 overflow-clip touch:rounded-xl touch:border touch:border-edge-muted"
+ >
+ {children}
+ </ComposerSurface>
+ {/* Tucked under the card so its fill shows through the rounded
+ corners, like the agent composer's repository drawer. */}
+ <EmailScheduleBar
+ state={ctxValue.schedule.state()}
+ operation={ctxValue.schedule.operation()}
+ onSelectTime={ctxValue.schedule.onSelect}
+ onCancelSchedule={ctxValue.schedule.onCancel}
+ class="-mt-6 rounded-b-[20px] border border-t-0 border-edge-muted px-4 pt-8 pb-2"
+ />
+ </div>
)}
>
<ComposeLayout
diff --git a/apps/web/src/features/email-compose/views/reply-envelope.tsx b/apps/web/src/features/email-compose/views/reply-envelope.tsx
index af435b3cc4..bdc91638d3 100644
--- a/apps/web/src/features/email-compose/views/reply-envelope.tsx
+++ b/apps/web/src/features/email-compose/views/reply-envelope.tsx
@@ -27,6 +27,7 @@ type ReplyEnvelopeProps = {
mobile: Accessor<boolean>;
portalScope: Accessor<'local' | undefined>;
replyType: Accessor<ReplyType | undefined>;
+ disabled: Accessor<boolean>;
};
/** Sender, recipients and subject, sharing field behavior across both layouts. */
@@ -137,6 +138,7 @@ export function ReplyEnvelope(props: ReplyEnvelopeProps) {
activeInboxId={props.activeInboxId()}
onSelect={props.onSenderChange}
portalScope={props.portalScope()}
+ disabled={props.disabled()}
/>
</div>
<div class="flex items-center ml-auto shrink-0">
@@ -144,6 +146,7 @@ export function ReplyEnvelope(props: ReplyEnvelopeProps) {
<Button
size="sm"
class="rounded-lg"
+ disabled={props.disabled()}
onClick={() => {
setShowCc(true);
queueMicrotask(() => ccRef()?.focus());
@@ -156,6 +159,7 @@ export function ReplyEnvelope(props: ReplyEnvelopeProps) {
<Button
size="sm"
class="rounded-lg"
+ disabled={props.disabled()}
onClick={() => {
setShowBcc(true);
queueMicrotask(() => bccRef()?.focus());
@@ -229,6 +233,7 @@ export function ReplyEnvelope(props: ReplyEnvelopeProps) {
e.currentTarget.blur();
}}
placeholder="Subject"
+ disabled={props.disabled()}
/>
</div>
</>
@@ -305,6 +310,7 @@ export function ReplyEnvelope(props: ReplyEnvelopeProps) {
activeInboxId={props.activeInboxId()}
onSelect={props.onSenderChange}
portalScope={props.portalScope()}
+ disabled={props.disabled()}
/>
</div>
@@ -322,6 +328,7 @@ export function ReplyEnvelope(props: ReplyEnvelopeProps) {
e.currentTarget.blur();
}}
placeholder="Subject:"
+ disabled={props.disabled()}
/>
</div>
</div>
diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsx
index 833beed871..a1f2f169b4 100644
--- a/apps/web/src/features/email-compose/views/reply-input.tsx
+++ b/apps/web/src/features/email-compose/views/reply-input.tsx
@@ -19,6 +19,10 @@ import type { LexicalEditor } from 'lexical';
import { $getRoot } from 'lexical';
import { createSignal, For, onMount, Show } from 'solid-js';
import { EmailDateSelector } from '../components/email-date-selector';
+import {
+ EmailScheduleBar,
+ EmailScheduleSummary,
+} from '../components/email-schedule-summary';
import { MacroSignatureButton } from '../components/macro-signature-button';
import { MobileReplyToolbar } from '../components/mobile-reply-toolbar';
import { SignaturePreview } from '../components/signature-preview';
@@ -40,6 +44,7 @@ type ReplyInputViewProps = Omit<
| 'drafts'
| 'attachmentStorage'
| 'delivery'
+ | 'draftLifecycle'
| 'notices'
| 'accounts'
| 'connectivity'
@@ -65,6 +70,7 @@ export function ReplyInputView(props: ReplyInputViewProps) {
drafts: composeContext.drafts,
attachmentStorage: composeContext.attachmentStorage,
delivery: composeContext.delivery,
+ draftLifecycle: composeContext.draftLifecycle,
notices: composeContext.notices,
accounts: composeContext.accounts,
connectivity: composeContext.connectivity,
@@ -83,6 +89,7 @@ export function ReplyInputView(props: ReplyInputViewProps) {
sideEffectOnSend: props.sideEffectOnSend,
onMarkDone: props.onMarkDone,
setShowReply: props.setShowReply,
+ host: props.host,
},
editor,
{ container: () => composeContainerRef, footer: () => bottomBarRef },
@@ -110,8 +117,15 @@ export function ReplyInputView(props: ReplyInputViewProps) {
handleAddAttachments,
handleRemoveAttachment,
handleSendTimeChange,
+ scheduleState,
+ selectedSendTime,
+ scheduleActionLabel,
+ scheduleOperation,
+ cancelSchedule,
+ schedulePickerDisabled,
+ editingDisabled,
+ sendUnavailableReason,
sendActionDisabled,
- scheduleSendDisabled,
toggleQuotedText,
} = state;
const sendActionHidden = () =>
@@ -153,6 +167,7 @@ export function ReplyInputView(props: ReplyInputViewProps) {
.onChange(state.onContentChange)
.withFilePaste({
onPasteFilesAndDirs: (files, directories) => {
+ if (editingDisabled()) return;
composeContext.editorFiles.uploadEditorFiles({
editor: editor(),
sourceId: props.sourceEntityId,
@@ -186,7 +201,6 @@ export function ReplyInputView(props: ReplyInputViewProps) {
scopeId: composeHotkeyScope,
description: 'Send email',
keyDownHandler: () => {
- if (form.sendTime()) return false;
sendEmail();
return true;
},
@@ -200,7 +214,6 @@ export function ReplyInputView(props: ReplyInputViewProps) {
scopeId: composeHotkeyScope,
description: 'Send and mark done',
keyDownHandler: () => {
- if (form.sendTime()) return false;
sendEmail(true);
return true;
},
@@ -278,8 +291,10 @@ export function ReplyInputView(props: ReplyInputViewProps) {
? attachment.contentType
: attachment.mimeType,
}}
- removable
- onRemove={() => handleRemoveAttachment(attachment)}
+ removable={!editingDisabled()}
+ onRemove={() => {
+ if (!editingDisabled()) handleRemoveAttachment(attachment);
+ }}
/>
)}
</For>
@@ -297,273 +312,337 @@ export function ReplyInputView(props: ReplyInputViewProps) {
}
size="icon-composer"
tooltip="Attach"
+ disabled={editingDisabled()}
>
<Paperclip />
</Button>
);
return (
- <Surface
- class={cn(
- 'relative flex flex-col flex-1 max-w-full min-h-0',
- isMobileDrawer() && 'min-h-full overflow-y-scroll overscroll-y-none',
- props.unframed ? 'rounded-lg' : 'rounded-xl bg-menu-glass glass-input'
- )}
- style={props.unframed ? { 'background-color': 'transparent' } : undefined}
- hideBorder={props.unframed}
- ref={(el) => {
- composeContainerRef = el;
- }}
- depth={2}
- solid
- >
- <Show when={isMobileDrawer()}>
- <MobileReplyToolbar
- discardLabel={savedDraftId() ? 'Delete draft' : 'Discard draft'}
- onDiscard={deleteDraftAndReset}
- attachRef={(element) =>
- fileSelector(element, () => ({
- multiple: true,
- onSelect: handleAddAttachments,
- }))
- }
- sendDisabled={sendActionDisabled() || sendActionHidden()}
- sending={isSending()}
- onSend={() => sendEmail()}
- />
- </Show>
- <ReplyEnvelope
- fields={state.recipients}
- values={form.recipients}
- options={props.session.recipientOptions}
- inboxes={composeContext.accounts.inboxes}
- activeInboxId={activeInboxId}
- senderEmail={activeInboxEmail}
- onSenderChange={persistDraftOnSenderSwitch}
- subject={form.subject}
- onSubjectChange={(subject) => {
- form.setSubject(subject);
- scheduleDraftSave();
- }}
- showSubject={!!props.isEditingExisting}
- mobile={isMobileDrawer}
- portalScope={composePortalScope}
- replyType={state.replyType}
- />
- <div
+ <>
+ <Surface
class={cn(
- isMobileDrawer()
- ? 'relative flex-1 flex flex-col'
- : 'size-full flex flex-col min-h-0',
- state.recipients.showExpandedRecipients() && 'mt-4'
+ 'relative flex flex-col flex-1 max-w-full min-h-0',
+ isMobileDrawer() && 'min-h-full overflow-y-scroll overscroll-y-none',
+ props.unframed ? 'rounded-lg' : 'rounded-xl bg-menu-glass glass-input'
)}
+ style={
+ props.unframed ? { 'background-color': 'transparent' } : undefined
+ }
+ hideBorder={props.unframed}
+ ref={(el) => {
+ composeContainerRef = el;
+ }}
+ depth={2}
+ solid
>
+ <Show when={isMobileDrawer()}>
+ <MobileReplyToolbar
+ discardLabel={savedDraftId() ? 'Delete draft' : 'Discard draft'}
+ onDiscard={deleteDraftAndReset}
+ attachRef={(element) =>
+ fileSelector(element, () => ({
+ multiple: true,
+ onSelect: handleAddAttachments,
+ }))
+ }
+ sendDisabled={sendActionDisabled() || sendActionHidden()}
+ sendLabel={scheduleActionLabel()}
+ sending={isSending()}
+ editingDisabled={editingDisabled()}
+ onSend={() => sendEmail()}
+ scheduleSummary={
+ <EmailScheduleSummary
+ state={scheduleState()}
+ operation={scheduleOperation()}
+ onSelectTime={handleSendTimeChange}
+ onCancelSchedule={cancelSchedule}
+ />
+ }
+ scheduleControl={
+ <Show when={composeContext.presentation.scheduleEnabled}>
+ <EmailDateSelector
+ mobile
+ compact
+ state={scheduleState()}
+ selectedTime={selectedSendTime()}
+ onSelectTime={handleSendTimeChange}
+ onCancelSchedule={cancelSchedule}
+ operation={scheduleOperation()}
+ disabled={schedulePickerDisabled()}
+ />
+ </Show>
+ }
+ />
+ </Show>
+ <ReplyEnvelope
+ fields={state.recipients}
+ values={form.recipients}
+ options={props.session.recipientOptions}
+ inboxes={composeContext.accounts.inboxes}
+ activeInboxId={activeInboxId}
+ senderEmail={activeInboxEmail}
+ onSenderChange={persistDraftOnSenderSwitch}
+ subject={form.subject}
+ onSubjectChange={(subject) => {
+ form.setSubject(subject);
+ scheduleDraftSave();
+ }}
+ showSubject={!!props.isEditingExisting}
+ mobile={isMobileDrawer}
+ portalScope={composePortalScope}
+ replyType={state.replyType}
+ disabled={editingDisabled}
+ />
<div
- ref={setScrollContainer}
class={cn(
- 'relative min-h-8 w-full flex flex-col placeholder:text-ink-placeholder placeholder:opacity-50 px-0 py-1',
isMobileDrawer()
- ? 'max-h-none flex-1 overflow-visible px-5 pt-6 pb-4'
- : cn(
- 'overflow-y-auto mobile:max-h-[calc(32*var(--dvh,1dvh))]',
- composerExpanded()
- ? // Cap to the thread viewport (minus composer chrome) so the
- // recipients row and send bar stay on screen together
- 'max-h-[min(calc(60*var(--dvh,1dvh)),calc(var(--thread-height,9999px)-14rem))]'
- : 'max-h-56'
- )
+ ? 'relative flex-1 flex flex-col'
+ : 'size-full flex flex-col min-h-0',
+ state.recipients.showExpandedRecipients() && 'mt-4'
)}
- onScroll={(e) => {
- if (composerExpanded() || e.currentTarget.scrollTop <= 0) return;
- setComposerExpanded(true);
- // Keep the send bar pinned while the box grows
- requestAnimationFrame(() => {
- bottomBarRef?.scrollIntoView({ block: 'nearest' });
- });
- }}
- onclick={() => {
- editor()?.focus();
- }}
- use:fileFolderDrop={{
- onDragStart: (valid) => setIsDragging(valid),
- onDragEnd: () => setIsDragging(false),
- onDrop: (files, directories, event) => {
- const currentEditor = editor();
- if (!currentEditor || !event) return;
- composeContext.editorFiles.uploadEditorFiles({
- editor: currentEditor,
- sourceId: props.sourceEntityId,
- files,
- directories,
- dropEvent: event,
- onUploaded: (ids) => {
- setIsDragging(false);
- ids.forEach(composeContext.editorFiles.makePublic);
- scheduleDraftSave();
- },
- });
- },
- }}
>
<div
- class={cn('absolute size-full inset-0', !isDragging() && 'hidden')}
- >
- <FileDropOverlay>Drop file(s) to attach</FileDropOverlay>
- </div>
- <MarkdownShell
- config={editorConfig}
+ ref={setScrollContainer}
class={cn(
- 'ph-no-capture cursor-text wrap-break-word text-base text-ink h-auto overflow-visible',
- // Quoted thread collapses behind the "⋯" pill below
- // (rule lives in LexicalMarkdown/styles.css — Tailwind arbitrary
- // variants turn the underscore in .macro_quote into a space)
- quoteCollapsed() && 'quote-collapsed',
- isDragging() && 'blur'
- )}
- disabled={isSending()}
- placeholder={
+ 'relative min-h-8 w-full flex flex-col placeholder:text-ink-placeholder placeholder:opacity-50 px-0 py-1',
isMobileDrawer()
- ? 'Use `@` to reference files'
- : 'Reply — @mention to share or cc people'
- }
- portalScope={isMobileDrawer() ? 'local' : 'split'}
- refFn={(el) => props.markdownDomRef?.(el)}
- onConnect={handleEditorConnect}
- />
- <Show when={!hasPaidAccess()}>
- <div class="text-ink/50 mt-[1lh]" data-watermark>
- <MacroSignatureButton
- visible={
- !composeContext.presentation.viewerLoading() &&
- !composeContext.hasPaidAccess()
- }
- onUpgrade={composeContext.presentation.onUpgrade}
- />
- </div>
- </Show>
- <Show when={isMobileDrawer()}>
- <AttachmentsRow />
- </Show>
- <Show when={scrollAreaSignatureHtml()}>
- {(html) => (
- <SignaturePreview
- mobile={composeContext.presentation.isMobile()}
- prepareLinks={composeContext.presentation.prepareSignatureLinks}
- html={html()}
- onDismiss={() => {
- // Dismissal is composer-local state worth keeping — latch
- // the seed so a draft upgrade can't remount it away.
- props.onEngaged?.();
- setIncludeSignature(false);
- }}
- />
+ ? 'max-h-none flex-1 overflow-visible px-5 pt-6 pb-4'
+ : cn(
+ 'overflow-y-auto mobile:max-h-[calc(32*var(--dvh,1dvh))]',
+ composerExpanded()
+ ? // Cap to the thread viewport (minus composer chrome) so the
+ // recipients row and send bar stay on screen together
+ 'max-h-[min(calc(60*var(--dvh,1dvh)),calc(var(--thread-height,9999px)-14rem))]'
+ : 'max-h-56'
+ )
)}
- </Show>
- </div>
- {/* Quoted-text controls live below the scroll area so they stay
- anchored to the composer bottom instead of scrolling with (and
- floating over) tall content. */}
- <Show when={form.replyAppended() && quoteCollapsed()}>
- <div class="shrink-0 flex items-center pt-1" data-corvu-no-drag="">
- <Button
- variant="ghost"
- size="icon-sm"
- class="rounded-md text-ink-extra-muted hover:text-ink-muted hover:bg-active"
- tooltip="Show quoted text"
- onclick={(e: MouseEvent) => {
- e.stopPropagation();
- setQuoteCollapsed(false);
- setComposerExpanded(true);
- }}
- >
- <DotsThree />
- </Button>
- </div>
- </Show>
- <Show
- when={
- props.replyingTo() &&
- // The collapse pill above already covers this state
- !(form.replyAppended() && quoteCollapsed())
- }
- >
- <div
- class="shrink-0 pt-1"
- data-corvu-no-drag=""
- onClick={(e) => e.stopPropagation()}
+ onScroll={(e) => {
+ if (composerExpanded() || e.currentTarget.scrollTop <= 0) return;
+ setComposerExpanded(true);
+ // Keep the send bar pinned while the box grows
+ requestAnimationFrame(() => {
+ bottomBarRef?.scrollIntoView({ block: 'nearest' });
+ });
+ }}
+ onclick={() => {
+ editor()?.focus();
+ }}
+ use:fileFolderDrop={{
+ onDragStart: (valid) => setIsDragging(valid),
+ onDragEnd: () => setIsDragging(false),
+ onDrop: (files, directories, event) => {
+ if (editingDisabled()) return;
+ const currentEditor = editor();
+ if (!currentEditor || !event) return;
+ composeContext.editorFiles.uploadEditorFiles({
+ editor: currentEditor,
+ sourceId: props.sourceEntityId,
+ files,
+ directories,
+ dropEvent: event,
+ onUploaded: (ids) => {
+ setIsDragging(false);
+ ids.forEach(composeContext.editorFiles.makePublic);
+ scheduleDraftSave();
+ },
+ });
+ },
+ }}
>
- <Tooltip
- label={
- form.replyAppended() ? 'Hide quoted text' : 'Show quoted text'
- }
+ <div
+ class={cn(
+ 'absolute size-full inset-0',
+ !isDragging() && 'hidden'
+ )}
>
- <KToggleButton
- as={Button}
+ <FileDropOverlay>Drop file(s) to attach</FileDropOverlay>
+ </div>
+ <MarkdownShell
+ config={editorConfig}
+ class={cn(
+ 'ph-no-capture cursor-text wrap-break-word text-base text-ink h-auto overflow-visible',
+ // Quoted thread collapses behind the "⋯" pill below
+ // (rule lives in LexicalMarkdown/styles.css — Tailwind arbitrary
+ // variants turn the underscore in .macro_quote into a space)
+ quoteCollapsed() && 'quote-collapsed',
+ isDragging() && 'blur'
+ )}
+ disabled={editingDisabled()}
+ placeholder={
+ isMobileDrawer()
+ ? 'Use `@` to reference files'
+ : 'Reply — @mention to share or cc people'
+ }
+ portalScope={isMobileDrawer() ? 'local' : 'split'}
+ refFn={(el) => props.markdownDomRef?.(el)}
+ onConnect={handleEditorConnect}
+ />
+ <Show when={!hasPaidAccess()}>
+ <div class="text-ink/50 mt-[1lh]" data-watermark>
+ <MacroSignatureButton
+ visible={
+ !composeContext.presentation.viewerLoading() &&
+ !composeContext.hasPaidAccess()
+ }
+ onUpgrade={composeContext.presentation.onUpgrade}
+ />
+ </div>
+ </Show>
+ <Show when={isMobileDrawer()}>
+ <AttachmentsRow />
+ </Show>
+ <Show when={scrollAreaSignatureHtml()}>
+ {(html) => (
+ <SignaturePreview
+ mobile={composeContext.presentation.isMobile()}
+ prepareLinks={
+ composeContext.presentation.prepareSignatureLinks
+ }
+ html={html()}
+ dismissable={!editingDisabled()}
+ onDismiss={() => {
+ // Dismissal is composer-local state worth keeping — latch
+ // the seed so a draft upgrade can't remount it away.
+ props.onEngaged?.();
+ setIncludeSignature(false);
+ }}
+ />
+ )}
+ </Show>
+ </div>
+ {/* Quoted-text controls live below the scroll area so they stay
+ anchored to the composer bottom instead of scrolling with (and
+ floating over) tall content. */}
+ <Show when={form.replyAppended() && quoteCollapsed()}>
+ <div class="shrink-0 flex items-center pt-1" data-corvu-no-drag="">
+ <Button
variant="ghost"
size="icon-sm"
- class="size-5 rounded bg-transparent p-0 text-ink-extra-muted hover:text-ink-muted [&_:where(svg)]:size-5"
- pressed={form.replyAppended()}
- onChange={toggleQuotedText}
+ class="rounded-md text-ink-extra-muted hover:text-ink-muted hover:bg-active"
+ tooltip="Show quoted text"
+ onclick={(e: MouseEvent) => {
+ e.stopPropagation();
+ setQuoteCollapsed(false);
+ setComposerExpanded(true);
+ }}
>
<DotsThree />
- </KToggleButton>
- </Tooltip>
- </div>
- </Show>
- <Show when={!isMobileDrawer()}>
- {/* Below the scroll area so quoted email content can never overlap it */}
- <AttachmentsRow class="px-4" />
- <Show when={footerSignatureHtml()}>
- {(html) => (
- <SignaturePreview
- mobile={composeContext.presentation.isMobile()}
- prepareLinks={composeContext.presentation.prepareSignatureLinks}
- html={html()}
- onDismiss={() => {
- // Dismissal is composer-local state worth keeping — latch
- // the seed so a draft upgrade can't remount it away.
- props.onEngaged?.();
- setIncludeSignature(false);
- }}
- />
- )}
+ </Button>
+ </div>
</Show>
- {/* Keep the footer intrinsic-height so it cannot overlap the signature. */}
- <div
- ref={bottomBarRef}
- class="shrink-0 flex items-center justify-end gap-1 pt-1.5"
+ <Show
+ when={
+ props.replyingTo() &&
+ // The collapse pill above already covers this state
+ !(form.replyAppended() && quoteCollapsed())
+ }
>
- <Button
- onClick={deleteDraftAndReset}
- tooltip={savedDraftId() ? 'Delete draft' : 'Discard'}
- size="icon-composer"
- >
- <Trash />
- </Button>
- <AttachButton />
- <Show
- when={
- composeContext.presentation.scheduleEnabled &&
- !sendActionHidden()
- }
+ <div
+ class="shrink-0 pt-1"
+ data-corvu-no-drag=""
+ onClick={(e) => e.stopPropagation()}
>
- <EmailDateSelector
- mobile={false}
- sendTime={form.sendTime() ?? null}
- onSendTimeChange={handleSendTimeChange}
- disabled={scheduleSendDisabled()}
- />
+ <Tooltip
+ label={
+ form.replyAppended() ? 'Hide quoted text' : 'Show quoted text'
+ }
+ >
+ <KToggleButton
+ as={Button}
+ variant="ghost"
+ size="icon-sm"
+ class="size-5 rounded bg-transparent p-0 text-ink-extra-muted hover:text-ink-muted [&_:where(svg)]:size-5"
+ pressed={form.replyAppended()}
+ disabled={editingDisabled()}
+ onChange={toggleQuotedText}
+ >
+ <DotsThree />
+ </KToggleButton>
+ </Tooltip>
+ </div>
+ </Show>
+ <Show when={!isMobileDrawer()}>
+ {/* Below the scroll area so quoted email content can never overlap it */}
+ <AttachmentsRow class="px-4" />
+ <Show when={footerSignatureHtml()}>
+ {(html) => (
+ <SignaturePreview
+ mobile={composeContext.presentation.isMobile()}
+ prepareLinks={
+ composeContext.presentation.prepareSignatureLinks
+ }
+ html={html()}
+ dismissable={!editingDisabled()}
+ onDismiss={() => {
+ // Dismissal is composer-local state worth keeping — latch
+ // the seed so a draft upgrade can't remount it away.
+ props.onEngaged?.();
+ setIncludeSignature(false);
+ }}
+ />
+ )}
</Show>
- <SendButton
- appearance="composer"
- disabled={sendActionDisabled()}
- pending={isSending()}
- hidden={sendActionHidden()}
- onClick={() => sendEmail()}
- />
- </div>
- </Show>
- </div>
- </Surface>
+ {/* Keep the footer intrinsic-height so it cannot overlap the signature. */}
+ <div
+ ref={bottomBarRef}
+ class="shrink-0 flex min-w-0 justify-end pt-1.5"
+ >
+ <div class="flex shrink-0 items-center gap-1">
+ <Button
+ onClick={deleteDraftAndReset}
+ tooltip={savedDraftId() ? 'Delete draft' : 'Discard'}
+ size="icon-composer"
+ disabled={editingDisabled()}
+ >
+ <Trash />
+ </Button>
+ <AttachButton />
+ <Show
+ when={
+ composeContext.presentation.scheduleEnabled &&
+ !sendActionHidden()
+ }
+ >
+ <div class="shrink-0">
+ <EmailDateSelector
+ mobile={false}
+ compact
+ state={scheduleState()}
+ selectedTime={selectedSendTime()}
+ onSelectTime={handleSendTimeChange}
+ onCancelSchedule={cancelSchedule}
+ operation={scheduleOperation()}
+ disabled={schedulePickerDisabled()}
+ />
+ </div>
+ </Show>
+ <SendButton
+ appearance="composer"
+ disabled={sendActionDisabled()}
+ pending={isSending()}
+ hidden={sendActionHidden()}
+ onClick={() => sendEmail()}
+ tooltip={sendUnavailableReason() ?? scheduleActionLabel()}
+ aria-label={scheduleActionLabel()}
+ />
+ </div>
+ </div>
+ </Show>
+ </div>
+ </Surface>
+ <Show when={!isMobileDrawer()}>
+ {/* The desktop reply sits in its message card; the bar spans the card's
+ padding so it reads as the card's footer, like the standalone
+ composer's drawer. */}
+ <EmailScheduleBar
+ state={scheduleState()}
+ operation={scheduleOperation()}
+ onSelectTime={handleSendTimeChange}
+ onCancelSchedule={cancelSchedule}
+ class="-mx-4 -mb-4 mt-3 rounded-b-[26.25px] border-t border-edge-muted px-4 py-2 touch:rounded-b-lg mobile:rounded-none"
+ />
+ </Show>
+ </>
);
}
diff --git a/apps/web/src/features/email-thread/views/thread-reply-input.tsx b/apps/web/src/features/email-thread/views/thread-reply-input.tsx
index ec0642dcb6..831581a17b 100644
--- a/apps/web/src/features/email-thread/views/thread-reply-input.tsx
+++ b/apps/web/src/features/email-thread/views/thread-reply-input.tsx
@@ -89,6 +89,7 @@ function ThreadReplyInputSession(props: ThreadReplyInputProps) {
<Layer depth={props.mobileDrawer ? 0 : 2}>
<ReplyInputView
context={viewContext.compose}
+ host={viewContext.composeHost}
session={{
thread: ctx.thread,
recipientOptions: ctx.recipientOptions,
diff --git a/apps/web/src/features/email-view/components/EmailEmptyState.tsx b/apps/web/src/features/email-view/components/EmailEmptyState.tsx
index 38cee55a1a..4429150973 100644
--- a/apps/web/src/features/email-view/components/EmailEmptyState.tsx
+++ b/apps/web/src/features/email-view/components/EmailEmptyState.tsx
@@ -28,6 +28,10 @@ function tabCopy(tab: EmailTab): { title: string; description: string } {
title: 'No sent email',
description: 'Email you send will appear here.',
}))
+ .with('scheduled', () => ({
+ title: 'No scheduled email',
+ description: 'Email you schedule to send later will appear here.',
+ }))
.with('calendar', () => ({
title: 'No calendar email',
description: 'Invitations and event updates will appear here.',
@@ -51,7 +55,9 @@ export function EmailEmptyState() {
const { state, setFacets, setInboxIds } = useEmailView();
const emailActive = useEmailLinksStatus();
const startAddInbox = useAddInboxFlow();
- const searchText = () => state.search.trim();
+ // Scheduled has no search or filters; text typed on another tab stays behind.
+ const searchText = () =>
+ state.tab === 'scheduled' ? '' : state.search.trim();
const noInboxesSelected = () => state.inboxIds?.length === 0;
const hasActiveFilters = () =>
Object.values(state.facets).some((optionIds) => optionIds.length > 0);
diff --git a/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx b/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx
index 684cd62b30..e6a13e54f7 100644
--- a/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx
+++ b/apps/web/src/features/email-view/components/EmailFilterDrawer.tsx
@@ -1,7 +1,7 @@
import { MobileFilterDrawer } from '@app/components/view-shell/MobileFilterDrawer';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import { Accordion } from '@kobalte/core/accordion';
-import { batch, For } from 'solid-js';
+import { batch, For, Show } from 'solid-js';
import { useEmailView } from '../email-view-context';
import { useEmailFilters } from '../filters/use-email-filters';
import { EmailInboxDrawerSection } from './EmailInboxSelector';
@@ -11,13 +11,15 @@ const INBOX_SECTION_ID = 'inbox';
export function EmailFilterDrawer() {
const { state, setInboxIds } = useEmailView();
const filters = useEmailFilters();
+ const showFacetFilters = () => state.tab !== 'scheduled';
return (
<MobileFilterDrawer
triggerLabel="Open email filters"
label="Email filters"
activeCount={
- filters.activeCount() + (state.inboxIds === undefined ? 0 : 1)
+ (showFacetFilters() ? filters.activeCount() : 0) +
+ (state.inboxIds === undefined ? 0 : 1)
}
onClear={() =>
batch(() => {
@@ -26,7 +28,9 @@ export function EmailFilterDrawer() {
})
}
>
- <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>
+ <MobileDrawer.Label class="pt-4">
+ {showFacetFilters() ? 'Filters' : 'Inboxes'}
+ </MobileDrawer.Label>
<Accordion
multiple
collapsible
@@ -34,37 +38,39 @@ export function EmailFilterDrawer() {
>
<div class="flex flex-col gap-3">
<EmailInboxDrawerSection value={INBOX_SECTION_ID} />
- <For each={filters.groups()}>
- {(group) => (
- <MobileFilterDrawer.Section
- value={group.id}
- label={group.label}
- activeCount={state.facets[group.id]?.length ?? 0}
- >
- <div
- role={
- group.selectionMode === 'single' ? 'radiogroup' : 'group'
- }
- aria-label={group.label}
+ <Show when={showFacetFilters()}>
+ <For each={filters.groups()}>
+ {(group) => (
+ <MobileFilterDrawer.Section
+ value={group.id}
+ label={group.label}
+ activeCount={state.facets[group.id]?.length ?? 0}
>
- <For each={group.options}>
- {(option) => (
- <MobileFilterDrawer.Option
- selectionMode={group.selectionMode}
- checked={filters.isSelected(group.id, option.id)}
- onChange={(checked) =>
- filters.setSelected(group.id, option.id, checked)
- }
- icon={option.icon?.()}
- >
- {option.label}
- </MobileFilterDrawer.Option>
- )}
- </For>
- </div>
- </MobileFilterDrawer.Section>
- )}
- </For>
+ <div
+ role={
+ group.selectionMode === 'single' ? 'radiogroup' : 'group'
+ }
+ aria-label={group.label}
+ >
+ <For each={group.options}>
+ {(option) => (
+ <MobileFilterDrawer.Option
+ selectionMode={group.selectionMode}
+ checked={filters.isSelected(group.id, option.id)}
+ onChange={(checked) =>
+ filters.setSelected(group.id, option.id, checked)
+ }
+ icon={option.icon?.()}
+ >
+ {option.label}
+ </MobileFilterDrawer.Option>
+ )}
+ </For>
+ </div>
+ </MobileFilterDrawer.Section>
+ )}
+ </For>
+ </Show>
</div>
</Accordion>
</MobileFilterDrawer>
diff --git a/apps/web/src/features/email-view/components/EmailHeader.tsx b/apps/web/src/features/email-view/components/EmailHeader.tsx
index 6990852f51..5980c5c2f6 100644
--- a/apps/web/src/features/email-view/components/EmailHeader.tsx
+++ b/apps/web/src/features/email-view/components/EmailHeader.tsx
@@ -6,7 +6,7 @@ import {
} from '@app/components/view-shell';
import { SidebarCreateButton } from '@app/components/view-shell/SidebarCreateButton';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
-import { createSignal } from 'solid-js';
+import { createSignal, Show } from 'solid-js';
import { composeEmail } from '../compose-email';
import { EMAIL_TABS } from '../constants';
import { useEmailView } from '../email-view-context';
@@ -66,6 +66,7 @@ export function EmailHeader(props: EmailHeaderProps) {
enabled: panel.isPanelActive,
search: {
description: 'Search email',
+ condition: () => state.tab !== 'scheduled',
run: () => {
searchInput?.focus();
searchInput?.select();
@@ -74,6 +75,7 @@ export function EmailHeader(props: EmailHeaderProps) {
},
filter: {
description: 'Filter email',
+ condition: () => state.tab !== 'scheduled',
run: () => {
setFilterOpen(true);
return true;
@@ -95,22 +97,24 @@ export function EmailHeader(props: EmailHeaderProps) {
</div>
</div>
- <div class="flex min-w-0 items-center justify-between gap-3">
- <SearchBar
- ref={(element) => (searchInput = element)}
- label="Search email"
- value={state.search}
- hotkey="cmd+f"
- onValueChange={(search) => setState('search', search)}
- onEscape={props.onSearchEscape}
- placeholder="Search email"
- class="max-w-md flex-1"
- />
- <EmailControls
- filterOpen={filterOpen()}
- onFilterOpenChange={setFilterOpen}
- />
- </div>
+ <Show when={state.tab !== 'scheduled'}>
+ <div class="flex min-w-0 items-center justify-between gap-3">
+ <SearchBar
+ ref={(element) => (searchInput = element)}
+ label="Search email"
+ value={state.search}
+ hotkey="cmd+f"
+ onValueChange={(search) => setState('search', search)}
+ onEscape={props.onSearchEscape}
+ placeholder="Search email"
+ class="max-w-md flex-1"
+ />
+ <EmailControls
+ filterOpen={filterOpen()}
+ onFilterOpenChange={setFilterOpen}
+ />
+ </div>
+ </Show>
</div>
);
}
diff --git a/apps/web/src/features/email-view/components/EmailSidebar.tsx b/apps/web/src/features/email-view/components/EmailSidebar.tsx
index 8b2dbdf078..c20385da7b 100644
--- a/apps/web/src/features/email-view/components/EmailSidebar.tsx
+++ b/apps/web/src/features/email-view/components/EmailSidebar.tsx
@@ -2,6 +2,7 @@ import { useViewTabHotkeys, ViewSidebar } from '@app/components/view-shell';
import { SidebarCreateHeader } from '@app/components/view-shell/SidebarCreateButton';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import CalendarBlankIcon from '@phosphor/calendar-blank.svg';
+import ClockIcon from '@phosphor/clock.svg';
import EnvelopeIcon from '@phosphor/envelope.svg';
import FileIcon from '@phosphor/file.svg';
import PaperPlaneTiltIcon from '@phosphor/paper-plane-tilt.svg';
@@ -22,6 +23,7 @@ const TAB_ICONS: Record<EmailTab, Component<{ class?: string }>> = {
important: SignalIcon,
noise: NoiseIcon,
sent: PaperPlaneTiltIcon,
+ scheduled: ClockIcon,
calendar: CalendarBlankIcon,
drafts: FileIcon,
shared: UsersThreeIcon,
diff --git a/apps/web/src/features/email-view/constants.ts b/apps/web/src/features/email-view/constants.ts
index ceafb351a1..2a7f4e598e 100644
--- a/apps/web/src/features/email-view/constants.ts
+++ b/apps/web/src/features/email-view/constants.ts
@@ -9,6 +9,7 @@ export const EMAIL_TABS: EmailTabItem[] = [
{ id: 'important', label: 'Signal' },
{ id: 'noise', label: 'Noise' },
{ id: 'sent', label: 'Sent' },
+ { id: 'scheduled', label: 'Scheduled' },
{ id: 'calendar', label: 'Calendar' },
{ id: 'drafts', label: 'Drafts' },
{ id: 'shared', label: 'Shared' },
diff --git a/apps/web/src/features/email-view/email-route.test.ts b/apps/web/src/features/email-view/email-route.test.ts
new file mode 100644
index 0000000000..cb4898b736
--- /dev/null
+++ b/apps/web/src/features/email-view/email-route.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+import { EMAIL_TAB_IDS } from './constants';
+import { emailTabSearchCodec } from './email-route';
+
+describe('email tab search params', () => {
+ it.each(EMAIL_TAB_IDS)('keeps the %s tab through the URL', (tab) => {
+ const params = emailTabSearchCodec.serialize({ tab });
+ expect(emailTabSearchCodec.parse(params)).toEqual({
+ value: { tab },
+ valid: true,
+ });
+ });
+});
diff --git a/apps/web/src/features/email-view/email-route.ts b/apps/web/src/features/email-view/email-route.ts
index 66013fcfac..f9289f328f 100644
--- a/apps/web/src/features/email-view/email-route.ts
+++ b/apps/web/src/features/email-view/email-route.ts
@@ -9,6 +9,7 @@ export const emailTabSearch = {
'important',
'noise',
'sent',
+ 'scheduled',
'calendar',
'drafts',
'shared',
diff --git a/apps/web/src/features/email-view/persistence.ts b/apps/web/src/features/email-view/persistence.ts
index ff027c4261..be1dc11872 100644
--- a/apps/web/src/features/email-view/persistence.ts
+++ b/apps/web/src/features/email-view/persistence.ts
@@ -21,7 +21,16 @@ const emailLocalStateStorage = createUserScopedStorage(
);
const emailTabSchema = z
- .enum(['important', 'noise', 'sent', 'calendar', 'drafts', 'shared', 'all'])
+ .enum([
+ 'important',
+ 'noise',
+ 'sent',
+ 'scheduled',
+ 'calendar',
+ 'drafts',
+ 'shared',
+ 'all',
+ ])
.catch('important');
const emailFacetsSchema = z.record(z.string(), z.array(z.string()));
diff --git a/apps/web/src/features/email-view/queries/email-query.test.ts b/apps/web/src/features/email-view/queries/email-query.test.ts
index 1efe78111b..88dbf70599 100644
--- a/apps/web/src/features/email-view/queries/email-query.test.ts
+++ b/apps/web/src/features/email-view/queries/email-query.test.ts
@@ -33,6 +33,7 @@ const TABS: EmailTab[] = [
'important',
'noise',
'sent',
+ 'scheduled',
'calendar',
'drafts',
'shared',
@@ -93,6 +94,7 @@ describe('buildEmailQuery', () => {
['important', 'inbox'],
['noise', 'inbox'],
['sent', 'sent'],
+ ['scheduled', 'drafts'],
['calendar', 'all'],
['drafts', 'drafts'],
['shared', 'all'],
diff --git a/apps/web/src/features/email-view/queries/email-query.ts b/apps/web/src/features/email-view/queries/email-query.ts
index 87ef0613cc..85049ab2ea 100644
--- a/apps/web/src/features/email-view/queries/email-query.ts
+++ b/apps/web/src/features/email-view/queries/email-query.ts
@@ -29,6 +29,9 @@ export const emailViewForTab = (tab: EmailTab): string =>
match(tab)
.with('important', 'noise', () => 'inbox')
.with('drafts', () => 'drafts')
+ // Scheduled has a dedicated REST-backed message list. Keep the dormant
+ // Soup source on drafts so its query shape remains valid while disabled.
+ .with('scheduled', () => 'drafts')
.with('sent', () => 'sent')
.with('calendar', 'shared', 'all', () => 'all')
.exhaustive();
@@ -72,7 +75,7 @@ function tabClause(tab: EmailTab): TargetExpr {
.with('shared', () => clause.eq('emailShared', 'only'))
// Sent and Drafts are scoped entirely by `emailView`; the server's sent
// view already covers every linked inbox, so no sender filter is needed.
- .with('drafts', 'sent', 'all', anyThread)
+ .with('drafts', 'scheduled', 'sent', 'all', anyThread)
.exhaustive()
);
}
diff --git a/apps/web/src/features/email-view/queries/email-search.ts b/apps/web/src/features/email-view/queries/email-search.ts
index 3b2c7a3ff0..82d048c217 100644
--- a/apps/web/src/features/email-view/queries/email-search.ts
+++ b/apps/web/src/features/email-view/queries/email-search.ts
@@ -37,7 +37,7 @@ function tabFilters(tab: EmailTab): EmailFilters {
shared: 'exclude' as const,
}))
.with('shared', () => ({ shared: 'only' as const }))
- .with('drafts', 'sent', 'all', () => ({}))
+ .with('drafts', 'scheduled', 'sent', 'all', () => ({}))
.exhaustive();
}
diff --git a/apps/web/src/features/email-view/queries/use-email-query.test.ts b/apps/web/src/features/email-view/queries/use-email-query.test.ts
index d885e4d87c..3b0292be1c 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.test.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.test.ts
@@ -9,9 +9,16 @@ import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { EmailTab, EmailViewState } from '../types';
import { buildEmailQuery } from './email-query';
-import { type EmailDataSource, useEmailDataSource } from './use-email-query';
+import {
+ type EmailDataSource,
+ type EmailDataSourceItem,
+ useEmailDataSource,
+} from './use-email-query';
const searchQueryMock = vi.hoisted(() => vi.fn());
+const scheduledRows = vi.hoisted(() => ({
+ current: [] as EmailDataSourceItem[],
+}));
vi.mock('@app/features/soup', async () => ({
...(await import('@app/features/soup/filters')),
@@ -27,6 +34,18 @@ vi.mock('@components/app/GlobalAppState', () => ({
}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'alice' }));
vi.mock('@queries/soup/items', () => ({ useSoupAstItemsQuery: vi.fn() }));
+vi.mock('./use-scheduled-email-source', () => ({
+ useScheduledEmailSource: () => ({
+ items: () => scheduledRows.current,
+ isLoading: () => false,
+ isFetching: () => false,
+ error: () => undefined,
+ hasMore: () => false,
+ isLoadingMore: () => false,
+ loadMore: async () => {},
+ refresh: async () => {},
+ }),
+}));
vi.mock('@service-storage/websocket', () => ({
storageWS: { reconnectIfDisconnected: vi.fn() },
createWebSocketJob: vi.fn(),
@@ -199,9 +218,35 @@ function mount(search = '') {
}
describe('Email list query transitions', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ scheduledRows.current = [];
+ });
afterEach(() => dispose?.());
+ it('lists the scheduled source on the Scheduled tab instead of soup rows', () => {
+ scheduledRows.current = [
+ {
+ kind: 'entity',
+ id: 'scheduled-row',
+ entity: {
+ ...email('scheduled'),
+ isDraft: true,
+ scheduledSendTime: '2026-09-27T12:00:00Z',
+ },
+ } as EmailDataSourceItem,
+ ];
+ const { source, setState } = mount();
+ expect(ids(source)).toEqual(['noise']);
+
+ setState('tab', 'scheduled');
+ expect(ids(source)).toEqual(['scheduled']);
+ expect(source.hasMore()).toBe(false);
+
+ setState('tab', 'noise');
+ expect(ids(source)).toEqual(['noise']);
+ });
+
it('does not show Noise rows under other tabs while their cache reads are pending', () => {
const { source, setState, setEntities, setLoading } = mount();
expect(ids(source)).toEqual(['noise']);
diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.ts
index d5d13551fd..888a12812c 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.ts
@@ -31,6 +31,7 @@ import { buildEmailQuery, type EmailQueryContext } from './email-query';
import { groupEmailEntitiesByDate } from './email-results';
import { buildEmailSearchRequest } from './email-search';
import { emailAdmissionBatches, mergeEmailAdmission } from './read-admission';
+import { useScheduledEmailSource } from './use-scheduled-email-source';
export type EmailDataSourceItem = SoupRow<WithNotification<EntityData>>;
@@ -63,7 +64,15 @@ function emailMatchesTab(
return match(tab)
.with('drafts', () => entity.isDraft)
.with('shared', () => userId !== undefined && entity.ownerId !== userId)
- .with('important', 'noise', 'sent', 'calendar', 'all', () => true)
+ .with(
+ 'important',
+ 'noise',
+ 'sent',
+ 'scheduled',
+ 'calendar',
+ 'all',
+ () => true
+ )
.exhaustive();
}
@@ -83,6 +92,8 @@ export function useEmailDataSource(
): EmailDataSource {
const notificationSource = useGlobalNotificationSource();
const userId = useUserId();
+ const scheduled = useScheduledEmailSource(state);
+ const showsScheduled = () => state.tab === 'scheduled';
const facetContext = createMemo(
(): EmailFacetContext => createTagFacetContext(options.tagSets())
@@ -103,8 +114,9 @@ export function useEmailDataSource(
// A restored tag selection waits for the tag sets rather than listing the
// whole mailbox and then narrowing.
const facetsReady = () => tagFacetReady(state.facets, options.tagSetsReady());
+ const sourceEnabled = () => facetsReady() && state.tab !== 'scheduled';
const query = useSoupAstItemsQuery(queryArgs, () => ({
- enabled: facetsReady(),
+ enabled: sourceEnabled(),
}));
const isListPending = () =>
!facetsReady() || query.isLoading || query.isPlaceholderData;
@@ -127,7 +139,7 @@ export function useEmailDataSource(
text: () => state.search,
// Held back with the list query so a tag selection is not stripped from
// the request before the sets that resolve it have loaded.
- enabled: facetsReady,
+ enabled: sourceEnabled,
disableLocalSearch: () => true,
buildRequest: (request) => buildEmailSearchRequest(queryContext(), request),
});
@@ -333,21 +345,27 @@ export function useEmailDataSource(
};
return {
- items,
- isLoading,
+ items: () => (showsScheduled() ? scheduled.items() : items()),
+ isLoading: () => (showsScheduled() ? scheduled.isLoading() : isLoading()),
isFetching: () => {
+ if (showsScheduled()) return scheduled.isFetching();
if (search.isSettling()) return true;
return usesServiceSearch() ? search.isFetching() : query.isFetching;
},
- error: () =>
- (usesServiceSearch() ? search.error() : query.error) ??
- retainedQueries()
- .map((lookup) => lookup.error())
- .find((error) => error instanceof Error) ??
- undefined,
- hasMore,
- isLoadingMore,
+ error: () => {
+ if (showsScheduled()) return scheduled.error();
+ return (
+ (usesServiceSearch() ? search.error() : query.error) ??
+ retainedQueries()
+ .map((lookup) => lookup.error())
+ .find((error) => error instanceof Error) ??
+ undefined
+ );
+ },
+ hasMore: () => !showsScheduled() && hasMore(),
+ isLoadingMore: () => !showsScheduled() && isLoadingMore(),
loadMore: async () => {
+ if (showsScheduled()) return;
if (usesServiceSearch()) {
await search.fetchNextPage();
return;
@@ -355,6 +373,10 @@ export function useEmailDataSource(
await query.fetchNextPage();
},
refresh: async () => {
+ if (showsScheduled()) {
+ await scheduled.refresh();
+ return;
+ }
await Promise.all([
usesServiceSearch() ? search.refetch() : query.refresh(),
...retainedQueries().map((lookup) => lookup.refresh()),
diff --git a/apps/web/src/features/email-view/queries/use-scheduled-email-source.test.ts b/apps/web/src/features/email-view/queries/use-scheduled-email-source.test.ts
new file mode 100644
index 0000000000..9cb1342f74
--- /dev/null
+++ b/apps/web/src/features/email-view/queries/use-scheduled-email-source.test.ts
@@ -0,0 +1,140 @@
+import type { Message } from '@service-email/generated/schemas';
+import { createRoot } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { EmailViewState } from '../types';
+import { useScheduledEmailSource } from './use-scheduled-email-source';
+
+const mocks = vi.hoisted(() => ({
+ links: {
+ isSuccess: true,
+ isError: false,
+ isLoading: false,
+ error: null as Error | null,
+ data: { links: [{ id: 'inbox-a' }] },
+ refetch: vi.fn(async () => {}),
+ },
+ scheduled: {
+ isSuccess: true,
+ isLoading: false,
+ isFetching: false,
+ error: null as Error | null,
+ data: [] as Message[],
+ refetch: vi.fn(async () => {}),
+ },
+ scheduledEnabled: undefined as (() => boolean) | undefined,
+}));
+
+vi.mock('@app/features/soup', async () => ({
+ ...(await import('@app/features/soup/collection/rows')),
+}));
+vi.mock('@components/app/GlobalAppState', () => ({
+ useGlobalNotificationSource: () => ({ notificationsByEntity: () => ({}) }),
+}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'alice' }));
+vi.mock('@queries/email/link', () => ({
+ useEmailLinksQuery: () => mocks.links,
+}));
+vi.mock('@queries/email/scheduled', () => ({
+ useScheduledMessagesQuery: (_linkIds: unknown, enabled: () => boolean) => {
+ mocks.scheduledEnabled = enabled;
+ return mocks.scheduled;
+ },
+}));
+
+function message(id: string, threadId: string, sendTime: string): Message {
+ return {
+ db_id: id,
+ thread_db_id: threadId,
+ link_id: 'inbox-a',
+ subject: `Subject ${id}`,
+ snippet: `Snippet ${id}`,
+ to: [{ email: '[email protected]', name: 'Peter' }],
+ cc: [],
+ bcc: [],
+ is_draft: true,
+ is_read: true,
+ is_sent: false,
+ is_starred: false,
+ has_attachments: false,
+ labels: [],
+ attachments: [],
+ attachments_draft: [],
+ attachments_forwarded: [],
+ scheduled_send_time: sendTime,
+ created_at: '2026-09-20T12:00:00Z',
+ updated_at: '2026-09-21T12:00:00Z',
+ } as Message;
+}
+
+let dispose: (() => void) | undefined;
+function mount() {
+ return createRoot((cleanup) => {
+ dispose = cleanup;
+ const [state] = createStore<EmailViewState>({
+ tab: 'scheduled',
+ search: '',
+ inboxIds: undefined,
+ facets: {},
+ collapsedSidebarSectionIds: [],
+ });
+ return useScheduledEmailSource(state);
+ });
+}
+
+describe('scheduled email source', () => {
+ afterEach(() => {
+ dispose?.();
+ vi.clearAllMocks();
+ mocks.links.isSuccess = true;
+ mocks.links.isError = false;
+ mocks.links.error = null;
+ mocks.scheduled.data = [];
+ });
+
+ it('lists one row per thread, soonest send first, timed by the send', () => {
+ mocks.scheduled.data = [
+ message('first', 'thread-a', '2026-09-27T12:00:00Z'),
+ message('second', 'thread-a', '2026-09-28T12:00:00Z'),
+ message('third', 'thread-b', '2026-09-29T12:00:00Z'),
+ ];
+ const source = mount();
+
+ const entities = source
+ .items()
+ .flatMap((row) => (row.kind === 'entity' ? [row.entity] : []));
+ expect(entities.map((entity) => entity.id)).toEqual([
+ 'thread-a',
+ 'thread-b',
+ ]);
+ expect(entities[0]).toMatchObject({
+ type: 'email',
+ name: 'Subject first',
+ isDraft: true,
+ ownerId: 'alice',
+ scheduledSendTime: '2026-09-27T12:00:00Z',
+ participants: [{ email: '[email protected]', name: 'Peter' }],
+ });
+ expect(source.hasMore()).toBe(false);
+ });
+
+ it('retries the inbox list when that is what failed', async () => {
+ mocks.links.isSuccess = false;
+ mocks.links.isError = true;
+ mocks.links.error = new Error('links failed');
+ const source = mount();
+
+ expect(mocks.scheduledEnabled?.()).toBe(false);
+ expect(source.error()).toBe(mocks.links.error);
+ await source.refresh();
+ expect(mocks.links.refetch).toHaveBeenCalledOnce();
+ expect(mocks.scheduled.refetch).not.toHaveBeenCalled();
+ });
+
+ it('refreshes the scheduled read once the inbox list has loaded', async () => {
+ const source = mount();
+ await source.refresh();
+ expect(mocks.scheduled.refetch).toHaveBeenCalledOnce();
+ expect(mocks.links.refetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/email-view/queries/use-scheduled-email-source.ts b/apps/web/src/features/email-view/queries/use-scheduled-email-source.ts
new file mode 100644
index 0000000000..338b29b30e
--- /dev/null
+++ b/apps/web/src/features/email-view/queries/use-scheduled-email-source.ts
@@ -0,0 +1,102 @@
+import { buildFlatSoupRows } from '@app/features/soup';
+import { withEntityNotifications } from '@app/features/soup/entity-notifications';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import { useUserId } from '@core/context/user';
+import type { EmailEntity } from '@entity';
+import { useEmailLinksQuery } from '@queries/email/link';
+import { useScheduledMessagesQuery } from '@queries/email/scheduled';
+import type { Message } from '@service-email/generated/schemas';
+import { createMemo } from 'solid-js';
+import type {
+ EmailDataSource,
+ EmailDataSourceInput,
+ EmailDataSourceItem,
+} from './use-email-query';
+
+/** A scheduled draft as its thread's list row, addressed like other drafts. */
+export function scheduledEmailEntity(
+ message: Message,
+ ownerId: string
+): EmailEntity {
+ return {
+ type: 'email',
+ id: message.thread_db_id,
+ name: message.subject ?? '',
+ ownerId,
+ isRead: true,
+ isDraft: true,
+ isImportant: false,
+ done: false,
+ snippet: message.snippet ?? undefined,
+ linkId: message.link_id,
+ participants: message.to.map((recipient) => ({
+ email: recipient.email,
+ name: recipient.name ?? undefined,
+ })),
+ scheduledSendTime: message.scheduled_send_time ?? undefined,
+ createdAt: message.created_at,
+ updatedAt: message.updated_at,
+ };
+}
+
+/**
+ * Scheduled mail for the selected inboxes, soonest first. The scheduled
+ * endpoint is authoritative here: soup rows carry no schedule, and a draft
+ * with only a local send time is not scheduled.
+ */
+export function useScheduledEmailSource(
+ state: EmailDataSourceInput
+): EmailDataSource {
+ const notificationSource = useGlobalNotificationSource();
+ const userId = useUserId();
+ const links = useEmailLinksQuery();
+ const linkIds = createMemo(() => {
+ if (!links.isSuccess) return [];
+ const available = links.data.links.map((link) => link.id);
+ if (state.inboxIds === undefined) return available;
+ const selected = new Set(state.inboxIds);
+ return available.filter((id) => selected.has(id));
+ });
+ const scheduled = useScheduledMessagesQuery(
+ linkIds,
+ () => state.tab === 'scheduled' && links.isSuccess
+ );
+
+ const items = createMemo((): EmailDataSourceItem[] => {
+ if (!scheduled.isSuccess) return [];
+ // One row per thread, like every other email list; the soonest send wins.
+ const threadIds = new Set<string>();
+ const entities = [];
+ for (const message of scheduled.data) {
+ if (threadIds.has(message.thread_db_id)) continue;
+ threadIds.add(message.thread_db_id);
+ entities.push(
+ withEntityNotifications(
+ scheduledEmailEntity(message, userId() ?? ''),
+ notificationSource
+ )
+ );
+ }
+ return buildFlatSoupRows(entities);
+ });
+
+ return {
+ items,
+ isLoading: () =>
+ links.isLoading || (linkIds().length > 0 && scheduled.isLoading),
+ isFetching: () => scheduled.isFetching,
+ error: () => links.error ?? scheduled.error ?? undefined,
+ hasMore: () => false,
+ isLoadingMore: () => false,
+ loadMore: async () => {},
+ refresh: async () => {
+ // The scheduled query waits on the inbox list, so a failed list is the
+ // thing to retry; the scheduled read follows once it succeeds.
+ if (links.isError) {
+ await links.refetch();
+ return;
+ }
+ await scheduled.refetch();
+ },
+ };
+}
diff --git a/apps/web/src/features/email-view/types.ts b/apps/web/src/features/email-view/types.ts
index 4c9d48a379..7147ad5d96 100644
--- a/apps/web/src/features/email-view/types.ts
+++ b/apps/web/src/features/email-view/types.ts
@@ -9,6 +9,7 @@ export type EmailTab =
| 'important'
| 'noise'
| 'sent'
+ | 'scheduled'
| 'calendar'
| 'drafts'
| 'shared'
diff --git a/apps/web/src/features/entity/components/Badges.tsx b/apps/web/src/features/entity/components/Badges.tsx
index 1715fcc27f..d59291be34 100644
--- a/apps/web/src/features/entity/components/Badges.tsx
+++ b/apps/web/src/features/entity/components/Badges.tsx
@@ -1,8 +1,15 @@
import { UserIcon } from '@core/component/UserIcon';
import { getDisplayName, tryMacroId } from '@core/user';
+import { formatTimeZoneAbbreviation } from '@core/util/date';
+import ClockIcon from '@phosphor/clock.svg';
import HashIcon from '@phosphor/hash.svg';
import UserPlus from '@phosphor/user-plus.svg';
import { cn, HoverCard } from '@ui';
+import { differenceInCalendarDays } from 'date-fns/differenceInCalendarDays';
+import { format } from 'date-fns/format';
+import { isThisYear } from 'date-fns/isThisYear';
+import { isToday } from 'date-fns/isToday';
+import { isTomorrow } from 'date-fns/isTomorrow';
import type { ParentProps } from 'solid-js';
import type { CallStatus } from '../types/entity';
@@ -84,6 +91,43 @@ export function DraftBadge() {
return <Badge class="text-warning border-edge-muted px-2">draft</Badge>;
}
+function scheduledSendLabel(time: Date): string {
+ const clock = format(time, 'h:mm a');
+ if (isToday(time)) return `Today, ${clock}`;
+ if (isTomorrow(time)) return `Tomorrow, ${clock}`;
+ // Only an upcoming send reads as a weekday; an overdue one keeps its date.
+ const daysAway = differenceInCalendarDays(time, new Date());
+ if (daysAway > 0 && daysAway < 7) return format(time, 'EEE, h:mm a');
+ if (isThisYear(time)) return format(time, 'MMM d, h:mm a');
+ return format(time, 'MMM d, yyyy');
+}
+
+/** When a scheduled row sends; list layouts show it in the timestamp slot. */
+export function ScheduledBadge(props: { sendTime: string }) {
+ const sendTime = () => new Date(props.sendTime);
+ const overdue = () => sendTime().getTime() <= Date.now();
+ return (
+ <Badge
+ class={cn(
+ 'ml-auto w-fit shrink-0 px-2',
+ overdue()
+ ? 'text-failure border-failure/20'
+ : 'text-accent border-accent/20'
+ )}
+ title={[
+ overdue() ? 'Overdue scheduled send' : 'Scheduled to send',
+ format(sendTime(), "EEE, MMM d, yyyy 'at' h:mm a"),
+ formatTimeZoneAbbreviation(sendTime()),
+ ]
+ .filter(Boolean)
+ .join(' ')}
+ >
+ <ClockIcon class="size-3" />
+ <span class="whitespace-nowrap">{scheduledSendLabel(sendTime())}</span>
+ </Badge>
+ );
+}
+
function _ImportantBadge() {
return (
<Badge class="text-accent bg-accent/10 px-2 border-accent/10">
diff --git a/apps/web/src/features/entity/components/ScheduledBadge.test.tsx b/apps/web/src/features/entity/components/ScheduledBadge.test.tsx
new file mode 100644
index 0000000000..a211353dd1
--- /dev/null
+++ b/apps/web/src/features/entity/components/ScheduledBadge.test.tsx
@@ -0,0 +1,51 @@
+import { formatTimeZoneAbbreviation } from '@core/util/date';
+import { cleanup, render } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ScheduledBadge } from './Badges';
+
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));
+
+// Thursday, Sep 24, 2026 at noon, local time.
+const NOW = new Date(2026, 8, 24, 12, 0);
+
+const label = (sendTime: Date) =>
+ render(() => <ScheduledBadge sendTime={sendTime.toISOString()} />).container
+ .textContent;
+
+describe('ScheduledBadge', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ });
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it('names the day relative to now for upcoming sends', () => {
+ expect(label(new Date(2026, 8, 24, 14, 13))).toBe('Today, 2:13 PM');
+ expect(label(new Date(2026, 8, 25, 14, 12))).toBe('Tomorrow, 2:12 PM');
+ expect(label(new Date(2026, 8, 28, 9, 45))).toBe('Mon, 9:45 AM');
+ expect(label(new Date(2026, 9, 24, 16, 30))).toBe('Oct 24, 4:30 PM');
+ expect(label(new Date(2027, 0, 3, 11, 5))).toBe('Jan 3, 2027');
+ });
+
+ it('gives the full send time and its zone on hover', () => {
+ const sendTime = new Date(2026, 8, 25, 14, 12);
+ const { container } = render(() => (
+ <ScheduledBadge sendTime={sendTime.toISOString()} />
+ ));
+ expect(container.firstElementChild?.getAttribute('title')).toBe(
+ `Scheduled to send Fri, Sep 25, 2026 at 2:12 PM ${formatTimeZoneAbbreviation(sendTime)}`
+ );
+ });
+
+ it('keeps an overdue send on its date instead of a weekday', () => {
+ const lastMonth = new Date(2026, 7, 31, 9, 0);
+ expect(label(lastMonth)).toBe('Aug 31, 9:00 AM');
+ const { container } = render(() => (
+ <ScheduledBadge sendTime={lastMonth.toISOString()} />
+ ));
+ expect(container.firstElementChild?.className).toContain('text-failure');
+ });
+});
diff --git a/apps/web/src/features/entity/composed/list-entity/email.tsx b/apps/web/src/features/entity/composed/list-entity/email.tsx
index b1fccc9ce0..98403d789e 100644
--- a/apps/web/src/features/entity/composed/list-entity/email.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/email.tsx
@@ -68,7 +68,8 @@ export function EmailInboxChip(props: { entity: EmailEntity; class?: string }) {
export function EmailIdentity(props: { entity: EmailEntity }) {
return (
<>
- <Show when={props.entity.isDraft}>
+ {/* A scheduled draft's badge is its send time, in the timestamp slot. */}
+ <Show when={props.entity.isDraft && !props.entity.scheduledSendTime}>
<DraftBadge />
</Show>
<span class="truncate min-w-0">
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
index df40e58054..4ba7030bc7 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
@@ -41,7 +41,11 @@ export function NarrowInboxLayout(props: LayoutProps) {
<Entity.Layout
class="w-full text-sm grid"
style={{
- 'grid-template-columns': 'auto 1fr 8ch',
+ // A scheduled send's badge is wider than a date, so it sizes its column.
+ 'grid-template-columns':
+ isEmailEntity(props.entity) && props.entity.scheduledSendTime
+ ? 'auto 1fr auto'
+ : 'auto 1fr 8ch',
'grid-template-rows': 'auto auto auto',
'grid-template-areas':
'"icon title timestamp" "icon body body" "icon body body"',
diff --git a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
index 5437c4915a..4faa1d002f 100644
--- a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
@@ -78,9 +78,14 @@ export function WideLayout(props: LayoutProps) {
'gap-y-2 gap-x-(--soup-row-column-gap) grid grid-rows-[1fr]',
// Drop the indicator column entirely when the checkbox is hidden so the
// content isn't indented by an empty gutter.
- props.hideCheckbox
- ? 'grid-cols-[1fr_auto_8ch]'
- : 'grid-cols-[var(--soup-row-indicator-width)_1fr_auto_8ch]',
+ // A scheduled send's badge is wider than a date, so it sizes its column.
+ isEmailEntity(props.entity) && props.entity.scheduledSendTime
+ ? props.hideCheckbox
+ ? 'grid-cols-[1fr_auto_auto]'
+ : 'grid-cols-[var(--soup-row-indicator-width)_1fr_auto_auto]'
+ : props.hideCheckbox
+ ? 'grid-cols-[1fr_auto_8ch]'
+ : 'grid-cols-[var(--soup-row-indicator-width)_1fr_auto_8ch]',
'[--title-width:10rem]'
)}
style={{
diff --git a/apps/web/src/features/entity/extractors/entity-timestamp.tsx b/apps/web/src/features/entity/extractors/entity-timestamp.tsx
index 57f250c9e7..679d2bbdcf 100644
--- a/apps/web/src/features/entity/extractors/entity-timestamp.tsx
+++ b/apps/web/src/features/entity/extractors/entity-timestamp.tsx
@@ -1,5 +1,7 @@
import type { DateValue } from '@core/util/date';
-import type { EntityData } from '../types/entity';
+import { Show } from 'solid-js';
+import { ScheduledBadge } from '../components/Badges';
+import { type EntityData, isEmailEntity } from '../types/entity';
import { formatTimestamp } from '../utils/timestamp';
export function EntityTimestamp(props: {
@@ -12,5 +14,17 @@ export function EntityTimestamp(props: {
if (props.entity.updatedAt) return props.entity.updatedAt;
return new Date();
};
- return <>{formatTimestamp(timestamp())}</>;
+ // A scheduled row's time is when it sends, in every list layout.
+ const scheduledSendTime = () =>
+ !props.overrideTimeStamp && isEmailEntity(props.entity)
+ ? props.entity.scheduledSendTime
+ : undefined;
+ return (
+ <Show
+ when={scheduledSendTime()}
+ fallback={<>{formatTimestamp(timestamp())}</>}
+ >
+ {(sendTime) => <ScheduledBadge sendTime={sendTime()} />}
+ </Show>
+ );
}
diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.ts
index 21bb76be3c..7dcafd9afe 100644
--- a/apps/web/src/features/entity/types/entity.ts
+++ b/apps/web/src/features/entity/types/entity.ts
@@ -285,6 +285,8 @@ export type EmailEntity = EntityBase & {
hasIcsAttachment?: boolean;
attachments?: EmailAttachment[];
properties?: SoupProperty[];
+ /** ISO 8601 time of the thread draft's confirmed scheduled send. */
+ scheduledSendTime?: string;
};
export type ProjectEntity = EntityBase & {
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
index 472601e973..3f2d5a310e 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
@@ -24,10 +24,7 @@ import { ComposeLayout } from '@app/features/email-compose/views/compose-layout'
import { EmailComposeToolbar } from '@app/features/email-compose/views/compose-toolbar';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { toast } from '@core/component/Toast/Toast';
-import {
- ENABLE_EMAIL_SCHEDULED_SEND,
- enableEmailSignatures,
-} from '@core/constant/featureFlags';
+import { enableEmailSignatures } from '@core/constant/featureFlags';
import { isMobile } from '@core/mobile/isMobile';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
@@ -215,11 +212,21 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
const ctx: ComposeContextValue = {
bodyActions: createComposeBodyActions(),
isMobile,
- scheduleEnabled: ENABLE_EMAIL_SCHEDULED_SEND,
+ // The AI tool has its own execute contract and does not expose scheduled send.
+ scheduleEnabled: false,
attachmentFailure: toast.failure,
subject,
attachments: () => [],
- sendTime: () => undefined,
+ schedule: {
+ state: () => ({ type: 'editing', intent: { type: 'immediate' } }),
+ selectedTime: () => undefined,
+ confirmedTime: () => undefined,
+ actionLabel: () => 'Send email',
+ operation: () => 'idle',
+ onSelect: () => false,
+ onCancel: async () => false,
+ pickerDisabled: () => true,
+ },
initialHtml: () => initialBody().html,
initialMarkdown: () => initialBody().markdown,
setRecipients: (field, value) => {
@@ -241,6 +248,7 @@ export function EmailDraftComposer(props: EmailDraftComposerProps) {
},
onSend: handleSend,
disabled: () => isSending() || uiDisabled(),
+ primaryActionDisabled: () => isSending() || uiDisabled(),
isSending,
isSavingDraft: () => false,
hasDraft: () => false,
diff --git a/apps/web/src/lib/core/component/Toast/Toast.tsx b/apps/web/src/lib/core/component/Toast/Toast.tsx
index 68e63a01e9..05adc70c22 100644
--- a/apps/web/src/lib/core/component/Toast/Toast.tsx
+++ b/apps/web/src/lib/core/component/Toast/Toast.tsx
@@ -337,6 +337,9 @@ function ToastContent(props: {
onDismiss?: () => void;
}) {
const styles = () => (props.toastType ? TOAST_STYLES[props.toastType] : null);
+ // Two actions beside the title squeeze it to a few characters; like the
+ // stacked custom layout, they get their own row under the description.
+ const stackActions = () => (props.actions?.length ?? 0) > 1;
const accentColor = () => {
if (props.custom?.color) return props.custom.color;
@@ -527,7 +530,7 @@ function ToastContent(props: {
>
{props.message}
</Toast.Title>
- <Show when={props.actions?.length}>
+ <Show when={props.actions?.length && !stackActions()}>
<ActionButtons
actions={props.actions!}
mobile={props.mobile}
@@ -541,11 +544,21 @@ function ToastContent(props: {
</Toast.CloseButton>
</Show>
</div>
- <Show when={props.subtext && !props.mobile}>
- <Toast.Description class="text-sm text-ink-extra-muted ml-7">
+ <Show when={props.subtext && (!props.mobile || stackActions())}>
+ <Toast.Description
+ class={cn(
+ 'ml-7 text-ink-extra-muted',
+ props.mobile ? 'text-xs' : 'text-sm'
+ )}
+ >
{props.subtext}
</Toast.Description>
</Show>
+ <Show when={stackActions()}>
+ <div class="mt-2 ml-7 flex flex-wrap gap-2">
+ <ActionButtons actions={props.actions!} mobile />
+ </div>
+ </Show>
</>
)}
</Match>
diff --git a/apps/web/src/lib/core/util/date.test.ts b/apps/web/src/lib/core/util/date.test.ts
new file mode 100644
index 0000000000..5b41201a9e
--- /dev/null
+++ b/apps/web/src/lib/core/util/date.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest';
+import { formatTimeZoneAbbreviation } from './date';
+
+describe('formatTimeZoneAbbreviation', () => {
+ it('names the zone in effect at the instant, across daylight saving', () => {
+ const summer = new Date('2026-07-01T16:00:00Z');
+ const winter = new Date('2027-01-03T16:00:00Z');
+ expect(formatTimeZoneAbbreviation(summer, 'America/New_York')).toBe('EDT');
+ expect(formatTimeZoneAbbreviation(winter, 'America/New_York')).toBe('EST');
+ expect(formatTimeZoneAbbreviation(winter, 'UTC')).toBe('UTC');
+ });
+});
diff --git a/apps/web/src/lib/core/util/date.ts b/apps/web/src/lib/core/util/date.ts
index 85ec7645fa..b52ca3ed32 100644
--- a/apps/web/src/lib/core/util/date.ts
+++ b/apps/web/src/lib/core/util/date.ts
@@ -41,6 +41,20 @@ export const formatTime = (
});
};
+/**
+ * The short timezone name in effect at `date`, e.g. 'EDT' in summer and 'EST'
+ * in winter for New York. Zones without an English abbreviation get an
+ * offset such as 'GMT+1'.
+ * @param timeZone - IANA timezone string. Defaults to system timezone.
+ */
+export const formatTimeZoneAbbreviation = (
+ date: Date,
+ timeZone?: string
+): string | undefined =>
+ new Intl.DateTimeFormat('en-US', { timeZoneName: 'short', timeZone })
+ .formatToParts(date)
+ .find((part) => part.type === 'timeZoneName')?.value;
+
/**
* Formats a date to a human readable string.
* @param date - Date object or Unix timestamp in seconds
diff --git a/apps/web/src/lib/queries/email/draft-lifecycle-events.ts b/apps/web/src/lib/queries/email/draft-lifecycle-events.ts
new file mode 100644
index 0000000000..f2bc7ad86b
--- /dev/null
+++ b/apps/web/src/lib/queries/email/draft-lifecycle-events.ts
@@ -0,0 +1,39 @@
+import { createCrossTabBus } from '@core/cross-tab/cross-tab-bus';
+
+export type DraftLifecycleChange = {
+ draftId: string;
+ inboxId?: string;
+ changedAt: number;
+};
+
+const lifecycleBus = createCrossTabBus<DraftLifecycleChange>({
+ channelName: 'macro-email-draft-lifecycle',
+ storageKey: 'macro:email-draft-lifecycle',
+ parse(value) {
+ if (typeof value !== 'object' || value === null) return null;
+ const candidate = value as Partial<DraftLifecycleChange>;
+ if (
+ typeof candidate.draftId !== 'string' ||
+ typeof candidate.changedAt !== 'number' ||
+ (candidate.inboxId !== undefined && typeof candidate.inboxId !== 'string')
+ ) {
+ return null;
+ }
+ return candidate as DraftLifecycleChange;
+ },
+ getMessageKey: (message) =>
+ `${message.draftId}:${message.inboxId ?? ''}:${message.changedAt}`,
+});
+
+export function publishDraftLifecycleChange(
+ draftId: string,
+ inboxId?: string
+): void {
+ lifecycleBus.publish({ draftId, inboxId, changedAt: Date.now() });
+}
+
+export function subscribeToDraftLifecycleChanges(
+ listener: (change: DraftLifecycleChange) => void
+): VoidFunction {
+ return lifecycleBus.subscribe(listener);
+}
diff --git a/apps/web/src/lib/queries/email/draft.ts b/apps/web/src/lib/queries/email/draft.ts
index c105e5aab0..7f65f0fa98 100644
--- a/apps/web/src/lib/queries/email/draft.ts
+++ b/apps/web/src/lib/queries/email/draft.ts
@@ -1,4 +1,3 @@
-import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/result';
import { Telemetry } from '@macro-inc/observability';
import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';
@@ -14,7 +13,6 @@ import { emailKeys } from './keys';
type CreateDraftParams = {
draft: ApiDraftInput;
- sendTime?: Date | null;
/** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */
linkId?: string;
/** Skip updating soup when the thread will immediately be marked done. */
@@ -31,20 +29,13 @@ export function useSaveDraftMutation(
mutationFn: async (vars: CreateDraftParams) => {
return await throwOnErr(
async () =>
- await emailClient.createDraft(
- {
- draft: vars.draft,
- send_time: vars.sendTime?.toISOString() ?? null,
- },
- vars.linkId
- )
+ await emailClient.createDraft({ draft: vars.draft }, vars.linkId)
);
},
...withCallbacks<CreateDraftResponse, Error, CreateDraftParams>(
{
onError(error) {
console.error('Failed to save draft', error);
- toast.failure('Failed to save draft');
},
onSuccess(data, vars) {
try {
@@ -104,7 +95,6 @@ export function useDeleteDraftMutation(
{
onError(error) {
console.error('Failed to delete draft', error);
- toast.failure('Failed to delete draft');
},
onSuccess(_data, vars) {
try {
diff --git a/apps/web/src/lib/queries/email/graphql/thread.ts b/apps/web/src/lib/queries/email/graphql/thread.ts
index 2e2c22abc6..7052506aa9 100644
--- a/apps/web/src/lib/queries/email/graphql/thread.ts
+++ b/apps/web/src/lib/queries/email/graphql/thread.ts
@@ -90,12 +90,13 @@ export function mapGraphqlThreadError(error: CombinedError): ThrownResultError {
* thrown as a ThrownResultError with typed result codes.
*/
export async function fetchGraphqlEmailThread(
- threadId: string
+ threadId: string,
+ offset = 0
): Promise<ApiThread> {
const client = getGraphqlSoupClient();
const variables: EmailThreadPageQueryVariables = {
threadId,
- offset: 0,
+ offset,
limit: DEFAULT_THREAD_MESSAGES_LIMIT,
};
const result = await client
diff --git a/apps/web/src/lib/queries/email/keys.ts b/apps/web/src/lib/queries/email/keys.ts
index b3d0eea4f4..d4731e6c29 100644
--- a/apps/web/src/lib/queries/email/keys.ts
+++ b/apps/web/src/lib/queries/email/keys.ts
@@ -14,6 +14,16 @@ export const emailKeys = createQueryKeys('email', {
threadMessages: (threadId: string) => ({
queryKey: ['messages', threadId],
}),
+ composeDraftState: (params: {
+ draftId: string;
+ threadId: string;
+ inboxId?: string;
+ }) => ({
+ queryKey: ['compose-draft-state', params],
+ }),
+ scheduledMessages: (linkIds: string[]) => ({
+ queryKey: [{ linkIds }],
+ }),
previews: (params: {
view: PreviewViewStandardLabel;
limit?: number;
diff --git a/apps/web/src/lib/queries/email/scheduled.test.ts b/apps/web/src/lib/queries/email/scheduled.test.ts
new file mode 100644
index 0000000000..b801fba93e
--- /dev/null
+++ b/apps/web/src/lib/queries/email/scheduled.test.ts
@@ -0,0 +1,81 @@
+import { ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fetchScheduledMessages } from './scheduled';
+
+const getScheduledMessages = vi.hoisted(() => vi.fn());
+vi.mock('@service-email/client', () => ({
+ emailClient: { getScheduledMessages },
+}));
+
+function message(
+ id: string,
+ linkId: string,
+ sendTime: string | null,
+ overrides: { isDraft?: boolean; isSent?: boolean } = {}
+) {
+ return {
+ db_id: id,
+ thread_db_id: `thread-${id}`,
+ link_id: linkId,
+ is_draft: overrides.isDraft ?? true,
+ is_sent: overrides.isSent ?? false,
+ scheduled_send_time: sendTime,
+ attachments: [],
+ attachments_draft: [],
+ attachments_forwarded: [],
+ bcc: [],
+ cc: [],
+ to: [],
+ created_at: '2026-09-23T00:00:00Z',
+ updated_at: '2026-09-23T00:00:00Z',
+ has_attachments: false,
+ is_read: true,
+ is_starred: false,
+ labels: [],
+ };
+}
+
+describe('fetchScheduledMessages', () => {
+ beforeEach(() => vi.resetAllMocks());
+
+ it('paginates each inbox, excludes undo-window rows, and orders by send time', async () => {
+ const firstPage = Array.from({ length: 100 }, (_, index) =>
+ message(
+ `a-${index}`,
+ 'a',
+ `2026-12-${String((index % 28) + 1).padStart(2, '0')}T12:00:00Z`
+ )
+ );
+ const finalA = message('a-final', 'a', '2026-10-01T12:00:00Z');
+ const inboxB = message('b-only', 'b', '2026-09-30T12:00:00Z');
+ const undoWindow = message('undo', 'b', '2026-09-29T12:00:00Z', {
+ isDraft: false,
+ });
+ const noSendTime = message('unscheduled', 'b', null);
+ getScheduledMessages.mockImplementation(
+ ({ offset }: { offset: number }, linkId: string) => {
+ if (linkId === 'a' && offset === 0)
+ return Promise.resolve(ok({ messages: firstPage }));
+ if (linkId === 'a') return Promise.resolve(ok({ messages: [finalA] }));
+ return Promise.resolve(
+ ok({ messages: [undoWindow, noSendTime, inboxB] })
+ );
+ }
+ );
+
+ const result = await fetchScheduledMessages(['a', 'b']);
+
+ expect(getScheduledMessages).toHaveBeenCalledWith(
+ { offset: 100, limit: 100 },
+ 'a'
+ );
+ expect(result).not.toContainEqual(
+ expect.objectContaining({ db_id: 'undo' })
+ );
+ expect(result).not.toContainEqual(
+ expect.objectContaining({ db_id: 'unscheduled' })
+ );
+ expect(result[0].db_id).toBe('b-only');
+ expect(result[1].db_id).toBe('a-final');
+ });
+});
diff --git a/apps/web/src/lib/queries/email/scheduled.ts b/apps/web/src/lib/queries/email/scheduled.ts
new file mode 100644
index 0000000000..7338c111f9
--- /dev/null
+++ b/apps/web/src/lib/queries/email/scheduled.ts
@@ -0,0 +1,61 @@
+import { throwOnErr } from '@core/util/result';
+import { emailClient } from '@service-email/client';
+import type { Message } from '@service-email/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { emailKeys } from './keys';
+
+const SCHEDULED_PAGE_SIZE = 100;
+
+async function fetchScheduledInbox(linkId: string): Promise<Message[]> {
+ const messages: Message[] = [];
+ let offset = 0;
+
+ for (;;) {
+ const page = await throwOnErr(() =>
+ emailClient.getScheduledMessages(
+ { offset, limit: SCHEDULED_PAGE_SIZE },
+ linkId
+ )
+ );
+ messages.push(...page.messages);
+ if (page.messages.length < SCHEDULED_PAGE_SIZE) return messages;
+ offset += page.messages.length;
+ }
+}
+
+export async function fetchScheduledMessages(
+ linkIds: string[]
+): Promise<Message[]> {
+ const inboxes = await Promise.all(linkIds.map(fetchScheduledInbox));
+ return inboxes
+ .flat()
+ .filter(
+ (message) =>
+ message.is_draft &&
+ !message.is_sent &&
+ message.scheduled_send_time != null
+ )
+ .sort(
+ (left, right) =>
+ new Date(left.scheduled_send_time!).getTime() -
+ new Date(right.scheduled_send_time!).getTime()
+ );
+}
+
+export function useScheduledMessagesQuery(
+ linkIds: Accessor<string[]>,
+ enabled: Accessor<boolean>
+) {
+ return useQuery(() => {
+ const selectedLinkIds = [...linkIds()].sort();
+ return {
+ queryKey: emailKeys.scheduledMessages(selectedLinkIds).queryKey,
+ enabled: enabled() && selectedLinkIds.length > 0,
+ queryFn: () => fetchScheduledMessages(selectedLinkIds),
+ refetchInterval: 15_000,
+ refetchOnReconnect: 'always' as const,
+ refetchOnWindowFocus: 'always' as const,
+ };
+ });
+}
diff --git a/apps/web/src/lib/queries/email/sync.ts b/apps/web/src/lib/queries/email/sync.ts
index cc5f76a4db..c3506028bb 100644
--- a/apps/web/src/lib/queries/email/sync.ts
+++ b/apps/web/src/lib/queries/email/sync.ts
@@ -1,5 +1,6 @@
import { toast } from '@core/component/Toast/Toast';
import { ENABLE_INBOX_SYNC_STATUS } from '@core/constant/featureFlags';
+import { queryClient } from '@queries/client';
import { invalidateAllSoup } from '@queries/soup/normalized-cache';
import {
BackfillStatus,
@@ -13,6 +14,7 @@ import {
invalidateBackfillJobs,
setBackfillProgress,
} from './backfill';
+import { emailKeys } from './keys';
import { invalidateEmailLinks } from './link';
const BACKFILL_SOUP_REFRESH_INTERVAL = 5_000;
@@ -52,6 +54,17 @@ export function handleRefreshEmail(payload: unknown): void {
const event = asRefreshEmailEvent(payload);
if (!event) return;
+ if (
+ event.event === 'upsert_message' ||
+ event.event === 'update_labels' ||
+ event.event === 'delete_message'
+ ) {
+ void queryClient.invalidateQueries({
+ queryKey: emailKeys.composeDraftState._def,
+ });
+ return;
+ }
+
// An inbox finished its async teardown — drop its now-deleted threads and
// settle its links row. This is the only reliable signal that teardown is
// done; refetching on the delete request itself races the cascade delete.
diff --git a/apps/web/src/lib/queries/email/thread-fresh.test.ts b/apps/web/src/lib/queries/email/thread-fresh.test.ts
new file mode 100644
index 0000000000..8721795465
--- /dev/null
+++ b/apps/web/src/lib/queries/email/thread-fresh.test.ts
@@ -0,0 +1,79 @@
+import type { ApiMessage, ApiThread } from '@service-email/generated/schemas';
+import { ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getThread = vi.hoisted(() => vi.fn());
+
+vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
+ enableGraphqlSoup: { key: 'enable-graphql-soup' },
+ // Authoritative lifecycle reads must bypass GraphQL even when it is enabled.
+ isFeatureEnabled: () => true,
+}));
+vi.mock('@service-email/client', () => ({ emailClient: { getThread } }));
+
+import { fetchFreshEmailThread } from './thread';
+
+function message(dbId: string): ApiMessage {
+ return {
+ attachments: [],
+ attachments_draft: [],
+ attachments_forwarded: [],
+ bcc: [],
+ cc: [],
+ created_at: '2026-09-21T00:00:00Z',
+ db_id: dbId,
+ has_attachments: false,
+ is_draft: dbId === 'late-draft',
+ is_read: true,
+ is_sent: dbId !== 'late-draft',
+ is_starred: false,
+ labels: [],
+ link_id: 'inbox',
+ thread_db_id: 'thread',
+ to: [],
+ updated_at: '2026-09-21T00:00:00Z',
+ };
+}
+
+function thread(messages: ApiMessage[]): ApiThread {
+ return {
+ access_level: 'owner',
+ created_at: '2026-09-21T00:00:00Z',
+ db_id: 'thread',
+ inbox_visible: true,
+ is_read: true,
+ link_id: 'inbox',
+ messages,
+ updated_at: '2026-09-21T00:00:00Z',
+ };
+}
+
+describe('fetchFreshEmailThread', () => {
+ beforeEach(() => getThread.mockReset());
+
+ it('continues past the first page until the requested draft is present', async () => {
+ const firstPage = thread(
+ Array.from({ length: 20 }, (_, index) => message(`sent-${index}`))
+ );
+ const lastPage = thread([message('late-draft')]);
+ getThread
+ .mockResolvedValueOnce(ok({ thread: firstPage }))
+ .mockResolvedValueOnce(ok({ thread: lastPage }));
+
+ const result = await fetchFreshEmailThread('thread', 'late-draft');
+
+ expect(getThread).toHaveBeenNthCalledWith(1, {
+ thread_id: 'thread',
+ offset: 0,
+ limit: 20,
+ });
+ expect(getThread).toHaveBeenNthCalledWith(2, {
+ thread_id: 'thread',
+ offset: 20,
+ limit: 20,
+ });
+ expect(result.messages).toHaveLength(21);
+ expect(result.messages.at(-1)?.db_id).toBe('late-draft');
+ });
+});
diff --git a/apps/web/src/lib/queries/email/thread.ts b/apps/web/src/lib/queries/email/thread.ts
index 11ac1f0ff9..7cec7c9bb4 100644
--- a/apps/web/src/lib/queries/email/thread.ts
+++ b/apps/web/src/lib/queries/email/thread.ts
@@ -117,6 +117,45 @@ export async function fetchAndCacheThread(
return ok({ thread: result.value });
}
+/**
+ * Read authoritative thread pages directly from REST, without GraphQL's
+ * in-flight deduplication or offline cache fallback. Drafts have no internal
+ * date and sort after sent messages, so continue until the requested message
+ * is present or the server has no more pages.
+ */
+export async function fetchFreshEmailThread(
+ threadId: string,
+ requiredMessageId?: string
+): Promise<Thread> {
+ let offset = 0;
+ let merged: Thread | undefined;
+
+ while (true) {
+ const page = (
+ await throwOnErr(() =>
+ emailClient.getThread({
+ thread_id: threadId,
+ offset,
+ limit: DEFAULT_THREAD_MESSAGES_LIMIT,
+ })
+ )
+ ).thread;
+
+ merged = merged
+ ? { ...page, messages: [...merged.messages, ...page.messages] }
+ : page;
+
+ if (
+ !requiredMessageId ||
+ page.messages.some((message) => message.db_id === requiredMessageId) ||
+ page.messages.length < DEFAULT_THREAD_MESSAGES_LIMIT
+ ) {
+ return merged;
+ }
+ offset += page.messages.length;
+ }
+}
+
/**
* Whether a thread's done state can actually be reversed.
*
@@ -684,6 +723,9 @@ function _useScheduleMessageMutation(
queryClient.invalidateQueries({
queryKey: emailKeys.previews._def,
});
+ queryClient.invalidateQueries({
+ queryKey: emailKeys.scheduledMessages._def,
+ });
},
},
callbacks
@@ -724,6 +766,11 @@ export function useUnscheduleMessageMutation(
queryKey: emailKeys.previews._def,
})
.catch(Telemetry.error);
+ void queryClient
+ .invalidateQueries({
+ queryKey: emailKeys.scheduledMessages._def,
+ })
+ .catch(Telemetry.error);
} catch (error) {
Telemetry.error(error);
}
diff --git a/apps/web/src/lib/queries/email/write-completion.test.tsx b/apps/web/src/lib/queries/email/write-completion.test.tsx
index 3a59d98240..fd7b9f0fb0 100644
--- a/apps/web/src/lib/queries/email/write-completion.test.tsx
+++ b/apps/web/src/lib/queries/email/write-completion.test.tsx
@@ -65,7 +65,11 @@ it('returns the saved identity when a subsequent cache refresh rejects', async (
).resolves.toEqual(response);
expect(mocks.report).toHaveBeenCalledWith(failure);
expect(mocks.failure).not.toHaveBeenCalled();
- expect(mocks.save).toHaveBeenCalledOnce();
+ expect(mocks.save).toHaveBeenCalledExactlyOnceWith(
+ { draft: { subject: 'Saved' } },
+ undefined
+ );
+ expect(mocks.save.mock.calls[0][0]).not.toHaveProperty('send_time');
});
it('keeps send successful and reconciles caches when analytics throws', async () => {
diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.ts
index 61dae48759..9176d60665 100644
--- a/apps/web/src/lib/service-clients/service-email/client.ts
+++ b/apps/web/src/lib/service-clients/service-email/client.ts
@@ -22,6 +22,7 @@ import type {
CreateDraftResponse,
GetAttachmentDocumentIDResponse,
GetAttachmentResponse,
+ GetScheduledResponse,
GetThreadResponse,
ListBackfillJobsResponse,
ListContactsResponse,
@@ -330,6 +331,23 @@ export const emailClient = {
).map((result) => result);
},
+ async getScheduledMessages(
+ args: { offset: number; limit: number },
+ linkId?: string
+ ) {
+ const params = new URLSearchParams({
+ offset: String(args.offset),
+ limit: String(args.limit),
+ });
+ return emailFetch<GetScheduledResponse>(
+ `/email/drafts/scheduled?${params.toString()}`,
+ {
+ method: 'GET',
+ headers: emailLinkHeaders(linkId),
+ }
+ );
+ },
+
async getLinks() {
return (
await emailFetch<ListLinksResponse>('/email/links', {
diff --git a/apps/web/src/lib/service-clients/service-email/generated/client.ts b/apps/web/src/lib/service-clients/service-email/generated/client.ts
index bb2a79dc13..c5716e638d 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/client.ts
@@ -871,11 +871,21 @@ export type upsertScheduledMessageResponse200 = {
status: 200;
};
+export type upsertScheduledMessageResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
export type upsertScheduledMessageResponse401 = {
data: ErrorResponse;
status: 401;
};
+export type upsertScheduledMessageResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
export type upsertScheduledMessageResponse404 = {
data: ErrorResponse;
status: 404;
@@ -891,7 +901,9 @@ export type upsertScheduledMessageResponseSuccess =
headers: Headers;
};
export type upsertScheduledMessageResponseError = (
+ | upsertScheduledMessageResponse400
| upsertScheduledMessageResponse401
+ | upsertScheduledMessageResponse403
| upsertScheduledMessageResponse404
| upsertScheduledMessageResponse500
) & {
@@ -931,7 +943,7 @@ export const upsertScheduledMessage = async (
};
/**
- * @summary Remove the scheduled send from a draft.
+ * @summary Remove the scheduled send from a draft, including immediate-send undo.
*/
export type deleteScheduledDraftResponse204 = {
data: void;
@@ -948,6 +960,11 @@ export type deleteScheduledDraftResponse401 = {
status: 401;
};
+export type deleteScheduledDraftResponse403 = {
+ data: ErrorResponse;
+ status: 403;
+};
+
export type deleteScheduledDraftResponse404 = {
data: ErrorResponse;
status: 404;
@@ -965,6 +982,7 @@ export type deleteScheduledDraftResponseSuccess =
export type deleteScheduledDraftResponseError = (
| deleteScheduledDraftResponse400
| deleteScheduledDraftResponse401
+ | deleteScheduledDraftResponse403
| deleteScheduledDraftResponse404
| deleteScheduledDraftResponse500
) & {
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts
index eeac0afe76..3e9da302f3 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/index.ts
@@ -279,6 +279,7 @@ export * from './upsertEmailFilterRequestEmailAddress';
export * from './upsertEmailFilterRequestEmailDomain';
export * from './upsertEmailFilterResponse';
export * from './upsertScheduledRequest';
+export * from './upsertScheduledRequestIncludeSignature';
export * from './upsertScheduledResponse';
export * from './userProvider';
export * from './value';
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequest.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequest.ts
index 4439cd199c..6c0ef59856 100644
--- a/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequest.ts
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequest.ts
@@ -4,8 +4,11 @@
* email_service
* OpenAPI spec version: 0.1.0
*/
+import type { UpsertScheduledRequestIncludeSignature } from './upsertScheduledRequestIncludeSignature';
export interface UpsertScheduledRequest {
- /** The time to send the message (ISO 8601 format) */
+ /** Per-message signature override; absent uses the inbox's send defaults. */
+ include_signature?: UpsertScheduledRequestIncludeSignature;
+ /** The time to send the message (ISO 8601 format). */
send_time: string;
}
diff --git a/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequestIncludeSignature.ts b/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequestIncludeSignature.ts
new file mode 100644
index 0000000000..9d93706b00
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-email/generated/schemas/upsertScheduledRequestIncludeSignature.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Per-message signature override; absent uses the inbox's send defaults.
+ */
+export type UpsertScheduledRequestIncludeSignature = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-email/openapi.json b/apps/web/src/lib/service-clients/service-email/openapi.json
index 3e604ad14b..8dcb753e95 100644
--- a/apps/web/src/lib/service-clients/service-email/openapi.json
+++ b/apps/web/src/lib/service-clients/service-email/openapi.json
@@ -780,6 +780,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
@@ -790,6 +800,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -816,7 +836,7 @@
"/email/drafts/scheduled/{message_id}": {
"delete": {
"tags": ["Draft Scheduling"],
- "summary": "Remove the scheduled send from a draft.",
+ "summary": "Remove the scheduled send from a draft, including immediate-send undo.",
"operationId": "delete_scheduled_draft",
"parameters": [
{
@@ -854,6 +874,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -5407,10 +5437,14 @@
"type": "object",
"required": ["send_time"],
"properties": {
+ "include_signature": {
+ "type": ["boolean", "null"],
+ "description": "Per-message signature override; absent uses the inbox's send defaults."
+ },
"send_time": {
"type": "string",
"format": "date-time",
- "description": "The time to send the message (ISO 8601 format)"
+ "description": "The time to send the message (ISO 8601 format)."
}
}
},
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index 525e68a973..b8a472a489 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -94,6 +94,7 @@ uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+email_db_client = { path = "../email_db_client" }
crm = { path = "../crm", features = ["outbound"] }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/crates/email/src/domain.rs b/crates/email/src/domain.rs
index bdda065ab0..9723b658de 100644
--- a/crates/email/src/domain.rs
+++ b/crates/email/src/domain.rs
@@ -8,4 +8,8 @@ pub mod assembler;
#[cfg(feature = "ports")]
pub mod ports;
#[cfg(feature = "ports")]
+pub mod scheduled;
+#[cfg(feature = "ports")]
+pub mod scheduled_delivery;
+#[cfg(feature = "ports")]
pub mod service;
diff --git a/crates/email/src/domain/models/error.rs b/crates/email/src/domain/models/error.rs
index 6ab4cbad13..210681a112 100644
--- a/crates/email/src/domain/models/error.rs
+++ b/crates/email/src/domain/models/error.rs
@@ -24,6 +24,12 @@ pub enum EmailErr {
/// The referenced message has already been sent and cannot be modified.
#[error("Message with id {0} has already been sent")]
MessageAlreadySent(Uuid),
+ /// Delivery has been committed, claimed, or completed and cannot be edited.
+ #[error("Message with id {0} is scheduled, processing, or already sent")]
+ MessageDeliveryConflict(Uuid),
+ /// Explicit scheduled delivery requires a time in the future.
+ #[error("Scheduled send time must be in the future")]
+ InvalidScheduleTime,
/// Cannot reply to a draft message.
#[error("Cannot reply to a draft")]
CannotReplyToDraft,
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index a2684ed39e..e35857d700 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -290,21 +290,12 @@ pub trait EmailRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<UpsertedContacts, Self::Err>> + Send;
/// Insert a message within a transaction, including thread insert (if new),
- /// recipients, scheduled message handling, thread metadata update, user
- /// history, and any client-handle bindings the input carries (upserted so
- /// replayed offline saves converge on the final row).
- ///
- /// A draft client handle is locked for the transaction and its binding
- /// re-read under that lock, so concurrent first saves of one handle settle
- /// on a single message and thread instead of each minting their own. The
- /// returned IDs are therefore the authoritative ones — a save that adopted
- /// a concurrent winner's row settled on IDs its own input never named.
- ///
- /// Returns `None` (rolling the transaction back) when the upsert's owner
- /// guard rejected the write: the message ID already exists but belongs to
- /// another inbox or is no longer an unsent draft. Defense-in-depth behind
- /// the handle resolution — validation reads can be raced, the guarded
- /// conflict clause cannot.
+ /// recipients, thread metadata update, and user history. Ordinary drafts never
+ /// schedule delivery; non-drafts may create an immediate-send undo window.
+ /// Lock and re-read client-handle bindings, bind handles to the final rows,
+ /// and return their authoritative IDs. Return None when an owner/sent guard
+ /// rejects the write; reject scheduled/processing identities transactionally.
+ /// If `new_thread` is Some, the thread is created inside the same transaction.
fn insert_message(
&self,
input: &ResolvedDraftInput,
@@ -312,7 +303,7 @@ pub trait EmailRepo: Send + Sync + 'static {
link_id: Uuid,
new_thread: Option<ThreadRow>,
is_draft: bool,
- ) -> impl Future<Output = Result<Option<SettledDraftIds>, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<SettledDraftIds>, EmailErr>> + Send;
/// Fetch a label by its database ID and link ID.
fn get_label_by_id(
diff --git a/crates/email/src/domain/scheduled.rs b/crates/email/src/domain/scheduled.rs
new file mode 100644
index 0000000000..b38097f116
--- /dev/null
+++ b/crates/email/src/domain/scheduled.rs
@@ -0,0 +1,141 @@
+//! Explicit scheduled-delivery transitions and their persistence boundary.
+
+pub use super::service::signature::SignaturePreparation;
+use chrono::{DateTime, Utc};
+use macro_event_broker::MacroEventBroker;
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use super::{
+ events::{
+ EmailMacroEvent, MessageSendCancelledMetadata, MessageSendQueuedMetadata, SendCancelReason,
+ },
+ models::EmailErr,
+ ports::EmailRepo,
+ service::EmailServiceImpl,
+};
+
+/// A user-confirmed change to a message's delivery schedule.
+#[derive(Debug, Clone, Copy)]
+pub enum ScheduleChange {
+ /// Commit or update a future delivery time.
+ Set(DateTime<Utc>),
+ /// Restore an unclaimed, unsent message to an editable draft.
+ Cancel,
+}
+
+/// Atomic persistence for schedule transitions. Implementations must serialize
+/// against claim/finalization and reject sent/processing messages. An absent
+/// schedule can only be cancelled idempotently for an unsent editable draft.
+pub trait EmailSchedulingRepo: Send + Sync {
+ /// Return the changed thread, or `None` for an already-cancelled draft.
+ fn change_schedule(
+ &self,
+ link_id: Uuid,
+ message_id: Uuid,
+ actor: &MacroUserIdStr<'_>,
+ change: ScheduleChange,
+ signature: Option<&SignaturePreparation>,
+ ) -> impl Future<Output = Result<Option<Uuid>, EmailErr>> + Send;
+}
+
+/// Authenticated explicit schedule/update/cancel use case.
+pub trait EmailSchedulingService: Send + Sync {
+ /// Authorize the actor's selected inbox and apply a guarded transition.
+ fn change_schedule(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ link_id: Uuid,
+ message_id: Uuid,
+ change: ScheduleChange,
+ include_signature: Option<bool>,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+}
+
+impl<T, U, E, CS, Eam, B> EmailSchedulingService for EmailServiceImpl<T, U, E, CS, Eam, B>
+where
+ T: EmailRepo + EmailSchedulingRepo,
+ U: Send + Sync,
+ E: Send + Sync,
+ CS: Send + Sync,
+ Eam: Send + Sync,
+ B: MacroEventBroker,
+ anyhow::Error: From<T::Err>,
+{
+ async fn change_schedule(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ link_id: Uuid,
+ message_id: Uuid,
+ change: ScheduleChange,
+ include_signature: Option<bool>,
+ ) -> Result<(), EmailErr> {
+ let link = self
+ .email_repo
+ .inboxes_for_macro_id(actor.clone())
+ .await
+ .map_err(anyhow::Error::from)?
+ .into_iter()
+ .find(|link| link.id == link_id)
+ .ok_or(EmailErr::Unauthorized)?;
+ validate_schedule_change(change, Utc::now())?;
+ let signature = if matches!(change, ScheduleChange::Set(_)) {
+ let settings = self.email_repo.fetch_email_settings(link_id).await
+ .inspect_err(|error| tracing::warn!(error=?error, "failed to fetch signature settings; skipping"))
+ .ok();
+ Some(SignaturePreparation {
+ settings,
+ include_signature,
+ })
+ } else {
+ None
+ };
+ let Some(thread_id) = self
+ .email_repo
+ .change_schedule(link_id, message_id, &actor, change, signature.as_ref())
+ .await?
+ else {
+ return Ok(());
+ };
+ let event = match change {
+ ScheduleChange::Set(send_time) => {
+ EmailMacroEvent::message_send_queued(MessageSendQueuedMetadata {
+ link_id,
+ owner: link.macro_id,
+ actor: Some(actor),
+ message_id,
+ thread_id,
+ scheduled_send_at: send_time,
+ is_scheduled: true,
+ })
+ }
+ ScheduleChange::Cancel => {
+ EmailMacroEvent::message_send_cancelled(MessageSendCancelledMetadata {
+ link_id,
+ owner: link.macro_id,
+ actor: Some(actor),
+ message_id,
+ thread_id,
+ reason: SendCancelReason::Undo,
+ })
+ }
+ };
+ self.publish_email_event(&event);
+ Ok(())
+ }
+}
+
+pub(crate) fn validate_schedule_change(
+ change: ScheduleChange,
+ now: DateTime<Utc>,
+) -> Result<(), EmailErr> {
+ if let ScheduleChange::Set(send_time) = change
+ && send_time <= now
+ {
+ return Err(EmailErr::InvalidScheduleTime);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email/src/domain/scheduled/test.rs b/crates/email/src/domain/scheduled/test.rs
new file mode 100644
index 0000000000..5d65a53ee7
--- /dev/null
+++ b/crates/email/src/domain/scheduled/test.rs
@@ -0,0 +1,16 @@
+use super::*;
+
+#[test]
+fn only_future_times_can_be_committed() {
+ let now = Utc::now();
+ assert!(validate_schedule_change(ScheduleChange::Set(now), now).is_err());
+ assert!(
+ validate_schedule_change(ScheduleChange::Set(now - chrono::Duration::seconds(1)), now)
+ .is_err()
+ );
+ assert!(
+ validate_schedule_change(ScheduleChange::Set(now + chrono::Duration::seconds(1)), now)
+ .is_ok()
+ );
+ assert!(validate_schedule_change(ScheduleChange::Cancel, now).is_ok());
+}
diff --git a/crates/email/src/domain/scheduled_delivery.rs b/crates/email/src/domain/scheduled_delivery.rs
new file mode 100644
index 0000000000..f42af356f3
--- /dev/null
+++ b/crates/email/src/domain/scheduled_delivery.rs
@@ -0,0 +1,64 @@
+//! Claim ownership for queue-driven email delivery. No database lock spans the
+//! provider call; only the invocation receiving a claim can release/finalize it.
+
+use uuid::Uuid;
+
+/// Atomic claim and completion persistence.
+pub trait ScheduledDeliveryRepo: Sync {
+ /// Proof that this invocation won the claim, including provider context.
+ type Claim: Send + Sync;
+ /// Provider result consumed by completion persistence.
+ type Sent: Send;
+
+ /// Claim a due, unsent, unclaimed message, committing before returning.
+ fn try_claim(
+ &self,
+ link_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = anyhow::Result<Option<Self::Claim>>> + Send;
+ /// Persist successful delivery and its post-commit side effects.
+ fn complete(
+ &self,
+ claim: &Self::Claim,
+ sent: Self::Sent,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
+ /// Release only this invocation's failed claim.
+ fn release(&self, claim: Self::Claim) -> impl Future<Output = anyhow::Result<()>> + Send;
+}
+
+/// Provider delivery, deliberately outside any persistence transaction.
+pub trait ScheduledMessageSender<Claim, Sent>: Sync {
+ /// Load the committed payload/attachments and send it through the provider.
+ fn send_claimed(&self, claim: &Claim) -> impl Future<Output = anyhow::Result<Sent>> + Send;
+}
+
+/// Deliver one queue item. Duplicate/stale items never release another worker's
+/// claim. Provider ambiguity/reconciliation retains the existing retry policy.
+pub async fn deliver_scheduled<R, S>(
+ repo: &R,
+ sender: &S,
+ link_id: Uuid,
+ message_id: Uuid,
+) -> anyhow::Result<()>
+where
+ R: ScheduledDeliveryRepo,
+ S: ScheduledMessageSender<R::Claim, R::Sent>,
+{
+ let Some(claim) = repo.try_claim(link_id, message_id).await? else {
+ return Ok(());
+ };
+ let result = async {
+ let sent = sender.send_claimed(&claim).await?;
+ repo.complete(&claim, sent).await
+ }
+ .await;
+ if result.is_err() {
+ let _ = repo.release(claim).await.inspect_err(|error| {
+ tracing::error!(error=?error, %message_id, %link_id, "failed to release owned delivery claim");
+ });
+ }
+ result
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email/src/domain/scheduled_delivery/test.rs b/crates/email/src/domain/scheduled_delivery/test.rs
new file mode 100644
index 0000000000..ee6debcb94
--- /dev/null
+++ b/crates/email/src/domain/scheduled_delivery/test.rs
@@ -0,0 +1,73 @@
+use super::*;
+use std::sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+};
+
+#[derive(Default)]
+struct Fake {
+ claimed: AtomicBool,
+ calls: Mutex<Vec<&'static str>>,
+ fail_send: bool,
+}
+
+impl ScheduledDeliveryRepo for Fake {
+ type Claim = ();
+ type Sent = ();
+
+ async fn try_claim(&self, _: Uuid, _: Uuid) -> anyhow::Result<Option<()>> {
+ self.calls.lock().unwrap().push("claim");
+ Ok((!self.claimed.swap(true, Ordering::SeqCst)).then_some(()))
+ }
+ async fn complete(&self, _: &(), _: ()) -> anyhow::Result<()> {
+ self.calls.lock().unwrap().push("complete");
+ Ok(())
+ }
+ async fn release(&self, _: ()) -> anyhow::Result<()> {
+ self.calls.lock().unwrap().push("release");
+ self.claimed.store(false, Ordering::SeqCst);
+ Ok(())
+ }
+}
+
+impl ScheduledMessageSender<(), ()> for Fake {
+ async fn send_claimed(&self, _: &()) -> anyhow::Result<()> {
+ self.calls.lock().unwrap().push("send");
+ anyhow::ensure!(!self.fail_send, "provider failed");
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn loser_never_sends_completes_or_releases_winner() {
+ let fake = Fake::default();
+ fake.claimed.store(true, Ordering::SeqCst);
+ deliver_scheduled(&fake, &fake, Uuid::nil(), Uuid::nil())
+ .await
+ .unwrap();
+ assert_eq!(*fake.calls.lock().unwrap(), ["claim"]);
+ assert!(fake.claimed.load(Ordering::SeqCst));
+}
+
+#[tokio::test]
+async fn successful_delivery_completes_without_a_late_release() {
+ let fake = Fake::default();
+ deliver_scheduled(&fake, &fake, Uuid::nil(), Uuid::nil())
+ .await
+ .unwrap();
+ assert_eq!(*fake.calls.lock().unwrap(), ["claim", "send", "complete"]);
+}
+
+#[tokio::test]
+async fn only_failed_winner_releases() {
+ let fake = Fake {
+ fail_send: true,
+ ..Fake::default()
+ };
+ assert!(
+ deliver_scheduled(&fake, &fake, Uuid::nil(), Uuid::nil())
+ .await
+ .is_err()
+ );
+ assert_eq!(*fake.calls.lock().unwrap(), ["claim", "send", "release"]);
+}
diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rs
index c29298f1f2..356cda0586 100644
--- a/crates/email/src/domain/service.rs
+++ b/crates/email/src/domain/service.rs
@@ -1,7 +1,7 @@
mod draft;
mod previews;
mod send;
-mod signature;
+pub(crate) mod signature;
mod thread;
mod thread_labels;
mod user;
diff --git a/crates/email/src/domain/service/draft.rs b/crates/email/src/domain/service/draft.rs
index 48b1a8ba16..f1897c3d36 100644
--- a/crates/email/src/domain/service/draft.rs
+++ b/crates/email/src/domain/service/draft.rs
@@ -28,8 +28,11 @@ where
&self,
link: &Link,
accessible_inboxes: &[Link],
- input: CreateDraftInput,
+ mut input: CreateDraftInput,
) -> Result<CreatedDraft, EmailErr> {
+ // Ordinary draft persistence never grants delivery authority. Keep the
+ // legacy field wire-compatible, but only explicit delivery can use it.
+ input.send_time = None;
self.prepare_and_insert_db_message(link, accessible_inboxes, input, true)
.await
}
@@ -243,6 +246,15 @@ where
if raced.is_some_and(|m| m.is_sent || !m.is_draft) {
return Err(EmailErr::MessageAlreadySent(draft_id));
}
+ if self
+ .email_repo
+ .scheduled_send_times_by_message_ids(&[msg.db_id])
+ .await
+ .map_err(anyhow::Error::from)?
+ .contains_key(&msg.db_id)
+ {
+ return Err(EmailErr::MessageDeliveryConflict(draft_id));
+ }
return Ok(DeletedUserDraft {
deleted: false,
thread_deleted: false,
@@ -339,17 +351,10 @@ where
let Some(settled) = self
.email_repo
.insert_message(&resolved, &contacts, link_id, new_thread, is_draft)
- .await
- .map_err(anyhow::Error::from)?
+ .await?
else {
- // The upsert's owner guard rejected the write: the row it landed
- // on is under another inbox or is no longer an unsent draft. Tell
- // the sent case apart, as the delete path does — the client
- // resets its composer on `MessageAlreadySent` but latches
- // autosave off on a not-found. Re-read through the handle when the
- // save carried one, since a concurrent first save may have
- // settled it on a row this save's input never named. Anything
- // else stays the opaque not-found the validation read reports.
+ // A concurrent first save can settle a client handle on a different
+ // row. Classify the authoritative row, not our discarded candidate.
let rejected_id = match resolved.draft_client_id {
Some(handle) => self
.email_repo
@@ -364,10 +369,20 @@ where
.get_simple_message(rejected_id, &accessible_link_ids)
.await
.map_err(anyhow::Error::from)?;
- if rejected.is_some_and(|m| m.is_sent || !m.is_draft) {
- return Err(EmailErr::MessageAlreadySent(resolved.db_id));
+ if rejected.as_ref().is_some_and(|m| m.is_sent || !m.is_draft) {
+ return Err(EmailErr::MessageAlreadySent(rejected_id));
}
- return Err(EmailErr::MessageNotFound(resolved.db_id));
+ if rejected.is_some()
+ && self
+ .email_repo
+ .scheduled_send_times_by_message_ids(&[rejected_id])
+ .await
+ .map_err(anyhow::Error::from)?
+ .contains_key(&rejected_id)
+ {
+ return Err(EmailErr::MessageDeliveryConflict(rejected_id));
+ }
+ return Err(EmailErr::MessageNotFound(rejected_id));
};
Ok(CreatedDraft {
@@ -394,64 +409,27 @@ where
/// forwards (a `replying_to_id` is present) require
/// `signature_on_replies_forwards`. Best-effort — any failure just skips.
async fn maybe_inject_signature(&self, link: &Link, input: &mut CreateDraftInput) {
- if input.include_signature == Some(false) {
- // Honor "exclude" literally: drop any server-wrapped signature a
- // client may have baked in, rather than just declining to add one.
- if input
+ let settings = if input.include_signature == Some(false)
+ || input
.body_html
.as_deref()
.is_some_and(super::signature::has_signature)
- && let Some(body_html) = input.body_html.take()
- {
- input.body_html = Some(super::signature::strip_signature(&body_html));
- }
- return;
- }
- // Idempotent: if the body already carries a signature — a client still
- // baking it in during the FE cutover, or a re-sent message — don't add
- // another (and leave body_text alone too).
- if input
- .body_html
- .as_deref()
- .is_some_and(super::signature::has_signature)
{
- return;
- }
- let settings = match self.email_repo.fetch_email_settings(link.id).await {
- Ok(settings) => settings,
- Err(e) => {
- tracing::warn!(error = ?e, "failed to fetch settings for signature; skipping");
- return;
- }
- };
- let Some(signature) = settings.signature.filter(|s| !s.trim().is_empty()) else {
- return;
- };
- let include = match input.include_signature {
- Some(value) => value,
- None => {
- if input.replying_to_id.is_some() {
- settings.signature_on_replies_forwards
- } else {
- true
- }
- }
+ None
+ } else {
+ self.email_repo.fetch_email_settings(link.id).await
+ .inspect_err(|error| tracing::warn!(error=?error, "failed to fetch settings for signature; skipping"))
+ .ok()
};
- if !include {
- return;
- }
- if let Some(body_html) = input.body_html.take() {
- input.body_html = Some(super::signature::inject_signature(&body_html, &signature));
- }
- let plain = super::signature::signature_plain_text(&signature);
- if !plain.is_empty()
- && let Some(existing) = input.body_text.take().filter(|s| !s.is_empty())
- {
- // Only append to an existing plain-text body. HTML-only sends
- // (body_text None/empty, e.g. the AI path) keep no text part rather
- // than getting a signature-only one that drops the message body.
- input.body_text = Some(format!("{existing}\n\n{plain}"));
+ super::signature::SignaturePreparation {
+ settings,
+ include_signature: input.include_signature,
}
+ .apply(
+ input.replying_to_id.is_some(),
+ &mut input.body_html,
+ &mut input.body_text,
+ );
}
async fn validate_existing_message(
@@ -490,13 +468,26 @@ where
// across the move, and the delete's cascade drops any client-handle
// binding — the save's binding upsert re-points the handle at the
// recreated row in the same transaction, so queued offline saves
- // keep converging. A raced delete (`None`) is fine — the row is
- // gone either way, and a raced send is caught by the insert's
- // owner guard.
- self.email_repo
+ // keep converging. A guarded miss may instead mean the source is
+ // now scheduled: do not continue and adopt another reply draft in
+ // the target inbox while that committed source is still present.
+ let deleted = self
+ .email_repo
.delete_draft_message(msg.db_id, msg.thread_db_id, accessible_link_ids)
.await
.map_err(anyhow::Error::from)?;
+ if deleted.is_none()
+ && let Some(retained) = self
+ .email_repo
+ .get_simple_message(msg.db_id, accessible_link_ids)
+ .await
+ .map_err(anyhow::Error::from)?
+ {
+ if retained.is_sent || !retained.is_draft {
+ return Err(EmailErr::MessageAlreadySent(msg.db_id));
+ }
+ return Err(EmailErr::MessageDeliveryConflict(msg.db_id));
+ }
input.provider_id = None;
input.thread_db_id = None;
input.provider_thread_id = None;
diff --git a/crates/email/src/domain/service/signature.rs b/crates/email/src/domain/service/signature.rs
index 744c6e8775..b258e42cbf 100644
--- a/crates/email/src/domain/service/signature.rs
+++ b/crates/email/src/domain/service/signature.rs
@@ -9,6 +9,62 @@ mod test;
/// Marker class wrapping an injected signature.
const SIGNATURE_CLASS: &str = "macro-email-signature";
+/// Pure send-time signature policy, shared by immediate and scheduled delivery.
+/// Settings are fetched before entering the persistence transaction; application
+/// uses the current locked body so an autosave cannot race body preparation.
+#[derive(Debug, Clone, Default)]
+pub struct SignaturePreparation {
+ pub(crate) settings: Option<crate::domain::ports::LinkEmailSettings>,
+ pub(crate) include_signature: Option<bool>,
+}
+
+impl SignaturePreparation {
+ /// Apply the existing per-message override and inbox reply/forward defaults.
+ pub fn apply(
+ &self,
+ is_reply: bool,
+ body_html: &mut Option<String>,
+ body_text: &mut Option<String>,
+ ) {
+ if self.include_signature == Some(false) {
+ if body_html.as_deref().is_some_and(has_signature)
+ && let Some(html) = body_html.take()
+ {
+ *body_html = Some(strip_signature(&html));
+ }
+ return;
+ }
+ if body_html.as_deref().is_some_and(has_signature) {
+ return;
+ }
+ let Some(settings) = &self.settings else {
+ return;
+ };
+ let Some(signature) = settings
+ .signature
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ else {
+ return;
+ };
+ if !self
+ .include_signature
+ .unwrap_or(!is_reply || settings.signature_on_replies_forwards)
+ {
+ return;
+ }
+ if let Some(html) = body_html.take() {
+ *body_html = Some(inject_signature(&html, signature));
+ }
+ let plain = signature_plain_text(signature);
+ if !plain.is_empty()
+ && let Some(existing) = body_text.take().filter(|s| !s.is_empty())
+ {
+ *body_text = Some(format!("{existing}\n\n{plain}"));
+ }
+ }
+}
+
/// Whether the body already carries our signature in its own content (idempotency
/// for re-sends / an old client that still bakes it in). A signature inside a
/// quoted thread (`.macro_quote`) is the replied-to message's and is ignored.
diff --git a/crates/email/src/domain/service/signature/test.rs b/crates/email/src/domain/service/signature/test.rs
index ea937fd122..550af70e0e 100644
--- a/crates/email/src/domain/service/signature/test.rs
+++ b/crates/email/src/domain/service/signature/test.rs
@@ -1,5 +1,44 @@
use super::*;
+#[test]
+fn shared_send_preparation_respects_reply_defaults_and_explicit_override() {
+ let mut preparation = SignaturePreparation {
+ settings: Some(crate::domain::ports::LinkEmailSettings {
+ signature: Some("<p>Regards</p>".into()),
+ signature_on_replies_forwards: false,
+ }),
+ include_signature: None,
+ };
+ let mut html = Some("<p>Hello</p>".to_owned());
+ let mut text = Some("Hello".to_owned());
+ preparation.apply(true, &mut html, &mut text);
+ assert!(!has_signature(html.as_deref().unwrap()));
+ preparation.include_signature = Some(true);
+ preparation.apply(true, &mut html, &mut text);
+ preparation.apply(true, &mut html, &mut text);
+ assert_eq!(html.as_deref().unwrap().matches(SIGNATURE_CLASS).count(), 1);
+ assert_eq!(text.as_deref(), Some("Hello\n\nRegards"));
+ preparation.include_signature = Some(false);
+ preparation.apply(true, &mut html, &mut text);
+ assert!(!has_signature(html.as_deref().unwrap()));
+}
+
+#[test]
+fn signature_preparation_preserves_html_only_delivery() {
+ let preparation = SignaturePreparation {
+ settings: Some(crate::domain::ports::LinkEmailSettings {
+ signature: Some("<p>Regards</p>".into()),
+ signature_on_replies_forwards: false,
+ }),
+ include_signature: None,
+ };
+ let mut html = Some("<p>Hello</p>".to_owned());
+ let mut text = None;
+ preparation.apply(false, &mut html, &mut text);
+ assert!(has_signature(html.as_deref().unwrap()));
+ assert!(text.is_none());
+}
+
#[test]
fn appends_to_body_after_message_when_no_quote() {
let out = inject_signature("<body><p>Hi there</p></body>", "<p>Regards</p>");
diff --git a/crates/email/src/inbound/axum/draft_router.rs b/crates/email/src/inbound/axum/draft_router.rs
index 99ff0c1008..618bab6956 100644
--- a/crates/email/src/inbound/axum/draft_router.rs
+++ b/crates/email/src/inbound/axum/draft_router.rs
@@ -68,6 +68,7 @@ impl From<EmailErr> for CreateDraftError {
CreateDraftError::NotFound(err.to_string())
}
EmailErr::MessageAlreadySent(_)
+ | EmailErr::MessageDeliveryConflict(_)
| EmailErr::CannotReplyToDraft
| EmailErr::Base64DecodeError(_)
| EmailErr::Utf8Error(_) => CreateDraftError::Validation(err.to_string()),
diff --git a/crates/email/src/inbound/axum/send_router.rs b/crates/email/src/inbound/axum/send_router.rs
index ca94dce447..505ba94b87 100644
--- a/crates/email/src/inbound/axum/send_router.rs
+++ b/crates/email/src/inbound/axum/send_router.rs
@@ -68,6 +68,7 @@ impl From<EmailErr> for SendMessageError {
match &err {
EmailErr::MessageNotFound(_) => SendMessageError::NotFound(err.to_string()),
EmailErr::MessageAlreadySent(_)
+ | EmailErr::MessageDeliveryConflict(_)
| EmailErr::CannotReplyToDraft
| EmailErr::Base64DecodeError(_)
| EmailErr::Utf8Error(_) => SendMessageError::Validation(err.to_string()),
diff --git a/crates/email/src/outbound/email_pg_repo.rs b/crates/email/src/outbound/email_pg_repo.rs
index 7b30e4b5ca..dec8537d85 100644
--- a/crates/email/src/outbound/email_pg_repo.rs
+++ b/crates/email/src/outbound/email_pg_repo.rs
@@ -27,6 +27,7 @@ mod message;
mod preview;
mod preview_views;
mod project;
+mod scheduled;
mod settings;
mod thread;
@@ -307,7 +308,7 @@ impl EmailRepo for EmailPgRepo {
link_id: Uuid,
new_thread: Option<ThreadRow>,
is_draft: bool,
- ) -> Result<Option<SettledDraftIds>, Self::Err> {
+ ) -> Result<Option<SettledDraftIds>, EmailErr> {
draft::insert_message(&self.pool, input, contacts, link_id, new_thread, is_draft).await
}
diff --git a/crates/email/src/outbound/email_pg_repo/draft.rs b/crates/email/src/outbound/email_pg_repo/draft.rs
index b153c95454..f7d64e6fb1 100644
--- a/crates/email/src/outbound/email_pg_repo/draft.rs
+++ b/crates/email/src/outbound/email_pg_repo/draft.rs
@@ -1,5 +1,7 @@
use super::{client_id_mapping, message, thread};
-use crate::domain::models::{ResolvedDraftInput, SettledDraftIds, ThreadRow, UpsertedContacts};
+use crate::domain::models::{
+ EmailErr, ResolvedDraftInput, SettledDraftIds, ThreadRow, UpsertedContacts,
+};
use chrono::Utc;
use sqlx::PgPool;
use uuid::Uuid;
@@ -18,8 +20,8 @@ pub(crate) async fn insert_message(
link_id: Uuid,
new_thread: Option<ThreadRow>,
is_draft: bool,
-) -> Result<Option<SettledDraftIds>, sqlx::Error> {
- let mut tx = pool.begin().await?;
+) -> Result<Option<SettledDraftIds>, EmailErr> {
+ let mut tx = pool.begin().await.map_err(anyhow::Error::from)?;
let mut settled = SettledDraftIds {
message_db_id: input.db_id,
@@ -34,8 +36,12 @@ pub(crate) async fn insert_message(
// handle and re-read the binding under the lock: the loser adopts the row
// the winner settled on and updates it instead.
if let Some(client_id) = input.draft_client_id {
- client_id_mapping::lock_draft_client_id(&mut tx, client_id, link_id).await?;
- if let Some(bound) = client_id_mapping::bound_draft_row(&mut tx, client_id, link_id).await?
+ client_id_mapping::lock_draft_client_id(&mut tx, client_id, link_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if let Some(bound) = client_id_mapping::bound_draft_row(&mut tx, client_id, link_id)
+ .await
+ .map_err(anyhow::Error::from)?
&& bound.message_db_id != settled.message_db_id
{
settled = bound;
@@ -49,11 +55,36 @@ pub(crate) async fn insert_message(
thread_db_id,
} = settled;
+ // Serialize with schedule/cancel/claim before checking editability. The
+ // domain's earlier read cannot protect a save waiting on this transaction.
+ let existing = sqlx::query!(
+ "SELECT link_id, is_sent, is_draft FROM email_messages WHERE id = $1 FOR UPDATE",
+ message_db_id,
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ let was_missing = existing.is_none();
+ if let Some(existing) = existing {
+ if existing.link_id != link_id || existing.is_sent || !existing.is_draft {
+ return Ok(None);
+ }
+ let scheduled = sqlx::query_scalar!(
+ "SELECT EXISTS(SELECT 1 FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2) AS \"exists!\"",
+ message_db_id, link_id,
+ ).fetch_one(&mut *tx).await.map_err(anyhow::Error::from)?;
+ if scheduled {
+ return Err(EmailErr::MessageDeliveryConflict(message_db_id));
+ }
+ }
+
if let Some(thread) = new_thread {
- thread::insert_thread(&mut tx, &thread, link_id).await?;
+ thread::insert_thread(&mut tx, &thread, link_id)
+ .await
+ .map_err(anyhow::Error::from)?;
}
- let applied = upsert_draft(
+ let updated = upsert_draft(
&mut tx,
input,
message_db_id,
@@ -62,15 +93,29 @@ pub(crate) async fn insert_message(
link_id,
is_draft,
)
- .await?;
- if !applied {
- tx.rollback().await?;
+ .await
+ .map_err(anyhow::Error::from)?;
+ if !updated {
return Ok(None);
}
- // Only touch scheduling if send_time is explicitly provided.
- // Scheduling is managed via the dedicated /drafts/scheduled endpoints.
- if input.send_time.is_some() {
+ // A first save can miss an uncommitted insert in the initial SELECT, then
+ // wait on its unique-key conflict. ON CONFLICT's subquery keeps that older
+ // statement snapshot, so recheck after the upsert owns the message lock.
+ // A concurrent insert+schedule must roll back this entire stale write.
+ if was_missing {
+ let scheduled = sqlx::query_scalar!(
+ "SELECT EXISTS(SELECT 1 FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2) AS \"exists!\"",
+ message_db_id, link_id,
+ ).fetch_one(&mut *tx).await.map_err(anyhow::Error::from)?;
+ if scheduled {
+ return Err(EmailErr::MessageDeliveryConflict(message_db_id));
+ }
+ }
+
+ // Only immediate Send persists its internal undo-window delivery here.
+ // Ordinary draft writes never touch scheduling, even for legacy clients.
+ if !is_draft && input.send_time.is_some() {
message::process_scheduled_message(
&mut tx,
link_id,
@@ -78,25 +123,36 @@ pub(crate) async fn insert_message(
input.send_time,
input.actor_id.as_deref(),
)
- .await?;
+ .await
+ .map_err(anyhow::Error::from)?;
}
- message::upsert_recipients(&mut tx, message_db_id, contacts).await?;
+ message::upsert_recipients(&mut tx, message_db_id, contacts)
+ .await
+ .map_err(anyhow::Error::from)?;
- thread::update_thread_metadata(&mut tx, thread_db_id, link_id).await?;
+ thread::update_thread_metadata(&mut tx, thread_db_id, link_id)
+ .await
+ .map_err(anyhow::Error::from)?;
- thread::upsert_user_history(&mut tx, link_id, thread_db_id).await?;
+ thread::upsert_user_history(&mut tx, link_id, thread_db_id)
+ .await
+ .map_err(anyhow::Error::from)?;
- // Bind client handles to the settled rows in the same transaction, so a
- // replayed offline save resolves to this row instead of creating another.
+ // Persist handles with the actual settled identity, including a concurrent
+ // first-save winner and a draft recreated after sender migration.
if let Some(client_id) = input.draft_client_id {
- client_id_mapping::bind_draft_client_id(&mut tx, client_id, link_id, message_db_id).await?;
+ client_id_mapping::bind_draft_client_id(&mut tx, client_id, link_id, message_db_id)
+ .await
+ .map_err(anyhow::Error::from)?;
}
if let Some(client_id) = input.thread_client_id {
- client_id_mapping::bind_thread_client_id(&mut tx, client_id, link_id, thread_db_id).await?;
+ client_id_mapping::bind_thread_client_id(&mut tx, client_id, link_id, thread_db_id)
+ .await
+ .map_err(anyhow::Error::from)?;
}
- tx.commit().await?;
+ tx.commit().await.map_err(anyhow::Error::from)?;
Ok(Some(settled))
}
@@ -146,8 +202,8 @@ pub(crate) async fn upsert_draft(
headers_jsonb = EXCLUDED.headers_jsonb,
updated_at = NOW()
WHERE email_messages.link_id = EXCLUDED.link_id
- AND email_messages.is_draft
- AND NOT email_messages.is_sent
+ AND email_messages.is_draft AND NOT email_messages.is_sent
+ AND NOT EXISTS (SELECT 1 FROM email_scheduled_messages WHERE message_id = EXCLUDED.id AND link_id = EXCLUDED.link_id)
"#,
message_db_id,
input.provider_id,
@@ -173,5 +229,5 @@ pub(crate) async fn upsert_draft(
.execute(&mut *tx)
.await?;
- Ok(result.rows_affected() > 0)
+ Ok(result.rows_affected() == 1)
}
diff --git a/crates/email/src/outbound/email_pg_repo/message.rs b/crates/email/src/outbound/email_pg_repo/message.rs
index 239a42dedc..1fb8b248af 100644
--- a/crates/email/src/outbound/email_pg_repo/message.rs
+++ b/crates/email/src/outbound/email_pg_repo/message.rs
@@ -373,14 +373,20 @@ pub(crate) async fn delete_draft_message(
) -> Result<Option<DraftDeletion>, sqlx::Error> {
let mut tx = pool.begin().await?;
+ // Sender migration must not delete a draft whose delivery was committed
+ // after the service's initial validation. Match the shared lock order.
+ sqlx::query!(
+ "SELECT id FROM email_messages WHERE id = $1 FOR UPDATE",
+ message_id
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+
let deleted_link_id = sqlx::query_scalar!(
r#"
DELETE FROM email_messages
- WHERE id = $1
- AND thread_id = $2
- AND link_id = ANY($3)
- AND is_draft = true
- AND is_sent = false
+ WHERE id = $1 AND thread_id = $2 AND link_id = ANY($3) AND is_draft = true AND is_sent = false
+ AND NOT EXISTS (SELECT 1 FROM email_scheduled_messages WHERE message_id = $1 AND link_id = email_messages.link_id)
RETURNING link_id
"#,
message_id,
@@ -437,9 +443,9 @@ pub(super) async fn process_scheduled_message(
VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
ON CONFLICT (link_id, message_id) DO UPDATE SET
send_time = EXCLUDED.send_time,
- sent = EXCLUDED.sent,
actor_id = EXCLUDED.actor_id,
updated_at = NOW()
+ WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing
"#,
link_id,
message_db_id,
diff --git a/crates/email/src/outbound/email_pg_repo/scheduled.rs b/crates/email/src/outbound/email_pg_repo/scheduled.rs
new file mode 100644
index 0000000000..23d67a6e52
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/scheduled.rs
@@ -0,0 +1,104 @@
+use super::EmailPgRepo;
+use crate::domain::{
+ models::EmailErr,
+ scheduled::{EmailSchedulingRepo, ScheduleChange, SignaturePreparation},
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+impl EmailSchedulingRepo for EmailPgRepo {
+ async fn change_schedule(
+ &self,
+ link_id: Uuid,
+ message_id: Uuid,
+ actor: &MacroUserIdStr<'_>,
+ change: ScheduleChange,
+ signature: Option<&SignaturePreparation>,
+ ) -> Result<Option<Uuid>, EmailErr> {
+ change_schedule(&self.pool, link_id, message_id, actor, change, signature).await
+ }
+}
+
+async fn change_schedule(
+ pool: &sqlx::PgPool,
+ link_id: Uuid,
+ message_id: Uuid,
+ actor: &MacroUserIdStr<'_>,
+ change: ScheduleChange,
+ signature: Option<&SignaturePreparation>,
+) -> Result<Option<Uuid>, EmailErr> {
+ let mut tx = pool.begin().await.map_err(anyhow::Error::from)?;
+ // Every mutator locks message before schedule; no locks cross provider work.
+ let message = sqlx::query!(
+ "SELECT thread_id, is_draft, is_sent, replying_to_id, body_html_sanitized, body_text FROM email_messages WHERE id = $1 AND link_id = $2 FOR UPDATE",
+ message_id, link_id,
+ ).fetch_optional(&mut *tx).await.map_err(anyhow::Error::from)?
+ .ok_or(EmailErr::MessageNotFound(message_id))?;
+ let schedule = sqlx::query!(
+ "SELECT sent, processing FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2 FOR UPDATE",
+ message_id, link_id,
+ ).fetch_optional(&mut *tx).await.map_err(anyhow::Error::from)?;
+ if message.is_sent
+ || schedule
+ .as_ref()
+ .is_some_and(|row| row.sent || row.processing)
+ {
+ return Err(EmailErr::MessageDeliveryConflict(message_id));
+ }
+ match change {
+ ScheduleChange::Set(send_time) => {
+ if !message.is_draft {
+ return Err(EmailErr::MessageDeliveryConflict(message_id));
+ }
+ // Check again after acquiring locks so a delayed request cannot
+ // commit a time that expired while waiting for another transaction.
+ crate::domain::scheduled::validate_schedule_change(change, chrono::Utc::now())?;
+ // A confirmed time-only update must preserve the committed payload.
+ if schedule.is_none()
+ && let Some(signature) = signature
+ {
+ let mut html = message.body_html_sanitized;
+ let mut text = message.body_text;
+ signature.apply(message.replying_to_id.is_some(), &mut html, &mut text);
+ sqlx::query!(
+ "UPDATE email_messages SET body_html_sanitized = $1, body_text = $2, updated_at = NOW() WHERE id = $3 AND link_id = $4",
+ html, text, message_id, link_id,
+ ).execute(&mut *tx).await.map_err(anyhow::Error::from)?;
+ }
+ let updated = sqlx::query!(
+ r#"INSERT INTO email_scheduled_messages
+ (link_id, message_id, send_time, sent, processing, actor_id, created_at, updated_at)
+ VALUES ($1, $2, $3, false, false, $4, NOW(), NOW())
+ ON CONFLICT (link_id, message_id) DO UPDATE SET
+ send_time = EXCLUDED.send_time, actor_id = EXCLUDED.actor_id, updated_at = NOW()
+ WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing"#,
+ link_id, message_id, send_time, actor.as_ref(),
+ ).execute(&mut *tx).await.map_err(anyhow::Error::from)?;
+ if updated.rows_affected() != 1 {
+ return Err(EmailErr::MessageDeliveryConflict(message_id));
+ }
+ }
+ ScheduleChange::Cancel => {
+ if schedule.is_none() {
+ return if message.is_draft {
+ Ok(None)
+ } else {
+ Err(EmailErr::MessageDeliveryConflict(message_id))
+ };
+ }
+ let deleted = sqlx::query!(
+ "DELETE FROM email_scheduled_messages WHERE link_id = $1 AND message_id = $2 AND NOT sent AND NOT processing",
+ link_id, message_id,
+ ).execute(&mut *tx).await.map_err(anyhow::Error::from)?;
+ if deleted.rows_affected() != 1 {
+ return Err(EmailErr::MessageDeliveryConflict(message_id));
+ }
+ sqlx::query!(
+ "UPDATE email_messages SET is_draft = true, updated_at = NOW() WHERE id = $1 AND link_id = $2 AND NOT is_sent",
+ message_id, link_id,
+ ).execute(&mut *tx).await.map_err(anyhow::Error::from)?;
+ }
+ }
+ tx.commit().await.map_err(anyhow::Error::from)?;
+ Ok(Some(message.thread_id))
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rs
index 6d56ffc8b2..4b2324911e 100644
--- a/crates/email/src/outbound/email_pg_repo/test.rs
+++ b/crates/email/src/outbound/email_pg_repo/test.rs
@@ -9,6 +9,7 @@ mod message;
mod preview;
mod project;
mod project_scope_dynamic_query;
+mod scheduled;
mod settings;
mod signal_flag;
mod thread;
diff --git a/crates/email/src/outbound/email_pg_repo/test/draft.rs b/crates/email/src/outbound/email_pg_repo/test/draft.rs
index c8df6b68aa..d74dbde025 100644
--- a/crates/email/src/outbound/email_pg_repo/test/draft.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/draft.rs
@@ -697,8 +697,9 @@ async fn test_insert_draft_message_with_new_thread(pool: Pool<Postgres>) -> anyh
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../../fixtures", scripts("email_draft"))
)]
-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
-async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn test_autosave_ignores_send_time_but_immediate_send_preserves_undo_schedule(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
let repo = EmailPgRepo::new(pool.clone());
let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
@@ -735,15 +736,27 @@ async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) ->
repo.insert_message(&input, &contacts, link_id, None, true)
.await?;
- // Verify the scheduled message was created
- let row =
- sqlx::query("SELECT send_time, sent FROM email_scheduled_messages WHERE message_id = $1")
- .bind(message_db_id)
- .fetch_one(&pool)
- .await?;
+ let absent = sqlx::query!(
+ "SELECT send_time FROM email_scheduled_messages WHERE message_id = $1",
+ message_db_id
+ )
+ .fetch_optional(&pool)
+ .await?;
+ assert!(
+ absent.is_none(),
+ "ordinary autosave cannot commit a schedule"
+ );
- assert_eq!(row.get::<chrono::DateTime<Utc>, _>("send_time"), send_time);
- assert!(!row.get::<bool, _>("sent"));
+ repo.insert_message(&input, &contacts, link_id, None, false)
+ .await?;
+ let row = sqlx::query!(
+ "SELECT send_time, sent FROM email_scheduled_messages WHERE message_id = $1",
+ message_db_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(row.send_time, send_time);
+ assert!(!row.sent);
Ok(())
}
@@ -1188,6 +1201,73 @@ async fn test_save_racing_a_committed_binding_adopts_it(
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn test_client_handle_replay_cannot_replace_a_scheduled_or_sent_winner(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ use crate::domain::scheduled::{EmailSchedulingRepo, ScheduleChange};
+
+ let repo = EmailPgRepo::new(pool.clone());
+ let link = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let handle = macro_uuid::generate_uuid_v7();
+ let actor = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let contacts = UpsertedContacts {
+ from_contact_id: None,
+ recipients: vec![],
+ };
+ let (winner, winner_thread, winner_id) = first_save_of(handle, link, "confirmed content");
+ repo.insert_message(&winner, &contacts, link, Some(winner_thread), true)
+ .await?
+ .expect("the first save applies");
+ repo.change_schedule(
+ link,
+ winner_id,
+ &actor,
+ ScheduleChange::Set(Utc::now() + chrono::Duration::hours(1)),
+ None,
+ )
+ .await?;
+
+ // This queued save was captured before the first save confirmed its IDs.
+ let (replay, replay_thread, replay_id) = first_save_of(handle, link, "stale queued content");
+ assert!(matches!(
+ repo.insert_message(&replay, &contacts, link, Some(replay_thread.clone()), true)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(id)) if id == winner_id
+ ));
+ assert!(!message_exists(&pool, replay_id).await?);
+ assert!(!thread_exists(&pool, replay_thread.db_id).await?);
+ assert_eq!(
+ repo.message_id_for_client_draft_id(handle, &[link]).await?,
+ Some(winner_id)
+ );
+ let subject = sqlx::query_scalar!(
+ "SELECT subject FROM email_messages WHERE id = $1",
+ winner_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(subject.as_deref(), Some("confirmed content"));
+
+ sqlx::query!(
+ "UPDATE email_messages SET is_sent = true, is_draft = false WHERE id = $1",
+ winner_id
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ repo.insert_message(&replay, &contacts, link, Some(replay_thread.clone()), true)
+ .await?
+ .is_none()
+ );
+ assert!(!message_exists(&pool, replay_id).await?);
+ assert!(!thread_exists(&pool, replay_thread.db_id).await?);
+ Ok(())
+}
+
// A handle can name a binding under more than one accessible inbox when a
// move's cascade did not land, and the lookup breaks that tie by recency. A
// rebind has to count as the newest binding, or the handle keeps resolving to
diff --git a/crates/email/src/outbound/email_pg_repo/test/scheduled.rs b/crates/email/src/outbound/email_pg_repo/test/scheduled.rs
new file mode 100644
index 0000000000..a02ef8a0a6
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/test/scheduled.rs
@@ -0,0 +1,636 @@
+use super::*;
+use crate::domain::scheduled::{EmailSchedulingRepo, EmailSchedulingService, ScheduleChange};
+use crate::domain::service::EmailServiceImpl;
+use email_db_client::messages::scheduled::get::get_and_start_processing_scheduled_message;
+use macro_event_broker::NoopMacroEventBroker;
+
+fn identity() -> (Uuid, Uuid) {
+ (
+ Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(),
+ Uuid::parse_str("ee000002-0000-0000-0000-000000000002").unwrap(),
+ )
+}
+
+fn actor() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+fn future() -> ScheduleChange {
+ ScheduleChange::Set(Utc::now() + chrono::Duration::hours(1))
+}
+
+async fn wait_for_transaction_waiter(pool: &Pool<Postgres>, blocker: i32) -> anyhow::Result<()> {
+ tokio::time::timeout(std::time::Duration::from_secs(10), async {
+ loop {
+ let waiting = sqlx::query_scalar!(
+ "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND $1 = ANY(pg_blocking_pids(pid))) AS \"exists!\"",
+ blocker,
+ ).fetch_one(pool).await?;
+ if waiting {
+ return Ok::<_, sqlx::Error>(());
+ }
+ tokio::task::yield_now().await;
+ }
+ }).await??;
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn schedule_update_cancel_is_atomic_and_idempotent(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, message) = identity();
+ assert!(
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?
+ .is_some()
+ );
+ let later = Utc::now() + chrono::Duration::hours(2);
+ repo.change_schedule(link, message, &actor(), ScheduleChange::Set(later), None)
+ .await?;
+ let schedule = sqlx::query!(
+ "SELECT send_time, sent, processing FROM email_scheduled_messages WHERE message_id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(
+ schedule.send_time.timestamp_micros(),
+ later.timestamp_micros()
+ );
+ assert!(!schedule.sent && !schedule.processing);
+ assert!(
+ repo.change_schedule(link, message, &actor(), ScheduleChange::Cancel, None)
+ .await?
+ .is_some()
+ );
+ assert!(
+ repo.change_schedule(link, message, &actor(), ScheduleChange::Cancel, None)
+ .await?
+ .is_none()
+ );
+ let wrong_link = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc")?;
+ assert!(matches!(
+ repo.change_schedule(wrong_link, message, &actor(), ScheduleChange::Cancel, None)
+ .await,
+ Err(EmailErr::MessageNotFound(_))
+ ));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn sent_or_claimed_delivery_rejects_update_cancel_and_migration(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, message) = identity();
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ sqlx::query!(
+ "UPDATE email_scheduled_messages SET processing = true WHERE message_id = $1",
+ message
+ )
+ .execute(&pool)
+ .await?;
+ for change in [future(), ScheduleChange::Cancel] {
+ assert!(matches!(
+ repo.change_schedule(link, message, &actor(), change, None)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ }
+ assert!(
+ repo.delete_draft_message(
+ message,
+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?,
+ &[link],
+ )
+ .await?
+ .is_none()
+ );
+ sqlx::query!(
+ "UPDATE email_scheduled_messages SET processing = false, sent = true WHERE message_id = $1",
+ message
+ )
+ .execute(&pool)
+ .await?;
+ assert!(matches!(
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ let sent_message = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;
+ assert!(matches!(
+ repo.change_schedule(link, sent_message, &actor(), future(), None)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn service_authorizes_actor_and_validates_future_time(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let service = EmailServiceImpl {
+ email_repo: EmailPgRepo::new(pool),
+ frecency_service: (),
+ enqueuer: (),
+ crm_service: (),
+ entity_access_management_service: (),
+ macro_event_broker: NoopMacroEventBroker,
+ sent_undo_delay_secs: 5,
+ };
+ let (link, message) = identity();
+ let stranger = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ assert!(matches!(
+ service
+ .change_schedule(stranger, link, message, future(), None)
+ .await,
+ Err(EmailErr::Unauthorized)
+ ));
+ assert!(matches!(
+ service
+ .change_schedule(
+ actor(),
+ link,
+ message,
+ ScheduleChange::Set(Utc::now()),
+ None
+ )
+ .await,
+ Err(EmailErr::InvalidScheduleTime)
+ ));
+ service
+ .change_schedule(actor(), link, message, future(), None)
+ .await?;
+ service
+ .change_schedule(actor(), link, message, ScheduleChange::Cancel, None)
+ .await?;
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn scheduled_source_rejects_delete_and_migration_into_existing_reply(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ use crate::domain::models::CreateDraftInput;
+ use crate::domain::ports::NoOpEnqueuer;
+ use crm::domain::service::NoOpCrmService;
+ use frecency::{
+ domain::services::FrecencyQueryServiceImpl, outbound::postgres::FrecencyPgStorage,
+ };
+
+ let service = EmailServiceImpl {
+ email_repo: EmailPgRepo::new(pool.clone()),
+ frecency_service: FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(pool.clone())),
+ enqueuer: NoOpEnqueuer,
+ crm_service: NoOpCrmService,
+ entity_access_management_service: (),
+ macro_event_broker: NoopMacroEventBroker,
+ sent_undo_delay_secs: 5,
+ };
+ let (link, message) = identity();
+ service
+ .change_schedule(actor(), link, message, future(), None)
+ .await?;
+ assert!(matches!(
+ service.delete_draft_for_user_impl(actor(), message).await,
+ Err(EmailErr::MessageDeliveryConflict(id)) if id == message
+ ));
+ let target_link = Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc")?;
+ let target_draft = Uuid::parse_str("ee000005-0000-0000-0000-000000000005")?;
+ let input = CreateDraftInput {
+ db_id: Some(message),
+ provider_id: None,
+ replying_to_id: Some(Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?),
+ provider_thread_id: None,
+ thread_db_id: None,
+ subject: "must not overwrite the target reply".to_string(),
+ to: vec![],
+ cc: vec![],
+ bcc: vec![],
+ body_text: Some("stale autosave".to_string()),
+ body_html: None,
+ body_macro: None,
+ headers_json: None,
+ send_time: None,
+ include_signature: None,
+ actor: None,
+ draft_client_binding: None,
+ thread_client_binding: None,
+ };
+ assert!(matches!(
+ service.save_draft_for_user_impl(actor(), Some(target_link), input).await,
+ Err(EmailErr::MessageDeliveryConflict(id)) if id == message
+ ));
+ let subject = sqlx::query_scalar!(
+ "SELECT subject FROM email_messages WHERE id = $1",
+ target_draft
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(subject.as_deref(), Some("Re: Hello World"));
+ assert!(
+ service
+ .email_repo
+ .get_simple_message(message, &[link])
+ .await?
+ .is_some()
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn waiting_transition_observes_committed_claim(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, message) = identity();
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ let mut tx = pool.begin().await?;
+ let blocker = sqlx::query_scalar!("SELECT pg_backend_pid() AS \"pid!\"")
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "SELECT id FROM email_messages WHERE id = $1 FOR UPDATE",
+ message
+ )
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "UPDATE email_scheduled_messages SET processing = true WHERE message_id = $1",
+ message
+ )
+ .execute(&mut *tx)
+ .await?;
+ let cancel = tokio::spawn(async move {
+ repo.change_schedule(link, message, &actor(), ScheduleChange::Cancel, None)
+ .await
+ });
+ wait_for_transaction_waiter(&pool, blocker).await?;
+ tx.commit().await?;
+ assert!(matches!(
+ cancel.await?,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ Ok(())
+}
+
+fn stale_input(message: Uuid) -> ResolvedDraftInput {
+ ResolvedDraftInput {
+ db_id: message,
+ provider_id: None,
+ replying_to_id: None,
+ provider_thread_id: None,
+ thread_db_id: Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),
+ subject: "stale autosave".into(),
+ to: vec![],
+ cc: vec![],
+ bcc: vec![],
+ body_text: None,
+ body_html: None,
+ body_macro: None,
+ headers_json: None,
+ send_time: None,
+ actor_id: None,
+ draft_client_id: None,
+ thread_client_id: None,
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn stale_autosave_cannot_mutate_confirmed_claimed_or_sent_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, message) = identity();
+ let input = stale_input(message);
+ let contacts = UpsertedContacts {
+ from_contact_id: None,
+ recipients: vec![],
+ };
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ assert!(matches!(
+ repo.insert_message(&input, &contacts, link, None, true)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ sqlx::query!("UPDATE email_scheduled_messages SET send_time = NOW() - INTERVAL '1 minute' WHERE message_id = $1", message)
+ .execute(&pool).await?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_some()
+ );
+ assert!(matches!(
+ repo.insert_message(&input, &contacts, link, None, true)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ let mut tx = pool.begin().await?;
+ let blocker = sqlx::query_scalar!("SELECT pg_backend_pid() AS \"pid!\"")
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "UPDATE email_messages SET is_sent = true, is_draft = false WHERE id = $1",
+ message
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "UPDATE email_scheduled_messages SET sent = true, processing = false WHERE message_id = $1",
+ message
+ )
+ .execute(&mut *tx)
+ .await?;
+ let save = tokio::spawn(async move {
+ repo.insert_message(&input, &contacts, link, None, true)
+ .await
+ });
+ wait_for_transaction_waiter(&pool, blocker).await?;
+ tx.commit().await?;
+ assert!(save.await??.is_none());
+ let row = sqlx::query!(
+ "SELECT is_sent, is_draft, subject FROM email_messages WHERE id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(row.is_sent && !row.is_draft);
+ assert_ne!(row.subject.as_deref(), Some("stale autosave"));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn first_save_waiting_on_insert_cannot_overwrite_newly_confirmed_message(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, _) = identity();
+ let message = Uuid::new_v4();
+ let input = stale_input(message);
+ let mut tx = pool.begin().await?;
+ let blocker = sqlx::query_scalar!("SELECT pg_backend_pid() AS \"pid!\"")
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO email_messages (id, link_id, thread_id, subject, is_draft, is_sent) VALUES ($1, $2, $3, 'confirmed content', true, false)",
+ message, link, input.thread_db_id,
+ ).execute(&mut *tx).await?;
+ sqlx::query!(
+ "INSERT INTO email_scheduled_messages (message_id, link_id, send_time) VALUES ($1, $2, NOW() + INTERVAL '1 hour')",
+ message, link,
+ ).execute(&mut *tx).await?;
+ let save = tokio::spawn(async move {
+ repo.insert_message(
+ &input,
+ &UpsertedContacts {
+ from_contact_id: None,
+ recipients: vec![],
+ },
+ link,
+ None,
+ true,
+ )
+ .await
+ });
+ // Wait for the actual unique-key conflict, not just the task's first poll:
+ // the initial SELECT must have missed the uncommitted message and the
+ // upsert's statement snapshot must predate this transaction's commit.
+ wait_for_transaction_waiter(&pool, blocker).await?;
+ tx.commit().await?;
+ assert!(matches!(
+ save.await?,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ let subject = sqlx::query_scalar!("SELECT subject FROM email_messages WHERE id = $1", message)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(subject.as_deref(), Some("confirmed content"));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn update_or_cancel_before_claim_prevents_stale_queue_delivery(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, message) = identity();
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ sqlx::query!("UPDATE email_scheduled_messages SET send_time = NOW() - INTERVAL '1 minute' WHERE message_id = $1", message).execute(&pool).await?;
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_none()
+ );
+ repo.change_schedule(link, message, &actor(), ScheduleChange::Cancel, None)
+ .await?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_none()
+ );
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ sqlx::query!("UPDATE email_scheduled_messages SET send_time = NOW() - INTERVAL '1 minute' WHERE message_id = $1", message).execute(&pool).await?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_some()
+ );
+ for change in [future(), ScheduleChange::Cancel] {
+ assert!(matches!(
+ repo.change_schedule(link, message, &actor(), change, None)
+ .await,
+ Err(EmailErr::MessageDeliveryConflict(_))
+ ));
+ }
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn initial_schedule_prepares_signature_but_time_updates_preserve_content(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let (link, message) = identity();
+ sqlx::query!("INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature) VALUES ($1, true, '<p>Regards</p>')", link)
+ .execute(&pool).await?;
+ sqlx::query!("UPDATE email_messages SET body_html_sanitized = '<p>Hello</p>', body_text = 'Hello' WHERE id = $1", message)
+ .execute(&pool).await?;
+ let service = EmailServiceImpl {
+ email_repo: EmailPgRepo::new(pool.clone()),
+ frecency_service: (),
+ enqueuer: (),
+ crm_service: (),
+ entity_access_management_service: (),
+ macro_event_broker: NoopMacroEventBroker,
+ sent_undo_delay_secs: 5,
+ };
+ service
+ .change_schedule(actor(), link, message, future(), None)
+ .await?;
+ let original = sqlx::query!(
+ "SELECT body_html_sanitized, body_text FROM email_messages WHERE id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ let html = original.body_html_sanitized.as_deref().unwrap();
+ assert!(html.contains("Regards"));
+ assert_eq!(html.matches("macro-email-signature").count(), 1);
+ assert_eq!(original.body_text.as_deref(), Some("Hello\n\nRegards"));
+ sqlx::query!(
+ "UPDATE email_settings SET signature = '<p>Changed</p>' WHERE link_id = $1",
+ link
+ )
+ .execute(&pool)
+ .await?;
+ service
+ .change_schedule(actor(), link, message, future(), None)
+ .await?;
+ let updated = sqlx::query!(
+ "SELECT body_html_sanitized FROM email_messages WHERE id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(updated.body_html_sanitized, original.body_html_sanitized);
+ service
+ .change_schedule(actor(), link, message, ScheduleChange::Cancel, None)
+ .await?;
+ service
+ .change_schedule(actor(), link, message, future(), Some(false))
+ .await?;
+ let excluded = sqlx::query!(
+ "SELECT body_html_sanitized FROM email_messages WHERE id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(
+ !excluded
+ .body_html_sanitized
+ .unwrap()
+ .contains("macro-email-signature")
+ );
+ Ok(())
+}
+
+struct ClaimRepo(Pool<Postgres>);
+
+impl crate::domain::scheduled_delivery::ScheduledDeliveryRepo for ClaimRepo {
+ type Claim = (Uuid, Uuid);
+ type Sent = ();
+
+ async fn try_claim(&self, link: Uuid, message: Uuid) -> anyhow::Result<Option<Self::Claim>> {
+ Ok(
+ get_and_start_processing_scheduled_message(&self.0, link, message)
+ .await?
+ .map(|_| (link, message)),
+ )
+ }
+ async fn complete(&self, _: &Self::Claim, _: ()) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn release(&self, claim: Self::Claim) -> anyhow::Result<()> {
+ email_db_client::messages::scheduled::upsert::clear_scheduled_message_processing(
+ &self.0, claim.0, claim.1,
+ )
+ .await?;
+ Ok(())
+ }
+}
+
+#[derive(Default)]
+struct PendingProvider {
+ entered: tokio::sync::Notify,
+ finish: tokio::sync::Notify,
+}
+
+impl crate::domain::scheduled_delivery::ScheduledMessageSender<(Uuid, Uuid), ()>
+ for PendingProvider
+{
+ async fn send_claimed(&self, _: &(Uuid, Uuid)) -> anyhow::Result<()> {
+ self.entered.notify_one();
+ self.finish.notified().await;
+ Ok(())
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_draft"))
+)]
+async fn pending_provider_holds_no_locks_and_duplicate_cannot_release_claim(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ use crate::domain::scheduled_delivery::deliver_scheduled;
+ let repo = EmailPgRepo::new(pool.clone());
+ let (link, message) = identity();
+ repo.change_schedule(link, message, &actor(), future(), None)
+ .await?;
+ sqlx::query!("UPDATE email_scheduled_messages SET send_time = NOW() - INTERVAL '1 minute' WHERE message_id = $1", message).execute(&pool).await?;
+ let claims = ClaimRepo(pool.clone());
+ let provider = PendingProvider::default();
+ let delivery = deliver_scheduled(&claims, &provider, link, message);
+ tokio::pin!(delivery);
+ tokio::select! {
+ result = &mut delivery => panic!("delivery completed before provider was released: {result:?}"),
+ _ = provider.entered.notified() => {},
+ }
+ for change in [future(), ScheduleChange::Cancel] {
+ let caller = actor();
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ repo.change_schedule(link, message, &caller, change, None),
+ )
+ .await?;
+ assert!(matches!(result, Err(EmailErr::MessageDeliveryConflict(_))));
+ }
+ deliver_scheduled(&claims, &provider, link, message).await?;
+ let processing = sqlx::query_scalar!(
+ "SELECT processing FROM email_scheduled_messages WHERE message_id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(
+ processing,
+ "duplicate queue item cannot release the pending provider's claim"
+ );
+ provider.finish.notify_one();
+ delivery.await?;
+ Ok(())
+}
diff --git a/crates/email_db_client/src/messages/scheduled/get.rs b/crates/email_db_client/src/messages/scheduled/get.rs
index fed2e76b6f..285bd2205b 100644
--- a/crates/email_db_client/src/messages/scheduled/get.rs
+++ b/crates/email_db_client/src/messages/scheduled/get.rs
@@ -30,36 +30,41 @@ where
Ok(record)
}
-/// Retrieves a scheduled message by link_id and message_id, and sets processing to true
-/// Returns the message with the OLD processing value (before it was set to true)
-/// Returns None if the message doesn't exist
+/// Atomically claim a due, unsent, unclaimed message. The returned row is the
+/// owned claim (processing=true); None never grants permission to clear it.
#[tracing::instrument(skip(db), err)]
pub async fn get_and_start_processing_scheduled_message(
db: &sqlx::PgPool,
link_id: Uuid,
message_id: Uuid,
) -> anyhow::Result<Option<service::message::ScheduledMessage>> {
+ let mut tx = db.begin().await?;
+ // Same message -> schedule lock order as schedule/cancel and finalization.
+ let message = sqlx::query!(
+ "SELECT is_sent FROM email_messages WHERE id = $1 AND link_id = $2 FOR UPDATE",
+ message_id,
+ link_id,
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+ if message.is_none_or(|message| message.is_sent) {
+ return Ok(None);
+ }
let record = sqlx::query_as!(
service::message::ScheduledMessage,
r#"
- WITH old AS (
- SELECT link_id, message_id, send_time, sent, processing, actor_id
- FROM email_scheduled_messages
- WHERE link_id = $1 AND message_id = $2
- ), updated AS (
- UPDATE email_scheduled_messages
- SET processing = true, updated_at = NOW()
- WHERE link_id = $1 AND message_id = $2
- )
- SELECT link_id, message_id, send_time, sent, processing, actor_id
- FROM old
+ UPDATE email_scheduled_messages
+ SET processing = true, updated_at = NOW()
+ WHERE link_id = $1 AND message_id = $2
+ AND NOT sent AND NOT processing AND send_time <= NOW()
+ RETURNING link_id, message_id, send_time, sent, processing, actor_id
"#,
link_id,
message_id,
)
- .fetch_optional(db)
+ .fetch_optional(&mut *tx)
.await?;
-
+ tx.commit().await?;
Ok(record)
}
@@ -172,7 +177,10 @@ pub async fn get_scheduled_db_messages_by_link_id(
m.updated_at
FROM email_messages m
JOIN email_scheduled_messages sm ON m.id = sm.message_id
- WHERE m.link_id = $1 AND sm.sent = false
+ WHERE m.link_id = $1
+ AND m.is_draft = true
+ AND m.is_sent = false
+ AND sm.sent = false
ORDER BY m.created_at DESC
LIMIT $2 OFFSET $3
"#,
diff --git a/crates/email_db_client/src/messages/scheduled/test.rs b/crates/email_db_client/src/messages/scheduled/test.rs
index b1e61d29af..2586af4247 100644
--- a/crates/email_db_client/src/messages/scheduled/test.rs
+++ b/crates/email_db_client/src/messages/scheduled/test.rs
@@ -7,56 +7,32 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::types::Uuid;
use sqlx::{Pool, Postgres};
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
-)]
-async fn get_and_start_processing_returns_message_with_old_processing_value(
- pool: Pool<Postgres>,
-) -> Result<()> {
- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
-
- let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
- let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
-
- let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
-
- assert!(result.is_some());
- let scheduled_message = result.unwrap();
-
- // Should return the OLD processing value (false) before the update
- assert_eq!(scheduled_message.link_id, link_id);
- assert_eq!(scheduled_message.message_id, message_id);
- assert!(!scheduled_message.processing);
- assert!(!scheduled_message.sent);
- assert_eq!(
- scheduled_message.send_time,
- Utc.with_ymd_and_hms(2025, 1, 15, 10, 0, 0).unwrap()
- );
-
- Ok(())
+fn claim_identity() -> (Uuid, Uuid) {
+ (
+ Uuid::parse_str("00000000-0000-0000-0000-000000000e01").unwrap(),
+ Uuid::parse_str("00000000-0000-0000-0000-00000000e501").unwrap(),
+ )
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
)]
-async fn get_and_start_processing_sets_processing_to_true_in_database(
+async fn claim_returns_owned_processing_row_and_duplicate_skips(
pool: Pool<Postgres>,
) -> Result<()> {
- let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
- let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
-
- // First call should return processing = false (old value)
- let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
- assert!(result.is_some());
- assert!(!result.unwrap().processing);
-
- // Second call should return processing = true (the new old value after first update)
- let result2 = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
- assert!(result2.is_some());
- assert!(result2.unwrap().processing);
-
+ let (link, message) = claim_identity();
+ let claimed = get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .unwrap();
+ assert!(claimed.processing && !claimed.sent);
+ assert_eq!(claimed.link_id, link);
+ assert_eq!(claimed.message_id, message);
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_none()
+ );
Ok(())
}
@@ -64,21 +40,26 @@ async fn get_and_start_processing_sets_processing_to_true_in_database(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
)]
-async fn get_and_start_processing_returns_message_already_processing(
- pool: Pool<Postgres>,
-) -> Result<()> {
- let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
- let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e502")?;
-
- let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
-
- assert!(result.is_some());
- let scheduled_message = result.unwrap();
-
- // Should return the OLD processing value which is already true
- assert!(scheduled_message.processing);
- assert!(!scheduled_message.sent);
-
+async fn processing_and_sent_rows_are_not_claimed_or_changed(pool: Pool<Postgres>) -> Result<()> {
+ let (link, _) = claim_identity();
+ for (id, sent, processing) in [
+ ("00000000-0000-0000-0000-00000000e502", false, true),
+ ("00000000-0000-0000-0000-00000000e503", true, false),
+ ] {
+ let message = Uuid::parse_str(id)?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_none()
+ );
+ let row = sqlx::query!(
+ "SELECT sent, processing FROM email_scheduled_messages WHERE message_id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!((row.sent, row.processing), (sent, processing));
+ }
Ok(())
}
@@ -86,18 +67,23 @@ async fn get_and_start_processing_returns_message_already_processing(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
)]
-async fn get_and_start_processing_returns_already_sent_message(pool: Pool<Postgres>) -> Result<()> {
- let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
- let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e503")?;
-
- let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
-
- assert!(result.is_some());
- let scheduled_message = result.unwrap();
-
- assert!(scheduled_message.sent);
- assert!(!scheduled_message.processing);
-
+async fn wrong_inbox_and_missing_rows_are_not_claimed(pool: Pool<Postgres>) -> Result<()> {
+ let (link, message) = claim_identity();
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, Uuid::nil(), message)
+ .await?
+ .is_none()
+ );
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, Uuid::nil())
+ .await?
+ .is_none()
+ );
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_some()
+ );
Ok(())
}
@@ -105,17 +91,22 @@ async fn get_and_start_processing_returns_already_sent_message(pool: Pool<Postgr
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
)]
-async fn get_and_start_processing_returns_none_for_wrong_link_id(
- pool: Pool<Postgres>,
-) -> Result<()> {
- let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e02")?;
- let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
-
- let result =
- get_and_start_processing_scheduled_message(&pool, wrong_link_id, message_id).await?;
-
- assert!(result.is_none());
-
+async fn future_rows_are_not_marked_processing(pool: Pool<Postgres>) -> Result<()> {
+ let (link, message) = claim_identity();
+ sqlx::query!("UPDATE email_scheduled_messages SET send_time = NOW() + INTERVAL '1 hour' WHERE message_id = $1", message)
+ .execute(&pool).await?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_none()
+ );
+ let processing = sqlx::query_scalar!(
+ "SELECT processing FROM email_scheduled_messages WHERE message_id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(!processing);
Ok(())
}
@@ -123,17 +114,19 @@ async fn get_and_start_processing_returns_none_for_wrong_link_id(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
)]
-async fn get_and_start_processing_returns_none_for_nonexistent_message(
- pool: Pool<Postgres>,
-) -> Result<()> {
- let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
- let nonexistent_message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000ffff")?;
-
- let result =
- get_and_start_processing_scheduled_message(&pool, link_id, nonexistent_message_id).await?;
-
- assert!(result.is_none());
-
+async fn immediate_send_undo_rows_remain_claimable(pool: Pool<Postgres>) -> Result<()> {
+ let (link, message) = claim_identity();
+ sqlx::query!(
+ "UPDATE email_messages SET is_draft = false WHERE id = $1",
+ message
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ get_and_start_processing_scheduled_message(&pool, link, message)
+ .await?
+ .is_some()
+ );
Ok(())
}
@@ -141,23 +134,20 @@ async fn get_and_start_processing_returns_none_for_nonexistent_message(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
)]
-async fn get_and_start_processing_does_not_affect_other_messages(
- pool: Pool<Postgres>,
-) -> Result<()> {
- let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
- let message_id_1 = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
- let message_id_2 = Uuid::parse_str("00000000-0000-0000-0000-00000000e502")?;
-
- // Process message 1
- let result1 = get_and_start_processing_scheduled_message(&pool, link_id, message_id_1).await?;
- assert!(result1.is_some());
- assert!(!result1.unwrap().processing);
-
- // Message 2 should still have its original processing state (true)
- let result2 = get_and_start_processing_scheduled_message(&pool, link_id, message_id_2).await?;
- assert!(result2.is_some());
- assert!(result2.unwrap().processing);
-
+async fn concurrent_workers_have_exactly_one_winner(pool: Pool<Postgres>) -> Result<()> {
+ let (link, message) = claim_identity();
+ let (a, b) = tokio::join!(
+ get_and_start_processing_scheduled_message(&pool, link, message),
+ get_and_start_processing_scheduled_message(&pool, link, message),
+ );
+ assert_eq!(usize::from(a?.is_some()) + usize::from(b?.is_some()), 1);
+ let processing = sqlx::query_scalar!(
+ "SELECT processing FROM email_scheduled_messages WHERE message_id = $1",
+ message
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(processing);
Ok(())
}
diff --git a/crates/email_db_client/src/messages/scheduled/upsert.rs b/crates/email_db_client/src/messages/scheduled/upsert.rs
index d55d949b88..5ad047f4b8 100644
--- a/crates/email_db_client/src/messages/scheduled/upsert.rs
+++ b/crates/email_db_client/src/messages/scheduled/upsert.rs
@@ -7,7 +7,7 @@ pub async fn upsert_scheduled_message(
scheduled_message: service::message::ScheduledMessage,
) -> anyhow::Result<()> {
let db_message = db::message::ScheduledMessage::from(scheduled_message);
- sqlx::query!(
+ let result = sqlx::query!(
r#"
INSERT INTO email_scheduled_messages (
link_id, message_id, send_time, sent, actor_id,
@@ -16,9 +16,9 @@ pub async fn upsert_scheduled_message(
VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
ON CONFLICT (link_id, message_id) DO UPDATE SET
send_time = EXCLUDED.send_time,
- sent = EXCLUDED.sent,
actor_id = EXCLUDED.actor_id,
updated_at = NOW()
+ WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing
"#,
db_message.link_id,
db_message.message_id,
@@ -28,7 +28,10 @@ pub async fn upsert_scheduled_message(
)
.execute(&mut *tx)
.await?;
-
+ anyhow::ensure!(
+ result.rows_affected() == 1,
+ "scheduled message is already processing or sent"
+ );
Ok(())
}
@@ -47,8 +50,9 @@ where
UPDATE email_scheduled_messages
SET
sent = true,
+ processing = false,
updated_at = NOW()
- WHERE link_id = $1 AND message_id = $2
+ WHERE link_id = $1 AND message_id = $2 AND processing AND NOT sent
"#,
link_id,
message_id,
@@ -76,7 +80,7 @@ where
SET
processing = false,
updated_at = NOW()
- WHERE link_id = $1 AND message_id = $2
+ WHERE link_id = $1 AND message_id = $2 AND processing AND NOT sent
"#,
link_id,
message_id,
diff --git a/crates/email_db_client/src/messages/test.rs b/crates/email_db_client/src/messages/test.rs
index 9b02da30df..51abd125d6 100644
--- a/crates/email_db_client/src/messages/test.rs
+++ b/crates/email_db_client/src/messages/test.rs
@@ -151,6 +151,32 @@ async fn get_scheduled_db_messages_excludes_non_scheduled_messages(
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_excludes_immediate_send_undo_rows(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let immediate_send_id = Uuid::parse_str("00000000-0000-0000-0000-0000000d0001")?;
+ sqlx::query!(
+ "UPDATE email_messages SET is_draft = false WHERE id = $1",
+ immediate_send_id
+ )
+ .execute(&pool)
+ .await?;
+
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 100).await?;
+
+ assert!(
+ result.iter().all(|message| message.id != immediate_send_id),
+ "Immediate-send undo rows are not user-created scheduled drafts"
+ );
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
diff --git a/crates/graphql_email/src/mutation.rs b/crates/graphql_email/src/mutation.rs
index d6babd5dbb..b9481891dc 100644
--- a/crates/graphql_email/src/mutation.rs
+++ b/crates/graphql_email/src/mutation.rs
@@ -400,6 +400,10 @@ fn draft_mutation_error(error: &EmailErr) -> async_graphql::Error {
EmailErr::MessageAlreadySent(_) => {
("email draft has already been sent", "DRAFT_ALREADY_SENT")
}
+ EmailErr::MessageDeliveryConflict(_) => (
+ "cancel scheduled delivery before editing this draft",
+ "INVALID",
+ ),
EmailErr::MessageNotFound(_) => ("referenced email message not found", "NOT_FOUND"),
EmailErr::ThreadNotFound => ("email thread not found", "NOT_FOUND"),
EmailErr::InboxNotFound => ("email inbox not found", "INBOX_NOT_FOUND"),
diff --git a/crates/graphql_email/src/mutation/test.rs b/crates/graphql_email/src/mutation/test.rs
index 80181aa062..e119383943 100644
--- a/crates/graphql_email/src/mutation/test.rs
+++ b/crates/graphql_email/src/mutation/test.rs
@@ -252,6 +252,7 @@ struct TestEmailThreadOutput;
fn deterministic_draft_rejections_do_not_allow_retries() {
for error in [
EmailErr::MessageAlreadySent(Uuid::nil()),
+ EmailErr::MessageDeliveryConflict(Uuid::nil()),
EmailErr::MessageNotFound(Uuid::nil()),
EmailErr::ThreadNotFound,
EmailErr::InboxNotFound,
@@ -263,6 +264,16 @@ fn deterministic_draft_rejections_do_not_allow_retries() {
}
}
+#[test]
+fn scheduled_draft_conflict_is_a_deterministic_invalid_save() {
+ let mapped = draft_mutation_error(&EmailErr::MessageDeliveryConflict(Uuid::nil()));
+ assert_eq!(
+ mapped.extensions.as_ref().unwrap().get("code"),
+ Some(&async_graphql::Value::from("INVALID")),
+ );
+ assert_eq!(mapped.extensions.as_ref().unwrap().get("retryable"), None);
+}
+
#[derive(SimpleObject)]
struct TestEmailThread {
id: ID,
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 74f6065d06..87ed4b61b1 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -470,28 +470,71 @@ A failure from an older, unmounted editor must not overwrite a newer edited repl
A presentation or refresh error after successful delivery is not a reason to send
again.
-Send and schedule are refused with a notice while the device is offline, while a
-draft is still syncing (its save was accepted locally but not yet confirmed by the
-server; retry after a moment), or while an attachment has no completed upload. The
-composer keeps its content in each case. Attachments cannot be added while
-offline: a blocking notice explains and nothing is attached.
-For a new standalone email, a failed REST draft save is best-effort: Send can
-still proceed without a draft ID when no save was queued and no attachment is
-waiting to upload. A server rejection blocks sending even an existing draft.
-An internal draft-save failure, including a failed response read after the save
-commits, stays queued and retries with backoff. It must not permanently disable
-autosave; Send stays blocked until a save is confirmed. Invalid or unauthorized
-writes still stop retrying.
-Test this with a previously saved draft as well as a new one: a queued edit must
-block Send and scheduling until a save commits. Reopening a cached draft while
-offline must retain its uploaded attachments and confirmed scheduled time.
-
-While a schedule change is pending, immediate send and further schedule changes
-are disabled. Reply recipients cannot be edited or dragged during scheduling,
-sending, or discarding. A failed schedule or unschedule keeps the last confirmed time.
+Choosing or clearing a send time is local preparation only. The composer remains
+editable and autosaves normally, shows **Scheduled send: ...** (the time and the
+viewer's timezone, e.g. **Sep 25 at 8:00 AM EDT**) in a bar attached
+below the composer (a strip along the bottom of the message card for replies), and
+performs no schedule, unschedule, archive, or delivery request. The bar's **Cancel**,
+at its far right, clears the local choice; the clock's tooltip reads **Schedule send
+time**. The clock and
+primary arrow remain icon-sized; the clock turns accent-colored when a time is
+selected, while the primary action's accessible name and tooltip change from
+**Send email** to **Schedule send**. Clicking it or pressing `Ctrl`/`Cmd`+`Enter
+runs the same validation and is the only initial scheduling commitment. A selected
+time that has passed is rejected at submission rather than falling back to immediate
+send. Touch toolbars keep the summary inline beside their icons, with Cancel next to
+the time; when space is tight, that summary truncates or wraps separately from the
+fixed icon group. The
+former picker-auto-commit behavior was a defect and must not be restored.
+
+Only a successful scheduling response or authoritative lifecycle reconciliation
+shows **Scheduled for ...**. Confirmed scheduled composers are content-locked.
+Picking another time creates a local proposal while the original remains active;
+the bar continues to show the original time plus the proposed replacement and
+explains that the original remains active. **Update schedule** commits the proposal.
+Clearing that proposal does not cancel the original. **Cancel schedule** is a
+separate explicit action, and only its
+confirmed success returns the message to an editable draft. Failed schedule,
+update, or cancel requests retain the user's local intent and last authoritative
+time, and never fall through to immediate Send. At narrow split widths the bar's
+label truncates while Cancel stays at its far edge; the bar never covers discard,
+attachment, formatting, the clock, or the primary action. Reply recipients
+cannot be edited or dragged during a confirmed schedule or active delivery mutation.
+
+When verifying, use an intercepted or isolated delivery fixture: choose a time,
+confirm that the editable **Scheduled send** preview makes zero delivery calls, then use
+the primary button and `Ctrl`/`Cmd`+`Enter separately to confirm exactly one schedule
+call. Reopen a confirmed schedule to exercise proposal/update and explicit cancel.
+If a later lifecycle refresh fails, the confirmed result remains in place; stale
+observations must not undo it or create a recovery draft after a failed inbox move.
+Reconciliation resumes when a fresh poll or event-driven read succeeds.
If scheduling succeeds but marking the thread done fails, the email remains
scheduled and a notice explains the separate failure. Check the confirmed time
before retrying; do not treat that notice as a failed schedule.
+Keep a scheduled composer open through its due time when verifying the flow. It
+reconciles on email events, tab focus/reconnect, cross-tab schedule changes, and a
+short due-time poll. Confirmed delivery closes or disables the old composer and
+stops autosave/delete against the sent ID. Text from an edit that raced delivery
+is preserved as a new unsent draft, never submitted with the sent message ID.
+Recovery re-uploads local attachment files and restores forwarded attachments.
+Remote-only draft attachments cannot be copied after the original draft is gone;
+their pills are removed and a notice asks you to attach those files again.
+
+A successful initial schedule shows an **Email scheduled** notice whose description
+gives the full send time, with **Undo** and **View message** on their own row below
+it; a rescheduled email
+shows **Email rescheduled** with **View message**. Undo cancels the captured draft in
+the captured inbox and restores its editable body, envelope, and attachments; it must
+not overwrite a newer reply. View message opens the scheduled thread, or scrolls an
+inline reply back into view.
+The Email view's **Scheduled** tab lists only server-confirmed scheduled drafts,
+soonest first across the selected inboxes, as ordinary email rows: the recipients,
+subject, and snippet, with a clock-and-time badge (for example **Tomorrow, 2:12
+PM**) in place of the row's date; hovering it gives the full date, time, and
+timezone.
+Opening a row previews its thread like any other email; cancel from the opened
+message's bar. Search and filters are hidden on this tab. Immediate-send undo-window
+queue rows are not scheduled drafts and must not appear.
With the new app views enabled, mobile and tablet Email use a floating, horizontally
scrolling row of those tabs, with `Open email filters` at the left. The rest of the
diff --git a/packages/sdk/generated/email/sdk.gen.ts b/packages/sdk/generated/email/sdk.gen.ts
index 6e47751696..1ac9ac53be 100644
--- a/packages/sdk/generated/email/sdk.gen.ts
+++ b/packages/sdk/generated/email/sdk.gen.ts
@@ -188,7 +188,7 @@ export class Sdk extends HeyApiClient {
}
/**
- * Remove the scheduled send from a draft.
+ * Remove the scheduled send from a draft, including immediate-send undo.
*/
public deleteScheduledDraft<ThrowOnError extends boolean = false>(options: Options<DeleteScheduledDraftData, ThrowOnError>): RequestResult<DeleteScheduledDraftResponses, DeleteScheduledDraftErrors, ThrowOnError> {
return (options.client ?? this.client).delete<DeleteScheduledDraftResponses, DeleteScheduledDraftErrors, ThrowOnError>({ url: '/email/drafts/scheduled/{message_id}', ...options });
diff --git a/packages/sdk/generated/email/types.gen.ts b/packages/sdk/generated/email/types.gen.ts
index f119c65cd2..601a7db6a3 100644
--- a/packages/sdk/generated/email/types.gen.ts
+++ b/packages/sdk/generated/email/types.gen.ts
@@ -1130,7 +1130,11 @@ export type UpsertEmailFilterResponse = {
export type UpsertScheduledRequest = {
/**
- * The time to send the message (ISO 8601 format)
+ * Per-message signature override; absent uses the inbox's send defaults.
+ */
+ include_signature?: boolean | null;
+ /**
+ * The time to send the message (ISO 8601 format).
*/
send_time: string;
};
@@ -1437,7 +1441,9 @@ export type UpsertScheduledMessageData = {
};
export type UpsertScheduledMessageErrors = {
+ 400: ErrorResponse;
401: ErrorResponse;
+ 403: ErrorResponse;
404: ErrorResponse;
500: ErrorResponse;
};
@@ -1465,6 +1471,7 @@ export type DeleteScheduledDraftData = {
export type DeleteScheduledDraftErrors = {
400: ErrorResponse;
401: ErrorResponse;
+ 403: ErrorResponse;
404: ErrorResponse;
500: ErrorResponse;
};
diff --git a/packages/sdk/specs/email.json b/packages/sdk/specs/email.json
index 3e604ad14b..8dcb753e95 100644
--- a/packages/sdk/specs/email.json
+++ b/packages/sdk/specs/email.json
@@ -780,6 +780,16 @@
}
}
},
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
@@ -790,6 +800,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -816,7 +836,7 @@
"/email/drafts/scheduled/{message_id}": {
"delete": {
"tags": ["Draft Scheduling"],
- "summary": "Remove the scheduled send from a draft.",
+ "summary": "Remove the scheduled send from a draft, including immediate-send undo.",
"operationId": "delete_scheduled_draft",
"parameters": [
{
@@ -854,6 +874,16 @@
}
}
},
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -5407,10 +5437,14 @@
"type": "object",
"required": ["send_time"],
"properties": {
+ "include_signature": {
+ "type": ["boolean", "null"],
+ "description": "Per-message signature override; absent uses the inbox's send defaults."
+ },
"send_time": {
"type": "string",
"format": "date-time",
- "description": "The time to send the message (ISO 8601 format)"
+ "description": "The time to send the message (ISO 8601 format)."
}
}
},
diff --git a/services/email_service/src/api/email/drafts/scheduled/remove.rs b/services/email_service/src/api/email/drafts/scheduled/remove.rs
index 3b517844f6..09ae4e5934 100644
--- a/services/email_service/src/api/email/drafts/scheduled/remove.rs
+++ b/services/email_service/src/api/email/drafts/scheduled/remove.rs
@@ -1,142 +1,49 @@
-use crate::api::context::ApiContext;
-use axum::extract::{Path, State};
-use axum::http::StatusCode;
-use axum::response::{IntoResponse, Response};
-use axum::{Extension, Json};
-use email::domain::events::{EmailMacroEvent, MessageSendCancelledMetadata, SendCancelReason};
-use email_service::pubsub::publish_email_event;
+use crate::api::context::{ApiContext, AuthorizationService, EmailSvc};
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+};
+use axum_extra::extract::Cached;
+use email::domain::scheduled::{EmailSchedulingService, ScheduleChange};
+use email::inbound::axum::axum_impls::EmailLinkExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
-use models_email::service::link::Link;
-use strum_macros::AsRefStr;
-use thiserror::Error;
use uuid::Uuid;
-#[derive(Debug, Error, AsRefStr)]
-pub enum DeleteScheduledError {
- #[error("Scheduled message not found")]
- NotFound,
+use super::upsert::UpsertScheduledError;
- #[error("Message has already been sent")]
- AlreadySent,
-
- #[error("Failed to delete scheduled message")]
- QueryError(#[from] anyhow::Error),
-
- #[error("Database error")]
- DatabaseError(#[from] sqlx::Error),
-}
-
-impl IntoResponse for DeleteScheduledError {
- fn into_response(self) -> Response {
- let status_code = match &self {
- DeleteScheduledError::NotFound => StatusCode::NOT_FOUND,
- DeleteScheduledError::AlreadySent => StatusCode::BAD_REQUEST,
- DeleteScheduledError::QueryError(_) | DeleteScheduledError::DatabaseError(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
- };
-
- (
- status_code,
- Json(ErrorResponse {
- message: self.to_string().into(),
- }),
- )
- .into_response()
- }
-}
-
-/// Remove the scheduled send from a draft.
+/// Remove the scheduled send from a draft, including immediate-send undo.
#[utoipa::path(
- delete,
- tag = "Draft Scheduling",
- path = "/email/drafts/scheduled/{message_id}",
+ delete, tag = "Draft Scheduling", path = "/email/drafts/scheduled/{message_id}",
operation_id = "delete_scheduled_draft",
- params(
- ("message_id" = Uuid, Path, description = "The ID of the draft")
- ),
+ params(("message_id" = Uuid, Path, description = "The ID of the draft")),
responses(
(status = 204, description = "Scheduled send deleted successfully"),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx), err)]
+#[tracing::instrument(skip(ctx, authorization, link), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
- link: Extension<Link>,
+ Cached(authorization): Cached<
+ MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+ >,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<EmailSvc, AuthorizationService>>,
Path(message_id): Path<Uuid>,
-) -> Result<StatusCode, DeleteScheduledError> {
- let mut tx = ctx.db.begin().await?;
-
- // Check if the scheduled message exists and hasn't been sent
- let scheduled_message = email_db_client::messages::scheduled::get::get_scheduled_message(
- &mut *tx, link.id, message_id,
- )
- .await?;
-
- let Some(scheduled_message) = scheduled_message else {
- // No scheduled row under this link. If the message is already back to
- // a draft, a previous undo has applied (a duplicate click, or a retry
- // after a lost response) — idempotent success, so the client doesn't
- // surface a false "Failed to undo send" for an undo that worked.
- let message = email_db_client::messages::get_simple_messages::get_simple_message(
- &ctx.db,
- &message_id,
- &link.fusionauth_user_id,
+) -> Result<StatusCode, UpsertScheduledError> {
+ ctx.email_service
+ .service()
+ .change_schedule(
+ authorization.authorization.user.macro_user_id.clone(),
+ link.id,
+ message_id,
+ ScheduleChange::Cancel,
+ None,
)
.await?;
- return match message {
- Some(m) if m.is_draft => Ok(StatusCode::NO_CONTENT),
- _ => Err(DeleteScheduledError::NotFound),
- };
- };
-
- if scheduled_message.sent || scheduled_message.processing {
- return Err(DeleteScheduledError::AlreadySent);
- }
-
- email_db_client::messages::scheduled::delete::delete_scheduled_message(
- &mut *tx, link.id, message_id,
- )
- .await?;
-
- // if we undo send for a message, turn it back into a draft
- email_db_client::messages::update::update_message_draft_status(
- &mut tx, message_id, link.id, true,
- )
- .await?;
-
- tx.commit().await?;
-
- // Best-effort event: resolve the draft's thread for the payload.
- let thread_db_id = email_db_client::messages::get_simple_messages::get_simple_message(
- &ctx.db,
- &message_id,
- &link.fusionauth_user_id,
- )
- .await
- .inspect_err(
- |e| tracing::warn!(error=?e, %message_id, "skipping message_send_cancelled event: draft lookup failed"),
- )
- .ok()
- .flatten()
- .map(|m| m.thread_db_id);
- if let Some(thread_id) = thread_db_id {
- publish_email_event(
- ctx.macro_event_broker.as_ref(),
- &EmailMacroEvent::message_send_cancelled(MessageSendCancelledMetadata {
- link_id: link.id,
- owner: link.macro_id.clone(),
- actor: Some(link.macro_id.clone()),
- message_id,
- thread_id,
- reason: SendCancelReason::Undo,
- }),
- );
- }
-
Ok(StatusCode::NO_CONTENT)
}
diff --git a/services/email_service/src/api/email/drafts/scheduled/upsert.rs b/services/email_service/src/api/email/drafts/scheduled/upsert.rs
index 9e209dfced..9a2d4a6d02 100644
--- a/services/email_service/src/api/email/drafts/scheduled/upsert.rs
+++ b/services/email_service/src/api/email/drafts/scheduled/upsert.rs
@@ -1,44 +1,47 @@
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, AuthorizationService, EmailSvc};
+use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
-use axum::{Extension, Json};
-use email::domain::events::{EmailMacroEvent, MessageSendQueuedMetadata};
-use email_service::pubsub::publish_email_event;
+use axum_extra::extract::Cached;
+use email::domain::{
+ models::EmailErr,
+ scheduled::{EmailSchedulingService, ScheduleChange},
+};
+use email::inbound::axum::axum_impls::EmailLinkExtractor;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use model::response::ErrorResponse;
-use models_email::service::link::Link;
-use models_email::service::message::ScheduledMessage;
use sqlx_core::types::chrono::{DateTime, Utc};
-use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
use uuid::Uuid;
-#[derive(Debug, Error, AsRefStr)]
-pub enum UpsertScheduledError {
- #[error("Draft not found")]
- NotFound,
-
- #[error("Failed to upsert scheduled message")]
- QueryError(#[from] anyhow::Error),
-
- #[error("Database error")]
- DatabaseError(#[from] sqlx::Error),
-}
+#[derive(Debug, Error)]
+#[error("{0}")]
+pub struct UpsertScheduledError(#[from] EmailErr);
impl IntoResponse for UpsertScheduledError {
fn into_response(self) -> Response {
- let status_code = match &self {
- UpsertScheduledError::NotFound => StatusCode::NOT_FOUND,
- UpsertScheduledError::QueryError(_) | UpsertScheduledError::DatabaseError(_) => {
+ let status = match &self.0 {
+ EmailErr::MessageNotFound(_) => StatusCode::NOT_FOUND,
+ EmailErr::Unauthorized => StatusCode::FORBIDDEN,
+ EmailErr::MessageDeliveryConflict(_) | EmailErr::InvalidScheduleTime => {
+ StatusCode::BAD_REQUEST
+ }
+ _ => {
+ tracing::error!(error=?self.0, "schedule transition failed");
StatusCode::INTERNAL_SERVER_ERROR
}
};
-
+ let message = if status == StatusCode::INTERNAL_SERVER_ERROR {
+ "Failed to update scheduled message".to_owned()
+ } else {
+ self.to_string()
+ };
(
- status_code,
+ status,
Json(ErrorResponse {
- message: self.to_string().into(),
+ message: message.into(),
}),
)
.into_response()
@@ -47,8 +50,10 @@ impl IntoResponse for UpsertScheduledError {
#[derive(Debug, serde::Deserialize, ToSchema)]
pub struct UpsertScheduledRequest {
- /// The time to send the message (ISO 8601 format)
+ /// The time to send the message (ISO 8601 format).
pub send_time: DateTime<Utc>,
+ /// Per-message signature override; absent uses the inbox's send defaults.
+ pub include_signature: Option<bool>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
@@ -59,86 +64,39 @@ pub struct UpsertScheduledResponse {
/// Schedule or update a scheduled draft.
#[utoipa::path(
- put,
- tag = "Draft Scheduling",
- path = "/email/drafts/scheduled/{id}",
+ put, tag = "Draft Scheduling", path = "/email/drafts/scheduled/{id}",
operation_id = "upsert_scheduled_message",
- params(
- ("id" = Uuid, Path, description = "The ID of the draft message to schedule")
- ),
+ params(("id" = Uuid, Path, description = "The ID of the draft message to schedule")),
request_body = UpsertScheduledRequest,
responses(
(status = 200, body = UpsertScheduledResponse),
+ (status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx), err)]
+#[tracing::instrument(skip(ctx, authorization, link), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
- link: Extension<Link>,
+ Cached(authorization): Cached<
+ MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+ >,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<EmailSvc, AuthorizationService>>,
Path(draft_id): Path<Uuid>,
Json(request): Json<UpsertScheduledRequest>,
) -> Result<Json<UpsertScheduledResponse>, UpsertScheduledError> {
- // Check if the draft exists
- let draft_exists =
- email_db_client::messages::get::draft_exists_with_id(&ctx.db, link.id, draft_id).await?;
-
- if !draft_exists {
- return Err(UpsertScheduledError::NotFound);
- }
-
- // Create the scheduled message
- let scheduled_message = ScheduledMessage {
- link_id: link.id,
- message_id: draft_id,
- send_time: request.send_time,
- sent: false,
- processing: false,
- // This legacy transport only knows the link; the owner is the best
- // available attribution (matching the message_send_queued event
- // below).
- actor_id: Some(link.macro_id.to_string()),
- };
-
- // Upsert the scheduled message
- let mut tx = ctx.db.begin().await?;
- email_db_client::messages::scheduled::upsert::upsert_scheduled_message(
- &mut tx,
- scheduled_message,
- )
- .await?;
- tx.commit().await?;
-
- // Best-effort event: resolve the draft's thread for the payload.
- let thread_db_id = email_db_client::messages::get_simple_messages::get_simple_message(
- &ctx.db,
- &draft_id,
- &link.fusionauth_user_id,
- )
- .await
- .inspect_err(
- |e| tracing::warn!(error=?e, %draft_id, "skipping message_send_queued event: draft lookup failed"),
- )
- .ok()
- .flatten()
- .map(|m| m.thread_db_id);
- if let Some(thread_id) = thread_db_id {
- publish_email_event(
- ctx.macro_event_broker.as_ref(),
- &EmailMacroEvent::message_send_queued(MessageSendQueuedMetadata {
- link_id: link.id,
- owner: link.macro_id.clone(),
- actor: Some(link.macro_id.clone()),
- message_id: draft_id,
- thread_id,
- scheduled_send_at: request.send_time,
- is_scheduled: true,
- }),
- );
- }
-
+ ctx.email_service
+ .service()
+ .change_schedule(
+ authorization.authorization.user.macro_user_id.clone(),
+ link.id,
+ draft_id,
+ ScheduleChange::Set(request.send_time),
+ request.include_signature,
+ )
+ .await?;
Ok(Json(UpsertScheduledResponse {
message_id: draft_id,
send_time: request.send_time,
diff --git a/services/email_service/src/outbound.rs b/services/email_service/src/outbound.rs
index 23de65b836..8ab8ede71c 100644
--- a/services/email_service/src/outbound.rs
+++ b/services/email_service/src/outbound.rs
@@ -2,3 +2,5 @@
/// Email provider API adapters and composition types.
pub mod email_api;
+/// Persistence and provider adapters for scheduled-delivery claims.
+pub mod scheduled_delivery;
diff --git a/services/email_service/src/outbound/scheduled_delivery.rs b/services/email_service/src/outbound/scheduled_delivery.rs
new file mode 100644
index 0000000000..b31d8ee26f
--- /dev/null
+++ b/services/email_service/src/outbound/scheduled_delivery.rs
@@ -0,0 +1,312 @@
+//! PostgreSQL and provider adapters for scheduled email delivery.
+use crate::outbound::email_api::GmailApi;
+use crate::util::gmail::send::{
+ cleanup_draft_attachments, fetch_and_attach_draft_attachments,
+ fetch_and_attach_forwarded_attachments, generate_email_threading_headers,
+};
+use anyhow::Context;
+use chrono::Utc;
+use email::domain::events::{EmailEventOrigin, EmailMacroEvent, MessageSentMetadata};
+use email::domain::scheduled_delivery::{ScheduledDeliveryRepo, ScheduledMessageSender};
+use email_api_client::domain::models::{SendRequest, SentIds};
+use email_db_client::messages::scheduled::get::get_and_start_processing_scheduled_message;
+use macro_event_broker::{KafkaEventPublisher, MacroEventBroker, MacroEventBrokerService};
+use macro_user_id::cowlike::CowLike as _;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_email::service::{
+ attachment::AttachmentDraft,
+ link::Link,
+ message::{MessageToSend, ScheduledMessage},
+};
+use tokio_util::task::TaskTracker;
+use uuid::Uuid;
+
+/// Concrete worker adapters, wired by the scheduled worker's composition root.
+pub struct ScheduledDeliveryAdapter {
+ pub db: sqlx::PgPool,
+ pub email_api: GmailApi,
+ pub s3_client: s3_client::S3,
+ pub attachment_bucket: String,
+ pub macro_event_broker: MacroEventBrokerService<KafkaEventPublisher, TaskTracker>,
+}
+
+/// Context obtained only by winning an atomic database claim.
+pub struct ScheduledClaim {
+ link: Link,
+ schedule: ScheduledMessage,
+}
+
+/// Provider result and attachment cleanup data retained until DB completion.
+pub struct SentDelivery {
+ message: MessageToSend,
+ attachments: Option<Vec<AttachmentDraft>>,
+}
+
+impl ScheduledDeliveryRepo for ScheduledDeliveryAdapter {
+ type Claim = ScheduledClaim;
+ type Sent = SentDelivery;
+
+ async fn try_claim(
+ &self,
+ link_id: Uuid,
+ message_id: Uuid,
+ ) -> anyhow::Result<Option<ScheduledClaim>> {
+ let Some(link) = email_db_client::links::get::fetch_link_by_id(&self.db, link_id).await?
+ else {
+ return Ok(None);
+ };
+ Ok(
+ get_and_start_processing_scheduled_message(&self.db, link_id, message_id)
+ .await?
+ .map(|schedule| ScheduledClaim { link, schedule }),
+ )
+ }
+
+ async fn release(&self, claim: ScheduledClaim) -> anyhow::Result<()> {
+ email_db_client::messages::scheduled::upsert::clear_scheduled_message_processing(
+ &self.db,
+ claim.schedule.link_id,
+ claim.schedule.message_id,
+ )
+ .await?;
+ Ok(())
+ }
+
+ async fn complete(&self, claim: &ScheduledClaim, sent: SentDelivery) -> anyhow::Result<()> {
+ let ctx = self;
+ let link = &claim.link;
+ let data = &claim.schedule;
+ let scheduled_message = &claim.schedule;
+ let message_to_send = sent.message;
+ let db_attachments = sent.attachments;
+ let mut tx = ctx
+ .db
+ .begin()
+ .await
+ .context("Failed to begin transaction")?;
+
+ let result = process_sent_message(tx.as_mut(), &message_to_send).await;
+
+ match result {
+ Ok(_) => {
+ tx.commit().await.context("Failed to commit transaction")?;
+
+ // Gmail accepted the send and the DB updates are committed:
+ // publish the message_sent event resolving the earlier
+ // message_send_queued. The actor was persisted on the scheduled
+ // row at enqueue time; rows from before actor tracking decode to
+ // `None` (no attribution).
+ let actor = scheduled_message
+ .actor_id
+ .as_deref()
+ .and_then(|raw| MacroUserIdStr::parse_from_str(raw).ok())
+ .map(|actor| actor.into_owned());
+ if let (Some(message_db_id), Some(thread_db_id)) =
+ (message_to_send.db_id, message_to_send.thread_db_id)
+ {
+ let _ = ctx
+ .macro_event_broker
+ .send_event(&EmailMacroEvent::message_sent(MessageSentMetadata {
+ link_id: link.id,
+ owner: link.macro_id.clone(),
+ actor,
+ message_id: message_db_id,
+ thread_id: thread_db_id,
+ provider_message_id: message_to_send
+ .provider_id
+ .clone()
+ .unwrap_or_default(),
+ provider_thread_id: message_to_send
+ .provider_thread_id
+ .clone()
+ .unwrap_or_default(),
+ subject: Some(message_to_send.subject.clone()),
+ to_emails: message_to_send
+ .to
+ .iter()
+ .flatten()
+ .map(|c| c.email.clone())
+ .collect(),
+ cc_emails: message_to_send
+ .cc
+ .iter()
+ .flatten()
+ .map(|c| c.email.clone())
+ .collect(),
+ origin: EmailEventOrigin::UserAction,
+ sent_at: Utc::now(),
+ }))
+ .inspect_err(
+ |error| tracing::error!(error=?error, "failed to publish email event"),
+ );
+ }
+
+ // Cleanup attachments in the background after successful send
+ if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments)
+ {
+ let db = ctx.db.clone();
+ let s3_client = ctx.s3_client.clone();
+ let bucket = ctx.attachment_bucket.clone();
+ let link_id = link.id;
+ tokio::spawn(async move {
+ cleanup_draft_attachments(
+ db,
+ &s3_client,
+ bucket,
+ link_id,
+ draft_id,
+ attachments,
+ )
+ .await;
+ });
+ }
+ }
+ Err(e) => {
+ if let Err(rollback_err) = tx.rollback().await {
+ tracing::error!(
+ error = ?rollback_err,
+ link_id = ?data.link_id,
+ message_id = ?data.message_id,
+ "Failed to rollback transaction after marking messages as sent failure"
+ );
+ }
+ return Err(e);
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl ScheduledMessageSender<ScheduledClaim, SentDelivery> for ScheduledDeliveryAdapter {
+ async fn send_claimed(&self, claim: &ScheduledClaim) -> anyhow::Result<SentDelivery> {
+ let ctx = self;
+ let link = &claim.link;
+ let data = &claim.schedule;
+ // fetch message from db
+ let (mut message_to_send, sender_contact) =
+ email_db_client::messages::get::get_message_to_send(
+ &ctx.db,
+ data.message_id,
+ data.link_id,
+ )
+ .await
+ .context(format!(
+ "Failed to fetch message to gmail api for message_id {}",
+ data.message_id
+ ))?;
+
+ // generate headers
+ let (parent_message_id, references) =
+ generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, data.link_id)
+ .await;
+
+ // Include draft attachments (user-uploaded files from S3)
+ let db_attachments = fetch_and_attach_draft_attachments(
+ &ctx.db,
+ &ctx.s3_client,
+ ctx.attachment_bucket.as_str(),
+ link,
+ &mut message_to_send,
+ )
+ .await?;
+
+ // Include forwarded attachments (fetched from Gmail at send time)
+ fetch_and_attach_forwarded_attachments(&ctx.db, &ctx.email_api, link, &mut message_to_send)
+ .await?;
+
+ let send_request = SendRequest {
+ message: message_to_send.clone(),
+ from: sender_contact,
+ parent_message_id,
+ references,
+ };
+ let sent_ids = ctx
+ .email_api
+ .send_message(
+ link.id,
+ &send_request,
+ message_to_send.provider_thread_id.as_deref(),
+ )
+ .await
+ .context(format!(
+ "Failed to send message to gmail api for message_id {}",
+ data.message_id
+ ))?;
+ apply_sent_ids(&mut message_to_send, sent_ids);
+
+ Ok(SentDelivery {
+ message: message_to_send,
+ attachments: db_attachments,
+ })
+ }
+}
+
+fn apply_sent_ids(message: &mut MessageToSend, sent_ids: SentIds) {
+ message.provider_id = Some(sent_ids.provider_message_id);
+ message.provider_thread_id = Some(sent_ids.provider_thread_id);
+}
+
+/// Mark both the scheduled message and the regular message as sent, and update thread metadata
+///
+/// This function handles all database updates in a single transaction
+#[expect(
+ clippy::useless_asref,
+ reason = "We actually need the as_mut so we don't transfer ownership of the transaction"
+)]
+#[tracing::instrument(
+ skip(tx, message),
+ fields(
+ message_db_id = message.db_id.unwrap().to_string(),
+ link_id = message.link_id.to_string()
+ ),
+ err
+)]
+async fn process_sent_message(
+ tx: &mut sqlx::PgConnection,
+ message: &MessageToSend,
+) -> anyhow::Result<()> {
+ // mark message as non-draft
+ email_db_client::messages::update::mark_message_as_sent(
+ tx.as_mut(),
+ &message.provider_id.clone().unwrap_or_default(),
+ &message.provider_thread_id.clone().unwrap_or_default(),
+ message.link_id,
+ message.db_id.unwrap(),
+ )
+ .await?;
+
+ // mark scheduled message as sent
+ let finalized = email_db_client::messages::scheduled::upsert::mark_scheduled_message_as_sent(
+ tx.as_mut(),
+ message.link_id,
+ message.db_id.unwrap(),
+ )
+ .await?;
+ anyhow::ensure!(finalized, "scheduled delivery claim no longer exists");
+
+ // safe as it was fetched from the database - message is only inserted once thread is created
+ let thread_db_id = message.thread_db_id.unwrap();
+
+ // set provider id of thread - needed in case it's a thread with no other messages, as it wouldn't
+ // have a provider id yet
+ email_db_client::threads::update::update_thread_provider_id(
+ tx.as_mut(),
+ thread_db_id,
+ message.link_id,
+ &message.provider_thread_id.clone().unwrap(),
+ )
+ .await?;
+
+ email_db_client::threads::update::update_thread_metadata(
+ tx.as_mut(),
+ thread_db_id,
+ message.link_id,
+ )
+ .await?;
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/services/email_service/src/pubsub/scheduled/process/test.rs b/services/email_service/src/outbound/scheduled_delivery/test.rs
similarity index 100%
rename from services/email_service/src/pubsub/scheduled/process/test.rs
rename to services/email_service/src/outbound/scheduled_delivery/test.rs
diff --git a/services/email_service/src/pubsub/scheduled/context.rs b/services/email_service/src/pubsub/scheduled/context.rs
index a29483d1ae..2866b7373c 100644
--- a/services/email_service/src/pubsub/scheduled/context.rs
+++ b/services/email_service/src/pubsub/scheduled/context.rs
@@ -11,3 +11,18 @@ pub struct ScheduledContext {
pub attachment_bucket: String,
pub macro_event_broker: PubSubEventBroker,
}
+
+impl ScheduledContext {
+ /// Compose the worker's persistence/provider adapter without holding a DB transaction.
+ pub fn delivery_adapter(
+ &self,
+ ) -> crate::outbound::scheduled_delivery::ScheduledDeliveryAdapter {
+ crate::outbound::scheduled_delivery::ScheduledDeliveryAdapter {
+ db: self.db.clone(),
+ email_api: self.email_api.clone(),
+ s3_client: self.s3_client.clone(),
+ attachment_bucket: self.attachment_bucket.clone(),
+ macro_event_broker: self.macro_event_broker.clone(),
+ }
+ }
+}
diff --git a/services/email_service/src/pubsub/scheduled/process.rs b/services/email_service/src/pubsub/scheduled/process.rs
index 614949e087..2c637bfaa7 100644
--- a/services/email_service/src/pubsub/scheduled/process.rs
+++ b/services/email_service/src/pubsub/scheduled/process.rs
@@ -1,341 +1,26 @@
use crate::pubsub::scheduled::context::ScheduledContext;
-use crate::pubsub::util::publish_email_event;
-use crate::util::gmail::send::{
- cleanup_draft_attachments, fetch_and_attach_draft_attachments,
- fetch_and_attach_forwarded_attachments, generate_email_threading_headers,
-};
use anyhow::Context;
-use chrono::Utc;
-use email::domain::events::{EmailEventOrigin, EmailMacroEvent, MessageSentMetadata};
-use email_api_client::domain::models::{SendRequest, SentIds};
-use email_db_client::messages::scheduled::get::get_and_start_processing_scheduled_message;
-use macro_user_id::cowlike::CowLike as _;
-use macro_user_id::user_id::MacroUserIdStr;
-use models_email::service::message::MessageToSend;
+use email::domain::scheduled_delivery::deliver_scheduled;
use models_email::service::pubsub::ScheduledPubsubMessage;
-use sqlx_core::any::AnyConnectionBackend;
use sqs_worker::cleanup_message;
-#[cfg(test)]
-mod test;
-
#[tracing::instrument(skip(ctx, message), err)]
pub async fn process_message(
ctx: ScheduledContext,
message: &aws_sdk_sqs::types::Message,
) -> anyhow::Result<()> {
- // Parse the incoming message
let data = extract_scheduled_message(message)?;
-
- let result = process_scheduled_message_inner(&ctx, &data).await;
-
- if let Err(ref e) = result {
- tracing::error!(
- error = ?e,
- message_id = %data.message_id,
- link_id = %data.link_id,
- "Failed to process scheduled message"
- );
- }
-
- if let Err(clear_err) =
- email_db_client::messages::scheduled::upsert::clear_scheduled_message_processing(
- &ctx.db,
- data.link_id,
- data.message_id,
- )
- .await
- {
- tracing::error!(
- error = ?clear_err,
- message_id = %data.message_id,
- link_id = %data.link_id,
- "Failed to clear processing flag"
- );
- }
-
- result?;
-
+ let adapter = ctx.delivery_adapter();
+ deliver_scheduled(&adapter, &adapter, data.link_id, data.message_id).await?;
cleanup_message(&ctx.sqs_worker, message).await?;
-
Ok(())
}
-#[tracing::instrument(skip(ctx), err)]
-async fn process_scheduled_message_inner(
- ctx: &ScheduledContext,
- data: &ScheduledPubsubMessage,
-) -> anyhow::Result<()> {
- let link = email_db_client::links::get::fetch_link_by_id(&ctx.db, data.link_id).await?;
-
- let Some(link) = link else {
- tracing::debug!(link_id=%data.link_id, "Link not found - skipping");
- return Ok(());
- };
-
- // Get scheduled message from database
- let scheduled_message =
- match get_and_start_processing_scheduled_message(&ctx.db, data.link_id, data.message_id)
- .await
- {
- Ok(Some(msg)) => msg,
- Ok(None) => {
- tracing::info!(
- link_id = ?data.link_id,
- message_id = ?data.message_id,
- "Scheduled message not found"
- );
- return Ok(());
- }
- Err(e) => {
- return Err(e).context(format!(
- "Failed to fetch scheduled message from database for message_id {}",
- data.message_id
- ));
- }
- };
-
- if scheduled_message.sent {
- tracing::warn!(
- message_id=%data.message_id,
- link_id=%data.link_id,
- "Scheduled message already sent - skipping"
- );
- return Ok(());
- } else if scheduled_message.processing {
- tracing::warn!(
- message_id=%data.message_id,
- link_id=%data.link_id,
- "Scheduled message already being processed - skipping"
- );
- return Ok(());
- } else if scheduled_message.send_time > Utc::now() {
- tracing::warn!(
- message_id=%data.message_id,
- link_id=%data.link_id,
- send_time=scheduled_message.send_time.to_string(),
- "Scheduled message send_time is in the future - skipping"
- );
- return Ok(());
- }
-
- // fetch message from db
- let (mut message_to_send, sender_contact) =
- email_db_client::messages::get::get_message_to_send(&ctx.db, data.message_id, data.link_id)
- .await
- .context(format!(
- "Failed to fetch message to gmail api for message_id {}",
- data.message_id
- ))?;
-
- // generate headers
- let (parent_message_id, references) =
- generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, data.link_id)
- .await;
-
- // Include draft attachments (user-uploaded files from S3)
- let db_attachments = fetch_and_attach_draft_attachments(
- &ctx.db,
- &ctx.s3_client,
- ctx.attachment_bucket.as_str(),
- &link,
- &mut message_to_send,
- )
- .await?;
-
- // Include forwarded attachments (fetched from Gmail at send time)
- fetch_and_attach_forwarded_attachments(&ctx.db, &ctx.email_api, &link, &mut message_to_send)
- .await?;
-
- let send_request = SendRequest {
- message: message_to_send.clone(),
- from: sender_contact,
- parent_message_id,
- references,
- };
- let sent_ids = ctx
- .email_api
- .send_message(
- link.id,
- &send_request,
- message_to_send.provider_thread_id.as_deref(),
- )
- .await
- .context(format!(
- "Failed to send message to gmail api for message_id {}",
- data.message_id
- ))?;
- apply_sent_ids(&mut message_to_send, sent_ids);
-
- let mut tx = ctx
- .db
- .begin()
- .await
- .context("Failed to begin transaction")?;
-
- let result = process_sent_message(tx.as_mut(), &message_to_send).await;
-
- match result {
- Ok(_) => {
- tx.as_mut()
- .commit()
- .await
- .context("Failed to commit transaction")?;
-
- // Gmail accepted the send and the DB updates are committed:
- // publish the message_sent event resolving the earlier
- // message_send_queued. The actor was persisted on the scheduled
- // row at enqueue time; rows from before actor tracking decode to
- // `None` (no attribution).
- let actor = scheduled_message
- .actor_id
- .as_deref()
- .and_then(|raw| MacroUserIdStr::parse_from_str(raw).ok())
- .map(|actor| actor.into_owned());
- if let (Some(message_db_id), Some(thread_db_id)) =
- (message_to_send.db_id, message_to_send.thread_db_id)
- {
- publish_email_event(
- &ctx.macro_event_broker,
- &EmailMacroEvent::message_sent(MessageSentMetadata {
- link_id: link.id,
- owner: link.macro_id.clone(),
- actor,
- message_id: message_db_id,
- thread_id: thread_db_id,
- provider_message_id: message_to_send
- .provider_id
- .clone()
- .unwrap_or_default(),
- provider_thread_id: message_to_send
- .provider_thread_id
- .clone()
- .unwrap_or_default(),
- subject: Some(message_to_send.subject.clone()),
- to_emails: message_to_send
- .to
- .iter()
- .flatten()
- .map(|c| c.email.clone())
- .collect(),
- cc_emails: message_to_send
- .cc
- .iter()
- .flatten()
- .map(|c| c.email.clone())
- .collect(),
- origin: EmailEventOrigin::UserAction,
- sent_at: Utc::now(),
- }),
- );
- }
-
- // Cleanup attachments in the background after successful send
- if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments) {
- let db = ctx.db.clone();
- let s3_client = ctx.s3_client.clone();
- let bucket = ctx.attachment_bucket.clone();
- let link_id = link.id;
- tokio::spawn(async move {
- cleanup_draft_attachments(
- db,
- &s3_client,
- bucket,
- link_id,
- draft_id,
- attachments,
- )
- .await;
- });
- }
- }
- Err(e) => {
- if let Err(rollback_err) = tx.as_mut().rollback().await {
- tracing::error!(
- error = ?rollback_err,
- link_id = ?data.link_id,
- message_id = ?data.message_id,
- "Failed to rollback transaction after marking messages as sent failure"
- );
- }
- return Err(e);
- }
- }
-
- Ok(())
-}
-
-fn apply_sent_ids(message: &mut MessageToSend, sent_ids: SentIds) {
- message.provider_id = Some(sent_ids.provider_message_id);
- message.provider_thread_id = Some(sent_ids.provider_thread_id);
-}
-
-#[tracing::instrument(skip(message))]
+#[tracing::instrument(skip(message), err)]
fn extract_scheduled_message(
message: &aws_sdk_sqs::types::Message,
) -> anyhow::Result<ScheduledPubsubMessage> {
let message_body = message.body().context("message body not found")?;
-
serde_json::from_str(message_body)
.context("Failed to deserialize message body to ScheduledPubsubMessage")
}
-
-/// Mark both the scheduled message and the regular message as sent, and update thread metadata
-///
-/// This function handles all database updates in a single transaction
-#[expect(
- clippy::useless_asref,
- reason = "We actually need the as_mut so we don't transfer ownership of the transaction"
-)]
-#[tracing::instrument(
- skip(tx, message),
- fields(
- message_db_id = message.db_id.unwrap().to_string(),
- link_id = message.link_id.to_string()
- ),
- err
-)]
-async fn process_sent_message(
- tx: &mut sqlx::PgConnection,
- message: &MessageToSend,
-) -> anyhow::Result<()> {
- // mark scheduled message as sent
- email_db_client::messages::scheduled::upsert::mark_scheduled_message_as_sent(
- tx.as_mut(),
- message.link_id,
- message.db_id.unwrap(),
- )
- .await?;
-
- // mark message as non-draft
- email_db_client::messages::update::mark_message_as_sent(
- tx.as_mut(),
- &message.provider_id.clone().unwrap_or_default(),
- &message.provider_thread_id.clone().unwrap_or_default(),
- message.link_id,
- message.db_id.unwrap(),
- )
- .await?;
-
- // safe as it was fetched from the database - message is only inserted once thread is created
- let thread_db_id = message.thread_db_id.unwrap();
-
- // set provider id of thread - needed in case it's a thread with no other messages, as it wouldn't
- // have a provider id yet
- email_db_client::threads::update::update_thread_provider_id(
- tx.as_mut(),
- thread_db_id,
- message.link_id,
- &message.provider_thread_id.clone().unwrap(),
- )
- .await?;
-
- email_db_client::threads::update::update_thread_metadata(
- tx.as_mut(),
- thread_db_id,
- message.link_id,
- )
- .await?;
-
- Ok(())
-}