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.

feat(reminders): add email follow-ups and source-first reminder workflows (#7292)

gbirman12b976f70af4
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 38c8a15c85..b7465a1663 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -9342,24 +9342,43 @@
"crates/workspace-hack"
],
"reminders": [
+ "crates/activity",
"crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
"crates/broadcast",
+ "crates/calendar_events",
"crates/channel_sender",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
"crates/cowlike",
+ "crates/crm",
"crates/database_env_vars",
"crates/document_sub_type",
+ "crates/email",
+ "crates/email_utils",
"crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
"crates/genai_telemetry",
+ "crates/google_token",
"crates/harness_id",
"crates/harness_token",
+ "crates/initiative",
"crates/invite_email",
+ "crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_entrypoint",
@@ -9368,9 +9387,11 @@
"crates/macro_event_broker",
"crates/macro_event_topics",
"crates/macro_service_urls",
+ "crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mention_utils",
+ "crates/messages",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
@@ -9382,13 +9403,18 @@
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
+ "crates/models_properties",
"crates/non_empty",
"crates/notification",
"crates/notification_state",
"crates/prompt",
+ "crates/properties",
"crates/rate_limit",
"crates/reminders",
"crates/remote_env_var",
+ "crates/share_permission_db_utils",
+ "crates/system_properties",
+ "crates/unfurl",
"crates/workspace-hack"
],
"remote_env_var": [
diff --git a/.sqlx/query-08b109922b70a7958250245d2878ae372d8f84a1470c5eab6d1e20b08f2043ea.json b/.sqlx/query-08b109922b70a7958250245d2878ae372d8f84a1470c5eab6d1e20b08f2043ea.json
new file mode 100644
index 0000000000..5c6752949a
--- /dev/null
+++ b/.sqlx/query-08b109922b70a7958250245d2878ae372d8f84a1470c5eab6d1e20b08f2043ea.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_threads SET latest_inbound_message_ts = NULL, inbox_visible = false WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "08b109922b70a7958250245d2878ae372d8f84a1470c5eab6d1e20b08f2043ea"
+}
diff --git a/.sqlx/query-169514afd604067ffe4c814326807107ceab1d2dee771eed2cd3f3b6014eef99.json b/.sqlx/query-169514afd604067ffe4c814326807107ceab1d2dee771eed2cd3f3b6014eef99.json
deleted file mode 100644
index ae700070f8..0000000000
--- a/.sqlx/query-169514afd604067ffe4c814326807107ceab1d2dee771eed2cd3f3b6014eef99.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE email_threads\n SET\n inbox_visible = $1,\n is_read = $2,\n latest_inbound_message_ts = $3,\n latest_outbound_message_ts = $4,\n latest_non_spam_message_ts = $5,\n updated_at = NOW()\n WHERE\n id = $6 AND\n link_id = $7 AND\n (inbox_visible, is_read, latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts)\n IS DISTINCT FROM ($1, $2, $3, $4, $5)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Bool",
- "Bool",
- "Timestamptz",
- "Timestamptz",
- "Timestamptz",
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "169514afd604067ffe4c814326807107ceab1d2dee771eed2cd3f3b6014eef99"
-}
diff --git a/.sqlx/query-1974e68bb4636b3e7a50667a8ee06ce1bb2c5deed374ebd9b15fa4feb7e18b5e.json b/.sqlx/query-1974e68bb4636b3e7a50667a8ee06ce1bb2c5deed374ebd9b15fa4feb7e18b5e.json
new file mode 100644
index 0000000000..624fe0498b
--- /dev/null
+++ b/.sqlx/query-1974e68bb4636b3e7a50667a8ee06ce1bb2c5deed374ebd9b15fa4feb7e18b5e.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT inbox_visible, latest_inbound_message_ts, reminder_returned_at FROM email_threads WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "latest_inbound_message_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "reminder_returned_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "1974e68bb4636b3e7a50667a8ee06ce1bb2c5deed374ebd9b15fa4feb7e18b5e"
+}
diff --git a/.sqlx/query-22100d2f80b6a5e999c8140a72068523ad25e404e8d7668a8796d0a3a306375e.json b/.sqlx/query-22100d2f80b6a5e999c8140a72068523ad25e404e8d7668a8796d0a3a306375e.json
new file mode 100644
index 0000000000..a86bc93b71
--- /dev/null
+++ b/.sqlx/query-22100d2f80b6a5e999c8140a72068523ad25e404e8d7668a8796d0a3a306375e.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT reminder_returned_at FROM email_threads WHERE id = $1 AND link_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "reminder_returned_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "22100d2f80b6a5e999c8140a72068523ad25e404e8d7668a8796d0a3a306375e"
+}
diff --git a/.sqlx/query-2db782fa5ff33ca3709443a123d0b911552a2b5c3b19df359eac03ece1b9c195.json b/.sqlx/query-2db782fa5ff33ca3709443a123d0b911552a2b5c3b19df359eac03ece1b9c195.json
new file mode 100644
index 0000000000..2b336c9230
--- /dev/null
+++ b/.sqlx/query-2db782fa5ff33ca3709443a123d0b911552a2b5c3b19df359eac03ece1b9c195.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE reminder_email_followup SET payload = '{}'::jsonb WHERE reminder_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2db782fa5ff33ca3709443a123d0b911552a2b5c3b19df359eac03ece1b9c195"
+}
diff --git a/.sqlx/query-33ddee88dc492ff3c5c4029f8f4de5baedb42a64b001a2b318f22dc55617a991.json b/.sqlx/query-33ddee88dc492ff3c5c4029f8f4de5baedb42a64b001a2b318f22dc55617a991.json
new file mode 100644
index 0000000000..53416ee18a
--- /dev/null
+++ b/.sqlx/query-33ddee88dc492ff3c5c4029f8f4de5baedb42a64b001a2b318f22dc55617a991.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SET LOCAL idle_in_transaction_session_timeout = 0",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "33ddee88dc492ff3c5c4029f8f4de5baedb42a64b001a2b318f22dc55617a991"
+}
diff --git a/.sqlx/query-3942c35bfa639bdf692c1f5e718900d86e68d45af34ad41db2240be1f443eb0b.json b/.sqlx/query-3942c35bfa639bdf692c1f5e718900d86e68d45af34ad41db2240be1f443eb0b.json
new file mode 100644
index 0000000000..9e079e587f
--- /dev/null
+++ b/.sqlx/query-3942c35bfa639bdf692c1f5e718900d86e68d45af34ad41db2240be1f443eb0b.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT reminder_id, request AS \"request!: Json<EmailFollowupCommand>\" FROM reminder_email_operation\n WHERE user_id = $1 AND operation_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "reminder_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "request!: Json<EmailFollowupCommand>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "3942c35bfa639bdf692c1f5e718900d86e68d45af34ad41db2240be1f443eb0b"
+}
diff --git a/.sqlx/query-39abd56db9f3bd0a35a2614b6d6bdc3c6635310c80a760128d1293332e4c8313.json b/.sqlx/query-39abd56db9f3bd0a35a2614b6d6bdc3c6635310c80a760128d1293332e4c8313.json
new file mode 100644
index 0000000000..1fc7b8ea98
--- /dev/null
+++ b/.sqlx/query-39abd56db9f3bd0a35a2614b6d6bdc3c6635310c80a760128d1293332e4c8313.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT m.id, m.internal_date_ts AS received_at,\n (m.is_sent OR m.is_draft) AS \"outgoing!\",\n EXISTS (\n SELECT 1 FROM email_links l\n WHERE lower(l.email_address) = lower(c.email_address)\n AND (l.macro_id = $3 OR EXISTS (\n SELECT 1 FROM macro_user_links mul\n WHERE mul.link_id = l.id AND mul.primary_macro_id = $3\n ))\n ) AS \"from_self!\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.thread_id = $1 AND m.link_id = $2\n ORDER BY m.id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "received_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "outgoing!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "from_self!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ null,
+ null
+ ]
+ },
+ "hash": "39abd56db9f3bd0a35a2614b6d6bdc3c6635310c80a760128d1293332e4c8313"
+}
diff --git a/.sqlx/query-41b85fd7785e6c05bb6b710d5e0c4c524180eb49e95de51fb95dc6fc8cf56a7d.json b/.sqlx/query-41b85fd7785e6c05bb6b710d5e0c4c524180eb49e95de51fb95dc6fc8cf56a7d.json
new file mode 100644
index 0000000000..bf09778c54
--- /dev/null
+++ b/.sqlx/query-41b85fd7785e6c05bb6b710d5e0c4c524180eb49e95de51fb95dc6fc8cf56a7d.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_threads (id, link_id) VALUES ($1, $2)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "41b85fd7785e6c05bb6b710d5e0c4c524180eb49e95de51fb95dc6fc8cf56a7d"
+}
diff --git a/.sqlx/query-50dfd858334dd888d95f2e8404367af8fde56df34e05272846994f54797343d4.json b/.sqlx/query-50dfd858334dd888d95f2e8404367af8fde56df34e05272846994f54797343d4.json
new file mode 100644
index 0000000000..abdb359760
--- /dev/null
+++ b/.sqlx/query-50dfd858334dd888d95f2e8404367af8fde56df34e05272846994f54797343d4.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, 'followup', '[email protected]', 'followup')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "50dfd858334dd888d95f2e8404367af8fde56df34e05272846994f54797343d4"
+}
diff --git a/.sqlx/query-5325a9568dd9c6dc070c9f8ad9fc44b0fc9569cf66a7c37f3a94f0bc05e224d4.json b/.sqlx/query-5325a9568dd9c6dc070c9f8ad9fc44b0fc9569cf66a7c37f3a94f0bc05e224d4.json
new file mode 100644
index 0000000000..99fa987f5b
--- /dev/null
+++ b/.sqlx/query-5325a9568dd9c6dc070c9f8ad9fc44b0fc9569cf66a7c37f3a94f0bc05e224d4.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT payload AS \"payload!: Json<FollowupRecord>\" FROM reminder_email_followup\n WHERE state IN ('archiving', 'pending', 'returning') AND ($1::uuid IS NULL OR reminder_id > $1)\n ORDER BY reminder_id LIMIT $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "payload!: Json<FollowupRecord>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "5325a9568dd9c6dc070c9f8ad9fc44b0fc9569cf66a7c37f3a94f0bc05e224d4"
+}
diff --git a/.sqlx/query-5deab91e5dc01d8fc649a1605e7e7afbe43d6f382e4f1e1c7c7132922292b04e.json b/.sqlx/query-5deab91e5dc01d8fc649a1605e7e7afbe43d6f382e4f1e1c7c7132922292b04e.json
new file mode 100644
index 0000000000..ae15ec7e74
--- /dev/null
+++ b/.sqlx/query-5deab91e5dc01d8fc649a1605e7e7afbe43d6f382e4f1e1c7c7132922292b04e.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO reminder_email_followup (reminder_id, user_id, thread_id, link_id, state, payload)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (reminder_id) DO UPDATE SET state = EXCLUDED.state, payload = EXCLUDED.payload\n WHERE reminder_email_followup.user_id = EXCLUDED.user_id",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5deab91e5dc01d8fc649a1605e7e7afbe43d6f382e4f1e1c7c7132922292b04e"
+}
diff --git a/.sqlx/query-5e68b8982c0c077664888ac786b0011ec3daa3b6df02c7013da6e6e8079f4509.json b/.sqlx/query-5e68b8982c0c077664888ac786b0011ec3daa3b6df02c7013da6e6e8079f4509.json
new file mode 100644
index 0000000000..7600662716
--- /dev/null
+++ b/.sqlx/query-5e68b8982c0c077664888ac786b0011ec3daa3b6df02c7013da6e6e8079f4509.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO reminder_email_operation (user_id, operation_id, thread_id, request, reminder_id)\n VALUES ($1, $2, $3, $4, $5) ON CONFLICT (user_id, operation_id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Uuid",
+ "Jsonb",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5e68b8982c0c077664888ac786b0011ec3daa3b6df02c7013da6e6e8079f4509"
+}
diff --git a/.sqlx/query-61e7ef25d4b66fa59430caec78760c4642cace5c536b74d0a46851f247e0f2c4.json b/.sqlx/query-61e7ef25d4b66fa59430caec78760c4642cace5c536b74d0a46851f247e0f2c4.json
new file mode 100644
index 0000000000..c2d0c7df01
--- /dev/null
+++ b/.sqlx/query-61e7ef25d4b66fa59430caec78760c4642cace5c536b74d0a46851f247e0f2c4.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_labels (id, link_id, provider_label_id, name) VALUES ($1, $2, 'SENT', 'SENT')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "61e7ef25d4b66fa59430caec78760c4642cace5c536b74d0a46851f247e0f2c4"
+}
diff --git a/.sqlx/query-6e876d9d84e75e8a728561d18cac6a317c95cd43590f6485fdd23a9ecf0aa116.json b/.sqlx/query-6e876d9d84e75e8a728561d18cac6a317c95cd43590f6485fdd23a9ecf0aa116.json
new file mode 100644
index 0000000000..6c38e558ae
--- /dev/null
+++ b/.sqlx/query-6e876d9d84e75e8a728561d18cac6a317c95cd43590f6485fdd23a9ecf0aa116.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SET idle_in_transaction_session_timeout = '50ms'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "6e876d9d84e75e8a728561d18cac6a317c95cd43590f6485fdd23a9ecf0aa116"
+}
diff --git a/.sqlx/query-73bdc42122354f8eb051d7754aedbda47add5963ca53c335589db04ea1bab3f5.json b/.sqlx/query-73bdc42122354f8eb051d7754aedbda47add5963ca53c335589db04ea1bab3f5.json
new file mode 100644
index 0000000000..a0bae906cd
--- /dev/null
+++ b/.sqlx/query-73bdc42122354f8eb051d7754aedbda47add5963ca53c335589db04ea1bab3f5.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES\n ('d1000000-0000-0000-0000-000000000001', 'owner', '[email protected]', 'followup_owner'),\n ('d1000000-0000-0000-0000-000000000002', 'delegate', '[email protected]', 'followup_delegate')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "73bdc42122354f8eb051d7754aedbda47add5963ca53c335589db04ea1bab3f5"
+}
diff --git a/.sqlx/query-747ec3ab833e17695fe727b92ad7e50018ad0be230e2dc9cd671c40fdcea55f5.json b/.sqlx/query-747ec3ab833e17695fe727b92ad7e50018ad0be230e2dc9cd671c40fdcea55f5.json
new file mode 100644
index 0000000000..3739ece1c9
--- /dev/null
+++ b/.sqlx/query-747ec3ab833e17695fe727b92ad7e50018ad0be230e2dc9cd671c40fdcea55f5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT has_calendar_attachment FROM email_threads WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "has_calendar_attachment",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "747ec3ab833e17695fe727b92ad7e50018ad0be230e2dc9cd671c40fdcea55f5"
+}
diff --git a/.sqlx/query-7d30391da4c3725638be9442f12cce3dc53bd50cfc397f8daa973c4a7e22251a.json b/.sqlx/query-7d30391da4c3725638be9442f12cce3dc53bd50cfc397f8daa973c4a7e22251a.json
new file mode 100644
index 0000000000..79d79c6d84
--- /dev/null
+++ b/.sqlx/query-7d30391da4c3725638be9442f12cce3dc53bd50cfc397f8daa973c4a7e22251a.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 732849)) AS \"locked!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "locked!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "7d30391da4c3725638be9442f12cce3dc53bd50cfc397f8daa973c4a7e22251a"
+}
diff --git a/.sqlx/query-838135b559e17898abd72732aa324763e72d9e91ea5d1f9b5e493b5c395ec8ae.json b/.sqlx/query-838135b559e17898abd72732aa324763e72d9e91ea5d1f9b5e493b5c395ec8ae.json
new file mode 100644
index 0000000000..a8dc6362ef
--- /dev/null
+++ b/.sqlx/query-838135b559e17898abd72732aa324763e72d9e91ea5d1f9b5e493b5c395ec8ae.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT inbox_visible, latest_inbound_message_ts FROM email_threads WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "latest_inbound_message_ts",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "838135b559e17898abd72732aa324763e72d9e91ea5d1f9b5e493b5c395ec8ae"
+}
diff --git a/.sqlx/query-852e47ffa47afb353be2647be296e2cc49bfc26475bfd3845673214e241e4213.json b/.sqlx/query-852e47ffa47afb353be2647be296e2cc49bfc26475bfd3845673214e241e4213.json
new file mode 100644
index 0000000000..d3e78923dd
--- /dev/null
+++ b/.sqlx/query-852e47ffa47afb353be2647be296e2cc49bfc26475bfd3845673214e241e4213.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET is_sent = TRUE WHERE thread_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "852e47ffa47afb353be2647be296e2cc49bfc26475bfd3845673214e241e4213"
+}
diff --git a/.sqlx/query-86f4e8525e631e542347aeede363f94525c2b0ec3532fd8315223a5cffd23e85.json b/.sqlx/query-86f4e8525e631e542347aeede363f94525c2b0ec3532fd8315223a5cffd23e85.json
new file mode 100644
index 0000000000..a17a5dbd3b
--- /dev/null
+++ b/.sqlx/query-86f4e8525e631e542347aeede363f94525c2b0ec3532fd8315223a5cffd23e85.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO reminder (id, user_id, description, entity_type, entity_id, remind_at, next_run_at, enabled, completed_at)\n VALUES ($1, $2, COALESCE($3, 'Email follow-up'), 'email_thread', $4, $5, $5, $6, CASE WHEN $7 THEN now() END)\n ON CONFLICT (id) DO UPDATE SET remind_at = EXCLUDED.remind_at, next_run_at = EXCLUDED.next_run_at,\n enabled = EXCLUDED.enabled, completed_at = EXCLUDED.completed_at, updated_at = now()\n WHERE reminder.user_id = EXCLUDED.user_id",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Uuid",
+ "Timestamptz",
+ "Bool",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "86f4e8525e631e542347aeede363f94525c2b0ec3532fd8315223a5cffd23e85"
+}
diff --git a/.sqlx/query-8cfb7d9a0867557d4a56f2073f89620d9410e0ab4e0a50bbe2cc70d3f6a9be23.json b/.sqlx/query-8cfb7d9a0867557d4a56f2073f89620d9410e0ab4e0a50bbe2cc70d3f6a9be23.json
new file mode 100644
index 0000000000..4b24b32a50
--- /dev/null
+++ b/.sqlx/query-8cfb7d9a0867557d4a56f2073f89620d9410e0ab4e0a50bbe2cc70d3f6a9be23.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT is_signal FROM email_threads WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_signal",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "8cfb7d9a0867557d4a56f2073f89620d9410e0ab4e0a50bbe2cc70d3f6a9be23"
+}
diff --git a/.sqlx/query-8e916256efd1879917c9f1e955ac25a7ae3150e32393e4817526db7e0b6adef9.json b/.sqlx/query-8e916256efd1879917c9f1e955ac25a7ae3150e32393e4817526db7e0b6adef9.json
new file mode 100644
index 0000000000..8b998bf1b5
--- /dev/null
+++ b/.sqlx/query-8e916256efd1879917c9f1e955ac25a7ae3150e32393e4817526db7e0b6adef9.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM macro_user_links WHERE primary_macro_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8e916256efd1879917c9f1e955ac25a7ae3150e32393e4817526db7e0b6adef9"
+}
diff --git a/.sqlx/query-956decc6a22d7b954a65cdcc70755ac93003e13ba7a74a98c759275a8a28bf5e.json b/.sqlx/query-956decc6a22d7b954a65cdcc70755ac93003e13ba7a74a98c759275a8a28bf5e.json
new file mode 100644
index 0000000000..80a55364d4
--- /dev/null
+++ b/.sqlx/query-956decc6a22d7b954a65cdcc70755ac93003e13ba7a74a98c759275a8a28bf5e.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"User\" (id, email, macro_user_id) SELECT $1, '[email protected]', id FROM macro_user WHERE email = '[email protected]'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "956decc6a22d7b954a65cdcc70755ac93003e13ba7a74a98c759275a8a28bf5e"
+}
diff --git a/.sqlx/query-9ab969a2a65277268bde54c2b06934f478273630b69d4beea691bc56401dcf26.json b/.sqlx/query-9ab969a2a65277268bde54c2b06934f478273630b69d4beea691bc56401dcf26.json
new file mode 100644
index 0000000000..17805f4401
--- /dev/null
+++ b/.sqlx/query-9ab969a2a65277268bde54c2b06934f478273630b69d4beea691bc56401dcf26.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH effective AS (\n SELECT id AS thread_id, $1 OR (reminder_returned_at IS NOT NULL AND EXISTS (\n SELECT 1 FROM email_messages fm\n JOIN email_message_labels fml ON fml.message_id = fm.id\n JOIN email_labels fl ON fl.id = fml.label_id\n WHERE fm.thread_id = email_threads.id AND fl.provider_label_id = 'INBOX'\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels blocked\n JOIN email_labels bl ON bl.id = blocked.label_id\n WHERE blocked.message_id = fm.id AND bl.provider_label_id IN ('TRASH', 'SPAM')\n )\n )) AS inbox_visible\n FROM email_threads\n WHERE id = $6 AND link_id = $7\n )\n UPDATE email_threads t\n SET\n inbox_visible = effective.inbox_visible,\n is_read = $2,\n latest_inbound_message_ts = $3,\n latest_outbound_message_ts = $4,\n latest_non_spam_message_ts = $5,\n updated_at = NOW()\n FROM effective\n WHERE t.id = effective.thread_id\n AND (t.inbox_visible, t.is_read, t.latest_inbound_message_ts, t.latest_outbound_message_ts, t.latest_non_spam_message_ts)\n IS DISTINCT FROM (effective.inbox_visible, $2, $3, $4, $5)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "Bool",
+ "Timestamptz",
+ "Timestamptz",
+ "Timestamptz",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9ab969a2a65277268bde54c2b06934f478273630b69d4beea691bc56401dcf26"
+}
diff --git a/.sqlx/query-9c0b58996b37b423dc4113ad3b1d301ef694a1e1a07a8d67f14b8ecb4dfc7812.json b/.sqlx/query-9c0b58996b37b423dc4113ad3b1d301ef694a1e1a07a8d67f14b8ecb4dfc7812.json
new file mode 100644
index 0000000000..c67ead58d2
--- /dev/null
+++ b/.sqlx/query-9c0b58996b37b423dc4113ad3b1d301ef694a1e1a07a8d67f14b8ecb4dfc7812.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider) VALUES ($1, $2, 'followup', '[email protected]', 'GMAIL')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9c0b58996b37b423dc4113ad3b1d301ef694a1e1a07a8d67f14b8ecb4dfc7812"
+}
diff --git a/.sqlx/query-a8c25823d80a213351c1beaeeba4c1b4516b8674fbb2148aa618ad4f360709b7.json b/.sqlx/query-a8c25823d80a213351c1beaeeba4c1b4516b8674fbb2148aa618ad4f360709b7.json
new file mode 100644
index 0000000000..8e551465d5
--- /dev/null
+++ b/.sqlx/query-a8c25823d80a213351c1beaeeba4c1b4516b8674fbb2148aa618ad4f360709b7.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"User\" (id, email, macro_user_id) VALUES\n ('macro|[email protected]', '[email protected]', 'd1000000-0000-0000-0000-000000000001'),\n ('macro|[email protected]', '[email protected]', 'd1000000-0000-0000-0000-000000000002')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "a8c25823d80a213351c1beaeeba4c1b4516b8674fbb2148aa618ad4f360709b7"
+}
diff --git a/.sqlx/query-adc9064f28cc19e0475d574e1ceeef6398adbde7a0e8da3f0fb9c99be37f65f8.json b/.sqlx/query-adc9064f28cc19e0475d574e1ceeef6398adbde7a0e8da3f0fb9c99be37f65f8.json
new file mode 100644
index 0000000000..22dd058087
--- /dev/null
+++ b/.sqlx/query-adc9064f28cc19e0475d574e1ceeef6398adbde7a0e8da3f0fb9c99be37f65f8.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT inbox_visible, updated_at FROM email_threads WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "adc9064f28cc19e0475d574e1ceeef6398adbde7a0e8da3f0fb9c99be37f65f8"
+}
diff --git a/.sqlx/query-afd9feb0092b20cb90d2b39847a238f82db24fc1cc95468c3d3fc8e57719e86e.json b/.sqlx/query-afd9feb0092b20cb90d2b39847a238f82db24fc1cc95468c3d3fc8e57719e86e.json
new file mode 100644
index 0000000000..dd8cdb5516
--- /dev/null
+++ b/.sqlx/query-afd9feb0092b20cb90d2b39847a238f82db24fc1cc95468c3d3fc8e57719e86e.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_threads SET reminder_returned_at = NOW() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "afd9feb0092b20cb90d2b39847a238f82db24fc1cc95468c3d3fc8e57719e86e"
+}
diff --git a/.sqlx/query-b0f2f6bf6e78863cb38625f1f26303d3f195a82c23c3660fba2fb5706a6b98ab.json b/.sqlx/query-b0f2f6bf6e78863cb38625f1f26303d3f195a82c23c3660fba2fb5706a6b98ab.json
new file mode 100644
index 0000000000..2c868d98aa
--- /dev/null
+++ b/.sqlx/query-b0f2f6bf6e78863cb38625f1f26303d3f195a82c23c3660fba2fb5706a6b98ab.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_threads SET updated_at = '2000-01-01T00:00:00Z' WHERE id = $1 RETURNING updated_at",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "b0f2f6bf6e78863cb38625f1f26303d3f195a82c23c3660fba2fb5706a6b98ab"
+}
diff --git a/.sqlx/query-cb5a046733c0cfb8d7b74e560b1ba5fd89c0d9f7ab498a9fcaf782c2ee6e4871.json b/.sqlx/query-cb5a046733c0cfb8d7b74e560b1ba5fd89c0d9f7ab498a9fcaf782c2ee6e4871.json
new file mode 100644
index 0000000000..281218f34e
--- /dev/null
+++ b/.sqlx/query-cb5a046733c0cfb8d7b74e560b1ba5fd89c0d9f7ab498a9fcaf782c2ee6e4871.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT payload AS \"payload!: Json<FollowupRecord>\" FROM reminder_email_followup\n WHERE user_id = $1 AND reminder_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "payload!: Json<FollowupRecord>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "cb5a046733c0cfb8d7b74e560b1ba5fd89c0d9f7ab498a9fcaf782c2ee6e4871"
+}
diff --git a/.sqlx/query-cfd3ab7c022a44b5a2b497ddfe4b09fd5caa22e941d3a83791010085952d1b1a.json b/.sqlx/query-cfd3ab7c022a44b5a2b497ddfe4b09fd5caa22e941d3a83791010085952d1b1a.json
new file mode 100644
index 0000000000..51b20313f8
--- /dev/null
+++ b/.sqlx/query-cfd3ab7c022a44b5a2b497ddfe4b09fd5caa22e941d3a83791010085952d1b1a.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_message_labels (message_id, label_id) SELECT id, $2 FROM email_messages WHERE thread_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cfd3ab7c022a44b5a2b497ddfe4b09fd5caa22e941d3a83791010085952d1b1a"
+}
diff --git a/.sqlx/query-d02ce758b0b4686e78bff9567d25897748b089984094111d0c7e2d0b9439276d.json b/.sqlx/query-d02ce758b0b4686e78bff9567d25897748b089984094111d0c7e2d0b9439276d.json
new file mode 100644
index 0000000000..c8c852ca3a
--- /dev/null
+++ b/.sqlx/query-d02ce758b0b4686e78bff9567d25897748b089984094111d0c7e2d0b9439276d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT payload AS \"payload!: Json<FollowupRecord>\" FROM reminder_email_followup\n WHERE user_id = $1 AND thread_id = $2 ORDER BY created_at DESC, reminder_id DESC LIMIT 1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "payload!: Json<FollowupRecord>",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "d02ce758b0b4686e78bff9567d25897748b089984094111d0c7e2d0b9439276d"
+}
diff --git a/.sqlx/query-0f7f132f49d191ddb595ee96ac8fdae7e1c8f504512bb2d84121b091732bb8d4.json b/.sqlx/query-d5719d99feae9cf83c8c0e07de311784f69926638af6bac1fc91714b85d821af.json
similarity index 56%
rename from .sqlx/query-0f7f132f49d191ddb595ee96ac8fdae7e1c8f504512bb2d84121b091732bb8d4.json
rename to .sqlx/query-d5719d99feae9cf83c8c0e07de311784f69926638af6bac1fc91714b85d821af.json
index b0f5c026ca..4386f85ddc 100644
--- a/.sqlx/query-0f7f132f49d191ddb595ee96ac8fdae7e1c8f504512bb2d84121b091732bb8d4.json
+++ b/.sqlx/query-d5719d99feae9cf83c8c0e07de311784f69926638af6bac1fc91714b85d821af.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH trash_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'TRASH'\n ),\n important_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n TRUE AS \"inbox_visible!\",\n t.is_read,\n t.is_signal,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN important_labels il ON ml.label_id = il.id\n WHERE m_imp.thread_id = t.id\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery is fast as it only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.is_read,\n t.is_signal,\n t.project_id,\n t.latest_inbound_message_ts AS created_at,\n t.latest_inbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.inbox_visible = TRUE\n AND t.latest_inbound_message_ts IS NOT NULL\n\n -- The cursor logic is moved inside this subquery for maximum efficiency.\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN trash_labels tl ON ml.label_id = tl.id\n WHERE ml.message_id = m.id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n ",
+ "query": "\n WITH trash_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'TRASH'\n ),\n important_labels AS (\n SELECT id, link_id FROM email_labels WHERE link_id = ANY($1) AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n TRUE AS \"inbox_visible!\",\n t.is_read,\n t.is_signal,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n JOIN important_labels il ON ml.label_id = il.id\n WHERE m_imp.thread_id = t.id\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery is fast as it only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.is_read,\n t.is_signal,\n t.project_id,\n COALESCE(t.latest_inbound_message_ts, t.latest_outbound_message_ts, t.created_at) AS created_at,\n GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at) AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at))\n ELSE GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at)\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.inbox_visible = TRUE\n AND (t.latest_inbound_message_ts IS NOT NULL OR t.reminder_returned_at IS NOT NULL)\n\n -- The cursor logic is moved inside this subquery for maximum efficiency.\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at))\n ELSE GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at)\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN trash_labels tl ON ml.label_id = tl.id\n WHERE ml.message_id = m.id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n ",
"describe": {
"columns": [
{
@@ -115,8 +115,8 @@
false,
false,
null,
- true,
- true,
+ null,
+ null,
true,
false,
true,
@@ -130,5 +130,5 @@
false
]
},
- "hash": "0f7f132f49d191ddb595ee96ac8fdae7e1c8f504512bb2d84121b091732bb8d4"
+ "hash": "d5719d99feae9cf83c8c0e07de311784f69926638af6bac1fc91714b85d821af"
}
diff --git a/.sqlx/query-e989c1789d3ec66c72e224d107c64275b06508e6bb80960bb18e88ed050e900f.json b/.sqlx/query-e989c1789d3ec66c72e224d107c64275b06508e6bb80960bb18e88ed050e900f.json
new file mode 100644
index 0000000000..42ef2b92aa
--- /dev/null
+++ b/.sqlx/query-e989c1789d3ec66c72e224d107c64275b06508e6bb80960bb18e88ed050e900f.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM notification WHERE event_item_id = $1 AND event_item_type = 'reminder'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e989c1789d3ec66c72e224d107c64275b06508e6bb80960bb18e88ed050e900f"
+}
diff --git a/.sqlx/query-f2beae95c82ea9bbc9afb279a4b9ed66185c11f00d3608919b988ff8c4234c3f.json b/.sqlx/query-f2beae95c82ea9bbc9afb279a4b9ed66185c11f00d3608919b988ff8c4234c3f.json
new file mode 100644
index 0000000000..f51cc6b708
--- /dev/null
+++ b/.sqlx/query-f2beae95c82ea9bbc9afb279a4b9ed66185c11f00d3608919b988ff8c4234c3f.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_messages SET is_sent = true WHERE thread_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f2beae95c82ea9bbc9afb279a4b9ed66185c11f00d3608919b988ff8c4234c3f"
+}
diff --git a/.sqlx/query-f2c385527feb659c2860c556b9d99c3250384196f47c9d6e07950cfa3e65d614.json b/.sqlx/query-f2c385527feb659c2860c556b9d99c3250384196f47c9d6e07950cfa3e65d614.json
new file mode 100644
index 0000000000..9716d30c0d
--- /dev/null
+++ b/.sqlx/query-f2c385527feb659c2860c556b9d99c3250384196f47c9d6e07950cfa3e65d614.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id) VALUES ('macro|[email protected]', 'macro|[email protected]', $1)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f2c385527feb659c2860c556b9d99c3250384196f47c9d6e07950cfa3e65d614"
+}
diff --git a/.sqlx/query-f352597331c97a350007e991116375cfec7a584fda3e330f8269dee602cb6e26.json b/.sqlx/query-f352597331c97a350007e991116375cfec7a584fda3e330f8269dee602cb6e26.json
new file mode 100644
index 0000000000..225a89ba5e
--- /dev/null
+++ b/.sqlx/query-f352597331c97a350007e991116375cfec7a584fda3e330f8269dee602cb6e26.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE email_threads SET reminder_returned_at = $3 WHERE id = $1 AND link_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f352597331c97a350007e991116375cfec7a584fda3e330f8269dee602cb6e26"
+}
diff --git a/Cargo.lock b/Cargo.lock
index cc54eb6470..d6f601636e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15099,6 +15099,7 @@ dependencies = [
"chrono",
"chrono-tz",
"cron",
+ "email",
"entity_access",
"http-body-util",
"macro_authorization",
diff --git a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx
index eeccacabed..f097977b7d 100644
--- a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx
@@ -322,6 +322,7 @@ function MobileRender(
}
export type SplitFileMenuProps = {
+ onEmailReminderSaved?: () => void | Promise<void>;
id: string;
itemType: ItemType;
name: string;
@@ -367,6 +368,7 @@ export function SplitFileMenu(props: SplitFileMenuProps) {
// reminder brings the entity back, so it is marked done now. No soup list is
// behind this menu, so nothing advances.
const createReminderAction = makeCreateReminderAction({
+ onEmailSaved: props.onEmailReminderSaved,
onCreated: markReminderTargetDone(markDone),
});
const addTagAction = makeAddTagAction();
diff --git a/apps/web/src/features/block-email/component/EmailThreadControls.tsx b/apps/web/src/features/block-email/component/EmailThreadControls.tsx
index c1efd61957..c6ace23248 100644
--- a/apps/web/src/features/block-email/component/EmailThreadControls.tsx
+++ b/apps/web/src/features/block-email/component/EmailThreadControls.tsx
@@ -5,9 +5,10 @@ import EnvelopeSimpleIcon from '@phosphor/envelope-simple.svg';
import EnvelopeSimpleOpenIcon from '@phosphor/envelope-simple-open.svg';
import CheckBoldIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
import { Button } from '@ui';
-import { Show } from 'solid-js';
+import { type JSX, Show } from 'solid-js';
export function EmailThreadControls(props: {
+ reminder?: JSX.Element;
isOwnThread: boolean;
isDone: boolean;
isUnread: boolean;
@@ -16,50 +17,53 @@ export function EmailThreadControls(props: {
onToggleUnread: () => void;
}) {
return (
- <Show when={!isMobile()}>
- {/* Read-state toggle. Viewing the thread marks it read, so it
+ <>
+ {props.reminder}
+ <Show when={!isMobile()}>
+ {/* Read-state toggle. Viewing the thread marks it read, so it
starts as Mark as unread; marking unread flips it to a bold
accent closed envelope that re-marks the thread read. */}
- <Show when={props.isOwnThread}>
- <Button
- size="icon-md"
- label={props.isUnread ? 'Mark as read' : 'Mark as unread'}
- hotkey={
- props.isUnread
- ? TOKENS.entity.action.markRead
- : TOKENS.entity.action.markUnread
- }
- onClick={props.onToggleUnread}
- // Keep focus (and the hotkey scope cmd-K reads) in the thread
- // content: focusing the header would hide its commands.
- onMouseDown={(e) => e.preventDefault()}
- >
- <Show
- when={props.isUnread}
- fallback={<EnvelopeSimpleOpenIcon class="size-4" />}
+ <Show when={props.isOwnThread}>
+ <Button
+ size="icon-md"
+ label={props.isUnread ? 'Mark as read' : 'Mark as unread'}
+ hotkey={
+ props.isUnread
+ ? TOKENS.entity.action.markRead
+ : TOKENS.entity.action.markUnread
+ }
+ onClick={props.onToggleUnread}
+ // Keep focus (and the hotkey scope cmd-K reads) in the thread
+ // content: focusing the header would hide its commands.
+ onMouseDown={(e) => e.preventDefault()}
>
- <EnvelopeSimpleIcon class="size-4 text-accent" />
- </Show>
- </Button>
- </Show>
- <Show when={props.isOwnThread && props.canToggleDone}>
- <Button
- size="icon-md"
- label={props.isDone ? 'Mark as not done' : 'Mark done'}
- hotkey={
- props.isDone
- ? TOKENS.entity.action.markNotDone
- : TOKENS.entity.action.markDone
- }
- onClick={props.onToggleDone}
- // Same focus-preservation as the read-state toggle above.
- onMouseDown={(e) => e.preventDefault()}
- >
- <Show when={props.isDone} fallback={<CheckIcon class="size-4" />}>
- <CheckBoldIcon class="size-4 text-accent" />
- </Show>
- </Button>
+ <Show
+ when={props.isUnread}
+ fallback={<EnvelopeSimpleOpenIcon class="size-4" />}
+ >
+ <EnvelopeSimpleIcon class="size-4 text-accent" />
+ </Show>
+ </Button>
+ </Show>
+ <Show when={props.isOwnThread && props.canToggleDone}>
+ <Button
+ size="icon-md"
+ label={props.isDone ? 'Mark as not done' : 'Mark done'}
+ hotkey={
+ props.isDone
+ ? TOKENS.entity.action.markNotDone
+ : TOKENS.entity.action.markDone
+ }
+ onClick={props.onToggleDone}
+ // Same focus-preservation as the read-state toggle above.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <Show when={props.isDone} fallback={<CheckIcon class="size-4" />}>
+ <CheckBoldIcon class="size-4 text-accent" />
+ </Show>
+ </Button>
+ </Show>
</Show>
- </Show>
+ </>
);
}
diff --git a/apps/web/src/features/block-email/component/useEmailThreadTools.tsx b/apps/web/src/features/block-email/component/useEmailThreadTools.tsx
index 1b2b4f1a66..4904d05431 100644
--- a/apps/web/src/features/block-email/component/useEmailThreadTools.tsx
+++ b/apps/web/src/features/block-email/component/useEmailThreadTools.tsx
@@ -11,6 +11,7 @@ import {
openEntityInSplitFromUnifiedList,
trashEmails,
} from '@app/features/next-soup/utils';
+import { EmailReminderStatus } from '@app/features/reminders/email-reminder-status';
import type { BlockTool } from '@components/app/ResponsiveBlockToolbar';
import { getPermissions } from '@core/component/SharePermissions';
import { toast } from '@core/component/Toast/Toast';
@@ -295,6 +296,21 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {
tools,
menuTools: emailActions,
controls: {
+ get reminder() {
+ const entity = emailEntity();
+ return entity && isOwnThread() ? (
+ <EmailReminderStatus
+ entity={entity}
+ onSaved={async () => {
+ const navigation = props.listNavigation;
+ if (navigation?.afterReminderSaved)
+ await navigation.afterReminderSaved();
+ else if (navigation?.canNext()) navigation.next();
+ else if (navigation?.canPrevious()) navigation.previous();
+ }}
+ />
+ ) : undefined;
+ },
get isOwnThread() {
return isOwnThread();
},
diff --git a/apps/web/src/features/crm/preview-adapter.ts b/apps/web/src/features/crm/preview-adapter.ts
index 92c50bdc40..0cde3695b2 100644
--- a/apps/web/src/features/crm/preview-adapter.ts
+++ b/apps/web/src/features/crm/preview-adapter.ts
@@ -1,5 +1,12 @@
import { storageServiceClient } from '@service-storage/client';
-import { fetchCrmCompanyPreviews as fetchPreviews } from './queries/previews';
+import {
+ fetchCrmContactPreviews as fetchContacts,
+ fetchCrmCompanyPreviews as fetchPreviews,
+} from './queries/previews';
export function fetchCrmCompanyPreviews(ids: string[]) {
return fetchPreviews((input) => storageServiceClient.getCompany(input), ids);
}
+
+export function fetchCrmContactPreviews(ids: string[]) {
+ return fetchContacts((input) => storageServiceClient.getContact(input), ids);
+}
diff --git a/apps/web/src/features/crm/queries/previews.ts b/apps/web/src/features/crm/queries/previews.ts
index 978fda2060..4b7cfaee72 100644
--- a/apps/web/src/features/crm/queries/previews.ts
+++ b/apps/web/src/features/crm/queries/previews.ts
@@ -48,3 +48,30 @@ export async function fetchCrmCompanyPreviews(
})
);
}
+
+/** Contact titles use the same role-aware REST boundary as contact details. */
+export async function fetchCrmContactPreviews(
+ getContact: typeof storageServiceClient.getContact,
+ contactIds: string[]
+): Promise<PreviewItem[]> {
+ return await Promise.all(
+ contactIds.map(async (id) => {
+ const base = {
+ id,
+ type: 'crm_contact' as const,
+ loading: false as const,
+ };
+ const result = await getContact({ contactId: id });
+ if (result.isErr()) return { ...base, access: 'no_access' as const };
+ const contact = result.value;
+ const name = contact.name?.trim() || contact.email;
+ return {
+ ...base,
+ access: 'access' as const,
+ name,
+ rawName: name,
+ updatedAt: contact.updatedAt,
+ };
+ })
+ );
+}
diff --git a/apps/web/src/features/email-thread/context/email-thread-context.ts b/apps/web/src/features/email-thread/context/email-thread-context.ts
index d45d9babf9..81f04f09bd 100644
--- a/apps/web/src/features/email-thread/context/email-thread-context.ts
+++ b/apps/web/src/features/email-thread/context/email-thread-context.ts
@@ -66,6 +66,7 @@ export interface EmailThreadListNavigation {
canNext: Accessor<boolean>;
previous(): void;
next(): void;
+ afterReminderSaved?(): Promise<void>;
markDone(archiveThread: EmailThreadCommands['archiveThread']): void;
}
diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsx
index d724bf3f8d..7a7c15441a 100644
--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx
+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx
@@ -49,6 +49,7 @@ function EmailDetailHeader(
value: string;
focusThread: () => void;
controlsMount: HTMLDivElement | undefined;
+ onEmailReminderSaved: () => void | Promise<void>;
}
) {
const { emailEntity, permissions, menuTools, controls } =
@@ -84,6 +85,7 @@ function EmailDetailHeader(
permissions={permissions()}
ops={[]}
tools={menuTools}
+ onEmailReminderSaved={props.onEmailReminderSaved}
/>
</div>
</div>
@@ -158,6 +160,9 @@ export function EmailDetailView(props: {
scopeId: panel.splitHotkeyScope,
resolveEntity: commandEntity,
onDeleted: closeThread,
+ onEmailReminderSaved: async () => {
+ await listNavigation.afterReminderSaved?.();
+ },
});
let container: HTMLDivElement | undefined;
@@ -261,6 +266,9 @@ export function EmailDetailView(props: {
host={host}
chrome={({ createTask }) => (
<EmailDetailHeader
+ onEmailReminderSaved={async () => {
+ await listNavigation.afterReminderSaved?.();
+ }}
id={props.thread.id}
title={title()}
onCreateTask={createTask}
diff --git a/apps/web/src/features/email-view/use-email-detail-list-navigation.test.ts b/apps/web/src/features/email-view/use-email-detail-list-navigation.test.ts
new file mode 100644
index 0000000000..ff3db9e7a8
--- /dev/null
+++ b/apps/web/src/features/email-view/use-email-detail-list-navigation.test.ts
@@ -0,0 +1,102 @@
+import type { EmailEntity } from '@entity';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useEmailDetailListNavigation } from './use-email-detail-list-navigation';
+
+const mocks = vi.hoisted(() => ({
+ view: vi.fn(),
+ open: vi.fn(),
+ failure: vi.fn(),
+ loadMore: vi.fn(),
+}));
+vi.mock('./email-view-context', () => ({ useEmailView: mocks.view }));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.failure },
+}));
+vi.mock(
+ '@app/components/list',
+ async () => await import('@app/components/list/use-list-detail-navigation')
+);
+const disposals: (() => void)[] = [];
+beforeEach(() => vi.resetAllMocks());
+afterEach(() => {
+ for (const dispose of disposals.splice(0)) dispose();
+});
+function setup(ids: string[], current = 'b') {
+ const [rows, setRows] = createSignal(ids);
+ const [threadId, setThreadId] = createSignal(current);
+ const [hasMore, setHasMore] = createSignal(false);
+ mocks.view.mockReturnValue({
+ source: {
+ items: () =>
+ rows().map((id) => ({
+ kind: 'entity',
+ entity: { type: 'email', id, name: id } as EmailEntity,
+ })),
+ hasMore,
+ loadMore: mocks.loadMore,
+ error: () => undefined,
+ },
+ openThread: mocks.open,
+ });
+ const navigation = createRoot((dispose) => {
+ disposals.push(dispose);
+ return useEmailDetailListNavigation(threadId);
+ });
+ return { navigation, setRows, setHasMore, setThreadId };
+}
+describe('email reminder navigation', () => {
+ it('advances after the server event removes the saved row', async () => {
+ const { navigation, setRows } = setup(['a', 'b', 'c']);
+ setRows(['a', 'c']);
+ await navigation.afterReminderSaved?.();
+ expect(mocks.open).toHaveBeenCalledWith({ id: 'c', fallbackName: 'c' });
+ });
+ it('skips neighbors that no longer belong to the live filtered list', async () => {
+ const { navigation, setRows } = setup(['a', 'b', 'c', 'd']);
+ setRows(['a', 'd']);
+ await navigation.afterReminderSaved?.();
+ expect(mocks.open).toHaveBeenCalledWith({ id: 'd', fallbackName: 'd' });
+ });
+ it('falls back to a surviving previous email', async () => {
+ const { navigation, setRows } = setup(['a', 'b', 'c']);
+ setRows(['a']);
+ await navigation.afterReminderSaved?.();
+ expect(mocks.open).toHaveBeenCalledWith({ id: 'a', fallbackName: 'a' });
+ });
+ it('loads the next page before falling back when the removed email was last', async () => {
+ const { navigation, setRows, setHasMore } = setup(['a', 'b']);
+ setHasMore(true);
+ setRows(['a']);
+ mocks.loadMore.mockImplementation(async () => {
+ setRows(['a', 'c']);
+ setHasMore(false);
+ });
+ await navigation.afterReminderSaved?.();
+ expect(mocks.loadMore).toHaveBeenCalledOnce();
+ expect(mocks.open).toHaveBeenCalledWith({ id: 'c', fallbackName: 'c' });
+ });
+ it('does not navigate after the detail changes during pagination', async () => {
+ const { navigation, setRows, setHasMore, setThreadId } = setup(['a', 'b']);
+ setHasMore(true);
+ setRows(['a']);
+ mocks.loadMore.mockImplementation(async () => {
+ setRows(['a', 'c']);
+ setThreadId('other');
+ setHasMore(false);
+ });
+ await navigation.afterReminderSaved?.();
+ expect(mocks.open).not.toHaveBeenCalled();
+ });
+ it('does not reopen a removed candidate when the list becomes empty', async () => {
+ const { navigation, setRows } = setup(['a', 'b', 'c']);
+ setRows([]);
+ await navigation.afterReminderSaved?.();
+ expect(mocks.open).not.toHaveBeenCalled();
+ });
+ it('keeps the normal navigation path when the saved row remains in the source', async () => {
+ const { navigation } = setup(['a', 'b', 'c']);
+ await navigation.afterReminderSaved?.();
+ expect(mocks.open).toHaveBeenCalledWith({ id: 'c', fallbackName: 'c' });
+ });
+});
diff --git a/apps/web/src/features/email-view/use-email-detail-list-navigation.ts b/apps/web/src/features/email-view/use-email-detail-list-navigation.ts
index 0ce6ad41f6..f14bf18fa8 100644
--- a/apps/web/src/features/email-view/use-email-detail-list-navigation.ts
+++ b/apps/web/src/features/email-view/use-email-detail-list-navigation.ts
@@ -5,7 +5,7 @@ import type {
} from '@app/features/email-thread/context/email-thread-context';
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
-import type { Accessor } from 'solid-js';
+import { type Accessor, createMemo, onCleanup } from 'solid-js';
import { useEmailView } from './email-view-context';
import type { EmailDataSourceItem } from './queries/use-email-query';
@@ -14,6 +14,39 @@ export function useEmailDetailListNavigation(
threadId: Accessor<string>
): EmailThreadListNavigation {
const { source, openThread } = useEmailView();
+ const emails = () =>
+ source
+ .items()
+ .flatMap((row) =>
+ row.kind === 'entity' && row.entity.type === 'email' ? [row.entity] : []
+ );
+ // Label events can remove the saved thread before its HTTP response arrives.
+ // Retain its last position, but only navigate to candidates still in this view.
+ const reminderAnchor = createMemo<
+ | {
+ threadId: string;
+ next: string[];
+ previous: string[];
+ }
+ | undefined
+ >((previous) => {
+ const id = threadId();
+ const rows = emails();
+ const index = rows.findIndex((row) => row.id === id);
+ if (index < 0) return previous?.threadId === id ? previous : undefined;
+ return {
+ threadId: id,
+ next: rows.slice(index + 1).map((row) => row.id),
+ previous: rows
+ .slice(0, index)
+ .reverse()
+ .map((row) => row.id),
+ };
+ });
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
const navigation = useListDetailNavigation<EmailDataSourceItem, EntityData>({
currentId: threadId,
source,
@@ -32,6 +65,36 @@ export function useEmailDetailListNavigation(
return {
...navigation,
+ afterReminderSaved: async () => {
+ const id = threadId();
+ if (emails().some((row) => row.id === id)) {
+ await navigation.navigate(1, { fallbackDirection: -1 });
+ return;
+ }
+ const anchor = reminderAnchor();
+ if (!anchor || disposed) return;
+ const surviving = (ids: string[]) => {
+ const live = new Map(emails().map((row) => [row.id, row]));
+ return ids.map((candidate) => live.get(candidate)).find(Boolean);
+ };
+ try {
+ let next = surviving(anchor.next);
+ while (!next && source.hasMore() && !disposed && threadId() === id) {
+ const before = new Set(emails().map((row) => row.id));
+ await source.loadMore();
+ if (source.error()) throw source.error();
+ next =
+ surviving(anchor.next) ??
+ emails().find((row) => !before.has(row.id));
+ }
+ if (disposed || threadId() !== id) return;
+ const target = next ?? surviving(anchor.previous);
+ if (target) navigation.open(target);
+ } catch {
+ if (!disposed && threadId() === id)
+ toast.failure('Unable to open the next or previous email');
+ }
+ },
markDone: (archiveThread: EmailThreadCommands['archiveThread']) => {
void navigation.navigate(1, {
fallbackDirection: -1,
diff --git a/apps/web/src/features/entity/components/Badges.tsx b/apps/web/src/features/entity/components/Badges.tsx
index 9ceaeb0a47..d70711c8da 100644
--- a/apps/web/src/features/entity/components/Badges.tsx
+++ b/apps/web/src/features/entity/components/Badges.tsx
@@ -171,26 +171,6 @@ export function CallChannelNameBadge(props: { channelName: string }) {
);
}
-/**
- * What a reminder is about, beside its description.
- *
- * The same shape as {@link CallChannelNameBadge} — a reminder row is named by
- * its own text, so this is the only thing saying which entity it points at.
- * Presentational: the caller resolves the name and supplies the icon, since a
- * reminder can reference any entity type.
- */
-export function ReminderReferenceBadge(props: ParentProps<{ name: string }>) {
- return (
- <Badge
- class="ph-no-capture max-w-32 min-w-0 shrink-0 normal-case font-sans text-ink-extra-muted border-edge-muted px-2"
- title={props.name}
- >
- {props.children}
- <span class="truncate">{props.name}</span>
- </Badge>
- );
-}
-
/**
* How often a recurring reminder fires, e.g. "Every weekday at 9:00 AM".
*
diff --git a/apps/web/src/features/entity/composed/list-entity/reminder.tsx b/apps/web/src/features/entity/composed/list-entity/reminder.tsx
index a0c9c6bb8e..5a7c343bd9 100644
--- a/apps/web/src/features/entity/composed/list-entity/reminder.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/reminder.tsx
@@ -2,109 +2,22 @@ import {
describeReminderSchedule,
scheduleFromRow,
} from '@app/features/reminders/reminder-schedule';
-import {
- EntityIcon,
- reminderReferenceIconType,
-} from '@core/component/EntityIcon';
-import { useItemPreviewData } from '@core/component/ItemPreview';
-import { isAccessiblePreviewItem } from '@queries/preview';
import { Show } from 'solid-js';
-import {
- ReminderRecurrenceBadge,
- ReminderReferenceBadge,
-} from '../../components/Badges';
-import { Entity } from '../../entity';
+import { ReminderRecurrenceBadge } from '../../components/Badges';
+import { ReminderTitle } from '../../extractors/reminder-title';
import type { ReminderEntity } from '../../types/entity';
-type Reference = NonNullable<ReminderEntity['referencedEntity']>;
-
-/**
- * A reminder row always leads with the bell, so what it is about has to be
- * said beside its name.
- *
- * Which way round depends on whether the description is the user's own. The
- * composer's description step is optional, and skipping it names the reminder
- * after the entity — so the title either *is* the reference and takes its icon
- * inline, or it is the user's own text and the reference trails as a badge,
- * the way `CallWideContent` trails a call with its channel.
- */
export function ReminderWideContent(props: { entity: ReminderEntity }) {
- // Trails the row, after any reference badge, so the reading order is what the
- // reminder says, what it is about, then how often it repeats.
const recurrence = () =>
props.entity.scheduleType === 'recurring'
? describeReminderSchedule(scheduleFromRow(props.entity))
: undefined;
-
return (
<>
- <Show
- when={props.entity.referencedEntity}
- fallback={
- <span class="truncate">
- <Entity.Title entity={props.entity} />
- </span>
- }
- >
- {(reference) => (
- <ReferencedReminder entity={props.entity} reference={reference()} />
- )}
- </Show>
+ <ReminderTitle entity={props.entity} showNote />
<Show when={recurrence()}>
{(text) => <ReminderRecurrenceBadge recurrence={text()} />}
</Show>
</>
);
}
-
-function ReferencedReminder(props: {
- entity: ReminderEntity;
- reference: Reference;
-}) {
- const { item, name } = useItemPreviewData(() => ({
- id: props.reference.id,
- type: props.reference.type,
- }));
-
- // `name()` is the "Untitled" placeholder while the reference resolves and
- // for one the caller cannot see, so neither can be compared nor shown. Until
- // it lands the row is the bare description — no icon, no badge.
- const referenceName = () =>
- isAccessiblePreviewItem(item()) ? name().trim() || undefined : undefined;
-
- const titleIsReference = () => {
- const resolved = referenceName();
- return resolved !== undefined && resolved === props.entity.name?.trim();
- };
-
- return (
- <>
- {/* Grouped tighter than the row's own gap, so the icon reads as part of
- the name rather than as a second leading icon after the bell. */}
- <span class="flex min-w-0 items-center gap-1.5">
- <Show when={titleIsReference()}>
- <EntityIcon
- class="size-4 shrink-0"
- targetType={reminderReferenceIconType(props.reference)}
- size="fill"
- />
- </Show>
- <span class="truncate">
- <Entity.Title entity={props.entity} />
- </span>
- </span>
- <Show when={!titleIsReference() && referenceName()}>
- {(text) => (
- <ReminderReferenceBadge name={text()}>
- <EntityIcon
- class="size-3 shrink-0"
- targetType={reminderReferenceIconType(props.reference)}
- size="fill"
- theme="monochrome"
- />
- </ReminderReferenceBadge>
- )}
- </Show>
- </>
- );
-}
diff --git a/apps/web/src/features/entity/extractors/entity-title.tsx b/apps/web/src/features/entity/extractors/entity-title.tsx
index 4dd9a101f7..47424a266b 100644
--- a/apps/web/src/features/entity/extractors/entity-title.tsx
+++ b/apps/web/src/features/entity/extractors/entity-title.tsx
@@ -6,47 +6,45 @@ import { type JSX, Show } from 'solid-js';
import { match } from 'ts-pattern';
import { type EntityData, isGithubPrEntity } from '../types/entity';
import { isSearchEntity } from '../types/search';
+import { ReminderTitle } from './reminder-title';
function extractRawTitle(entity: EntityData): JSX.Element {
- return (
- match<EntityData, JSX.Element>(entity)
- .with({ type: 'document' }, (e) =>
- formatDocumentName(e.name, e.fileType, {
- fullyQualifiedBlockName: true,
- })
- )
- .with({ type: 'initiative' }, (e) => e.name || 'Untitled project')
- .with({ type: 'project' }, (e) => e.name)
- .with({ type: 'channel' }, (e) => e.name)
- .with({ type: 'channel_message' }, (e) => e.channelName)
- .with({ type: 'channel_thread' }, (e) => e.name)
- .with({ type: 'email' }, (e) => e.name || '(No Subject)')
- .with({ type: 'agent_session' }, (e) => e.name || 'Agent session')
- .with({ type: 'chat' }, (e) => e.name)
- .with({ type: 'call' }, (e) => e.name || blockNameToDefaultFile('call'))
- .with(
- { type: 'automation' },
- (e) => e.name || blockNameToDefaultFile('automation')
- )
- .when(isGithubPrEntity, (e) => (
- <>
- {e.metadata.name}{' '}
- <span class="text-ink-extra-muted font-normal">
- #{e.metadata.number}
- </span>
- </>
- ))
- .with({ type: 'foreign' }, (e) => e.name)
- .with({ type: 'crm_company' }, (e) => e.name || 'Unknown Company')
- .with(
- { type: 'crm_contact' },
- (e) => e.name || e.email || 'Unknown Contact'
- )
- // A reminder's name is its description — there is no separate title.
- .with({ type: 'reminder' }, (e) => e.name || 'Reminder')
- .with({ type: 'calendar_event' }, (e) => e.name || '(No title)')
- .otherwise(() => 'Unknown')
- );
+ return match<EntityData, JSX.Element>(entity)
+ .with({ type: 'document' }, (e) =>
+ formatDocumentName(e.name, e.fileType, {
+ fullyQualifiedBlockName: true,
+ })
+ )
+ .with({ type: 'initiative' }, (e) => e.name || 'Untitled project')
+ .with({ type: 'project' }, (e) => e.name)
+ .with({ type: 'channel' }, (e) => e.name)
+ .with({ type: 'channel_message' }, (e) => e.channelName)
+ .with({ type: 'channel_thread' }, (e) => e.name)
+ .with({ type: 'email' }, (e) => e.name || '(No Subject)')
+ .with({ type: 'agent_session' }, (e) => e.name || 'Agent session')
+ .with({ type: 'chat' }, (e) => e.name)
+ .with({ type: 'call' }, (e) => e.name || blockNameToDefaultFile('call'))
+ .with(
+ { type: 'automation' },
+ (e) => e.name || blockNameToDefaultFile('automation')
+ )
+ .when(isGithubPrEntity, (e) => (
+ <>
+ {e.metadata.name}{' '}
+ <span class="text-ink-extra-muted font-normal">
+ #{e.metadata.number}
+ </span>
+ </>
+ ))
+ .with({ type: 'foreign' }, (e) => e.name)
+ .with({ type: 'crm_company' }, (e) => e.name || 'Unknown Company')
+ .with(
+ { type: 'crm_contact' },
+ (e) => e.name || e.email || 'Unknown Contact'
+ )
+ .with({ type: 'reminder' }, (e) => e.name || 'Reminder')
+ .with({ type: 'calendar_event' }, (e) => e.name || '(No title)')
+ .otherwise(() => 'Unknown');
}
function extractSearchHighlight(entity: EntityData): string | undefined {
@@ -55,6 +53,19 @@ function extractSearchHighlight(entity: EntityData): string | undefined {
}
export function EntityTitle(props: { entity: EntityData }) {
+ const reminder = () =>
+ props.entity.type === 'reminder' ? props.entity : undefined;
+ return (
+ <Show
+ when={reminder()}
+ fallback={<OrdinaryEntityTitle entity={props.entity} />}
+ >
+ {(entity) => <ReminderTitle entity={entity()} showNote />}
+ </Show>
+ );
+}
+
+function OrdinaryEntityTitle(props: { entity: EntityData }) {
const titleData = () => {
const searchHighlight = extractSearchHighlight(props.entity);
if (searchHighlight) {
diff --git a/apps/web/src/features/entity/extractors/reminder-title.test.tsx b/apps/web/src/features/entity/extractors/reminder-title.test.tsx
new file mode 100644
index 0000000000..9082d6d0bb
--- /dev/null
+++ b/apps/web/src/features/entity/extractors/reminder-title.test.tsx
@@ -0,0 +1,39 @@
+import type { ReminderEntity } from '@entity';
+import { cleanup, render, screen } from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import { ReminderTitle } from './reminder-title';
+
+const state = vi.hoisted(() => ({
+ source: { loading: false, access: 'access', name: 'Actual email subject' },
+}));
+vi.mock('@queries/preview', () => ({
+ useItemPreview: () => [() => state.source],
+ isAccessiblePreviewItem: (item: typeof state.source) =>
+ !item.loading && item.access === 'access',
+}));
+afterEach(cleanup);
+const entity = {
+ type: 'reminder',
+ id: 'r',
+ name: 'Remember this',
+ description: 'Remember this',
+ referencedEntity: { id: 'e', type: 'email' },
+} as ReminderEntity;
+it('leads with the current source title and keeps the personal note secondary', () => {
+ state.source = {
+ loading: false,
+ access: 'access',
+ name: 'Actual email subject',
+ };
+ render(() => <ReminderTitle entity={entity} showNote />);
+ expect(screen.getByText('Actual email subject')).toBeTruthy();
+ expect(screen.getByText('Remember this').className).toContain(
+ 'text-ink-muted'
+ );
+});
+it('never presents a stale source title when access is lost', () => {
+ state.source = { loading: false, access: 'no_access', name: 'Private title' };
+ render(() => <ReminderTitle entity={entity} showNote />);
+ expect(screen.getByText('Unavailable email')).toBeTruthy();
+ expect(screen.queryByText('Private title')).toBeNull();
+});
diff --git a/apps/web/src/features/entity/extractors/reminder-title.tsx b/apps/web/src/features/entity/extractors/reminder-title.tsx
new file mode 100644
index 0000000000..0eeaa23a62
--- /dev/null
+++ b/apps/web/src/features/entity/extractors/reminder-title.tsx
@@ -0,0 +1,61 @@
+import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
+import { Show, Suspense } from 'solid-js';
+import type { ReminderEntity } from '../types/entity';
+
+/** Attached reminders take their identity from the current, accessible source. */
+export function ReminderTitle(props: {
+ entity: ReminderEntity;
+ showNote?: boolean;
+}) {
+ return (
+ <Show
+ when={props.entity.referencedEntity}
+ fallback={<span class="truncate">{props.entity.name || 'Reminder'}</span>}
+ >
+ {(reference) => (
+ <Suspense fallback={<span class="text-ink-muted">Loading…</span>}>
+ <SourceTitle
+ entity={props.entity}
+ reference={reference()}
+ showNote={props.showNote}
+ />
+ </Suspense>
+ )}
+ </Show>
+ );
+}
+
+function SourceTitle(props: {
+ entity: ReminderEntity;
+ reference: NonNullable<ReminderEntity['referencedEntity']>;
+ showNote?: boolean;
+}) {
+ const [item] = useItemPreview(() => ({
+ id: props.reference.id,
+ type: props.reference.type,
+ }));
+ const title = () => {
+ const source = item();
+ if (source.loading) return 'Loading…';
+ if (isAccessiblePreviewItem(source)) return source.name;
+ return `Unavailable ${props.reference.subType === 'task' ? 'task' : props.reference.type.replaceAll('_', ' ')}`;
+ };
+ const note = () =>
+ props.entity.description.trim() !== title().trim()
+ ? props.entity.description
+ : undefined;
+ return (
+ <span class="flex min-w-0 flex-col justify-center">
+ <span class="truncate" title={title()}>
+ {title()}
+ </span>
+ <Show when={props.showNote && note()}>
+ {(text) => (
+ <span class="truncate text-xs font-normal text-ink-muted">
+ {text()}
+ </span>
+ )}
+ </Show>
+ </span>
+ );
+}
diff --git a/apps/web/src/features/home/home-view-context.tsx b/apps/web/src/features/home/home-view-context.tsx
index 01e5ab8b00..0ad578fa9e 100644
--- a/apps/web/src/features/home/home-view-context.tsx
+++ b/apps/web/src/features/home/home-view-context.tsx
@@ -1,6 +1,7 @@
import { channelsSearch } from '@app/features/channels-view/channels-route';
import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';
import { driveSearch } from '@app/features/drive-view/primitives/drive-search';
+import { reminderSourceContent } from '@app/features/reminders/reminder-source';
import type { FacetSelection } from '@app/features/soup/filters/facets/types';
import { makePersistedState } from '@app/lib/persistence';
import {
@@ -16,6 +17,7 @@ import {
previewBlockTarget,
} from '@components/app/previewTarget';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import { isBlockAlias, resolveBlockAlias } from '@core/constant/allBlocks';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
import type { ContextProviderProps } from '@solid-primitives/context';
@@ -187,17 +189,27 @@ export const [HomeViewProvider, useHomeView] = createAssertedContextProvider<
const [previewNavigationRequest, setPreviewNavigationRequest] =
createSignal(0);
const openPreview = (entity: PreviewSelection) => {
- if (entity.type === 'calendar_event') {
- return openCalendarEvent(entity);
- }
+ if (entity.type === 'calendar_event') return openCalendarEvent(entity);
if (entity.type === 'reminder') {
- navigate(
- { route: homeReminderRoute, params: { reminderId: entity.id } },
- { search: withTab(homeDetailSearch()) }
- );
- return true;
+ const source = reminderSourceContent(entity);
+ if (!source) {
+ navigate(
+ { route: homeReminderRoute, params: { reminderId: entity.id } },
+ { search: withTab(homeDetailSearch()) }
+ );
+ return true;
+ }
+ return openPreviewTarget({
+ blockType: resolveBlockAlias(source.type),
+ blockId: source.id,
+ aliasContext: isBlockAlias(source.type)
+ ? { alias: source.type, baseType: resolveBlockAlias(source.type) }
+ : undefined,
+ });
}
- const target = previewBlockTarget(entity);
+ return openPreviewTarget(previewBlockTarget(entity));
+ };
+ const openPreviewTarget = (target: PreviewBlockTarget) => {
if (!selectPreview.canSelect(target)) return false;
const current = previewTarget();
if (
diff --git a/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts b/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts
index 2caa85c62a..a03a81d928 100644
--- a/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts
+++ b/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts
@@ -196,7 +196,7 @@ describe('makeCreateReminderAction', () => {
// Marking done from a list moves focus off the row, which needs the list.
it('passes the list to the created handler when driven from one', async () => {
const onCreated = vi.fn();
- const target = entity('email', 'thread-1');
+ const target = entity('document', 'doc-1');
const soup = soupState();
await makeCreateReminderAction({ onCreated }).executeWithSoup(
@@ -209,6 +209,43 @@ describe('makeCreateReminderAction', () => {
expect(onCreated).toHaveBeenCalledWith(target, { soup, advances: true });
});
+ it.each([false, true])(
+ 'email save has one navigation owner (host callback: %s)',
+ async (hosted) => {
+ const onCreated = vi.fn();
+ const onEmailSaved = vi.fn();
+ const target = entity('email', 'thread-1');
+ const next = { id: 'thread-2', original: entity('email', 'thread-2') };
+ const focus = vi.fn();
+ const clear = vi.fn();
+ const onNavigate = vi.fn();
+ const soup = {
+ navigate: { peekOffset: () => ({ row: next, index: 1 }) },
+ focus: { set: focus },
+ selection: { clear },
+ } as unknown as SoupState;
+ await makeCreateReminderAction({
+ onCreated,
+ onEmailSaved: hosted ? onEmailSaved : undefined,
+ }).executeWithSoup([target], soup, { advances: true, onNavigate });
+ expect(focus).not.toHaveBeenCalled();
+ await composerOnCreated()?.();
+ expect(onCreated).not.toHaveBeenCalled();
+ if (hosted) {
+ expect(onEmailSaved).toHaveBeenCalledOnce();
+ expect(focus).not.toHaveBeenCalled();
+ expect(onNavigate).not.toHaveBeenCalled();
+ } else {
+ expect(onEmailSaved).not.toHaveBeenCalled();
+ expect(focus).toHaveBeenCalledWith('thread-2');
+ expect(onNavigate).toHaveBeenCalledWith({
+ actionId: 'create-reminder',
+ entity: next.original,
+ });
+ }
+ }
+ );
+
// Whether the list moves on is the surface's answer, carried through to the
// handler rather than guessed at from the list.
it('carries a list that does not advance through to the handler', async () => {
diff --git a/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts b/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts
index f39aadf2da..2c8d410aa6 100644
--- a/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-create-reminder-action.ts
@@ -31,6 +31,7 @@ export type ReminderCreatedHandler = (
type MakeCreateReminderOptions = {
onCreated?: ReminderCreatedHandler;
+ onEmailSaved?: () => void | Promise<void>;
};
/**
@@ -59,7 +60,10 @@ export const makeCreateReminderAction = (
const [entity] = entities;
if (!entity || !canExecute(entity)) return;
openReminderComposer(entity, {
- onCreated: () => options?.onCreated?.(entity),
+ onCreated: () =>
+ entity.type === 'email'
+ ? options?.onEmailSaved?.()
+ : options?.onCreated?.(entity),
});
};
@@ -74,6 +78,37 @@ export const makeCreateReminderAction = (
) => {
const [entity] = entities;
if (!entity || !canExecute(entity)) return;
+ if (entity.type === 'email') {
+ const next = [1, -1]
+ .map((direction) =>
+ soup.navigate.peekOffset(direction, {
+ wrapNavigation: false,
+ skipGroupHeaders: true,
+ skipLoadMore: true,
+ })
+ )
+ .find(
+ (candidate) => candidate && candidate.row.original.id !== entity.id
+ )?.row;
+ openReminderComposer(entity, {
+ onCreated: async () => {
+ // A hosted email view owns pagination and its navigation history.
+ if (options?.onEmailSaved) {
+ await options.onEmailSaved();
+ return;
+ }
+ if (opts.advances) {
+ soup.selection.clear();
+ soup.focus.set(next?.id);
+ opts.onNavigate?.({
+ actionId: 'create-reminder',
+ entity: next?.original,
+ });
+ }
+ },
+ });
+ return;
+ }
// Opening the composer doesn't change the list, so selection and focus are
// left where they are until the reminder exists — `onCreated` is what moves
// them, by way of marking the row done.
diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts
index 12cbcecb62..96ef6e3c86 100644
--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts
+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.test.ts
@@ -2,14 +2,14 @@ import type { EntityData, ReminderEntity } from '@entity';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
- openEntityInSplitFromUnifiedList: vi.fn(),
+ openReminderDetail: vi.fn(),
remindersEnabled: true,
activeSplit: { id: 'controller' } as unknown,
}));
// The action opens the reminder's editor the same way a row click does.
-vi.mock('../utils', () => ({
- openEntityInSplitFromUnifiedList: mocks.openEntityInSplitFromUnifiedList,
+vi.mock('@app/features/reminders/reminder-navigation', () => ({
+ openReminderDetail: mocks.openReminderDetail,
}));
vi.mock('@app/signal/splitLayout', () => ({
@@ -51,10 +51,10 @@ describe('makeEditReminderAction', () => {
const row = reminder();
makeEditReminderAction().execute([row]);
- expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledWith(
- row,
+ expect(mocks.openReminderDetail).toHaveBeenCalledWith(
+ row.id,
expect.objectContaining({
- splitHandle: mocks.activeSplit,
+ handle: mocks.activeSplit,
referredFrom: null,
})
);
@@ -63,7 +63,7 @@ describe('makeEditReminderAction', () => {
it('does nothing for an empty selection', () => {
makeEditReminderAction().execute([]);
- expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();
+ expect(mocks.openReminderDetail).not.toHaveBeenCalled();
});
// The editor is about one reminder's time, so a multi-select is not a batch —
@@ -73,9 +73,9 @@ describe('makeEditReminderAction', () => {
makeEditReminderAction().execute([first, reminder({ id: 'rem-2' })]);
- expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledOnce();
- expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledWith(
- first,
+ expect(mocks.openReminderDetail).toHaveBeenCalledOnce();
+ expect(mocks.openReminderDetail).toHaveBeenCalledWith(
+ first.id,
expect.anything()
);
});
@@ -83,7 +83,7 @@ describe('makeEditReminderAction', () => {
it('does not open the editor for a non-reminder', () => {
makeEditReminderAction().execute([entity('document')]);
- expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();
+ expect(mocks.openReminderDetail).not.toHaveBeenCalled();
});
it('cannot run when the reminders flag is off', () => {
@@ -99,7 +99,7 @@ describe('makeEditReminderAction', () => {
makeEditReminderAction().execute([reminder()]);
- expect(mocks.openEntityInSplitFromUnifiedList).not.toHaveBeenCalled();
+ expect(mocks.openReminderDetail).not.toHaveBeenCalled();
});
// The soup context menu and soup command menu both drive actions through
@@ -112,6 +112,6 @@ describe('makeEditReminderAction', () => {
>[1]
);
- expect(mocks.openEntityInSplitFromUnifiedList).toHaveBeenCalledOnce();
+ expect(mocks.openReminderDetail).toHaveBeenCalledOnce();
});
});
diff --git a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts
index 50d8a9b1fa..79f36c205c 100644
--- a/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-edit-reminder-action.ts
@@ -1,16 +1,10 @@
+import { openReminderDetail } from '@app/features/reminders/reminder-navigation';
import { globalSplitManager } from '@app/signal/splitLayout';
import { enableReminders, isFeatureEnabled } from '@core/constant/featureFlags';
import type { EntityData } from '@entity';
-import { openEntityInSplitFromUnifiedList } from '../utils';
import type { EntityActionListState } from './entity-action-context';
-/**
- * Edit an existing reminder — its description, its schedule, or both.
- *
- * Opens the reminder's editor the same way a row click does: through
- * {@link openEntityInSplitFromUnifiedList}, which resolves the reminder to its
- * native detail route. Single-entity only, like creating one.
- */
+/** Edit scheduling without following an attached reminder to its source. */
export const makeEditReminderAction = () => {
const canExecute = (entity: EntityData): boolean =>
isFeatureEnabled(enableReminders) && entity.type === 'reminder';
@@ -21,8 +15,8 @@ export const makeEditReminderAction = () => {
// otherwise still fire against a row that has since changed.
if (!entity || entity.type !== 'reminder' || !canExecute(entity)) return;
- openEntityInSplitFromUnifiedList(entity, {
- splitHandle: globalSplitManager()?.activeSplit(),
+ openReminderDetail(entity.id, {
+ handle: globalSplitManager()?.activeSplit(),
referredFrom: null,
});
};
diff --git a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
index 12719eaa63..daca3d0ca3 100644
--- a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
+++ b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
@@ -59,6 +59,7 @@ export type UseBlockEntityCommandsOptions = {
scopeId?: string;
resolveEntity?: () => EntityData | undefined;
onDeleted?: () => void;
+ onEmailReminderSaved?: () => void | Promise<void>;
};
export const useBlockEntityCommands = (
@@ -173,6 +174,7 @@ export const useBlockEntityCommands = (
// after `advanceSplitTo` so the follow-up advances exactly as 'e' does.
const createReminderAction = makeCreateReminderAction({
onCreated: markReminderTargetDone(markDone, advanceSplitTo),
+ onEmailSaved: options.onEmailReminderSaved,
});
/**
@@ -198,6 +200,7 @@ export const useBlockEntityCommands = (
if (soup && selectedRow) {
void createReminderAction.executeWithSoup([selectedRow.original], soup, {
advances: true,
+ onNavigate: advanceSplitTo,
});
return true;
}
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 6b519c26d6..2326fd2de1 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -214,6 +214,54 @@ describe('reminder navigation', () => {
}
);
+ it('opens an attached task in its requested Drive route rather than reusing another document', async () => {
+ const openWithSplit = vi.fn(() => ({ status: 'navigating' as const }));
+ setGlobalSplitManager({
+ activeSplit: () => undefined,
+ openWithSplit,
+ } as unknown as SplitManager);
+ await openEntityInSplitFromUnifiedList(
+ {
+ ...reminder,
+ referencedEntity: {
+ id: 'task-b',
+ type: 'document',
+ fileType: 'md',
+ subType: 'task',
+ },
+ } as EntityData,
+ {}
+ );
+ expect(openWithSplit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'component',
+ id: 'documents',
+ entryMetadata: expect.objectContaining({
+ route: expect.objectContaining({
+ matches: expect.arrayContaining([
+ expect.objectContaining({
+ params: { documentId: 'task-b', documentType: 'task' },
+ }),
+ ]),
+ }),
+ }),
+ }),
+ expect.objectContaining({ allowDuplicate: true })
+ );
+ });
+
+ it('opens an attached email directly in a new tab', () => {
+ openEntityInNewTab({
+ entity: {
+ ...reminder,
+ referencedEntity: { id: 'email-1', type: 'email' },
+ } as EntityData,
+ });
+ expect(operationMocks.openExternalUrl).toHaveBeenCalledWith(
+ expect.stringMatching(/\/app\/email\/email-1$/)
+ );
+ });
+
it('uses the same reminder component URL for a new browser tab', () => {
openEntityInNewTab({ entity: reminder });
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index f8ca028707..0910db73fa 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -20,6 +20,7 @@ import {
reminderDetailDestination,
reminderDetailUrl,
} from '@app/features/reminders/reminder-navigation';
+import { reminderSourceContent } from '@app/features/reminders/reminder-source';
import { reviewsHostedContent } from '@app/features/reviews-view/reviews-hosted-content';
import { withListNavigationSource } from '@app/features/soup/collection/list-navigation-source';
import {
@@ -274,7 +275,15 @@ export const openEntityInNewTab = ({
location ??= getRowClickFallbackLocation(entity);
if (entity.type === 'reminder') {
if (!isFeatureEnabled(enableReminders)) return;
- openExternalUrl(reminderDetailUrl(entity.id));
+ const source = reminderSourceContent(entity);
+ openExternalUrl(
+ source
+ ? new URL(
+ `/app/${source.type}/${encodeURIComponent(source.id)}`,
+ window.location.origin
+ ).toString()
+ : reminderDetailUrl(entity.id)
+ );
return;
}
@@ -711,6 +720,26 @@ export const openEntityInSplitFromUnifiedList = async (
sourceContent?.type === 'component' && isListViewID(sourceContent.id)
? sourceContent.id
: undefined;
+ const source = reminderSourceContent(entity);
+ if (source) {
+ const hostedContent = driveHostedContent(source, {
+ allowDocuments: !isTouchDevice(),
+ });
+ const referredFrom = options.referredFrom ?? sourceListView;
+ let content = hostedContent ?? source;
+ if (splitHandle && referredFrom && isListViewID(referredFrom)) {
+ content = withListNavigationSource(content, splitHandle);
+ }
+ splitManager.openWithSplit(content, {
+ allowDuplicate: allowDuplicate || hostedContent !== undefined,
+ activate: true,
+ handle: splitHandle,
+ preferNewSplit: openInNewSplit,
+ mergeHistory,
+ referredFrom: options.referredFrom ?? sourceListView,
+ });
+ return;
+ }
openReminderDetail(entity.id, {
manager: splitManager,
handle: splitHandle,
@@ -994,7 +1023,10 @@ function getEntitySplitContent(entity: EntityData) {
return { type: 'contact' as const, id: entity.id };
})
.with({ type: 'reminder' }, (entity) => {
- return reminderDetailDestination(entity.id).content;
+ return (
+ reminderSourceContent(entity) ??
+ reminderDetailDestination(entity.id).content
+ );
})
// Calendar events open the singleton Calendar application view; the open
// path branches before reaching here, so this only serves duplicate checks.
diff --git a/apps/web/src/features/reminders/ReminderComposerModal.test.tsx b/apps/web/src/features/reminders/ReminderComposerModal.test.tsx
index 81987cc1dd..3419eb2805 100644
--- a/apps/web/src/features/reminders/ReminderComposerModal.test.tsx
+++ b/apps/web/src/features/reminders/ReminderComposerModal.test.tsx
@@ -9,6 +9,7 @@ import { createSignal, type ParentProps, Show } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { ReminderComposerModal } from './ReminderComposerModal';
import {
+ chooseReminderTarget,
closeReminderComposer,
openStandaloneReminderComposer,
reminderComposerOpen,
@@ -34,6 +35,10 @@ vi.mock('@core/component/Toast/Toast', () => ({
vi.mock('@entity/components/EntitySelectionBadge', () => ({
EntitySelectionBadge: () => null,
}));
+vi.mock('./views/reminder-entity-picker', () => ({
+ ReminderEntityPicker: () => null,
+}));
+vi.mock('@entity', () => ({ Entity: { Icon: () => null, Title: () => null } }));
vi.mock('@ui', () => {
const Slot = (props: ParentProps) => props.children;
return {
@@ -111,6 +116,7 @@ it('keeps the draft open and prevents concurrent duplicate submits', async () =>
);
const onCreated = vi.fn();
openStandaloneReminderComposer({ onCreated });
+ chooseReminderTarget();
render(() => <ReminderComposerModal />);
const input = screen.getByRole('textbox', {
@@ -148,6 +154,7 @@ it('retries with the same draft and opens View while route application is deferr
.mockResolvedValueOnce(savedReminder());
const onCreated = vi.fn();
openStandaloneReminderComposer({ onCreated });
+ chooseReminderTarget();
render(() => <ReminderComposerModal />);
const input = screen.getByRole('textbox', {
@@ -187,6 +194,7 @@ it('waits for a deferred mutation before closing and running the follow-up', asy
);
const onCreated = vi.fn();
openStandaloneReminderComposer({ onCreated });
+ chooseReminderTarget();
render(() => <ReminderComposerModal />);
fireEvent.submit(screen.getByRole('form', { name: 'Reminder form' }));
diff --git a/apps/web/src/features/reminders/ReminderComposerModal.tsx b/apps/web/src/features/reminders/ReminderComposerModal.tsx
index 71d61862d1..7762c5b5e8 100644
--- a/apps/web/src/features/reminders/ReminderComposerModal.tsx
+++ b/apps/web/src/features/reminders/ReminderComposerModal.tsx
@@ -1,7 +1,7 @@
import { openReminderDetail } from '@app/features/reminders/reminder-navigation';
import { toast } from '@core/component/Toast/Toast';
-import type { EntityData } from '@entity';
-import { EntitySelectionBadge } from '@entity/components/EntitySelectionBadge';
+import { Entity, type EntityData } from '@entity';
+
import {
reminderTarget,
useCreateReminderMutation,
@@ -10,13 +10,15 @@ import { refetchSoupEntity } from '@queries/soup/cache';
import type { CreateReminderRequest } from '@service-storage/generated/schemas/createReminderRequest';
import type { Reminder } from '@service-storage/generated/schemas/reminder';
import type { ReminderSchedule } from '@service-storage/generated/schemas/reminderSchedule';
-import { ActionDialogShell, Dialog } from '@ui';
+import { ActionDialogShell, Button, Dialog } from '@ui';
import { createSignal, Show } from 'solid-js';
import { ReminderForm } from './ReminderForm';
import {
+ chooseReminderTarget,
closeReminderComposer,
reminderComposerOpen,
reminderComposerState,
+ showReminderEntityPicker,
takeReminderCreatedHandler,
} from './reminder-composer';
import {
@@ -24,6 +26,8 @@ import {
resolveReminderDescription,
resolveStandaloneDescription,
} from './reminder-schedule';
+import { EmailReminderComposer } from './views/email-reminder-composer';
+import { ReminderEntityPicker } from './views/reminder-entity-picker';
const CREATE_FAILURE_MESSAGE =
'We couldn’t save this reminder. Your draft is still here—try again. If the request timed out, it may already exist; check Reminders before retrying.';
@@ -159,42 +163,83 @@ export function ReminderComposerModal() {
class="w-[calc(100vw-2rem)] max-w-110"
>
<ActionDialogShell>
- <Show when={hasTarget()}>
- <ReminderForm
- layout="dialog"
- header={
- <ActionDialogShell.Header>
- <ActionDialogShell.Title>New reminder</ActionDialogShell.Title>
- <ActionDialogShell.Description>
- Choose when you’d like to be reminded.
- </ActionDialogShell.Description>
- </ActionDialogShell.Header>
- }
- placeholder={
- standalone()
- ? "What's the reminder?"
- : "What's the reminder? (optional)"
- }
- descriptionRequired={standalone()}
- submitLabel="Set reminder"
- autofocus
- pending={submitting()}
- error={saveError()}
- reference={
+ <Show
+ when={reminderComposerState.choosing}
+ fallback={
+ <Show
+ when={entity()?.type === 'email'}
+ fallback={
+ <Show when={hasTarget()}>
+ <ReminderForm
+ layout="dialog"
+ header={
+ <ActionDialogShell.Header>
+ <ActionDialogShell.Title>
+ {standalone() ? 'New reminder' : 'Remind me'}
+ </ActionDialogShell.Title>
+ <ActionDialogShell.Description>
+ Choose when you’d like to be reminded.
+ </ActionDialogShell.Description>
+ </ActionDialogShell.Header>
+ }
+ placeholder={
+ standalone()
+ ? 'What would you like to remember?'
+ : "What's the reminder? (optional)"
+ }
+ descriptionRequired={standalone()}
+ optionalNote={!standalone()}
+ submitLabel="Set reminder"
+ autofocus
+ pending={submitting()}
+ error={saveError()}
+ reference={
+ <Show when={entity()}>
+ {(target) => (
+ <div class="flex min-w-0 items-center gap-3 rounded-lg border border-edge-muted p-3">
+ <span class="size-6 shrink-0">
+ <Entity.Icon entity={target()} />
+ </span>
+ <span class="min-w-0 flex-1 font-medium">
+ <Entity.Title entity={target()} />
+ </span>
+ <Show when={!submitting()}>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={showReminderEntityPicker}
+ >
+ Change
+ </Button>
+ </Show>
+ </div>
+ )}
+ </Show>
+ }
+ onCancel={() => {
+ if (submitting()) return;
+ setSaveError(undefined);
+ closeReminderComposer();
+ }}
+ onSubmit={(values) => void handleSubmit(values)}
+ />
+ </Show>
+ }
+ >
<Show when={entity()}>
{(target) => (
- <div class="flex min-w-0">
- <EntitySelectionBadge entity={target()} />
- </div>
+ <EmailReminderComposer
+ entity={target()}
+ onPending={setSubmitting}
+ />
)}
</Show>
- }
- onCancel={() => {
- if (submitting()) return;
- setSaveError(undefined);
- closeReminderComposer();
- }}
- onSubmit={(values) => void handleSubmit(values)}
+ </Show>
+ }
+ >
+ <ReminderEntityPicker
+ onSelect={chooseReminderTarget}
+ onWrite={() => chooseReminderTarget()}
/>
</Show>
</ActionDialogShell>
diff --git a/apps/web/src/features/reminders/ReminderEditorSplit.tsx b/apps/web/src/features/reminders/ReminderEditorSplit.tsx
index f229de50fa..ee806cd23a 100644
--- a/apps/web/src/features/reminders/ReminderEditorSplit.tsx
+++ b/apps/web/src/features/reminders/ReminderEditorSplit.tsx
@@ -24,6 +24,7 @@ import { Button } from '@ui';
import {
createMemo,
createSignal,
+ type JSX,
Match,
onCleanup,
Show,
@@ -35,6 +36,7 @@ import {
reminderEditPatch,
resolveEditedDescription,
} from './reminder-schedule';
+import { EmailReminderDetails } from './views/email-reminder-details';
/** The display type an inline mention takes for the referenced entity. */
type MentionType = NonNullable<ReminderEntity['referencedEntity']>['type'];
@@ -219,64 +221,68 @@ function ReminderDetailsForId(props: {
<Switch>
<Match when={query.isSuccess ? query.data : undefined}>
{(reminder) => (
- <ReminderForm
- initialDescription={reminder().description}
- initialSchedule={reminder().schedule}
- initialRemindAt={reminder().nextRunAt}
- placeholder="Reminder description"
- submitLabel="Save"
- pending={updateReminder.isPending}
- error={updateError()}
- reference={
- <>
- <Show when={reference()}>
- {(ref) => (
- <div class="flex flex-col gap-1">
- <span class="text-xs font-medium text-ink-muted">
- Original item
- </span>
- <div class="flex">
- <ItemPreview id={ref().id} type={ref().type} />
+ <EmailDetailsGate reminder={reminder()} onClose={props.onClose}>
+ <ReminderForm
+ initialDescription={reminder().description}
+ initialSchedule={reminder().schedule}
+ initialRemindAt={reminder().nextRunAt}
+ placeholder="Reminder description"
+ submitLabel="Save"
+ pending={updateReminder.isPending}
+ error={updateError()}
+ reference={
+ <>
+ <Show when={reference()}>
+ {(ref) => (
+ <div class="flex flex-col gap-1">
+ <span class="text-xs font-medium text-ink-muted">
+ Original item
+ </span>
+ <div class="flex">
+ <ItemPreview id={ref().id} type={ref().type} />
+ </div>
</div>
- </div>
- )}
- </Show>
- <Show
- when={calendarUiEnabled() ? calendarEventId() : undefined}
- >
- {(eventId) => (
- <div class="flex flex-col gap-1">
- <span class="text-xs font-medium text-ink-muted">
- Original item
- </span>
- <Button
- type="button"
- variant="outline"
- size="sm"
- class="self-start"
- onClick={() =>
- void openCalendarEventSplit({
- eventId: eventId(),
- })
- }
- >
- <CalendarBlankIcon class="size-4" />
- Open calendar event
- </Button>
- </div>
- )}
- </Show>
- </>
- }
- revertOnCancel
- onCancel={(wasDirty) => {
- setUpdateError(undefined);
- // Reverting an edit keeps the panel open; a clean cancel
- // dismisses the preview.
- if (!wasDirty) props.onClose();
- }}
- onSubmit={(values) => void save(values, reminder())}
- />
+ )}
+ </Show>
+ <Show
+ when={
+ calendarUiEnabled() ? calendarEventId() : undefined
+ }
+ >
+ {(eventId) => (
+ <div class="flex flex-col gap-1">
+ <span class="text-xs font-medium text-ink-muted">
+ Original item
+ </span>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ class="self-start"
+ onClick={() =>
+ void openCalendarEventSplit({
+ eventId: eventId(),
+ })
+ }
+ >
+ <CalendarBlankIcon class="size-4" />
+ Open calendar event
+ </Button>
+ </div>
+ )}
+ </Show>
+ </>
+ }
+ revertOnCancel
+ onCancel={(wasDirty) => {
+ setUpdateError(undefined);
+ // Reverting an edit keeps the panel open; a clean cancel
+ // dismisses the preview.
+ if (!wasDirty) props.onClose();
+ }}
+ onSubmit={(values) => void save(values, reminder())}
+ />
+ </EmailDetailsGate>
)}
</Match>
<Match when={query.isPending}>
@@ -305,3 +311,30 @@ export function ReminderEditorSplit(props: { reminderId: string | undefined }) {
/>
);
}
+
+function EmailDetailsGate(props: {
+ reminder: Reminder;
+ onClose: () => void;
+ children: JSX.Element;
+}) {
+ return (
+ <Show
+ when={
+ props.reminder.entityType === 'email_thread'
+ ? props.reminder.entityId
+ : undefined
+ }
+ fallback={props.children}
+ >
+ {(threadId) => (
+ <EmailReminderDetails
+ reminder={props.reminder}
+ threadId={threadId()}
+ onClose={props.onClose}
+ >
+ {props.children}
+ </EmailReminderDetails>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/reminders/ReminderForm.tsx b/apps/web/src/features/reminders/ReminderForm.tsx
index 081064ab72..3a42d1c92c 100644
--- a/apps/web/src/features/reminders/ReminderForm.tsx
+++ b/apps/web/src/features/reminders/ReminderForm.tsx
@@ -82,6 +82,8 @@ export interface ReminderFormProps {
placeholder: string;
/** A standalone reminder has no entity to name it after, so it needs a title. */
descriptionRequired?: boolean;
+ /** Attached creation keeps a personal note optional and secondary. */
+ optionalNote?: boolean;
/** A card or chip for the entity this reminder is about, shown above the title. */
reference?: JSX.Element;
submitLabel: string;
@@ -384,11 +386,13 @@ export function ReminderForm(props: ReminderFormProps) {
const whenLabelId = createUniqueId();
const whenInputId = createUniqueId();
const whenOptionsId = createUniqueId();
+ const [noteOpen, setNoteOpen] = createSignal(false);
+ let whenRef: HTMLInputElement | undefined;
let titleRef: HTMLInputElement | undefined;
let errorRef: HTMLDivElement | undefined;
let customControlsRef: HTMLDivElement | undefined;
onMount(() => {
- if (props.autofocus) titleRef?.focus();
+ if (props.autofocus) (props.optionalNote ? whenRef : titleRef)?.focus();
});
const pickedOnceDateTime = () =>
@@ -713,28 +717,45 @@ export function ReminderForm(props: ReminderFormProps) {
class="flex min-w-0 flex-col gap-3"
disabled={props.pending}
>
- <div class="flex flex-col gap-2">
- <label
- for={descriptionId}
- class="text-xs font-medium text-ink-muted"
- >
- Reminder
- </label>
- <Input
- id={descriptionId}
- ref={titleRef}
- type="text"
- value={description()}
- onInput={(event) => setDescription(event.currentTarget.value)}
- placeholder={props.placeholder}
- aria-label="Reminder description"
- // Counts UTF-16 code units where the service counts characters, so this
- // only ever stops short of the real limit, never past it. The
- // description resolvers apply the exact cap.
- maxLength={REMINDER_DESCRIPTION_MAX_LENGTH}
- size="lg"
- />
- </div>
+ <Show
+ when={!props.optionalNote || noteOpen()}
+ fallback={
+ <Button
+ variant="ghost"
+ size="sm"
+ class="self-start"
+ onClick={() => {
+ setNoteOpen(true);
+ queueMicrotask(() => titleRef?.focus());
+ }}
+ >
+ Add a note
+ </Button>
+ }
+ >
+ <div class="flex flex-col gap-2">
+ <label
+ for={descriptionId}
+ class="text-xs font-medium text-ink-muted"
+ >
+ {props.optionalNote ? 'Note' : 'Reminder'}
+ </label>
+ <Input
+ id={descriptionId}
+ ref={titleRef}
+ type="text"
+ value={description()}
+ onInput={(event) => setDescription(event.currentTarget.value)}
+ placeholder={props.placeholder}
+ aria-label="Reminder description"
+ // Counts UTF-16 code units where the service counts characters, so this
+ // only ever stops short of the real limit, never past it. The
+ // description resolvers apply the exact cap.
+ maxLength={REMINDER_DESCRIPTION_MAX_LENGTH}
+ size="lg"
+ />
+ </div>
+ </Show>
<Show when={repeat() === 'once'}>
<section
@@ -750,6 +771,7 @@ export function ReminderForm(props: ReminderFormProps) {
</label>
<Input
id={whenInputId}
+ ref={whenRef}
type="text"
value={whenQuery()}
onInput={(event) => setWhenQuery(event.currentTarget.value)}
diff --git a/apps/web/src/features/reminders/components/email-reminder-form.test.tsx b/apps/web/src/features/reminders/components/email-reminder-form.test.tsx
new file mode 100644
index 0000000000..8d39aa3710
--- /dev/null
+++ b/apps/web/src/features/reminders/components/email-reminder-form.test.tsx
@@ -0,0 +1,68 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { EmailReminderForm } from './email-reminder-form';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-01T12:00:00Z'));
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+function setup(
+ overrides: Partial<Parameters<typeof EmailReminderForm>[0]> = {}
+) {
+ const onSave = vi.fn();
+ const onCancel = vi.fn();
+ render(() => (
+ <EmailReminderForm
+ subject="A known conversation"
+ pending={false}
+ onSave={onSave}
+ onCancel={onCancel}
+ {...overrides}
+ />
+ ));
+ return { onSave, onCancel };
+}
+describe('email reminder time-first form', () => {
+ it('uses the known subject, defaults to no reply and parses a relative time', () => {
+ const { onSave } = setup();
+ expect(screen.queryByLabelText('Reminder description')).toBeNull();
+ fireEvent.input(screen.getByLabelText('When'), {
+ target: { value: 'in 30m' },
+ });
+ fireEvent.submit(screen.getByLabelText('When').closest('form')!);
+ expect(onSave).toHaveBeenCalledWith(
+ new Date('2026-10-01T12:30:00Z'),
+ 'if_no_reply'
+ );
+ });
+ it('preserves the existing instant on an untouched edit and exposes removal', () => {
+ const onRemove = vi.fn();
+ const { onSave } = setup({
+ initialTime: '2026-11-01T06:30:15Z',
+ initialCondition: 'regardless',
+ onRemove,
+ });
+ fireEvent.submit(screen.getByLabelText('When').closest('form')!);
+ expect(onSave).toHaveBeenCalledWith(
+ new Date('2026-11-01T06:30:15Z'),
+ 'regardless'
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+ expect(onRemove).toHaveBeenCalledOnce();
+ });
+ it('keeps invalid and pending submissions from writing', () => {
+ const { onSave } = setup({ pending: true });
+ fireEvent.submit(screen.getByLabelText('When').closest('form')!);
+ expect(onSave).not.toHaveBeenCalled();
+ });
+ it('cancel never submits', () => {
+ const { onCancel, onSave } = setup();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(onCancel).toHaveBeenCalledOnce();
+ expect(onSave).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/reminders/components/email-reminder-form.tsx b/apps/web/src/features/reminders/components/email-reminder-form.tsx
new file mode 100644
index 0000000000..b3d13b220c
--- /dev/null
+++ b/apps/web/src/features/reminders/components/email-reminder-form.tsx
@@ -0,0 +1,271 @@
+import { getDefaultTimezone } from '@core/util/cron';
+import { parseTime, useDateSearch } from '@core/util/dateSearch/useDateSearch';
+import { ActionDialogShell, Button, Input, SegmentedControl } from '@ui';
+import {
+ createSignal,
+ createUniqueId,
+ For,
+ type JSX,
+ onMount,
+ Show,
+} from 'solid-js';
+import {
+ EventDateField,
+ EventTimeInput,
+} from '../../calendar/components/composer/EventDateTimeInputs';
+import {
+ formatReminderInstant,
+ parseLocalReminderDateTime,
+ REMINDER_DEFAULT_TIME,
+ reminderQuickPresets,
+} from '../reminder-schedule';
+
+export type EmailReminderCondition = 'if_no_reply' | 'regardless';
+
+/** Time-first, single-occurrence email form. The host owns persistence. */
+export function EmailReminderForm(props: {
+ subject: string;
+ header?: JSX.Element;
+ autofocus?: boolean;
+ initialTime?: string;
+ initialCondition?: EmailReminderCondition;
+ pending: boolean;
+ error?: string;
+ onSave: (at: Date, condition: EmailReminderCondition) => void;
+ onRemove?: () => void;
+ onCancel: () => void;
+}) {
+ let whenInput: HTMLInputElement | undefined;
+ // The server status may load after the dialog's initial autofocus pass.
+ onMount(() => {
+ if (props.autofocus) queueMicrotask(() => whenInput?.focus());
+ });
+ const now = new Date();
+ const zone = getDefaultTimezone();
+ const presets = reminderQuickPresets(now);
+ const presetTime = (at: Date) =>
+ new Intl.DateTimeFormat(undefined, {
+ timeZone: zone,
+ hour: 'numeric',
+ minute: '2-digit',
+ }).format(at);
+ const presetDay = (at: Date) =>
+ new Intl.DateTimeFormat(undefined, {
+ timeZone: zone,
+ weekday: 'short',
+ month: 'short',
+ day: 'numeric',
+ }).format(at);
+ const seed = props.initialTime
+ ? new Date(props.initialTime)
+ : presets[0].date;
+ const [instant, setInstant] = createSignal<Date | undefined>(seed);
+ const [query, setQuery] = createSignal('');
+ const [custom, setCustom] = createSignal(false);
+ const pad = (n: number) => String(n).padStart(2, '0');
+ const dateValue = (at: Date) =>
+ `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`;
+ const timeValue = (at: Date) =>
+ `${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}`;
+ const [date, setDate] = createSignal(dateValue(seed));
+ const [time, setTime] = createSignal(timeValue(seed));
+ const [condition, setCondition] = createSignal<EmailReminderCondition>(
+ props.initialCondition ?? 'if_no_reply'
+ );
+ const id = createUniqueId();
+ const options = useDateSearch({
+ query,
+ baseDate: now,
+ defaultTime: REMINDER_DEFAULT_TIME,
+ });
+ const parsed = () => {
+ const option = options()[0];
+ const wallTime = parseTime(query())?.time;
+ if (
+ !option ||
+ (wallTime &&
+ (option.date.getHours() !== wallTime.hours ||
+ option.date.getMinutes() !== wallTime.minutes))
+ )
+ return;
+ return option.date;
+ };
+ const selected = () =>
+ query().trim()
+ ? parsed()
+ : (instant() ?? parseLocalReminderDateTime(date(), time()));
+ const valid = () => {
+ const at = selected();
+ return at !== undefined && at.getTime() > Date.now();
+ };
+ const choose = (at: Date) => {
+ setInstant(at);
+ setDate(dateValue(at));
+ setTime(timeValue(at));
+ setQuery('');
+ };
+ return (
+ <>
+ <ActionDialogShell.Body>
+ {props.header}
+ <p class="truncate text-sm text-ink-muted" title={props.subject}>
+ {props.subject}
+ </p>
+ <form
+ id={id}
+ class="flex min-w-0 flex-col gap-3"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const at = selected();
+ if (!props.pending && valid() && at) props.onSave(at, condition());
+ }}
+ >
+ <fieldset
+ disabled={props.pending}
+ class="flex min-w-0 flex-col gap-3"
+ >
+ <label
+ for={`${id}-when`}
+ class="text-xs font-medium text-ink-muted"
+ >
+ When
+ </label>
+ <Input
+ ref={whenInput}
+ id={`${id}-when`}
+ size="lg"
+ value={query()}
+ onInput={(event) => setQuery(event.currentTarget.value)}
+ placeholder="Try “tomorrow 9am” or “in 30m”"
+ autocomplete="off"
+ aria-invalid={!valid()}
+ />
+ <Show when={!query().trim()}>
+ <div class="grid min-w-0 grid-cols-1 gap-2 min-[480px]:grid-cols-2">
+ <For each={presets}>
+ {(preset) => (
+ <Button
+ type="button"
+ variant={
+ selected()?.getTime() === preset.date.getTime()
+ ? 'accent'
+ : 'outline'
+ }
+ class="h-auto min-h-11 min-w-0 justify-between gap-x-3 px-3 py-2 text-left whitespace-normal min-[480px]:flex-col min-[480px]:items-start"
+ onClick={() => choose(preset.date)}
+ >
+ <span class="text-xs">{preset.label}</span>
+ <span class="text-right text-xxs text-ink-muted min-[480px]:text-left">
+ {preset.id === 'next-week'
+ ? `${presetDay(preset.date)} · ${presetTime(preset.date)}`
+ : presetTime(preset.date)}
+ </span>
+ </Button>
+ )}
+ </For>
+ </div>
+ </Show>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setCustom(!custom())}
+ >
+ Choose date &amp; time
+ </Button>
+ <Show when={custom()}>
+ <div class="grid min-w-0 gap-2 min-[360px]:grid-cols-2">
+ <EventDateField
+ label="Reminder date"
+ value={date()}
+ portalScope="local"
+ onChange={(value) => {
+ setQuery('');
+ if (value !== date()) setInstant(undefined);
+ setDate(value);
+ }}
+ />
+ <EventTimeInput
+ id={`${id}-time`}
+ label="Time"
+ value={time()}
+ step={1}
+ onChange={(option) => {
+ setQuery('');
+ setInstant(undefined);
+ setTime(option.value);
+ }}
+ onClear={() => {
+ setQuery('');
+ setInstant(undefined);
+ setTime('');
+ }}
+ />
+ </div>
+ </Show>
+ <p class="text-xs text-ink-muted" role="status">
+ {valid()
+ ? formatReminderInstant(selected()!, zone, now)
+ : 'Choose a future time. Times skipped by a clock change are unavailable.'}
+ </p>
+ <SegmentedControl<EmailReminderCondition>
+ aria-label="Reminder condition"
+ class="self-start"
+ value={condition()}
+ onChange={setCondition}
+ options={[
+ {
+ value: 'if_no_reply',
+ label: 'If no reply',
+ disabled: props.pending,
+ },
+ {
+ value: 'regardless',
+ label: 'Regardless',
+ disabled: props.pending,
+ },
+ ]}
+ />
+ </fieldset>
+ <Show when={props.error}>
+ <p role="alert" class="text-xs text-failure-ink">
+ {props.error}
+ </p>
+ </Show>
+ </form>
+ </ActionDialogShell.Body>
+ <ActionDialogShell.Footer>
+ <Show when={props.onRemove}>
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={props.pending}
+ onClick={() => props.onRemove?.()}
+ >
+ Remove
+ </Button>
+ </Show>
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={props.pending}
+ onClick={props.onCancel}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ form={id}
+ variant="accent"
+ disabled={props.pending || !valid()}
+ >
+ {props.pending
+ ? 'Saving…'
+ : props.initialTime
+ ? 'Save changes'
+ : 'Remind me'}
+ </Button>
+ </ActionDialogShell.Footer>
+ </>
+ );
+}
diff --git a/apps/web/src/features/reminders/email-reminder-status.test.tsx b/apps/web/src/features/reminders/email-reminder-status.test.tsx
new file mode 100644
index 0000000000..b2a38cd34a
--- /dev/null
+++ b/apps/web/src/features/reminders/email-reminder-status.test.tsx
@@ -0,0 +1,44 @@
+import type { EntityData } from '@entity';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { afterEach, expect, it, vi } from 'vitest';
+import { EmailReminderStatus } from './email-reminder-status';
+
+const mocks = vi.hoisted(() => ({
+ execute: vi.fn(),
+ makeAction: vi.fn(),
+ activeCommand: vi.fn(),
+}));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: true }),
+}));
+vi.mock('@queries/reminders/email-followup', () => ({
+ useEmailFollowupQuery: () => ({ isSuccess: true, data: null }),
+}));
+vi.mock('../next-soup/actions/make-create-reminder-action', () => ({
+ makeCreateReminderAction: mocks.makeAction,
+}));
+vi.mock('@core/hotkey/utils', () => ({
+ getActiveCommandByToken: mocks.activeCommand,
+ runCommand: vi.fn(),
+}));
+vi.mock('@ui', () => ({
+ Button: (props: { label: string; onClick: () => void }) => (
+ <button onClick={props.onClick}>{props.label}</button>
+ ),
+}));
+afterEach(cleanup);
+it('always targets its visible thread even when another surface owns the active hotkey', () => {
+ mocks.makeAction.mockReturnValue({ execute: mocks.execute });
+ mocks.activeCommand.mockReturnValue({ id: 'another-thread-command' });
+ const entity = {
+ id: 'visible-thread',
+ type: 'email',
+ name: 'Subject',
+ } as EntityData;
+ const onSaved = vi.fn();
+ render(() => <EmailReminderStatus entity={entity} onSaved={onSaved} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Remind me' }));
+ expect(mocks.execute).toHaveBeenCalledWith([entity]);
+ expect(mocks.makeAction).toHaveBeenCalledWith({ onEmailSaved: onSaved });
+ expect(mocks.activeCommand).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/reminders/email-reminder-status.tsx b/apps/web/src/features/reminders/email-reminder-status.tsx
new file mode 100644
index 0000000000..cd6ec20614
--- /dev/null
+++ b/apps/web/src/features/reminders/email-reminder-status.tsx
@@ -0,0 +1,56 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { enableReminders } from '@core/constant/featureFlags';
+import { TOKENS } from '@core/hotkey/tokens';
+import type { EntityData } from '@entity';
+import BellIcon from '@phosphor/bell-simple.svg';
+import { useEmailFollowupQuery } from '@queries/reminders/email-followup';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { makeCreateReminderAction } from '../next-soup/actions/make-create-reminder-action';
+
+/** App-facing status/action, mounted only when the reminder flag is enabled. */
+export function EmailReminderStatus(props: {
+ entity: EntityData;
+ onSaved?: () => void | Promise<void>;
+}) {
+ const enabled = useFeatureFlag(enableReminders);
+ return (
+ <Show when={enabled().enabled}>
+ <EmailReminderStatusContent {...props} />
+ </Show>
+ );
+}
+function EmailReminderStatusContent(props: {
+ entity: EntityData;
+ onSaved?: () => void | Promise<void>;
+}) {
+ const query = useEmailFollowupQuery(() => props.entity.id);
+ const reminder = () => (query.isSuccess ? query.data : undefined);
+ const pending = () =>
+ reminder()?.state === 'pending' || reminder()?.state === 'archiving';
+ const label = () =>
+ pending()
+ ? `Reminder set for ${new Date(reminder()!.remindAt).toLocaleString()}`
+ : reminder()?.state === 'returned'
+ ? 'Reminder returned — remind me again'
+ : 'Remind me';
+ const action = makeCreateReminderAction({ onEmailSaved: props.onSaved });
+ return (
+ <Button
+ size="icon-md"
+ label={label()}
+ hotkey={TOKENS.entity.action.createReminder}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => {
+ action.execute([props.entity]);
+ }}
+ >
+ <BellIcon
+ class="size-4"
+ classList={{
+ 'text-accent': pending() || reminder()?.state === 'returned',
+ }}
+ />
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/reminders/queries/use-reminder-picker-items.test.ts b/apps/web/src/features/reminders/queries/use-reminder-picker-items.test.ts
new file mode 100644
index 0000000000..d5c2b2ec6e
--- /dev/null
+++ b/apps/web/src/features/reminders/queries/use-reminder-picker-items.test.ts
@@ -0,0 +1,54 @@
+import { createRoot } from 'solid-js';
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ search: {
+ isSuccess: true,
+ isPlaceholderData: true,
+ data: [{ id: 'old', type: 'email', name: 'Old result' }],
+ hasNextPage: true,
+ fetchNextPage: vi.fn(),
+ },
+ browse: {
+ isSuccess: true,
+ data: [{ id: 'recent', type: 'email', name: 'Project recent' }],
+ hasNextPage: true,
+ fetchNextPage: vi.fn(),
+ },
+}));
+vi.mock('@core/context/quickAccess', () => ({
+ useQuickAccess: () => ({
+ useList: () => ({ items: () => [], hasMore: () => false }),
+ }),
+}));
+vi.mock('@entity', () => ({ createEmailsInfiniteQuery: () => mocks.browse }));
+vi.mock('@queries/soup/search', () => ({
+ useSearchSoupQuery: () => mocks.search,
+}));
+vi.mock('@queries/reminders/reminders', () => ({ reminderTarget: () => true }));
+
+import { useReminderPickerItems } from './use-reminder-picker-items';
+
+beforeEach(() => vi.clearAllMocks());
+it('excludes retained old-query results while keeping locally matched emails', () =>
+ createRoot((dispose) => {
+ mocks.search.isPlaceholderData = true;
+ const source = useReminderPickerItems(
+ () => 'Project',
+ () => 'Project'
+ );
+ expect(source.items().map((item) => item.data.id)).toEqual(['recent']);
+ dispose();
+ }));
+it('paginates matching email results while searching', async () => {
+ const source = createRoot(() =>
+ useReminderPickerItems(
+ () => 'Project',
+ () => 'Project'
+ )
+ );
+ expect(source.hasMore()).toBe(true);
+ await source.loadMore();
+ expect(mocks.search.fetchNextPage).toHaveBeenCalledOnce();
+ expect(mocks.browse.fetchNextPage).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/reminders/queries/use-reminder-picker-items.ts b/apps/web/src/features/reminders/queries/use-reminder-picker-items.ts
new file mode 100644
index 0000000000..086878341d
--- /dev/null
+++ b/apps/web/src/features/reminders/queries/use-reminder-picker-items.ts
@@ -0,0 +1,80 @@
+import { useQuickAccess } from '@core/context/quickAccess';
+import { createEmailsInfiniteQuery, type EntityData } from '@entity';
+import { reminderTarget } from '@queries/reminders/reminders';
+import { useSearchSoupQuery } from '@queries/soup/search';
+import type { Accessor } from 'solid-js';
+
+/** Quick Access does not yet hydrate emails; use the existing email browse/search adapters. */
+export function useReminderPickerItems(
+ search: Accessor<string>,
+ settledSearch: Accessor<string>
+) {
+ const recent = useQuickAccess().useList({
+ buckets: [
+ 'task',
+ 'document',
+ 'note',
+ 'chat',
+ 'channel',
+ 'dm',
+ 'project',
+ 'crm_company',
+ ],
+ searchTerm: search,
+ });
+ const emails = createEmailsInfiniteQuery(() => ({ view: 'all', limit: 50 }));
+ const emailSearch = useSearchSoupQuery(
+ () => ({
+ params: { page_size: 20 },
+ body: {
+ query: settledSearch(),
+ match_type: 'partial',
+ include: ['emails'],
+ search_on: 'name',
+ },
+ }),
+ () => ({ enabled: settledSearch().trim().length >= 3 })
+ );
+ const items = () => {
+ const term = search().trim().toLowerCase();
+ const browsed = emails.isSuccess
+ ? emails.data.filter((email) => email.name.toLowerCase().includes(term))
+ : [];
+ const searched =
+ settledSearch() === search() &&
+ emailSearch.isSuccess &&
+ !emailSearch.isPlaceholderData
+ ? emailSearch.data
+ : [];
+ const combined: EntityData[] = [
+ ...recent.items().map((item) => item.data),
+ ...browsed,
+ ...searched,
+ ];
+ const unique = new Map<string, { data: EntityData }>();
+ for (const data of combined) {
+ if (reminderTarget(data)) unique.set(`${data.type}:${data.id}`, { data });
+ }
+ return [...unique.values()];
+ };
+ const searching = () => settledSearch().trim().length >= 3;
+ return {
+ items,
+ isLoading: () =>
+ recent.isLoading() || emails.isLoading || emailSearch.isFetching,
+ hasMore: () =>
+ recent.hasMore() ||
+ (searching() ? emailSearch.hasNextPage : emails.hasNextPage),
+ isLoadingMore: () =>
+ recent.isLoadingMore() ||
+ (searching()
+ ? emailSearch.isFetchingNextPage
+ : emails.isFetchingNextPage),
+ loadMore: async () => {
+ if (recent.hasMore()) await recent.loadMore();
+ if (searching()) {
+ if (emailSearch.hasNextPage) await emailSearch.fetchNextPage();
+ } else if (emails.hasNextPage) await emails.fetchNextPage();
+ },
+ };
+}
diff --git a/apps/web/src/features/reminders/reminder-composer.test.ts b/apps/web/src/features/reminders/reminder-composer.test.ts
index 31d4da3c32..804d82617a 100644
--- a/apps/web/src/features/reminders/reminder-composer.test.ts
+++ b/apps/web/src/features/reminders/reminder-composer.test.ts
@@ -1,12 +1,15 @@
+import { pressedKeys, setPressedKeys } from '@core/hotkey/state';
import type { EntityData } from '@entity';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ chooseReminderTarget,
closeReminderComposer,
openReminderComposer,
openStandaloneReminderComposer,
reminderComposerOpen,
reminderComposerState,
+ showReminderEntityPicker,
takeReminderCreatedHandler,
} from './reminder-composer';
@@ -33,6 +36,20 @@ describe('reminder composer state', () => {
expect(reminderComposerState.entity).toBeUndefined();
});
+ it('clears keys held during dismissal so H can reopen without a modifier reset', () => {
+ openReminderComposer(doc('doc-1', 'Q3 Contract'));
+ setPressedKeys(new Set(['escape']));
+ closeReminderComposer();
+ expect([...pressedKeys()]).toEqual([]);
+
+ // The next keydown is a plain H, rather than the stale escape+h chord.
+ setPressedKeys((held) => new Set([...held, 'h']));
+ expect([...pressedKeys()]).toEqual(['h']);
+ openReminderComposer(doc('doc-1', 'Q3 Contract'));
+ expect(reminderComposerOpen()).toBe(true);
+ closeReminderComposer();
+ });
+
// Reopening must fully replace the target, or a reminder could be attached to
// the previously opened entity.
it('replaces the entity when reopened for another one', () => {
@@ -63,7 +80,7 @@ describe('reminder composer standalone mode', () => {
openStandaloneReminderComposer();
expect(reminderComposerOpen()).toBe(true);
- expect(reminderComposerState.standalone).toBe(true);
+ expect(reminderComposerState.choosing).toBe(true);
expect(reminderComposerState.entity).toBeUndefined();
});
@@ -82,7 +99,7 @@ describe('reminder composer standalone mode', () => {
openStandaloneReminderComposer();
expect(reminderComposerState.entity).toBeUndefined();
- expect(reminderComposerState.standalone).toBe(true);
+ expect(reminderComposerState.choosing).toBe(true);
});
it('drops the standalone flag when opened for an entity', () => {
@@ -123,3 +140,17 @@ describe('reminder composer created handler', () => {
expect(takeReminderCreatedHandler()).toBeUndefined();
});
});
+
+it('chooses an entity or freeform without retaining an old target callback', () => {
+ const onCreated = vi.fn();
+ openReminderComposer(doc('old', 'Old task'), { onCreated });
+ showReminderEntityPicker();
+ chooseReminderTarget(doc('new', 'New task'));
+ expect(reminderComposerState.entity?.id).toBe('new');
+ expect(reminderComposerState.choosing).toBeUndefined();
+ expect(takeReminderCreatedHandler()).toBeUndefined();
+ showReminderEntityPicker();
+ chooseReminderTarget();
+ expect(reminderComposerState.entity).toBeUndefined();
+ expect(reminderComposerState.standalone).toBe(true);
+});
diff --git a/apps/web/src/features/reminders/reminder-composer.ts b/apps/web/src/features/reminders/reminder-composer.ts
index 1d67d47a85..c3385401ea 100644
--- a/apps/web/src/features/reminders/reminder-composer.ts
+++ b/apps/web/src/features/reminders/reminder-composer.ts
@@ -1,3 +1,4 @@
+import { clearPressedKeys } from '@core/hotkey/state';
import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';
import type { EntityData } from '@entity';
import { batch } from 'solid-js';
@@ -17,6 +18,7 @@ interface ReminderComposerState {
* reminder from nothing to compose.
*/
standalone?: boolean;
+ choosing?: boolean;
}
/** What the surface that opened the composer does once the reminder exists. */
@@ -66,22 +68,34 @@ export function openReminderComposer(
}
/**
- * Open the composer to create a reminder about nothing.
- *
- * There is no entity to name it after, so its description is the one field it
- * cannot skip — see `resolveStandaloneDescription`.
+ * Open reminder creation without a preselected source. The picker offers an
+ * entity association or a freeform reminder with a required description.
*/
export function openStandaloneReminderComposer(options?: {
onCreated?: ReminderCreatedHandler;
}) {
createdHandler = options?.onCreated;
batch(() => {
- setState(reconcile({ entity: undefined, standalone: true }));
+ setState(reconcile({ entity: undefined, choosing: true }));
setReminderComposerOpen(true);
});
}
+/** Switch targets within the open composer, retaining the invoking callback. */
+export function chooseReminderTarget(entity?: EntityData) {
+ setState(reconcile(entity ? { entity } : { standalone: true }));
+}
+
+export function showReminderEntityPicker() {
+ // A different target must never run the original row’s archive/navigation callback.
+ createdHandler = undefined;
+ setState(reconcile({ choosing: true }));
+}
+
export function closeReminderComposer() {
+ // Escape dismisses the dialog outside the hotkey command runner. Its keyup
+ // can be lost during focus restoration, so don't carry held keys into H.
+ if (reminderComposerOpen()) clearPressedKeys();
createdHandler = undefined;
batch(() => {
setReminderComposerOpen(false);
diff --git a/apps/web/src/features/reminders/reminder-navigation.test.ts b/apps/web/src/features/reminders/reminder-navigation.test.ts
index 375d433e4c..e73d9d0870 100644
--- a/apps/web/src/features/reminders/reminder-navigation.test.ts
+++ b/apps/web/src/features/reminders/reminder-navigation.test.ts
@@ -14,6 +14,16 @@ import {
reminderDetailUrl,
reminderIdFromDetailContent,
} from './reminder-navigation';
+import { reminderSourceContent } from './reminder-source';
+
+vi.mock('@core/constant/allBlocks', () => ({
+ itemToBlockName: (item: {
+ referencedEntity: { type: string; fileType?: string; subType?: string };
+ }) =>
+ item.referencedEntity.subType ??
+ item.referencedEntity.fileType ??
+ item.referencedEntity.type,
+}));
afterEach(() => setGlobalSplitManager(undefined));
@@ -132,3 +142,23 @@ describe('openReminderDetail', () => {
});
});
});
+
+it('opens attached sources while retaining explicit reminder detail destinations', () => {
+ expect(
+ reminderSourceContent({ referencedEntity: { id: 'email', type: 'email' } })
+ ).toEqual({ type: 'email', id: 'email' });
+ expect(
+ reminderSourceContent({
+ referencedEntity: {
+ id: 'task',
+ type: 'document',
+ fileType: 'md',
+ subType: 'task',
+ },
+ })
+ ).toEqual({ type: 'task', id: 'task' });
+ expect(reminderSourceContent({})).toBeUndefined();
+ expect(reminderDetailDestination('reminder').content.id).toBe(
+ 'reminder-detail'
+ );
+});
diff --git a/apps/web/src/features/reminders/reminder-navigation.ts b/apps/web/src/features/reminders/reminder-navigation.ts
index 166a6a3ff6..97f2441c63 100644
--- a/apps/web/src/features/reminders/reminder-navigation.ts
+++ b/apps/web/src/features/reminders/reminder-navigation.ts
@@ -68,7 +68,7 @@ export function reminderDetailContent(reminderId: string): SplitContent {
};
}
-/** A reminder always opens its details first; source navigation lives there. */
+/** Explicit management destination, also used for freeform reminders. */
export type ReminderDetailDestination = {
kind: 'reminder-detail';
reminderId: string;
diff --git a/apps/web/src/features/reminders/reminder-source.ts b/apps/web/src/features/reminders/reminder-source.ts
new file mode 100644
index 0000000000..27b6e3ef5a
--- /dev/null
+++ b/apps/web/src/features/reminders/reminder-source.ts
@@ -0,0 +1,19 @@
+import type { SplitContent } from '@components/app/split-layout/layoutManager';
+import { itemToBlockName } from '@core/constant/allBlocks';
+import type { ReminderEntity } from '@entity';
+
+/** Source content for ordinary opening; explicit editing retains reminder identity. */
+export function reminderSourceContent(
+ reminder: Pick<ReminderEntity, 'referencedEntity'>
+): Exclude<SplitContent, { type: 'component' }> | undefined {
+ const reference = reminder.referencedEntity;
+ if (!reference) return;
+ const type =
+ reference.type === 'crm_company'
+ ? 'company'
+ : reference.type === 'crm_contact'
+ ? 'contact'
+ : itemToBlockName({ type: 'reminder', referencedEntity: reference });
+ if (type === 'unknown') return;
+ return { type, id: reference.id };
+}
diff --git a/apps/web/src/features/reminders/views/email-reminder-composer.test.tsx b/apps/web/src/features/reminders/views/email-reminder-composer.test.tsx
new file mode 100644
index 0000000000..6b2587ae2f
--- /dev/null
+++ b/apps/web/src/features/reminders/views/email-reminder-composer.test.tsx
@@ -0,0 +1,221 @@
+import type { EntityData } from '@entity';
+import type { EmailFollowup } from '@service-storage/generated/schemas/emailFollowup';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { EmailReminderComposer } from './email-reminder-composer';
+
+const mocks = vi.hoisted(() => ({
+ execute: vi.fn(),
+ query: vi.fn(),
+ pushUndo: vi.fn(),
+ takeHandler: vi.fn(),
+ navigate: vi.fn(),
+ close: vi.fn(),
+ success: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock('@queries/reminders/email-followup', () => ({
+ executeEmailFollowup: mocks.execute,
+ useEmailFollowupQuery: mocks.query,
+}));
+vi.mock('@queries/undo', () => ({
+ useMutationUndoContext: () => ({ pushUndo: mocks.pushUndo }),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: mocks.success, failure: mocks.failure },
+}));
+vi.mock('../reminder-composer', () => ({
+ closeReminderComposer: mocks.close,
+ takeReminderCreatedHandler: mocks.takeHandler,
+}));
+vi.mock('../components/email-reminder-form', () => ({
+ EmailReminderForm: (props: {
+ onSave: (at: Date, condition: 'if_no_reply') => void;
+ onRemove?: () => void;
+ pending: boolean;
+ }) => (
+ <>
+ <button
+ disabled={props.pending}
+ onClick={() =>
+ props.onSave(new Date('2026-12-01T12:00:00Z'), 'if_no_reply')
+ }
+ >
+ Save
+ </button>
+ <button onClick={props.onRemove}>Remove</button>
+ </>
+ ),
+}));
+vi.mock('@ui', () => ({
+ ActionDialogShell: {
+ Body: () => null,
+ Header: () => null,
+ Title: () => null,
+ Description: () => null,
+ },
+ Button: () => null,
+}));
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.pushUndo.mockReturnValue({ undo: vi.fn() });
+});
+afterEach(cleanup);
+it('keeps initial navigation and removal undo when a lost response is discovered before retry', async () => {
+ const [current, setCurrent] = createSignal<EmailFollowup | null>(null);
+ mocks.query.mockReturnValue({
+ isSuccess: true,
+ get data() {
+ return current();
+ },
+ });
+ mocks.takeHandler.mockReturnValueOnce(mocks.navigate);
+ mocks.execute.mockRejectedValueOnce(new Error('Response lost'));
+ render(() => (
+ <EmailReminderComposer
+ entity={{ id: 'thread', type: 'email', name: 'Subject' } as EntityData}
+ onPending={() => {}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')
+ ).toBe(false)
+ );
+ const saved: EmailFollowup = {
+ condition: 'if_no_reply',
+ linkId: 'inbox',
+ remindAt: '2026-12-01T12:00:00.000Z',
+ reminderId: 'reminder',
+ revision: mocks.execute.mock.calls[0][1].operationId,
+ state: 'pending',
+ threadId: 'thread',
+ };
+ setCurrent(saved);
+ mocks.execute.mockImplementationOnce(async (_thread, _command, after) => {
+ await after(saved);
+ return saved;
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(mocks.pushUndo).toHaveBeenCalledOnce());
+ expect(mocks.execute.mock.calls[1][1].operationId).toBe(
+ mocks.execute.mock.calls[0][1].operationId
+ );
+ expect(mocks.navigate).toHaveBeenCalledOnce();
+ await mocks.pushUndo.mock.calls[0][0].undo();
+ expect(mocks.execute).toHaveBeenLastCalledWith(
+ 'thread',
+ expect.objectContaining({
+ type: 'remove',
+ expectedRevision: saved.revision,
+ undo: true,
+ })
+ );
+});
+
+it('undoes removal by scheduling the captured time and condition again', async () => {
+ const previous: EmailFollowup = {
+ condition: 'regardless',
+ linkId: 'inbox',
+ remindAt: '2026-12-01T12:00:00.000Z',
+ reminderId: 'reminder',
+ revision: 'original',
+ state: 'pending',
+ threadId: 'thread',
+ };
+ mocks.query.mockReturnValue({ isSuccess: true, data: previous });
+ mocks.execute.mockResolvedValueOnce({
+ ...previous,
+ revision: 'removed',
+ state: 'removed',
+ });
+ render(() => (
+ <EmailReminderComposer
+ entity={{ id: 'thread', type: 'email', name: 'Subject' } as EntityData}
+ onPending={() => {}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+ await waitFor(() => expect(mocks.pushUndo).toHaveBeenCalledOnce());
+ await mocks.pushUndo.mock.calls[0][0].undo();
+ expect(mocks.execute).toHaveBeenLastCalledWith(
+ 'thread',
+ expect.objectContaining({
+ type: 'set',
+ expectedRevision: null,
+ remindAt: previous.remindAt,
+ condition: 'regardless',
+ })
+ );
+});
+
+it('reports rolled-back creation without claiming that a reply arrived', async () => {
+ mocks.query.mockReturnValue({ isSuccess: true, data: null });
+ mocks.execute.mockResolvedValueOnce({ state: 'removed' });
+ render(() => (
+ <EmailReminderComposer
+ entity={{ id: 'thread', type: 'email', name: 'Subject' } as EntityData}
+ onPending={() => {}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(mocks.failure).toHaveBeenCalledWith(
+ 'The reminder was not set. The conversation has been restored.'
+ )
+ );
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.pushUndo).not.toHaveBeenCalled();
+});
+
+it.each(['Save', 'Remove'])(
+ 'starts a fresh %s operation when another writer changes the revision',
+ async (action) => {
+ const previous: EmailFollowup = {
+ condition: 'if_no_reply',
+ linkId: 'inbox',
+ remindAt: '2026-12-01T12:00:00.000Z',
+ reminderId: 'reminder',
+ revision: 'original',
+ state: 'pending',
+ threadId: 'thread',
+ };
+ const [current, setCurrent] = createSignal(previous);
+ mocks.query.mockReturnValue({
+ isSuccess: true,
+ get data() {
+ return current();
+ },
+ });
+ mocks.execute.mockRejectedValue(new Error('Conflict'));
+ render(() => (
+ <EmailReminderComposer
+ entity={{ id: 'thread', type: 'email', name: 'Subject' } as EntityData}
+ onPending={() => {}}
+ />
+ ));
+ fireEvent.click(screen.getByRole('button', { name: action }));
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: action }).hasAttribute('disabled')
+ ).toBe(false)
+ );
+ setCurrent({ ...previous, revision: 'other-writer' });
+ fireEvent.click(screen.getByRole('button', { name: action }));
+ await waitFor(() => expect(mocks.execute).toHaveBeenCalledTimes(2));
+ expect(mocks.execute.mock.calls[1][1].expectedRevision).toBe(
+ 'other-writer'
+ );
+ expect(mocks.execute.mock.calls[1][1].operationId).not.toBe(
+ mocks.execute.mock.calls[0][1].operationId
+ );
+ }
+);
diff --git a/apps/web/src/features/reminders/views/email-reminder-composer.tsx b/apps/web/src/features/reminders/views/email-reminder-composer.tsx
new file mode 100644
index 0000000000..5a553eac51
--- /dev/null
+++ b/apps/web/src/features/reminders/views/email-reminder-composer.tsx
@@ -0,0 +1,236 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { EntityData } from '@entity';
+import {
+ executeEmailFollowup,
+ useEmailFollowupQuery,
+} from '@queries/reminders/email-followup';
+import { useMutationUndoContext } from '@queries/undo';
+import type { EmailFollowup } from '@service-storage/generated/schemas/emailFollowup';
+import type { EmailFollowupCommand } from '@service-storage/generated/schemas/emailFollowupCommand';
+import { ActionDialogShell, Button } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import {
+ type EmailReminderCondition,
+ EmailReminderForm,
+} from '../components/email-reminder-form';
+import {
+ closeReminderComposer,
+ showReminderEntityPicker,
+ takeReminderCreatedHandler,
+} from '../reminder-composer';
+
+export function EmailReminderComposer(props: {
+ entity: EntityData;
+ onPending: (pending: boolean) => void;
+}) {
+ const query = useEmailFollowupQuery(() => props.entity.id);
+ const undo = useMutationUndoContext();
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+ // Retain the exact command through retries of an uncertain write.
+ let lastCommand: EmailFollowupCommand | undefined;
+ let operationSnapshot:
+ | { operationId: string; previous: EmailFollowup | null | undefined }
+ | undefined;
+ const current = () => (query.isSuccess ? query.data : undefined);
+ const active = () =>
+ current()?.state === 'pending' || current()?.state === 'archiving';
+ const submit = async (command: EmailFollowupCommand) => {
+ if (pending()) return;
+ setPending(true);
+ props.onPending(true);
+ setError(undefined);
+ if (operationSnapshot?.operationId !== command.operationId) {
+ operationSnapshot = {
+ operationId: command.operationId,
+ previous: current(),
+ };
+ }
+ // A background read may discover a write whose response was lost. Undo
+ // and navigation still belong to the state before that operation began.
+ const { previous } = operationSnapshot;
+ let result;
+ try {
+ result = await executeEmailFollowup(
+ props.entity.id,
+ command,
+ async (saved) => {
+ if (
+ command.type === 'set' &&
+ saved.state === 'pending' &&
+ previous?.state !== 'pending' &&
+ previous?.state !== 'archiving'
+ ) {
+ await takeReminderCreatedHandler()?.();
+ }
+ }
+ );
+ } catch {
+ setError(
+ 'Couldn’t confirm the change. Your time is still here; retrying this request is safe.'
+ );
+ setPending(false);
+ props.onPending(false);
+ return;
+ }
+ takeReminderCreatedHandler();
+ const threadId = props.entity.id;
+ setPending(false);
+ props.onPending(false);
+ closeReminderComposer();
+ const showUndo = (message: string, undoCommand: EmailFollowupCommand) => {
+ const handle = undo.pushUndo({
+ label: 'Email reminder',
+ undo: async () => {
+ await executeEmailFollowup(threadId, undoCommand);
+ },
+ });
+ toast.success(message, {
+ actions: [
+ {
+ label: 'Undo',
+ onClick: () =>
+ void handle.undo({
+ onError: () =>
+ toast.failure(
+ 'The reminder changed. Open it to make changes.'
+ ),
+ }),
+ },
+ ],
+ });
+ };
+ if (command.type === 'set' && result.state === 'pending') {
+ showUndo(
+ 'Email reminder set',
+ previous?.state === 'pending'
+ ? {
+ type: 'set',
+ operationId: crypto.randomUUID(),
+ expectedRevision: result.revision,
+ remindAt: previous.remindAt,
+ condition: previous.condition,
+ }
+ : {
+ type: 'remove',
+ operationId: crypto.randomUUID(),
+ expectedRevision: result.revision,
+ undo: true,
+ }
+ );
+ } else if (
+ command.type === 'remove' &&
+ result.state === 'removed' &&
+ previous?.state === 'pending'
+ ) {
+ showUndo('Email reminder removed', {
+ type: 'set',
+ operationId: crypto.randomUUID(),
+ expectedRevision: null,
+ remindAt: previous.remindAt,
+ condition: previous.condition,
+ });
+ } else if (command.type === 'remove') {
+ toast.success('Email reminder removed');
+ } else if (result.state === 'removed') {
+ toast.failure(
+ 'The reminder was not set. The conversation has been restored.'
+ );
+ } else if (result.state === 'returned') {
+ toast.success(
+ 'The reminder has already returned this conversation to the inbox'
+ );
+ } else {
+ toast.success('Email reminder cancelled');
+ }
+ };
+ const save = (at: Date, condition: EmailReminderCondition) => {
+ const values = {
+ type: 'set' as const,
+ remindAt: at.toISOString(),
+ condition,
+ expectedRevision: active() ? current()?.revision : undefined,
+ };
+ if (
+ !lastCommand ||
+ lastCommand.type !== 'set' ||
+ lastCommand.remindAt !== values.remindAt ||
+ lastCommand.condition !== condition ||
+ ((lastCommand.expectedRevision ?? undefined) !==
+ (values.expectedRevision ?? undefined) &&
+ current()?.revision !== lastCommand.operationId)
+ ) {
+ lastCommand = { ...values, operationId: crypto.randomUUID() };
+ }
+ void submit(lastCommand);
+ };
+ return (
+ <Show
+ when={query.isSuccess}
+ fallback={
+ <ActionDialogShell.Body>
+ <ActionDialogShell.Title>Remind me</ActionDialogShell.Title>
+ <p role="status">
+ {query.isError
+ ? 'Couldn’t load this email reminder.'
+ : 'Loading reminder…'}
+ </p>
+ <Show when={query.isError}>
+ <Button onClick={() => void query.refetch()}>Retry</Button>
+ </Show>
+ <Button onClick={closeReminderComposer}>Cancel</Button>
+ </ActionDialogShell.Body>
+ }
+ >
+ <EmailReminderForm
+ autofocus
+ header={
+ <ActionDialogShell.Header>
+ <div class="flex items-center justify-between gap-3">
+ <ActionDialogShell.Title>Remind me</ActionDialogShell.Title>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={pending()}
+ onClick={showReminderEntityPicker}
+ >
+ Change item
+ </Button>
+ </div>
+ <ActionDialogShell.Description>
+ Move this conversation out of the inbox until the selected time.
+ </ActionDialogShell.Description>
+ </ActionDialogShell.Header>
+ }
+ subject={props.entity.name}
+ initialTime={active() ? current()?.remindAt : undefined}
+ initialCondition={active() ? current()?.condition : undefined}
+ pending={pending()}
+ error={error()}
+ onSave={save}
+ onCancel={closeReminderComposer}
+ onRemove={
+ active()
+ ? () => {
+ const revision = current()?.revision;
+ if (!revision) return;
+ if (
+ !lastCommand ||
+ lastCommand.type !== 'remove' ||
+ (lastCommand.expectedRevision !== revision &&
+ revision !== lastCommand.operationId)
+ )
+ lastCommand = {
+ type: 'remove',
+ operationId: crypto.randomUUID(),
+ expectedRevision: revision,
+ undo: false,
+ };
+ void submit(lastCommand);
+ }
+ : undefined
+ }
+ />
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/reminders/views/email-reminder-details.test.tsx b/apps/web/src/features/reminders/views/email-reminder-details.test.tsx
new file mode 100644
index 0000000000..f69f531bc6
--- /dev/null
+++ b/apps/web/src/features/reminders/views/email-reminder-details.test.tsx
@@ -0,0 +1,91 @@
+import type { EmailFollowup } from '@service-storage/generated/schemas/emailFollowup';
+import type { Reminder } from '@service-storage/generated/schemas/reminder';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { EmailReminderDetails } from './email-reminder-details';
+
+const mocks = vi.hoisted(() => ({ execute: vi.fn(), query: vi.fn() }));
+vi.mock('@queries/reminders/email-followup', () => ({
+ executeEmailFollowup: mocks.execute,
+ useEmailFollowupQuery: mocks.query,
+}));
+vi.mock('@core/component/ItemPreview', () => ({ ItemPreview: () => null }));
+vi.mock('@core/component/Toast/Toast', () => ({ toast: { success: vi.fn() } }));
+vi.mock('../components/email-reminder-form', () => ({
+ EmailReminderForm: (props: {
+ onSave: (at: Date, condition: 'if_no_reply') => void;
+ pending: boolean;
+ }) => (
+ <button
+ disabled={props.pending}
+ onClick={() =>
+ props.onSave(new Date('2026-12-01T12:00:00Z'), 'if_no_reply')
+ }
+ >
+ Save
+ </button>
+ ),
+}));
+beforeEach(() => vi.resetAllMocks());
+afterEach(cleanup);
+
+it.each([false, true])(
+ 'retries against a refetched revision (competing writer: %s)',
+ async (competing) => {
+ const initial: EmailFollowup = {
+ condition: 'if_no_reply',
+ linkId: 'inbox',
+ remindAt: '2026-12-01T12:00:00.000Z',
+ reminderId: 'reminder',
+ revision: 'original',
+ state: 'pending',
+ threadId: 'thread',
+ };
+ const [current, setCurrent] = createSignal(initial);
+ mocks.query.mockReturnValue({
+ isSuccess: true,
+ get data() {
+ return current();
+ },
+ });
+ mocks.execute.mockRejectedValueOnce(new Error('Response lost'));
+ const close = vi.fn();
+ render(() => (
+ <EmailReminderDetails
+ reminder={{ id: 'reminder', description: 'Subject' } as Reminder}
+ threadId="thread"
+ onClose={close}
+ >
+ <p>Generic editor</p>
+ </EmailReminderDetails>
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: 'Save' }).hasAttribute('disabled')
+ ).toBe(false)
+ );
+ const first = mocks.execute.mock.calls[0][1];
+ setCurrent({
+ ...initial,
+ revision: competing ? 'competing' : first.operationId,
+ });
+ mocks.execute.mockResolvedValueOnce(current());
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(close).toHaveBeenCalledOnce());
+ const second = mocks.execute.mock.calls[1][1];
+ if (competing) {
+ expect(second.operationId).not.toBe(first.operationId);
+ expect(second.expectedRevision).toBe('competing');
+ } else {
+ expect(second).toEqual(first);
+ }
+ }
+);
diff --git a/apps/web/src/features/reminders/views/email-reminder-details.tsx b/apps/web/src/features/reminders/views/email-reminder-details.tsx
new file mode 100644
index 0000000000..5c99bd9b6d
--- /dev/null
+++ b/apps/web/src/features/reminders/views/email-reminder-details.tsx
@@ -0,0 +1,101 @@
+import { ItemPreview } from '@core/component/ItemPreview';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ executeEmailFollowup,
+ useEmailFollowupQuery,
+} from '@queries/reminders/email-followup';
+import type { EmailFollowupCommand } from '@service-storage/generated/schemas/emailFollowupCommand';
+import type { Reminder } from '@service-storage/generated/schemas/reminder';
+import { createSignal, type JSX, Show } from 'solid-js';
+import { EmailReminderForm } from '../components/email-reminder-form';
+
+/** Generic email-attached reminders retain their ordinary editor. */
+export function EmailReminderDetails(props: {
+ reminder: Reminder;
+ threadId: string;
+ onClose: () => void;
+ children: JSX.Element;
+}) {
+ const query = useEmailFollowupQuery(() => props.threadId);
+ const followup = () =>
+ query.isSuccess && query.data?.reminderId === props.reminder.id
+ ? query.data
+ : undefined;
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal<string>();
+ let lastCommand: EmailFollowupCommand | undefined;
+ const save = async (command: EmailFollowupCommand) => {
+ if (pending()) return;
+ // Preserve the identity for retries with the same requested fields.
+ const retry =
+ lastCommand && command.expectedRevision === lastCommand.operationId
+ ? { ...command, expectedRevision: lastCommand.expectedRevision }
+ : command;
+ if (
+ !lastCommand ||
+ JSON.stringify({ ...lastCommand, operationId: undefined }) !==
+ JSON.stringify({ ...retry, operationId: undefined })
+ )
+ lastCommand = command;
+ setPending(true);
+ setError(undefined);
+ try {
+ await executeEmailFollowup(props.threadId, lastCommand);
+ } catch {
+ setPending(false);
+ setError('Couldn’t save. Your changes are still here; retrying is safe.');
+ return;
+ }
+ setPending(false);
+ toast.success(
+ command.type === 'remove'
+ ? 'Email reminder removed'
+ : 'Email reminder updated'
+ );
+ props.onClose();
+ };
+ return (
+ <Show
+ when={query.isSuccess || query.isError}
+ fallback={<p role="status">Loading reminder…</p>}
+ >
+ <Show
+ when={followup()?.state === 'pending' ? followup() : undefined}
+ fallback={props.children}
+ >
+ {(current) => (
+ <>
+ <div class="mb-4">
+ <ItemPreview id={props.threadId} type="email" />
+ </div>
+ <EmailReminderForm
+ subject={props.reminder.description}
+ initialTime={current().remindAt}
+ initialCondition={current().condition}
+ pending={pending()}
+ error={error()}
+ onCancel={props.onClose}
+ onSave={(at, condition) =>
+ void save({
+ type: 'set',
+ operationId: crypto.randomUUID(),
+ expectedRevision: current().revision,
+ remindAt: at.toISOString(),
+ condition,
+ })
+ }
+ onRemove={() =>
+ void save({
+ type: 'remove',
+ operationId: crypto.randomUUID(),
+ expectedRevision: current().revision,
+ undo: false,
+ })
+ }
+ />
+ </>
+ )}
+ </Show>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/reminders/views/reminder-entity-picker.test.tsx b/apps/web/src/features/reminders/views/reminder-entity-picker.test.tsx
new file mode 100644
index 0000000000..4cbe35bb86
--- /dev/null
+++ b/apps/web/src/features/reminders/views/reminder-entity-picker.test.tsx
@@ -0,0 +1,73 @@
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { Dialog } from '@ui';
+import { afterEach, expect, it, vi } from 'vitest';
+import { ReminderEntityPicker } from './reminder-entity-picker';
+
+vi.mock('@entity', () => ({
+ createEmailsInfiniteQuery: () => ({
+ isSuccess: true,
+ data: [{ id: 'email-1', type: 'email', name: 'Project update' }],
+ hasNextPage: false,
+ }),
+ Entity: {
+ Icon: () => null,
+ Title: (props: { entity: { name: string } }) => props.entity.name,
+ },
+}));
+vi.mock('@queries/soup/search', () => ({
+ useSearchSoupQuery: () => ({ isSuccess: false }),
+}));
+vi.mock('@queries/reminders/reminders', () => ({
+ reminderTarget: () => ({ entityType: 'document', entityId: 'task' }),
+}));
+vi.mock('@core/context/quickAccess', () => ({
+ useQuickAccess: () => ({
+ useList: (options: { searchTerm: () => string }) => ({
+ items: () =>
+ [
+ { data: { id: 'task-1', type: 'document', name: 'Review proposal' } },
+ ].filter((item) =>
+ item.data.name
+ .toLowerCase()
+ .includes(options.searchTerm().toLowerCase())
+ ),
+ isLoading: () => false,
+ hasMore: () => false,
+ }),
+ }),
+}));
+vi.stubGlobal('scrollTo', vi.fn());
+afterEach(cleanup);
+
+it('searches locally and selects an entity with the keyboard without opening it', () => {
+ const select = vi.fn();
+ render(() => (
+ <Dialog open>
+ <ReminderEntityPicker onSelect={select} onWrite={vi.fn()} />
+ </Dialog>
+ ));
+ const input = screen.getByRole('combobox');
+ expect(document.activeElement).toBe(input);
+ fireEvent.input(input, { target: { value: 'project' } });
+ expect(screen.queryByText('Review proposal')).toBeNull();
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(select).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'email-1' })
+ );
+});
+
+it('offers freeform even with no matching entities', () => {
+ const write = vi.fn();
+ render(() => (
+ <Dialog open>
+ <ReminderEntityPicker onSelect={vi.fn()} onWrite={write} />
+ </Dialog>
+ ));
+ fireEvent.input(screen.getByRole('combobox'), {
+ target: { value: 'unmatched' },
+ });
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Write a reminder instead' })
+ );
+ expect(write).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/features/reminders/views/reminder-entity-picker.tsx b/apps/web/src/features/reminders/views/reminder-entity-picker.tsx
new file mode 100644
index 0000000000..9830493c95
--- /dev/null
+++ b/apps/web/src/features/reminders/views/reminder-entity-picker.tsx
@@ -0,0 +1,137 @@
+import { Entity, type EntityData } from '@entity';
+import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import PencilSimple from '@phosphor/pencil-simple.svg';
+import { debounce } from '@solid-primitives/scheduled';
+import {
+ ActionDialogShell,
+ Button,
+ CommandMenuList,
+ CommandMenuSearchInput,
+ createCommandListController,
+} from '@ui';
+import {
+ createSignal,
+ createUniqueId,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import { useReminderPickerItems } from '../queries/use-reminder-picker-items';
+
+/** A local Command-K-style selection; it never changes the global command menu. */
+export function ReminderEntityPicker(props: {
+ onSelect: (entity: EntityData) => void;
+ onWrite: () => void;
+}) {
+ const [search, setSearch] = createSignal('');
+ const [settledSearch, setSettledSearch] = createSignal('');
+ const settle = debounce(setSettledSearch, 150);
+ onCleanup(settle.clear);
+ const results = useReminderPickerItems(search, settledSearch);
+ const items = results.items;
+ const controller = createCommandListController({
+ items,
+ onSelect: (item) => props.onSelect(item.data),
+ });
+ const listId = createUniqueId();
+ let input: HTMLInputElement | undefined;
+ // This picker can replace a schedule form inside the already-open dialog.
+ onMount(() => input?.focus());
+ return (
+ <>
+ <ActionDialogShell.Body>
+ <ActionDialogShell.Header>
+ <ActionDialogShell.Title>Remind me about…</ActionDialogShell.Title>
+ <ActionDialogShell.Description>
+ Pick something to come back to.
+ </ActionDialogShell.Description>
+ </ActionDialogShell.Header>
+ <div class="flex items-center gap-2 border-b border-edge-muted pb-3">
+ <MagnifyingGlass class="size-4 shrink-0 text-ink-muted" />
+ <CommandMenuSearchInput
+ ref={input}
+ value={search()}
+ placeholder="Search emails, tasks, docs…"
+ aria-label="Search reminder items"
+ role="combobox"
+ autocomplete="off"
+ aria-expanded={true}
+ aria-controls={listId}
+ aria-activedescendant={
+ items().length
+ ? `${listId}-${controller.selectedIndex()}`
+ : undefined
+ }
+ onInput={(event) => {
+ setSearch(event.currentTarget.value);
+ settle(event.currentTarget.value);
+ controller.setSelectedIndex(0);
+ }}
+ onKeyDown={(event) => {
+ if (event.isComposing) return;
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ controller.selectNext();
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ controller.selectPrevious();
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ controller.selectSelected();
+ }
+ }}
+ />
+ </div>
+ <div class="min-h-32">
+ <p class="text-xs text-ink-muted">
+ {search().trim() ? 'Matching items' : 'Recent items'}
+ </p>
+ <CommandMenuList
+ id={listId}
+ items={items()}
+ selectedIndex={controller.selectedIndex()}
+ itemId={(_, index) => `${listId}-${index}`}
+ scrollSelectedIntoView={controller.shouldScrollSelectedIntoView()}
+ onItemMouseMove={controller.setSelectedIndexFromPointer}
+ onSelect={(item) => props.onSelect(item.data)}
+ class="max-h-64 -mx-2.5"
+ >
+ {(item) => (
+ <>
+ <span class="size-5 shrink-0">
+ <Entity.Icon entity={item.data} />
+ </span>
+ <span class="min-w-0 flex-1 truncate">
+ <Entity.Title entity={item.data} />
+ </span>
+ </>
+ )}
+ </CommandMenuList>
+ <Show when={!items().length}>
+ <p role="status" class="py-6 text-center text-sm text-ink-muted">
+ {results.isLoading() ? 'Loading items…' : 'No matching items'}
+ </p>
+ </Show>
+ <Show when={results.hasMore()}>
+ <Button
+ variant="ghost"
+ onClick={() => void results.loadMore()}
+ disabled={results.isLoadingMore()}
+ >
+ Load more
+ </Button>
+ </Show>
+ </div>
+ </ActionDialogShell.Body>
+ <ActionDialogShell.Footer>
+ <Button
+ variant="ghost"
+ class="w-full justify-start gap-2"
+ onClick={props.onWrite}
+ >
+ <PencilSimple class="size-4" /> Write a reminder instead
+ </Button>
+ </ActionDialogShell.Footer>
+ </>
+ );
+}
diff --git a/apps/web/src/lib/core/component/EntityIcon.test.tsx b/apps/web/src/lib/core/component/EntityIcon.test.tsx
index 51b71522ff..206f860e40 100644
--- a/apps/web/src/lib/core/component/EntityIcon.test.tsx
+++ b/apps/web/src/lib/core/component/EntityIcon.test.tsx
@@ -83,6 +83,26 @@ const entityGlyphs: [
['project', { type: 'project' }, FolderIcon],
['calendar', { type: 'calendar_event' }, CalendarIcon],
['reminder', { type: 'reminder' }, ReminderIcon],
+ [
+ 'email reminder',
+ { type: 'reminder', referencedEntity: { id: 'email', type: 'email' } },
+ EnvelopeIcon,
+ 'email',
+ ],
+ [
+ 'task reminder',
+ {
+ type: 'reminder',
+ referencedEntity: {
+ id: 'task',
+ type: 'document',
+ fileType: 'md',
+ subType: 'task',
+ },
+ },
+ ListChecksIcon,
+ 'task',
+ ],
['call', { type: 'call' }, PhoneIcon],
['automation', { type: 'automation' }, AutomationIcon],
[
diff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsx
index 009e41517b..1148771591 100644
--- a/apps/web/src/lib/core/component/EntityIcon.tsx
+++ b/apps/web/src/lib/core/component/EntityIcon.tsx
@@ -627,7 +627,11 @@ export function getEntityIconType(entity: EntityIconData): EntityWithValidIcon {
.with({ type: 'initiative' }, () => 'initiative')
.with({ type: 'project' }, () => 'project')
.with({ type: 'calendar_event' }, () => 'calendar')
- .with({ type: 'reminder' }, () => 'reminder')
+ .with({ type: 'reminder' }, (e) =>
+ e.referencedEntity
+ ? reminderReferenceIconType(e.referencedEntity)
+ : 'reminder'
+ )
.with({ type: 'call' }, () => 'call')
.with({ type: 'automation' }, () => 'automation')
.with({ type: 'foreign' }, (e) => {
@@ -660,6 +664,8 @@ const UNRESOLVED_ICONS: ReadonlySet<string> = new Set(['default', 'unknown']);
export function reminderReferenceIconType(
reference: NonNullable<ReminderEntity['referencedEntity']>
): EntityWithValidIcon {
+ if (reference.type === 'crm_company') return 'company';
+ if (reference.type === 'crm_contact') return 'contact';
const blockName = itemToBlockName(
{
type: reference.type,
diff --git a/apps/web/src/lib/queries/preview/fetchers.ts b/apps/web/src/lib/queries/preview/fetchers.ts
index dcc59d9768..43d063ba50 100644
--- a/apps/web/src/lib/queries/preview/fetchers.ts
+++ b/apps/web/src/lib/queries/preview/fetchers.ts
@@ -1,4 +1,7 @@
-import { fetchCrmCompanyPreviews } from '@app/features/crm/preview-adapter';
+import {
+ fetchCrmCompanyPreviews,
+ fetchCrmContactPreviews,
+} from '@app/features/crm/preview-adapter';
import { itemToSafeName } from '@core/constant/allBlocks';
import {
enableGraphqlSoup,
@@ -401,6 +404,7 @@ export async function fetchRestPreviewBatch(
doFetch(fetchProjectPreviews, filterMapToId(items, 'project')),
doFetch(fetchEmailPreviews, filterMapToId(items, 'email')),
doFetch(fetchCrmCompanyPreviews, filterMapToId(items, 'crm_company')),
+ doFetch(fetchCrmContactPreviews, filterMapToId(items, 'crm_contact')),
doFetch(fetchCalendarEventPreviews, filterMapToId(items, 'calendar_event')),
]);
const resultMap = new Map<string, PreviewItem>();
diff --git a/apps/web/src/lib/queries/preview/tests/contact-fetcher.test.ts b/apps/web/src/lib/queries/preview/tests/contact-fetcher.test.ts
new file mode 100644
index 0000000000..50a8aabd73
--- /dev/null
+++ b/apps/web/src/lib/queries/preview/tests/contact-fetcher.test.ts
@@ -0,0 +1,47 @@
+import { err, ok } from 'neverthrow';
+import { expect, it, vi } from 'vitest';
+
+const getContact = vi.hoisted(() => vi.fn());
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { getContact },
+}));
+vi.mock('@core/constant/allBlocks', () => ({ itemToSafeName: () => '' }));
+vi.mock('@service-cognition/client', () => ({ cognitionApiServiceClient: {} }));
+vi.mock('@service-email/client', () => ({ emailClient: {} }));
+vi.mock('@service-storage/messages', () => ({ entityMessagesClient: {} }));
+vi.mock('../../email/thread', () => ({ threadQueryOptions: vi.fn() }));
+vi.mock('../../client', () => ({ queryClient: {} }));
+vi.mock('../../agent-session/mention-fetchers', () => ({
+ fetchAgentSessionMentionPreviews: vi.fn(),
+}));
+
+import { fetchRestPreviewBatch } from '../fetchers';
+
+it('dispatches contact title lookup and preserves denied access', async () => {
+ getContact.mockResolvedValueOnce(
+ ok({
+ name: 'Alex Morgan',
+ email: '[email protected]',
+ updatedAt: '2026-10-01',
+ })
+ );
+ const visible = await fetchRestPreviewBatch([
+ { type: 'crm_contact', id: 'contact-1' },
+ ]);
+ expect(getContact).toHaveBeenCalledWith({ contactId: 'contact-1' });
+ expect(visible.get('contact-1')).toMatchObject({
+ access: 'access',
+ name: 'Alex Morgan',
+ type: 'crm_contact',
+ });
+ getContact.mockResolvedValueOnce(err({ status: 404 }));
+ const denied = await fetchRestPreviewBatch([
+ { type: 'crm_contact', id: 'contact-2' },
+ ]);
+ expect(denied.get('contact-2')).toEqual({
+ id: 'contact-2',
+ type: 'crm_contact',
+ access: 'no_access',
+ loading: false,
+ });
+});
diff --git a/apps/web/src/lib/queries/reminders/email-followup.test.ts b/apps/web/src/lib/queries/reminders/email-followup.test.ts
new file mode 100644
index 0000000000..afede4086a
--- /dev/null
+++ b/apps/web/src/lib/queries/reminders/email-followup.test.ts
@@ -0,0 +1,99 @@
+import type { EmailFollowup } from '@service-storage/generated/schemas/emailFollowup';
+import type { EmailFollowupCommand } from '@service-storage/generated/schemas/emailFollowupCommand';
+import { ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { emailKeys } from '../email/keys';
+import { executeEmailFollowup } from './email-followup';
+
+const mocks = vi.hoisted(() => ({
+ write: vi.fn(),
+ setData: vi.fn(),
+ invalidate: vi.fn(),
+ refetch: vi.fn(),
+ graphql: vi.fn(),
+ refreshGraphql: vi.fn(),
+ fetchThread: vi.fn(),
+}));
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { reminders: { setEmailFollowup: mocks.write } },
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableGraphqlSoup: 'graphql',
+ isFeatureEnabled: mocks.graphql,
+}));
+vi.mock('../client', () => ({
+ queryClient: {
+ setQueryData: mocks.setData,
+ invalidateQueries: mocks.invalidate,
+ },
+}));
+vi.mock('../soup/cache', () => ({ refetchSoupEntity: mocks.refetch }));
+vi.mock('../soup/graphql/active-queries', () => ({
+ refreshActiveGraphqlSoupQueries: mocks.refreshGraphql,
+}));
+vi.mock('../email/graphql/thread', () => ({
+ fetchGraphqlEmailThread: mocks.fetchThread,
+}));
+const result: EmailFollowup = {
+ condition: 'if_no_reply',
+ linkId: 'inbox',
+ remindAt: '2026-12-01T12:00:00Z',
+ reminderId: 'reminder',
+ revision: 'operation',
+ state: 'pending',
+ threadId: 'thread',
+};
+const command: EmailFollowupCommand = {
+ type: 'set',
+ operationId: 'operation',
+ remindAt: result.remindAt,
+ condition: result.condition,
+};
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.write.mockResolvedValue(ok(result));
+});
+describe('email follow-up cache reconciliation', () => {
+ it('refreshes REST thread and preview state after persistence', async () => {
+ const after = vi.fn();
+ await expect(
+ executeEmailFollowup('thread', command, after)
+ ).resolves.toEqual(result);
+ expect(after).toHaveBeenCalledWith(result);
+ expect(mocks.invalidate).toHaveBeenCalledWith({
+ queryKey: emailKeys.threadMessages('thread').queryKey,
+ });
+ expect(mocks.invalidate).toHaveBeenCalledWith({
+ queryKey: emailKeys.previews._def,
+ });
+ expect(mocks.refreshGraphql).not.toHaveBeenCalled();
+ });
+ it('refreshes GraphQL lists and the thread even when host navigation fails', async () => {
+ mocks.graphql.mockReturnValue(true);
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ await expect(
+ executeEmailFollowup('thread', command, async () => {
+ throw new Error('Host disposed');
+ })
+ ).resolves.toEqual(result);
+ expect(mocks.refreshGraphql).toHaveBeenCalledOnce();
+ expect(mocks.fetchThread).toHaveBeenCalledWith('thread');
+ expect(mocks.refetch).toHaveBeenCalledWith('thread', 'emailThread');
+ } finally {
+ log.mockRestore();
+ }
+ });
+ it('does not turn a cache failure into a retryable write failure', async () => {
+ mocks.invalidate.mockRejectedValue(new Error('Refresh failed'));
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ await expect(executeEmailFollowup('thread', command)).resolves.toEqual(
+ result
+ );
+ } finally {
+ log.mockRestore();
+ }
+ expect(mocks.write).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/lib/queries/reminders/email-followup.ts b/apps/web/src/lib/queries/reminders/email-followup.ts
new file mode 100644
index 0000000000..e645b87d81
--- /dev/null
+++ b/apps/web/src/lib/queries/reminders/email-followup.ts
@@ -0,0 +1,65 @@
+import {
+ enableGraphqlSoup,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
+import { throwOnErr } from '@core/util/result';
+import { storageServiceClient } from '@service-storage/client';
+import type { EmailFollowup } from '@service-storage/generated/schemas/emailFollowup';
+import type { EmailFollowupCommand } from '@service-storage/generated/schemas/emailFollowupCommand';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { queryClient } from '../client';
+import { fetchGraphqlEmailThread } from '../email/graphql/thread';
+import { emailKeys } from '../email/keys';
+import { refetchSoupEntity } from '../soup/cache';
+import { refreshActiveGraphqlSoupQueries } from '../soup/graphql/active-queries';
+import { reminderKeys } from './keys';
+
+export function useEmailFollowupQuery(threadId: Accessor<string>) {
+ return useQuery(() => ({
+ queryKey: reminderKeys.email(threadId()).queryKey,
+ queryFn: () =>
+ throwOnErr(() =>
+ storageServiceClient.reminders.getEmailFollowup(threadId())
+ ),
+ refetchInterval: 30_000,
+ }));
+}
+
+/** One server command owns scheduling and inbox movement. No client archive. */
+export async function executeEmailFollowup(
+ threadId: string,
+ command: EmailFollowupCommand,
+ afterPersisted?: (result: EmailFollowup) => void | Promise<void>
+) {
+ const result = await throwOnErr(() =>
+ storageServiceClient.reminders.setEmailFollowup(threadId, command)
+ );
+ // Presentation/cache failures must not make the successful write retryable.
+ queryClient.setQueryData(reminderKeys.email(threadId).queryKey, result);
+ try {
+ await afterPersisted?.(result);
+ } catch (error) {
+ console.error('Email reminder saved but navigation failed', error);
+ }
+ try {
+ await Promise.all([
+ refetchSoupEntity(threadId, 'emailThread'),
+ refetchSoupEntity(result.reminderId, 'reminder'),
+ queryClient.invalidateQueries({
+ queryKey: emailKeys.threadMessages(threadId).queryKey,
+ }),
+ queryClient.invalidateQueries({ queryKey: emailKeys.previews._def }),
+ ...(isFeatureEnabled(enableGraphqlSoup)
+ ? [refreshActiveGraphqlSoupQueries(), fetchGraphqlEmailThread(threadId)]
+ : []),
+ queryClient.invalidateQueries({ queryKey: reminderKeys.list._def }),
+ queryClient.invalidateQueries({
+ queryKey: reminderKeys.detail(result.reminderId).queryKey,
+ }),
+ ]);
+ } catch (error) {
+ console.error('Email reminder saved but refresh failed', error);
+ }
+ return result;
+}
diff --git a/apps/web/src/lib/queries/reminders/keys.ts b/apps/web/src/lib/queries/reminders/keys.ts
index deeab55493..0a918ed364 100644
--- a/apps/web/src/lib/queries/reminders/keys.ts
+++ b/apps/web/src/lib/queries/reminders/keys.ts
@@ -9,4 +9,5 @@ export const reminderKeys = createQueryKeys('reminders', {
list: (params: ListRemindersParams = {}) => [params],
/** A single reminder by id. */
detail: (id: string) => [id],
+ email: (threadId: string) => [threadId],
});
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index a4943526bb..594246ea27 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -93,6 +93,8 @@ import type { DocumentResponseMetadataWithContent } from './generated/schemas/do
import type { DocumentTeamShareResponse } from './generated/schemas/documentTeamShareResponse';
import type { EditAnchorResponse } from './generated/schemas/editAnchorResponse';
import type { EditCommentResponse } from './generated/schemas/editCommentResponse';
+import type { EmailFollowup } from './generated/schemas/emailFollowup';
+import type { EmailFollowupCommand } from './generated/schemas/emailFollowupCommand';
import type { ExportDocumentResponse } from './generated/schemas/exportDocumentResponse';
import type { Favorite } from './generated/schemas/favorite';
import type { FavoritesList } from './generated/schemas/favoritesList';
@@ -2450,6 +2452,20 @@ export const storageServiceClient = {
},
},
reminders: {
+ async getEmailFollowup(threadId: string) {
+ return (
+ await dssFetch<{ followup: EmailFollowup | null }>(
+ `/reminders/email/${threadId}`,
+ { method: 'GET' }
+ )
+ ).map((response) => response.followup);
+ },
+ async setEmailFollowup(threadId: string, command: EmailFollowupCommand) {
+ return await dssFetch<EmailFollowup>(`/reminders/email/${threadId}`, {
+ method: 'PUT',
+ body: JSON.stringify(command),
+ });
+ },
async createReminder(params: CreateReminderRequest) {
return await dssFetch<Reminder>('/reminders', {
method: 'POST',
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowup.ts
new file mode 100644
index 0000000000..2e1e78ecc9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowup.ts
@@ -0,0 +1,28 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EmailReminderCondition } from './emailReminderCondition';
+import type { FollowupState } from './followupState';
+
+/**
+ * Public status shown on email and in the Reminders editor.
+ */
+export interface EmailFollowup {
+ /** Condition, defaulting to no reply for new follow-ups. */
+ condition: EmailReminderCondition;
+ /** Canonical owned/delegated inbox. */
+ linkId: string;
+ /** Confirmed schedule. */
+ remindAt: string;
+ /** Its ordinary reminder, used by the existing alert/management surfaces. */
+ reminderId: string;
+ /** Last accepted operation; edits/removal compare this to prevent stale undo. */
+ revision: string;
+ /** Durable lifecycle progress. */
+ state: FollowupState;
+ /** Conversation identity. */
+ threadId: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommand.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommand.ts
new file mode 100644
index 0000000000..23f6da47d7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommand.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EmailFollowupCommandOneOf } from './emailFollowupCommandOneOf';
+import type { EmailFollowupCommandOneOfFour } from './emailFollowupCommandOneOfFour';
+
+/**
+ * Idempotent email command. Reusing an operation ID with different data fails.
+ */
+export type EmailFollowupCommand =
+ | EmailFollowupCommandOneOf
+ | EmailFollowupCommandOneOfFour;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOf.ts
new file mode 100644
index 0000000000..8043450138
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOf.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { EmailFollowupCommandOneOfExpectedRevision } from './emailFollowupCommandOneOfExpectedRevision';
+import type { EmailFollowupCommandOneOfType } from './emailFollowupCommandOneOfType';
+import type { EmailReminderCondition } from './emailReminderCondition';
+
+/**
+ * Create or edit one follow-up. An edit requires the displayed revision.
+ */
+export type EmailFollowupCommandOneOf = {
+ /** Reply condition. */
+ condition: EmailReminderCondition;
+ /** None for creation, the current revision for edits. */
+ expectedRevision?: EmailFollowupCommandOneOfExpectedRevision;
+ /** Unique request identity retained across network retries. */
+ operationId: string;
+ /** One future instant; conditional recurrence is deliberately absent. */
+ remindAt: string;
+ type: EmailFollowupCommandOneOfType;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfExpectedRevision.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfExpectedRevision.ts
new file mode 100644
index 0000000000..ca3a60f113
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfExpectedRevision.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * None for creation, the current revision for edits.
+ */
+export type EmailFollowupCommandOneOfExpectedRevision = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfFour.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfFour.ts
new file mode 100644
index 0000000000..35e1469eb8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfFour.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EmailFollowupCommandOneOfFourType } from './emailFollowupCommandOneOfFourType';
+
+/**
+ * Cancel and restore the conversation without leaving a future alert.
+ */
+export type EmailFollowupCommandOneOfFour = {
+ /** Reject removal if a newer edit has replaced this operation. */
+ expectedRevision: string;
+ /** Unique request identity. */
+ operationId: string;
+ type: EmailFollowupCommandOneOfFourType;
+ /** Undo restores original visibility; ordinary Remove returns to inbox. */
+ undo?: boolean;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfFourType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfFourType.ts
new file mode 100644
index 0000000000..3330ebac8e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfFourType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EmailFollowupCommandOneOfFourType =
+ (typeof EmailFollowupCommandOneOfFourType)[keyof typeof EmailFollowupCommandOneOfFourType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EmailFollowupCommandOneOfFourType = {
+ remove: 'remove',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfType.ts
new file mode 100644
index 0000000000..3dd4f07d29
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupCommandOneOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type EmailFollowupCommandOneOfType =
+ (typeof EmailFollowupCommandOneOfType)[keyof typeof EmailFollowupCommandOneOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EmailFollowupCommandOneOfType = {
+ set: 'set',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupResponse.ts
new file mode 100644
index 0000000000..d7beaca1a9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EmailFollowupResponseFollowup } from './emailFollowupResponseFollowup';
+
+/**
+ * Lookup response, including an email with no follow-up yet.
+ */
+export interface EmailFollowupResponse {
+ followup?: EmailFollowupResponseFollowup;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupResponseFollowup.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupResponseFollowup.ts
new file mode 100644
index 0000000000..c61fb7ee85
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailFollowupResponseFollowup.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EmailFollowup } from './emailFollowup';
+
+export type EmailFollowupResponseFollowup = null | EmailFollowup;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailReminderCondition.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailReminderCondition.ts
new file mode 100644
index 0000000000..71828a0424
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/emailReminderCondition.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When an email follow-up should return the conversation.
+ */
+export type EmailReminderCondition =
+ (typeof EmailReminderCondition)[keyof typeof EmailReminderCondition];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const EmailReminderCondition = {
+ if_no_reply: 'if_no_reply',
+ regardless: 'regardless',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/followupState.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/followupState.ts
new file mode 100644
index 0000000000..a2a7281734
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/followupState.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Durable progress of an email operation.
+ */
+export type FollowupState = (typeof FollowupState)[keyof typeof FollowupState];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const FollowupState = {
+ archiving: 'archiving',
+ pending: 'pending',
+ returning: 'returning',
+ returned: 'returned',
+ cancelled: 'cancelled',
+ removed: 'removed',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index ff6af104b1..f5068a6765 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -704,6 +704,16 @@ export * from './emailFilters';
export * from './emailFiltersCalendarOnly';
export * from './emailFiltersImportance';
export * from './emailFiltersIsRead';
+export * from './emailFollowup';
+export * from './emailFollowupCommand';
+export * from './emailFollowupCommandOneOf';
+export * from './emailFollowupCommandOneOfExpectedRevision';
+export * from './emailFollowupCommandOneOfFour';
+export * from './emailFollowupCommandOneOfFourType';
+export * from './emailFollowupCommandOneOfType';
+export * from './emailFollowupResponse';
+export * from './emailFollowupResponseFollowup';
+export * from './emailReminderCondition';
export * from './emptyResponse';
export * from './ensureCollabSurfaceRequest';
export * from './ensureCollabSurfaceRequestParentEntityType';
@@ -765,6 +775,7 @@ export * from './fileTypeUpdate';
export * from './fileTypeUpdateOneOf';
export * from './folderItem';
export * from './folderItemFileType';
+export * from './followupState';
export * from './foreignEntity';
export * from './foreignEntityFilters';
export * from './genericErrorResponse';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 14f63f64f7..93f5577be1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -35267,6 +35267,143 @@ export const createReminderBody = zod
})
.describe('Request body for creating a reminder.');
+/**
+ * @summary Read an email follow-up and reconcile inbound reply cancellation.
+ */
+export const getEmailFollowupParams = zod.object({
+ thread_id: zod.uuid(),
+});
+
+export const getEmailFollowupResponse = zod
+ .object({
+ followup: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ condition: zod
+ .enum(['if_no_reply', 'regardless'])
+ .describe(
+ 'When an email follow-up should return the conversation.'
+ ),
+ linkId: zod.uuid().describe('Canonical owned\/delegated inbox.'),
+ remindAt: zod.iso.datetime({}).describe('Confirmed schedule.'),
+ reminderId: zod
+ .uuid()
+ .describe(
+ 'Its ordinary reminder, used by the existing alert\/management surfaces.'
+ ),
+ revision: zod
+ .uuid()
+ .describe(
+ 'Last accepted operation; edits\/removal compare this to prevent stale undo.'
+ ),
+ state: zod
+ .enum([
+ 'archiving',
+ 'pending',
+ 'returning',
+ 'returned',
+ 'cancelled',
+ 'removed',
+ ])
+ .describe('Durable progress of an email operation.'),
+ threadId: zod.uuid().describe('Conversation identity.'),
+ })
+ .describe(
+ 'Public status shown on email and in the Reminders editor.'
+ ),
+ ])
+ .optional(),
+ })
+ .describe('Lookup response, including an email with no follow-up yet.');
+
+/**
+ * @summary Schedule, edit or remove one email follow-up as an idempotent operation.
+ */
+export const setEmailFollowupParams = zod.object({
+ thread_id: zod.uuid(),
+});
+
+export const setEmailFollowupBody = zod
+ .union([
+ zod
+ .object({
+ condition: zod
+ .enum(['if_no_reply', 'regardless'])
+ .describe('When an email follow-up should return the conversation.'),
+ expectedRevision: zod
+ .uuid()
+ .nullish()
+ .describe('None for creation, the current revision for edits.'),
+ operationId: zod
+ .uuid()
+ .describe('Unique request identity retained across network retries.'),
+ remindAt: zod.iso
+ .datetime({})
+ .describe(
+ 'One future instant; conditional recurrence is deliberately absent.'
+ ),
+ type: zod.enum(['set']),
+ })
+ .describe(
+ 'Create or edit one follow-up. An edit requires the displayed revision.'
+ ),
+ zod
+ .object({
+ expectedRevision: zod
+ .uuid()
+ .describe(
+ 'Reject removal if a newer edit has replaced this operation.'
+ ),
+ operationId: zod.uuid().describe('Unique request identity.'),
+ type: zod.enum(['remove']),
+ undo: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Undo restores original visibility; ordinary Remove returns to inbox.'
+ ),
+ })
+ .describe(
+ 'Cancel and restore the conversation without leaving a future alert.'
+ ),
+ ])
+ .describe(
+ 'Idempotent email command. Reusing an operation ID with different data fails.'
+ );
+
+export const setEmailFollowupResponse = zod
+ .object({
+ condition: zod
+ .enum(['if_no_reply', 'regardless'])
+ .describe('When an email follow-up should return the conversation.'),
+ linkId: zod.uuid().describe('Canonical owned\/delegated inbox.'),
+ remindAt: zod.iso.datetime({}).describe('Confirmed schedule.'),
+ reminderId: zod
+ .uuid()
+ .describe(
+ 'Its ordinary reminder, used by the existing alert\/management surfaces.'
+ ),
+ revision: zod
+ .uuid()
+ .describe(
+ 'Last accepted operation; edits\/removal compare this to prevent stale undo.'
+ ),
+ state: zod
+ .enum([
+ 'archiving',
+ 'pending',
+ 'returning',
+ 'returned',
+ 'cancelled',
+ 'removed',
+ ])
+ .describe('Durable progress of an email operation.'),
+ threadId: zod.uuid().describe('Conversation identity.'),
+ })
+ .describe('Public status shown on email and in the Reminders editor.');
+
/**
* @summary Fetch one of the caller's reminders.
*/
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 7e0fbcf447..16630c62d9 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -14286,6 +14286,124 @@
}
}
},
+ "/reminders/email/{thread_id}": {
+ "get": {
+ "tags": ["reminders"],
+ "summary": "Read an email follow-up and reconcile inbound reply cancellation.",
+ "operationId": "get_email_followup",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EmailFollowupResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["reminders"],
+ "summary": "Schedule, edit or remove one email follow-up as an idempotent operation.",
+ "operationId": "set_email_followup",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EmailFollowupCommand"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EmailFollowup"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/reminders/{id}": {
"get": {
"tags": ["reminders"],
@@ -23717,6 +23835,136 @@
}
}
},
+ "EmailFollowup": {
+ "type": "object",
+ "description": "Public status shown on email and in the Reminders editor.",
+ "required": [
+ "reminderId",
+ "threadId",
+ "linkId",
+ "condition",
+ "remindAt",
+ "revision",
+ "state"
+ ],
+ "properties": {
+ "condition": {
+ "$ref": "#/components/schemas/EmailReminderCondition",
+ "description": "Condition, defaulting to no reply for new follow-ups."
+ },
+ "linkId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Canonical owned/delegated inbox."
+ },
+ "remindAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Confirmed schedule."
+ },
+ "reminderId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Its ordinary reminder, used by the existing alert/management surfaces."
+ },
+ "revision": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Last accepted operation; edits/removal compare this to prevent stale undo."
+ },
+ "state": {
+ "$ref": "#/components/schemas/FollowupState",
+ "description": "Durable lifecycle progress."
+ },
+ "threadId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Conversation identity."
+ }
+ }
+ },
+ "EmailFollowupCommand": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Create or edit one follow-up. An edit requires the displayed revision.",
+ "required": ["operationId", "remindAt", "condition", "type"],
+ "properties": {
+ "condition": {
+ "$ref": "#/components/schemas/EmailReminderCondition",
+ "description": "Reply condition."
+ },
+ "expectedRevision": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "None for creation, the current revision for edits."
+ },
+ "operationId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Unique request identity retained across network retries."
+ },
+ "remindAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "One future instant; conditional recurrence is deliberately absent."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["set"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Cancel and restore the conversation without leaving a future alert.",
+ "required": ["operationId", "expectedRevision", "type"],
+ "properties": {
+ "expectedRevision": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Reject removal if a newer edit has replaced this operation."
+ },
+ "operationId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Unique request identity."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["remove"]
+ },
+ "undo": {
+ "type": "boolean",
+ "description": "Undo restores original visibility; ordinary Remove returns to inbox."
+ }
+ }
+ }
+ ],
+ "description": "Idempotent email command. Reusing an operation ID with different data fails."
+ },
+ "EmailFollowupResponse": {
+ "type": "object",
+ "description": "Lookup response, including an email with no follow-up yet.",
+ "properties": {
+ "followup": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EmailFollowup",
+ "description": "Most recent specialized follow-up, if any."
+ }
+ ]
+ }
+ }
+ },
+ "EmailReminderCondition": {
+ "type": "string",
+ "description": "When an email follow-up should return the conversation.",
+ "enum": ["if_no_reply", "regardless"]
+ },
"EmptyResponse": {
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
@@ -24777,6 +25025,18 @@
}
}
},
+ "FollowupState": {
+ "type": "string",
+ "description": "Durable progress of an email operation.",
+ "enum": [
+ "archiving",
+ "pending",
+ "returning",
+ "returned",
+ "cancelled",
+ "removed"
+ ]
+ },
"ForeignEntity": {
"type": "object",
"description": "A persisted mapping to an entity owned by an external system.",
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 549899cf38..61e25da130 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -427,7 +427,7 @@ pub async fn build_tool_service_context_from_env(
entity_access_service.clone(),
document_tool_context.service.clone(),
chat_tool_context.service.clone(),
- user_email_service,
+ user_email_service.clone(),
);
let anthropic_tool_context = build_anthropic_tool_context();
@@ -469,6 +469,7 @@ pub async fn build_tool_service_context_from_env(
notification_tool_context,
reminders_tool_context: crate::tool_context::build_reminders_tool_context(
pool.clone(),
+ user_email_service.clone(),
entity_access_service.clone(),
),
import_tool_context: ToolImportToolContext::unwired(),
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 9c5ed6c4f9..ab433374ef 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1052,25 +1052,37 @@ pub type ToolNotificationService = notification::domain::service::NotificationRe
pub type ToolNotificationToolContext = NotificationToolContext<ToolNotificationService>;
/// Type alias for the reminders service implementation used by AI tools.
-pub type ToolRemindersService = reminders::domain::service::RemindersServiceImpl<
- reminders::outbound::pg_reminders_repo::PgRemindersRepo,
->;
+pub type ToolRemindersService =
+ reminders::domain::email_followup::reminder_service::EmailRemindersService<
+ reminders::domain::service::RemindersServiceImpl<
+ reminders::outbound::pg_reminders_repo::PgRemindersRepo,
+ >,
+ reminders::outbound::pg_reminders_repo::PgRemindersRepo,
+ ToolUserEmailService,
+ reminders::domain::ports::SystemClock,
+ >;
/// Type alias for the reminders tool context.
pub type ToolRemindersToolContext =
RemindersToolContext<ToolRemindersService, ToolEntityAccessService>;
-/// Build the reminders tool context from a database pool.
+/// Build the reminders tool context with the same email lifecycle as HTTP.
///
/// The reminder tools go through the same access receipts the HTTP API does,
/// so this needs the entity access service as well as the repository.
pub fn build_reminders_tool_context(
pool: sqlx::PgPool,
+ email_service: Arc<ToolUserEmailService>,
entity_access_service: Arc<ToolEntityAccessService>,
) -> ToolRemindersToolContext {
+ let repo = reminders::outbound::pg_reminders_repo::PgRemindersRepo::new(pool);
RemindersToolContext::new(
- reminders::domain::service::RemindersServiceImpl::new(
- reminders::outbound::pg_reminders_repo::PgRemindersRepo::new(pool),
+ reminders::domain::email_followup::reminder_service::EmailRemindersService::new(
+ reminders::domain::service::RemindersServiceImpl::new(repo.clone()),
+ reminders::domain::email_followup::service::EmailFollowupService::new(
+ repo,
+ (*email_service).clone(),
+ ),
),
entity_access_service,
)
diff --git a/crates/email/src/domain.rs b/crates/email/src/domain.rs
index 7610cf6d38..6ca23b3867 100644
--- a/crates/email/src/domain.rs
+++ b/crates/email/src/domain.rs
@@ -3,6 +3,8 @@ pub mod activity;
#[cfg(feature = "calendar_invitations")]
pub mod calendar_invitation_parser;
pub mod events;
+#[cfg(feature = "ports")]
+pub mod followup;
#[cfg(feature = "calendar_invitations")]
pub mod invitation_extraction;
#[cfg(feature = "calendar_invitations")]
diff --git a/crates/email/src/domain/followup.rs b/crates/email/src/domain/followup.rs
new file mode 100644
index 0000000000..536d9e53c8
--- /dev/null
+++ b/crates/email/src/domain/followup.rs
@@ -0,0 +1,125 @@
+//! Email-owned capabilities used by conditional reminders.
+//!
+//! A reminder never edits message dates or infers replies from thread updates.
+//! The inbox identity is resolved again for every operation, including dispatch.
+
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::models::EmailErr;
+
+/// Persisted boundary between existing mail and a genuinely new reply.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ReplyBaseline {
+ /// Capture time, independent of mutable thread timestamps.
+ pub captured_at: DateTime<Utc>,
+ /// Provider messages already present when the reminder was set.
+ pub message_ids: Vec<Uuid>,
+}
+
+/// Small message facts needed to classify a reply, without loading bodies.
+#[derive(Debug, Clone)]
+pub struct FollowupMessage {
+ /// Stable database identity (provider replays upsert the same identity).
+ pub id: Uuid,
+ /// Provider's immutable arrival time, not the ingestion time.
+ pub received_at: Option<DateTime<Utc>>,
+ /// Drafts and SENT messages, including provider send-as aliases, are outgoing.
+ pub outgoing: bool,
+ /// Whether the sender is one of the viewer's accessible inbox identities.
+ pub from_self: bool,
+}
+
+/// Authorized thread facts; inaccessible/deleted threads produce no snapshot.
+#[derive(Debug, Clone)]
+pub struct FollowupThread {
+ /// Canonical inbox, resolved from the thread rather than the primary inbox.
+ pub link_id: Uuid,
+ /// Subject used as the reminder description.
+ pub subject: String,
+ /// Current visibility, retained for coherent undo.
+ pub inbox_visible: bool,
+ /// Previous reminder ordering, retained when undo restores the inbox.
+ pub returned_at: Option<DateTime<Utc>>,
+ /// Trashed/spam threads must never be resurrected by a follow-up.
+ pub unavailable: bool,
+ /// Persisted messages, excluding bodies and recipient lists.
+ pub messages: Vec<FollowupMessage>,
+}
+
+impl FollowupThread {
+ /// Capture stable identities and the server clock before archiving.
+ pub fn baseline(&self, now: DateTime<Utc>) -> ReplyBaseline {
+ ReplyBaseline {
+ captured_at: now,
+ message_ids: self.messages.iter().map(|message| message.id).collect(),
+ }
+ }
+
+ /// Label changes, outgoing mail, drafts, replays and historical backfill
+ /// cannot satisfy this predicate. A delayed live arrival can, provided its
+ /// provider arrival time is after the reminder's boundary.
+ pub fn has_reply(&self, baseline: &ReplyBaseline) -> bool {
+ self.messages.iter().any(|message| {
+ !message.outgoing
+ && !message.from_self
+ && message
+ .received_at
+ .is_some_and(|at| at > baseline.captured_at)
+ && !baseline.message_ids.contains(&message.id)
+ })
+ }
+}
+
+/// Email facts and mutations exposed to the reminder domain.
+pub trait EmailFollowupMailbox: Send + Sync + 'static {
+ /// Resolve owned/delegated access and inspect this conversation.
+ fn followup_thread(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<Option<FollowupThread>, EmailErr>> + Send;
+
+ /// Apply a reminder's inbox state, checking the same inbox and access again.
+ /// `returned_at` is honest inbox ordering metadata, never a message date.
+ /// Unlike ordinary unarchive, this explicitly permits sent-only threads.
+ fn set_followup_inbox(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ link_id: Uuid,
+ visible: bool,
+ returned_at: Option<DateTime<Utc>>,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+}
+
+/// Persistence capabilities specific to the email side of follow-ups.
+pub trait EmailFollowupRepo: Send + Sync + 'static {
+ /// Load message identity/classification facts for an authorized thread.
+ fn followup_messages(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<FollowupMessage>, EmailErr>> + Send;
+
+ /// Read ordering metadata without widening the generic thread model.
+ fn followup_returned_at(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<Option<DateTime<Utc>>, EmailErr>> + Send;
+
+ /// Store a return timestamp separately from immutable mail activity.
+ fn set_followup_returned_at(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ returned_at: Option<DateTime<Utc>>,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/email/src/domain/followup/test.rs b/crates/email/src/domain/followup/test.rs
new file mode 100644
index 0000000000..88d005d9d8
--- /dev/null
+++ b/crates/email/src/domain/followup/test.rs
@@ -0,0 +1,45 @@
+use super::*;
+use chrono::Duration;
+
+#[test]
+fn only_new_inbound_mail_after_the_boundary_counts() {
+ let now = Utc::now();
+ let existing = Uuid::from_u128(1);
+ let mut thread = FollowupThread {
+ link_id: Uuid::from_u128(2),
+ subject: "Subject".into(),
+ returned_at: None,
+ inbox_visible: true,
+ unavailable: false,
+ messages: vec![FollowupMessage {
+ id: existing,
+ received_at: Some(now),
+ outgoing: false,
+ from_self: false,
+ }],
+ };
+ let baseline = thread.baseline(now);
+ // Provider replay, even if its date has changed, keeps the saved identity.
+ thread.messages[0].received_at = Some(now + Duration::seconds(1));
+ assert!(!thread.has_reply(&baseline));
+ thread.messages.push(FollowupMessage {
+ id: Uuid::from_u128(3),
+ received_at: Some(now - Duration::days(1)),
+ outgoing: false,
+ from_self: false,
+ });
+ assert!(!thread.has_reply(&baseline), "historical backfill");
+ let message = thread.messages.last_mut().unwrap();
+ message.received_at = Some(now + Duration::seconds(1));
+ message.outgoing = true;
+ assert!(
+ !thread.has_reply(&baseline),
+ "sent or draft, including aliases"
+ );
+ let message = thread.messages.last_mut().unwrap();
+ message.outgoing = false;
+ message.from_self = true;
+ assert!(!thread.has_reply(&baseline), "own/delegated inbox sender");
+ thread.messages.last_mut().unwrap().from_self = false;
+ assert!(thread.has_reply(&baseline));
+}
diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rs
index 356cda0586..2adf4f3971 100644
--- a/crates/email/src/domain/service.rs
+++ b/crates/email/src/domain/service.rs
@@ -1,4 +1,5 @@
mod draft;
+mod followup;
mod previews;
mod send;
pub(crate) mod signature;
diff --git a/crates/email/src/domain/service/followup.rs b/crates/email/src/domain/service/followup.rs
new file mode 100644
index 0000000000..c246abac9a
--- /dev/null
+++ b/crates/email/src/domain/service/followup.rs
@@ -0,0 +1,132 @@
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use crate::domain::{
+ followup::{EmailFollowupMailbox, EmailFollowupRepo, FollowupThread},
+ models::{EmailErr, label::system_labels},
+ ports::{EmailMessageEnqueuer, EmailRepo},
+};
+use frecency::domain::ports::FrecencyQueryService;
+use macro_event_broker::MacroEventBroker;
+
+use super::EmailServiceImpl;
+
+impl<T, U, E, CS, Eam, B> EmailFollowupMailbox for EmailServiceImpl<T, U, E, CS, Eam, B>
+where
+ T: EmailRepo + EmailFollowupRepo,
+ U: FrecencyQueryService,
+ E: EmailMessageEnqueuer,
+ CS: crm::domain::service::CrmService,
+ Eam: Send + Sync + 'static,
+ B: MacroEventBroker,
+ anyhow::Error: From<T::Err> + From<E::Err>,
+{
+ async fn followup_thread(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Result<Option<FollowupThread>, EmailErr> {
+ let Some(link) = self
+ .email_repo
+ .owned_link_for_thread(thread_id, user.clone())
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ else {
+ return Ok(None);
+ };
+ let Some(thread) = self
+ .email_repo
+ .thread_by_id(thread_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ else {
+ return Ok(None);
+ };
+ let messages = self
+ .email_repo
+ .followup_messages(user, thread_id, link.id)
+ .await?;
+ if messages.is_empty() {
+ return Ok(None);
+ }
+ let labels = self
+ .email_repo
+ .labels_by_thread_ids(&[thread_id])
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+ let latest = self
+ .email_repo
+ .latest_content_message_rows(&[thread_id])
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+ Ok(Some(FollowupThread {
+ link_id: link.id,
+ subject: latest
+ .into_iter()
+ .next()
+ .and_then(|message| message.subject)
+ .filter(|subject| !subject.trim().is_empty())
+ .unwrap_or_else(|| "Email follow-up".into()),
+ inbox_visible: thread.inbox_visible,
+ returned_at: self
+ .email_repo
+ .followup_returned_at(thread_id, link.id)
+ .await?,
+ unavailable: labels.iter().any(|label| {
+ matches!(
+ label.provider_label_id.as_str(),
+ system_labels::TRASH | system_labels::SPAM
+ )
+ }),
+ messages,
+ }))
+ }
+
+ async fn set_followup_inbox(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ link_id: Uuid,
+ visible: bool,
+ returned_at: Option<DateTime<Utc>>,
+ ) -> Result<(), EmailErr> {
+ let facts = self
+ .followup_thread(user.clone(), thread_id)
+ .await?
+ .filter(|facts| facts.link_id == link_id && !facts.unavailable)
+ .ok_or(EmailErr::ThreadNotFound)?;
+ let link = self
+ .email_repo
+ .owned_link_for_thread(thread_id, user.clone())
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .filter(|link| link.id == facts.link_id)
+ .ok_or(EmailErr::ThreadNotFound)?;
+ let label = self
+ .email_repo
+ .list_labels_by_link_id(link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .into_iter()
+ .find(|label| label.provider_label_id == system_labels::INBOX)
+ .ok_or(EmailErr::LabelNotFound)?;
+ // Persist the explicit return before provider work/events can observe
+ // INBOX, so sent-only metadata reconciliation sees the same intent.
+ // A failed label write leaves a timestamp on an archived thread, which
+ // remains excluded by inbox visibility and is retried by the workflow.
+ if visible {
+ self.email_repo
+ .set_followup_returned_at(thread_id, link_id, returned_at)
+ .await?;
+ }
+ self.update_thread_labels_with_actor(&link, thread_id, label.id, visible, Some(user))
+ .await?;
+ if !visible {
+ self.email_repo
+ .set_followup_returned_at(thread_id, link_id, None)
+ .await?;
+ }
+ Ok(())
+ }
+}
diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rs
index 9fe428c70a..08387cddd2 100644
--- a/crates/email/src/domain/service/thread_labels.rs
+++ b/crates/email/src/domain/service/thread_labels.rs
@@ -179,7 +179,7 @@ where
}
#[tracing::instrument(err, skip(self, link))]
- async fn update_thread_labels_with_actor(
+ pub(super) async fn update_thread_labels_with_actor(
&self,
link: &Link,
thread_id: Uuid,
diff --git a/crates/email/src/outbound/email_pg_repo.rs b/crates/email/src/outbound/email_pg_repo.rs
index 18f624feef..2bf29bd20a 100644
--- a/crates/email/src/outbound/email_pg_repo.rs
+++ b/crates/email/src/outbound/email_pg_repo.rs
@@ -21,6 +21,7 @@ mod db_types;
mod draft;
mod dynamic;
mod email_filter;
+mod followup;
mod label;
mod link;
mod message;
diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs
index 773a071535..cfb7232361 100644
--- a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs
+++ b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs
@@ -1014,7 +1014,7 @@ pub(super) fn escape_like_pattern(s: &str) -> String {
pub(super) fn build_view_thread_filter(view: &PreviewView) -> SqlFragment {
match view {
PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => SqlFragment::raw(
- " AND t.inbox_visible = TRUE AND t.latest_inbound_message_ts IS NOT NULL",
+ " AND t.inbox_visible = TRUE AND (t.latest_inbound_message_ts IS NOT NULL OR t.reminder_returned_at IS NOT NULL)",
),
PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {
SqlFragment::raw(" AND t.latest_outbound_message_ts IS NOT NULL")
@@ -1091,7 +1091,7 @@ pub(super) fn get_sort_timestamp_field(view: &PreviewView) -> &'static str {
"t.latest_outbound_message_ts"
}
PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => {
- "t.latest_inbound_message_ts"
+ "GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at)"
}
_ => "COALESCE(t.latest_non_spam_message_ts, t.updated_at)",
}
diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs b/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs
index 8eb19c4116..a51720de7e 100644
--- a/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs
+++ b/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs
@@ -534,7 +534,10 @@ fn test_get_sort_timestamp_field_sent() {
fn test_get_sort_timestamp_field_inbox() {
let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
let result = get_sort_timestamp_field(&view);
- assert_eq!(result, "t.latest_inbound_message_ts");
+ assert_eq!(
+ result,
+ "GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at)"
+ );
}
#[test]
diff --git a/crates/email/src/outbound/email_pg_repo/followup.rs b/crates/email/src/outbound/email_pg_repo/followup.rs
new file mode 100644
index 0000000000..d20bf4e44e
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/followup.rs
@@ -0,0 +1,78 @@
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use super::EmailPgRepo;
+use crate::domain::{
+ followup::{EmailFollowupRepo, FollowupMessage},
+ models::EmailErr,
+};
+
+impl EmailFollowupRepo for EmailPgRepo {
+ async fn followup_messages(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ link_id: Uuid,
+ ) -> Result<Vec<FollowupMessage>, EmailErr> {
+ sqlx::query_as!(
+ FollowupMessage,
+ r#"
+ SELECT m.id, m.internal_date_ts AS received_at,
+ (m.is_sent OR m.is_draft) AS "outgoing!",
+ EXISTS (
+ SELECT 1 FROM email_links l
+ WHERE lower(l.email_address) = lower(c.email_address)
+ AND (l.macro_id = $3 OR EXISTS (
+ SELECT 1 FROM macro_user_links mul
+ WHERE mul.link_id = l.id AND mul.primary_macro_id = $3
+ ))
+ ) AS "from_self!"
+ FROM email_messages m
+ LEFT JOIN email_contacts c ON c.id = m.from_contact_id
+ WHERE m.thread_id = $1 AND m.link_id = $2
+ ORDER BY m.id
+ "#,
+ thread_id,
+ link_id,
+ user.as_ref(),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
+ async fn followup_returned_at(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ ) -> Result<Option<DateTime<Utc>>, EmailErr> {
+ sqlx::query_scalar!(
+ "SELECT reminder_returned_at FROM email_threads WHERE id = $1 AND link_id = $2",
+ thread_id,
+ link_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map(Option::flatten)
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
+ async fn set_followup_returned_at(
+ &self,
+ thread_id: Uuid,
+ link_id: Uuid,
+ returned_at: Option<DateTime<Utc>>,
+ ) -> Result<(), EmailErr> {
+ sqlx::query!(
+ "UPDATE email_threads SET reminder_returned_at = $3 WHERE id = $1 AND link_id = $2",
+ thread_id,
+ link_id,
+ returned_at,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))?;
+ Ok(())
+ }
+}
diff --git a/crates/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs b/crates/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
index 3222d6a61f..be4bbfd8ac 100644
--- a/crates/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
+++ b/crates/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
@@ -63,28 +63,28 @@ pub(crate) async fn new_inbox_preview_cursor(
t.is_read,
t.is_signal,
t.project_id,
- t.latest_inbound_message_ts AS created_at,
- t.latest_inbound_message_ts AS updated_at,
+ COALESCE(t.latest_inbound_message_ts, t.latest_outbound_message_ts, t.created_at) AS created_at,
+ GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at) AS updated_at,
uh.updated_at AS viewed_at,
CASE $5 -- sort_method_str
WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)
- ELSE t.latest_inbound_message_ts
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at))
+ ELSE GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at)
END AS effective_ts
FROM email_threads t
LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
WHERE
t.link_id = ANY($1)
AND t.inbox_visible = TRUE
- AND t.latest_inbound_message_ts IS NOT NULL
+ AND (t.latest_inbound_message_ts IS NOT NULL OR t.reminder_returned_at IS NOT NULL)
-- The cursor logic is moved inside this subquery for maximum efficiency.
AND (($3::timestamptz IS NULL) OR (
-- This CASE must exactly match the one that defines `effective_ts`
CASE $5 -- sort_method_str
WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)
- ELSE t.latest_inbound_message_ts
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at))
+ ELSE GREATEST(t.latest_inbound_message_ts, t.reminder_returned_at)
END, t.id
) < ($3::timestamptz, $4::uuid))
ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rs
index 4b2324911e..bc5e2aabc8 100644
--- a/crates/email/src/outbound/email_pg_repo/test.rs
+++ b/crates/email/src/outbound/email_pg_repo/test.rs
@@ -46,3 +46,5 @@ async fn sync_all_signal_flags(pool: &Pool<Postgres>) -> anyhow::Result<()> {
}
Ok(())
}
+
+mod followup;
diff --git a/crates/email/src/outbound/email_pg_repo/test/followup.rs b/crates/email/src/outbound/email_pg_repo/test/followup.rs
new file mode 100644
index 0000000000..a47467319f
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/test/followup.rs
@@ -0,0 +1,133 @@
+use super::thread_unread::service;
+use super::*;
+use crate::domain::followup::EmailFollowupMailbox;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn followup_return_authorizes_the_thread_inbox_and_supports_sent_only(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread = uuid::uuid!("11111111-1111-1111-1111-111111111111");
+ let link = uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
+ let owner = MacroUserIdStr::try_from_email("[email protected]")?;
+ let mailbox = service(pool.clone());
+ sqlx::query!(
+ "UPDATE email_messages SET is_sent = true WHERE thread_id = $1",
+ thread
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!("UPDATE email_threads SET latest_inbound_message_ts = NULL, inbox_visible = false WHERE id = $1", thread).execute(&pool).await?;
+ let before = mailbox
+ .followup_thread(owner.clone(), thread)
+ .await?
+ .unwrap();
+ assert_eq!(before.link_id, link);
+ assert!(before.messages.iter().all(|message| message.outgoing));
+ assert!(!before.has_reply(&before.baseline(Utc::now())));
+ assert!(
+ mailbox
+ .set_followup_inbox(
+ owner.clone(),
+ thread,
+ Uuid::now_v7(),
+ true,
+ Some(Utc::now())
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ mailbox
+ .followup_thread(MacroUserIdStr::try_from_email("[email protected]")?, thread)
+ .await?
+ .is_none()
+ );
+ mailbox
+ .set_followup_inbox(owner.clone(), thread, link, true, Some(Utc::now()))
+ .await?;
+ let returned = sqlx::query!("SELECT inbox_visible, latest_inbound_message_ts, reminder_returned_at FROM email_threads WHERE id = $1", thread).fetch_one(&pool).await?;
+ assert!(returned.inbox_visible);
+ assert!(
+ returned.latest_inbound_message_ts.is_none(),
+ "must not invent an inbound message"
+ );
+ assert!(returned.reminder_returned_at.is_some());
+ mailbox
+ .set_followup_inbox(owner, thread, link, false, None)
+ .await?;
+ assert!(
+ !mailbox
+ .email_repo
+ .thread_by_id(thread)
+ .await?
+ .unwrap()
+ .inbox_visible
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_thread_labels", "email_thread_unread", "email_thread_archive")
+ )
+)]
+async fn followup_uses_delegated_inbox_and_rechecks_revocation(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread = uuid::uuid!("11111111-1111-1111-1111-111111111111");
+ let link = uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
+ sqlx::query!(r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+ ('d1000000-0000-0000-0000-000000000001', 'owner', '[email protected]', 'followup_owner'),
+ ('d1000000-0000-0000-0000-000000000002', 'delegate', '[email protected]', 'followup_delegate')"#).execute(&pool).await?;
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES
+ ('macro|[email protected]', '[email protected]', 'd1000000-0000-0000-0000-000000000001'),
+ ('macro|[email protected]', '[email protected]', 'd1000000-0000-0000-0000-000000000002')"#
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!("INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id) VALUES ('macro|[email protected]', 'macro|[email protected]', $1)", link).execute(&pool).await?;
+ let mailbox = service(pool.clone());
+ let delegate = MacroUserIdStr::try_from_email("[email protected]")?;
+ assert_eq!(
+ mailbox
+ .followup_thread(delegate.clone(), thread)
+ .await?
+ .unwrap()
+ .link_id,
+ link
+ );
+ mailbox
+ .set_followup_inbox(delegate.clone(), thread, link, false, None)
+ .await?;
+ mailbox
+ .set_followup_inbox(delegate.clone(), thread, link, true, Some(Utc::now()))
+ .await?;
+ sqlx::query!(
+ "DELETE FROM macro_user_links WHERE primary_macro_id = $1",
+ delegate.as_ref()
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ mailbox
+ .followup_thread(delegate.clone(), thread)
+ .await?
+ .is_none()
+ );
+ assert!(
+ mailbox
+ .set_followup_inbox(delegate, thread, link, true, Some(Utc::now()))
+ .await
+ .is_err()
+ );
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/preview.rs b/crates/email/src/outbound/email_pg_repo/test/preview.rs
index 960a043128..1b5a66cf40 100644
--- a/crates/email/src/outbound/email_pg_repo/test/preview.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/preview.rs
@@ -229,3 +229,37 @@ async fn test_contacts_by_thread_ids_empty_input(pool: Pool<Postgres>) -> anyhow
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn returned_thread_without_message_timestamps_has_created_at(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread = Uuid::parse_str("20000003-0000-0000-0000-000000000003")?;
+ sqlx::query(
+ "UPDATE email_threads SET inbox_visible = true, reminder_returned_at = NOW() WHERE id = $1",
+ )
+ .bind(thread)
+ .execute(&pool)
+ .await?;
+ let rows = crate::outbound::email_pg_repo::preview_views::new_inbox::new_inbox_preview_cursor(
+ &pool,
+ &[Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?],
+ 50,
+ &Query::new(None, SimpleSortMethod::UpdatedAt, ()),
+ )
+ .await?;
+ let returned = rows
+ .iter()
+ .find(|row| row.id == thread)
+ .expect("returned thread must remain readable");
+ let created: chrono::DateTime<chrono::Utc> =
+ sqlx::query_scalar("SELECT created_at FROM email_threads WHERE id = $1")
+ .bind(thread)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(returned.created_at, created);
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/thread.rs b/crates/email/src/outbound/email_pg_repo/test/thread.rs
index eb769369d1..3152b953f4 100644
--- a/crates/email/src/outbound/email_pg_repo/test/thread.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/thread.rs
@@ -653,3 +653,74 @@ async fn test_upsert_user_history_updates_timestamp(pool: Pool<Postgres>) -> any
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_thread_labels"))
+)]
+async fn returned_sent_only_metadata_preserves_visibility_without_rewriting(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread_id = uuid::uuid!("11111111-1111-1111-1111-111111111111");
+ let link_id = uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
+ let sent_label = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO email_labels (id, link_id, provider_label_id, name) VALUES ($1, $2, 'SENT', 'SENT')",
+ sent_label, link_id,
+ ).execute(&pool).await?;
+ sqlx::query!(
+ "UPDATE email_messages SET is_sent = TRUE WHERE thread_id = $1",
+ thread_id
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO email_message_labels (message_id, label_id) SELECT id, $2 FROM email_messages WHERE thread_id = $1",
+ thread_id, sent_label,
+ ).execute(&pool).await?;
+ let mut tx = pool.begin().await?;
+ super::super::thread::update_thread_metadata(&mut tx, thread_id, link_id).await?;
+ tx.commit().await?;
+ // All ordinary metadata already matches, including raw inbox_visible=false.
+ sqlx::query!(
+ "UPDATE email_threads SET reminder_returned_at = NOW() WHERE id = $1",
+ thread_id
+ )
+ .execute(&pool)
+ .await?;
+ let mut tx = pool.begin().await?;
+ super::super::thread::update_thread_metadata(&mut tx, thread_id, link_id).await?;
+ tx.commit().await?;
+ let restored = sqlx::query!(
+ "SELECT inbox_visible, latest_inbound_message_ts FROM email_threads WHERE id = $1",
+ thread_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(
+ restored.inbox_visible,
+ "the effective override must repair false visibility"
+ );
+ assert!(restored.latest_inbound_message_ts.is_none());
+
+ // A fixed old timestamp makes an unintended rewrite observable without sleeps.
+ let previous = sqlx::query_scalar!(
+ "UPDATE email_threads SET updated_at = '2000-01-01T00:00:00Z' WHERE id = $1 RETURNING updated_at",
+ thread_id,
+ ).fetch_one(&pool).await?;
+ let mut tx = pool.begin().await?;
+ super::super::thread::update_thread_metadata(&mut tx, thread_id, link_id).await?;
+ tx.commit().await?;
+ let repeated = sqlx::query!(
+ "SELECT inbox_visible, updated_at FROM email_threads WHERE id = $1",
+ thread_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(repeated.inbox_visible);
+ assert_eq!(
+ repeated.updated_at, previous,
+ "matching effective visibility must not rewrite metadata"
+ );
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/thread.rs b/crates/email/src/outbound/email_pg_repo/thread.rs
index 6bbd683988..ede56207c2 100644
--- a/crates/email/src/outbound/email_pg_repo/thread.rs
+++ b/crates/email/src/outbound/email_pg_repo/thread.rs
@@ -755,19 +755,33 @@ async fn update_db_thread_metadata(
) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
- UPDATE email_threads
+ WITH effective AS (
+ SELECT id AS thread_id, $1 OR (reminder_returned_at IS NOT NULL AND EXISTS (
+ SELECT 1 FROM email_messages fm
+ JOIN email_message_labels fml ON fml.message_id = fm.id
+ JOIN email_labels fl ON fl.id = fml.label_id
+ WHERE fm.thread_id = email_threads.id AND fl.provider_label_id = 'INBOX'
+ AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels blocked
+ JOIN email_labels bl ON bl.id = blocked.label_id
+ WHERE blocked.message_id = fm.id AND bl.provider_label_id IN ('TRASH', 'SPAM')
+ )
+ )) AS inbox_visible
+ FROM email_threads
+ WHERE id = $6 AND link_id = $7
+ )
+ UPDATE email_threads t
SET
- inbox_visible = $1,
+ inbox_visible = effective.inbox_visible,
is_read = $2,
latest_inbound_message_ts = $3,
latest_outbound_message_ts = $4,
latest_non_spam_message_ts = $5,
updated_at = NOW()
- WHERE
- id = $6 AND
- link_id = $7 AND
- (inbox_visible, is_read, latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts)
- IS DISTINCT FROM ($1, $2, $3, $4, $5)
+ FROM effective
+ WHERE t.id = effective.thread_id
+ AND (t.inbox_visible, t.is_read, t.latest_inbound_message_ts, t.latest_outbound_message_ts, t.latest_non_spam_message_ts)
+ IS DISTINCT FROM (effective.inbox_visible, $2, $3, $4, $5)
"#,
inbox_visible,
is_read,
diff --git a/crates/email_db_client/src/threads/update.rs b/crates/email_db_client/src/threads/update.rs
index bb549a81e4..91e422f480 100644
--- a/crates/email_db_client/src/threads/update.rs
+++ b/crates/email_db_client/src/threads/update.rs
@@ -28,19 +28,33 @@ async fn update_db_thread_metadata(
) -> anyhow::Result<()> {
sqlx::query!(
r#"
- UPDATE email_threads
+ WITH effective AS (
+ SELECT id AS thread_id, $1 OR (reminder_returned_at IS NOT NULL AND EXISTS (
+ SELECT 1 FROM email_messages fm
+ JOIN email_message_labels fml ON fml.message_id = fm.id
+ JOIN email_labels fl ON fl.id = fml.label_id
+ WHERE fm.thread_id = email_threads.id AND fl.provider_label_id = 'INBOX'
+ AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels blocked
+ JOIN email_labels bl ON bl.id = blocked.label_id
+ WHERE blocked.message_id = fm.id AND bl.provider_label_id IN ('TRASH', 'SPAM')
+ )
+ )) AS inbox_visible
+ FROM email_threads
+ WHERE id = $6 AND link_id = $7
+ )
+ UPDATE email_threads t
SET
- inbox_visible = $1,
+ inbox_visible = effective.inbox_visible,
is_read = $2,
latest_inbound_message_ts = $3,
latest_outbound_message_ts = $4,
latest_non_spam_message_ts = $5,
updated_at = NOW()
- WHERE
- id = $6 AND
- link_id = $7 AND
- (inbox_visible, is_read, latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts)
- IS DISTINCT FROM ($1, $2, $3, $4, $5)
+ FROM effective
+ WHERE t.id = effective.thread_id
+ AND (t.inbox_visible, t.is_read, t.latest_inbound_message_ts, t.latest_outbound_message_ts, t.latest_non_spam_message_ts)
+ IS DISTINCT FROM (effective.inbox_visible, $2, $3, $4, $5)
"#,
inbox_visible,
is_read,
diff --git a/crates/email_db_client/src/threads/update/test.rs b/crates/email_db_client/src/threads/update/test.rs
index 19ffbbb6d0..b770e2d71e 100644
--- a/crates/email_db_client/src/threads/update/test.rs
+++ b/crates/email_db_client/src/threads/update/test.rs
@@ -332,3 +332,68 @@ async fn repeated_metadata_recompute_is_noop(pool: Pool<Postgres>) -> anyhow::Re
);
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../email/fixtures", scripts("email_thread_labels"))
+)]
+async fn returned_sent_only_metadata_preserves_visibility_without_rewriting(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let sent_label = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO email_labels (id, link_id, provider_label_id, name) VALUES ($1, $2, 'SENT', 'SENT')",
+ sent_label, link_id,
+ ).execute(&pool).await?;
+ sqlx::query!(
+ "UPDATE email_messages SET is_sent = TRUE WHERE thread_id = $1",
+ thread_id
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO email_message_labels (message_id, label_id) SELECT id, $2 FROM email_messages WHERE thread_id = $1",
+ thread_id, sent_label,
+ ).execute(&pool).await?;
+ update_thread_metadata(&mut *pool.acquire().await?, thread_id, link_id).await?;
+ // All ordinary metadata already matches, including raw inbox_visible=false.
+ sqlx::query!(
+ "UPDATE email_threads SET reminder_returned_at = NOW() WHERE id = $1",
+ thread_id
+ )
+ .execute(&pool)
+ .await?;
+ update_thread_metadata(&mut *pool.acquire().await?, thread_id, link_id).await?;
+ let restored = sqlx::query!(
+ "SELECT inbox_visible, latest_inbound_message_ts FROM email_threads WHERE id = $1",
+ thread_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(
+ restored.inbox_visible,
+ "the effective override must repair false visibility"
+ );
+ assert!(restored.latest_inbound_message_ts.is_none());
+
+ // A fixed old timestamp makes an unintended rewrite observable without sleeps.
+ let previous = sqlx::query_scalar!(
+ "UPDATE email_threads SET updated_at = '2000-01-01T00:00:00Z' WHERE id = $1 RETURNING updated_at",
+ thread_id,
+ ).fetch_one(&pool).await?;
+ update_thread_metadata(&mut *pool.acquire().await?, thread_id, link_id).await?;
+ let repeated = sqlx::query!(
+ "SELECT inbox_visible, updated_at FROM email_threads WHERE id = $1",
+ thread_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert!(repeated.inbox_visible);
+ assert_eq!(
+ repeated.updated_at, previous,
+ "matching effective visibility must not rewrite metadata"
+ );
+ Ok(())
+}
diff --git a/crates/macro_db_client/migrations/20261001151559_email_followups.sql b/crates/macro_db_client/migrations/20261001151559_email_followups.sql
new file mode 100644
index 0000000000..89a5bfd695
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001151559_email_followups.sql
@@ -0,0 +1,31 @@
+-- Additive: generic reminders retain their existing behavior.
+ALTER TABLE email_threads ADD COLUMN reminder_returned_at TIMESTAMPTZ;
+
+-- Workflow state belongs to reminders; email mutations remain email-owned.
+CREATE TABLE reminder_email_followup (
+ reminder_id UUID PRIMARY KEY REFERENCES reminder(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
+ thread_id UUID NOT NULL REFERENCES email_threads(id) ON DELETE CASCADE,
+ link_id UUID NOT NULL REFERENCES email_links(id) ON DELETE CASCADE,
+ state TEXT NOT NULL CHECK (state IN ('archiving', 'pending', 'returning', 'returned', 'cancelled', 'removed')),
+ payload JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE UNIQUE INDEX reminder_email_followup_active
+ ON reminder_email_followup(user_id, thread_id)
+ WHERE state IN ('archiving', 'pending', 'returning');
+CREATE INDEX reminder_email_followup_thread
+ ON reminder_email_followup(user_id, thread_id, created_at DESC);
+CREATE INDEX reminder_email_followup_reconcile
+ ON reminder_email_followup(reminder_id)
+ WHERE state IN ('archiving', 'pending', 'returning');
+
+-- Retain request identities after removal so a delayed retry cannot resurrect it.
+CREATE TABLE reminder_email_operation (
+ user_id TEXT NOT NULL REFERENCES "User"(id) ON DELETE CASCADE,
+ operation_id UUID NOT NULL,
+ thread_id UUID NOT NULL REFERENCES email_threads(id) ON DELETE CASCADE,
+ request JSONB NOT NULL,
+ reminder_id UUID NOT NULL REFERENCES reminder(id) ON DELETE CASCADE,
+ PRIMARY KEY(user_id, operation_id)
+);
diff --git a/crates/macro_db_client/migrations/20261001153540_retain_email_followup_tombstones.sql b/crates/macro_db_client/migrations/20261001153540_retain_email_followup_tombstones.sql
new file mode 100644
index 0000000000..2479883fe3
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001153540_retain_email_followup_tombstones.sql
@@ -0,0 +1,9 @@
+-- Preserve workflow identity after a thread/inbox is deleted. Otherwise cascade
+-- would leave an enabled ordinary reminder with no specialization, allowing a
+-- queued occurrence to bypass the deleted-thread check. The owning user's and
+-- reminder's cascades still clean up this state; reconciliation disables it.
+ALTER TABLE reminder_email_followup
+ DROP CONSTRAINT reminder_email_followup_thread_id_fkey,
+ DROP CONSTRAINT reminder_email_followup_link_id_fkey;
+ALTER TABLE reminder_email_operation
+ DROP CONSTRAINT reminder_email_operation_thread_id_fkey;
diff --git a/crates/macro_db_client/migrations/20261001162806_email_followup_inbox_and_operation_indexes.sql b/crates/macro_db_client/migrations/20261001162806_email_followup_inbox_and_operation_indexes.sql
new file mode 100644
index 0000000000..720558b2eb
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001162806_email_followup_inbox_and_operation_indexes.sql
@@ -0,0 +1,5 @@
+-- no-transaction
+-- Support per-inbox ordering and cursor scans for returned reminders.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_threads_inbox_reminder_sort
+ ON email_threads (link_id, (GREATEST(latest_inbound_message_ts, reminder_returned_at)) DESC, id DESC)
+ WHERE inbox_visible = TRUE;
diff --git a/crates/macro_db_client/migrations/20261001165226_email_followup_operation_index.sql b/crates/macro_db_client/migrations/20261001165226_email_followup_operation_index.sql
new file mode 100644
index 0000000000..42a4d510bf
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001165226_email_followup_operation_index.sql
@@ -0,0 +1,3 @@
+-- Foreign-key cleanup must not scan the retained operation history.
+CREATE INDEX IF NOT EXISTS idx_reminder_email_operation_reminder
+ ON reminder_email_operation (reminder_id);
diff --git a/crates/reminders/Cargo.toml b/crates/reminders/Cargo.toml
index f7c9933fab..b484dfd09a 100644
--- a/crates/reminders/Cargo.toml
+++ b/crates/reminders/Cargo.toml
@@ -31,10 +31,11 @@ inbound = [
]
notify = ["dep:model_notifications", "dep:notification", "outbound"]
outbound = ["ports"]
-ports = ["dep:entity_access", "dep:tracing"]
-postgres = ["dep:macro_uuid", "dep:sqlx", "outbound"]
+ports = ["dep:entity_access", "dep:tracing", "dep:email", "dep:serde_json"]
+postgres = ["dep:macro_uuid", "dep:sqlx", "dep:tokio", "outbound"]
[dependencies]
+email = { path = "../email", optional = true, default-features = false, features = ["ports"] }
ai_toolset = { path = "../ai_toolset", optional = true }
anyhow = { workspace = true, optional = true }
async-trait = { workspace = true, optional = true }
diff --git a/crates/reminders/src/domain.rs b/crates/reminders/src/domain.rs
index 8b08f72863..f5f05a096e 100644
--- a/crates/reminders/src/domain.rs
+++ b/crates/reminders/src/domain.rs
@@ -5,3 +5,6 @@ pub mod models;
pub mod ports;
#[cfg(feature = "ports")]
pub mod service;
+
+#[cfg(feature = "ports")]
+pub mod email_followup;
diff --git a/crates/reminders/src/domain/email_followup.rs b/crates/reminders/src/domain/email_followup.rs
new file mode 100644
index 0000000000..6415d2b08f
--- /dev/null
+++ b/crates/reminders/src/domain/email_followup.rs
@@ -0,0 +1,210 @@
+//! Durable single-thread email reminder workflow.
+//!
+//! Every writer (including generic edit/remove and dispatch) takes the same
+//! user/thread lock. Intent is stored before email side effects; the minute
+//! sweep retries incomplete intent after a crash. Operation identities outlive
+//! cancellation, so a timed-out request cannot recreate a removed follow-up.
+
+use super::{models::ReminderError, ports::RemindersRepo};
+use chrono::{DateTime, Utc};
+use email::domain::followup::ReplyBaseline;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+pub mod dispatch;
+pub mod reminder_service;
+pub mod service;
+
+/// When an email follow-up should return the conversation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum EmailReminderCondition {
+ /// Cancel when a new inbound reply arrives after the captured baseline.
+ #[default]
+ IfNoReply,
+ /// Return even if a reply has arrived.
+ Regardless,
+}
+
+/// Durable progress of an email operation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum FollowupState {
+ /// Intent saved; archive needs to finish.
+ Archiving,
+ /// Archived and waiting for a reply or the selected time.
+ Pending,
+ /// Removal/undo requested; inbox restoration needs to finish.
+ Returning,
+ /// Due-time return succeeded; alert delivery may still be retrying.
+ Returned,
+ /// New reply, deleted thread, trash or lost access made it ineligible.
+ Cancelled,
+ /// User removed/undid the follow-up and restoration finished.
+ Removed,
+}
+
+impl FollowupState {
+ /// Stable indexed database spelling.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Archiving => "archiving",
+ Self::Pending => "pending",
+ Self::Returning => "returning",
+ Self::Returned => "returned",
+ Self::Cancelled => "cancelled",
+ Self::Removed => "removed",
+ }
+ }
+ /// Whether this workflow reserves the user's one active slot.
+ pub fn active(self) -> bool {
+ matches!(self, Self::Archiving | Self::Pending | Self::Returning)
+ }
+}
+
+/// Public status shown on email and in the Reminders editor.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct EmailFollowup {
+ /// Its ordinary reminder, used by the existing alert/management surfaces.
+ pub reminder_id: Uuid,
+ /// Conversation identity.
+ pub thread_id: Uuid,
+ /// Canonical owned/delegated inbox.
+ pub link_id: Uuid,
+ /// Condition, defaulting to no reply for new follow-ups.
+ pub condition: EmailReminderCondition,
+ /// Confirmed schedule.
+ pub remind_at: DateTime<Utc>,
+ /// Last accepted operation; edits/removal compare this to prevent stale undo.
+ pub revision: Uuid,
+ /// Durable lifecycle progress.
+ pub state: FollowupState,
+}
+
+/// Persisted private state. Reply identities never need to reach the browser.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FollowupRecord {
+ /// Public projection.
+ pub followup: EmailFollowup,
+ /// Authenticated owner, not necessarily the inbox owner for delegation.
+ pub user_id: MacroUserIdStr<'static>,
+ /// Stable reply boundary.
+ pub baseline: ReplyBaseline,
+ /// Undo restores original visibility, including sent-only conversations.
+ pub original_inbox_visible: bool,
+ /// Preserve ordering when undo/rollback restores the original inbox state.
+ #[serde(default)]
+ pub original_returned_at: Option<DateTime<Utc>>,
+ /// Whether this is an undo/rollback rather than an explicit return.
+ #[serde(default)]
+ pub restore_original: bool,
+ /// Visibility desired by an explicit remove/undo operation.
+ pub restore_inbox_visible: bool,
+ /// A reply-triggered restoration finishes without a reminder alert.
+ #[serde(default)]
+ pub cancel_on_restore: bool,
+}
+
+/// Lookup response, including an email with no follow-up yet.
+#[derive(Debug, Serialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct EmailFollowupResponse {
+ /// Most recent specialized follow-up, if any.
+ pub followup: Option<EmailFollowup>,
+}
+
+/// Idempotent email command. Reusing an operation ID with different data fails.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(
+ tag = "type",
+ rename_all = "snake_case",
+ rename_all_fields = "camelCase"
+)]
+pub enum EmailFollowupCommand {
+ /// Create or edit one follow-up. An edit requires the displayed revision.
+ Set {
+ /// Unique request identity retained across network retries.
+ #[serde(rename = "operationId")]
+ operation_id: Uuid,
+ /// None for creation, the current revision for edits.
+ #[serde(rename = "expectedRevision")]
+ expected_revision: Option<Uuid>,
+ /// One future instant; conditional recurrence is deliberately absent.
+ #[serde(rename = "remindAt")]
+ remind_at: DateTime<Utc>,
+ /// Reply condition.
+ condition: EmailReminderCondition,
+ },
+ /// Cancel and restore the conversation without leaving a future alert.
+ Remove {
+ /// Unique request identity.
+ #[serde(rename = "operationId")]
+ operation_id: Uuid,
+ /// Reject removal if a newer edit has replaced this operation.
+ #[serde(rename = "expectedRevision")]
+ expected_revision: Uuid,
+ /// Undo restores original visibility; ordinary Remove returns to inbox.
+ #[serde(default)]
+ undo: bool,
+ },
+}
+
+impl EmailFollowupCommand {
+ /// Request identity shared by create/edit/remove.
+ pub fn operation_id(&self) -> Uuid {
+ match self {
+ Self::Set { operation_id, .. } | Self::Remove { operation_id, .. } => *operation_id,
+ }
+ }
+}
+
+/// Repository contract for the durable workflow, alongside ordinary reminders.
+pub trait EmailFollowupRepo: RemindersRepo {
+ /// A database-wide lock; dropping it releases serialization after a crash.
+ type Guard: Send;
+ /// Serialize every operation affecting this user/thread, across processes.
+ fn lock_followup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ thread: Uuid,
+ ) -> impl Future<Output = Result<Self::Guard, ReminderError>> + Send;
+ /// Most recently created workflow for this thread, including terminal state.
+ fn thread_followup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ thread: Uuid,
+ ) -> impl Future<Output = Result<Option<FollowupRecord>, ReminderError>> + Send;
+ /// Resolve a reminder's specialization, without treating generic email reminders as follow-ups.
+ fn reminder_followup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ reminder: Uuid,
+ ) -> impl Future<Output = Result<Option<FollowupRecord>, ReminderError>> + Send;
+ /// Return the previously accepted command and associated reminder identity.
+ fn previous_operation(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ operation: Uuid,
+ ) -> impl Future<Output = Result<Option<(Uuid, EmailFollowupCommand)>, ReminderError>> + Send;
+ /// Atomically persist intent, its operation identity and the ordinary reminder.
+ /// The caller holds the user/thread guard. `description` is supplied on create.
+ fn save_followup(
+ &self,
+ record: &FollowupRecord,
+ command: Option<&EmailFollowupCommand>,
+ description: Option<&str>,
+ ) -> impl Future<Output = Result<(), ReminderError>> + Send;
+ /// Page active workflows by reminder ID so every minute can reconcile replies
+ /// and unfinished email effects, even when no browser is connected.
+ fn reconciliation_page(
+ &self,
+ after: Option<Uuid>,
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<FollowupRecord>, ReminderError>> + Send;
+}
diff --git a/crates/reminders/src/domain/email_followup/dispatch.rs b/crates/reminders/src/domain/email_followup/dispatch.rs
new file mode 100644
index 0000000000..f3de5ae836
--- /dev/null
+++ b/crates/reminders/src/domain/email_followup/dispatch.rs
@@ -0,0 +1,78 @@
+//! Serialize email dispatch with edits/removal while reusing occurrence alerts.
+use super::{EmailFollowupRepo, service::EmailFollowupService};
+use crate::domain::{
+ models::{DeliveryOutcome, DueFiring, ReminderError, SweepSummary},
+ ports::{Clock, ReminderDispatch, ReminderDispatchRepo},
+};
+use email::domain::followup::EmailFollowupMailbox;
+
+/// Decorates the existing dispatcher with email reconciliation and inbox return.
+pub struct EmailReminderDispatch<D, R, E, C> {
+ generic: D,
+ email: EmailFollowupService<R, E, C>,
+}
+impl<D, R, E, C> EmailReminderDispatch<D, R, E, C> {
+ /// Use the same workflow/repository as the HTTP service.
+ pub fn new(generic: D, email: EmailFollowupService<R, E, C>) -> Self {
+ Self { generic, email }
+ }
+}
+impl<
+ D: ReminderDispatch,
+ R: EmailFollowupRepo + ReminderDispatchRepo,
+ E: EmailFollowupMailbox,
+ C: Clock,
+> ReminderDispatch for EmailReminderDispatch<D, R, E, C>
+{
+ async fn sweep(&self) -> Result<SweepSummary, ReminderError> {
+ // Due delivery checks its own email facts. Recovery of unrelated email
+ // workflows must not delay fan-out or suppress ordinary reminders.
+ let result = self.generic.sweep().await;
+ if let Err(error) = self.email.reconcile().await {
+ tracing::error!(error = ?error, "email follow-up reconciliation failed; will retry next sweep");
+ }
+ result
+ }
+ async fn deliver(&self, firing: DueFiring) -> Result<DeliveryOutcome, ReminderError> {
+ let Some(due) = self
+ .email
+ .repo
+ .find_due_reminder(firing)
+ .await
+ .map_err(|error| {
+ ReminderError::Internal(rootcause::Report::new(error).into_dynamic())
+ })?
+ else {
+ return Ok(DeliveryOutcome::Gone);
+ };
+ let Some(record) = self
+ .email
+ .repo
+ .reminder_followup(&due.owner_id, due.reminder.id)
+ .await?
+ else {
+ return self.generic.deliver(firing).await;
+ };
+ let _guard = self
+ .email
+ .repo
+ .lock_followup(&due.owner_id, record.followup.thread_id)
+ .await?;
+ let Some(mut record) = self
+ .email
+ .repo
+ .reminder_followup(&due.owner_id, due.reminder.id)
+ .await?
+ else {
+ return Ok(DeliveryOutcome::Gone);
+ };
+ if !self
+ .email
+ .return_due_locked(&mut record, firing.scheduled_for)
+ .await?
+ {
+ return Ok(DeliveryOutcome::Gone);
+ }
+ self.generic.deliver(firing).await
+ }
+}
diff --git a/crates/reminders/src/domain/email_followup/reminder_service.rs b/crates/reminders/src/domain/email_followup/reminder_service.rs
new file mode 100644
index 0000000000..01888c2349
--- /dev/null
+++ b/crates/reminders/src/domain/email_followup/reminder_service.rs
@@ -0,0 +1,155 @@
+//! Preserve the specialization when the ordinary Reminders surface edits it.
+use super::{service::EmailFollowupService, *};
+use crate::domain::{
+ models::*,
+ ports::{Clock, RemindersService},
+ service::receipt_owner_and_id,
+};
+use email::domain::followup::EmailFollowupMailbox;
+use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+/// Application-facing service, composing generic reminders and email behavior.
+#[derive(Clone)]
+pub struct EmailRemindersService<S, R, E, C> {
+ generic: S,
+ email: EmailFollowupService<R, E, C>,
+}
+impl<S, R, E, C> EmailRemindersService<S, R, E, C> {
+ /// Wire one shared email workflow into CRUD and dispatch.
+ pub fn new(generic: S, email: EmailFollowupService<R, E, C>) -> Self {
+ Self { generic, email }
+ }
+}
+impl<S: RemindersService, R: EmailFollowupRepo, E: EmailFollowupMailbox, C: Clock> RemindersService
+ for EmailRemindersService<S, R, E, C>
+{
+ async fn get_email_followup(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread: Uuid,
+ ) -> Result<Option<EmailFollowup>, ReminderError> {
+ self.email.get(user, thread).await
+ }
+ async fn execute_email_followup(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread: Uuid,
+ command: EmailFollowupCommand,
+ ) -> Result<EmailFollowup, ReminderError> {
+ self.email.execute(user, thread, command).await
+ }
+ async fn create_reminder(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ request: CreateReminder,
+ receipt: Option<EntityAccessReceipt<AnyEntityPermission>>,
+ ) -> Result<Reminder, ReminderError> {
+ self.generic.create_reminder(user, request, receipt).await
+ }
+ async fn get_reminder(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ ) -> Result<Reminder, ReminderError> {
+ self.generic.get_reminder(receipt).await
+ }
+ async fn list_reminders(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ filter: ReminderFilter,
+ ) -> Result<ReminderPage, ReminderError> {
+ self.generic.list_reminders(user, filter).await
+ }
+ async fn list_reminders_for_soup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ query: SoupReminderQuery<'_>,
+ ) -> Result<Vec<ReminderForSoup>, ReminderError> {
+ self.generic.list_reminders_for_soup(user, query).await
+ }
+ async fn update_reminder(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ mut patch: ReminderPatch,
+ ) -> Result<Reminder, ReminderError> {
+ let (user, id) = receipt_owner_and_id(&receipt)?;
+ let Some(record) = self.email.repo.reminder_followup(&user, id).await? else {
+ return self.generic.update_reminder(receipt, patch).await;
+ };
+ let _guard = self
+ .email
+ .repo
+ .lock_followup(&user, record.followup.thread_id)
+ .await?;
+ let record = self
+ .email
+ .repo
+ .reminder_followup(&user, id)
+ .await?
+ .ok_or(ReminderError::NotFound)?;
+ if patch.enabled == Some(true) || patch.completed == Some(false) {
+ return Err(ReminderError::BadRequest(
+ "Use Remind me on the email to schedule it again".into(),
+ ));
+ }
+ if let Some(schedule) = patch.schedule.take() {
+ let ReminderSchedule::Once { remind_at } = schedule else {
+ return Err(ReminderError::BadRequest(
+ "Email follow-ups cannot repeat".into(),
+ ));
+ };
+ if patch.enabled == Some(false) || patch.completed == Some(true) {
+ return Err(ReminderError::BadRequest(
+ "Reschedule or remove the email reminder separately".into(),
+ ));
+ }
+ self.email
+ .execute_locked(
+ user.clone(),
+ record.followup.thread_id,
+ EmailFollowupCommand::Set {
+ operation_id: Uuid::now_v7(),
+ expected_revision: Some(record.followup.revision),
+ remind_at,
+ condition: record.followup.condition,
+ },
+ )
+ .await?;
+ }
+ if patch.enabled == Some(false) || patch.completed == Some(true) {
+ self.email.retire_locked(record).await?;
+ patch.enabled = None;
+ patch.completed = None;
+ }
+ if patch.is_empty() {
+ self.generic.get_reminder(receipt).await
+ } else {
+ self.generic.update_reminder(receipt, patch).await
+ }
+ }
+ async fn delete_reminder(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ ) -> Result<(), ReminderError> {
+ let (user, id) = receipt_owner_and_id(&receipt)?;
+ let Some(record) = self.email.repo.reminder_followup(&user, id).await? else {
+ return self.generic.delete_reminder(receipt).await;
+ };
+ let _guard = self
+ .email
+ .repo
+ .lock_followup(&user, record.followup.thread_id)
+ .await?;
+ let record = self
+ .email
+ .repo
+ .reminder_followup(&user, id)
+ .await?
+ .ok_or(ReminderError::NotFound)?;
+ self.email.retire_locked(record).await?;
+ // Keep the tombstone and request identities: a delayed create retry must
+ // not schedule another follow-up after removal.
+ Ok(())
+ }
+}
diff --git a/crates/reminders/src/domain/email_followup/service.rs b/crates/reminders/src/domain/email_followup/service.rs
new file mode 100644
index 0000000000..7ecd78d02e
--- /dev/null
+++ b/crates/reminders/src/domain/email_followup/service.rs
@@ -0,0 +1,366 @@
+//! Orchestration shared by the email API, generic reminder edits and dispatch.
+
+use super::*;
+use crate::domain::ports::{Clock, SystemClock};
+use chrono::{DateTime, Utc};
+use email::domain::followup::EmailFollowupMailbox;
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+/// Email-specialized reminder lifecycle over the existing reminders repository.
+#[derive(Clone)]
+pub struct EmailFollowupService<R, E, C = SystemClock> {
+ /// Shared reminder persistence.
+ pub(crate) repo: R,
+ /// Email-owned authorization and inbox operations.
+ pub(crate) mailbox: E,
+ pub(crate) clock: C,
+}
+
+impl<R, E> EmailFollowupService<R, E> {
+ /// Compose email behavior without importing its outbound adapter.
+ pub fn new(repo: R, mailbox: E) -> Self {
+ Self {
+ repo,
+ mailbox,
+ clock: SystemClock,
+ }
+ }
+}
+
+fn internal(error: impl std::error::Error + Send + Sync + 'static) -> ReminderError {
+ ReminderError::Internal(rootcause::Report::new(error).into_dynamic())
+}
+
+fn conflict() -> ReminderError {
+ ReminderError::BadRequest("This email reminder changed. Reopen it before editing.".into())
+}
+
+impl<R: EmailFollowupRepo, E: EmailFollowupMailbox, C: Clock> EmailFollowupService<R, E, C> {
+ /// Read after reconciling reply/access facts; never expose another user's thread.
+ pub async fn get(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread: Uuid,
+ ) -> Result<Option<EmailFollowup>, ReminderError> {
+ let _guard = self.repo.lock_followup(&user, thread).await?;
+ let facts = self
+ .mailbox
+ .followup_thread(user.clone(), thread)
+ .await
+ .map_err(internal)?
+ .ok_or(ReminderError::EntityAccessDenied)?;
+ let Some(mut record) = self.repo.thread_followup(&user, thread).await? else {
+ return Ok(None);
+ };
+ if facts.link_id != record.followup.link_id {
+ return Err(ReminderError::EntityAccessDenied);
+ }
+ self.reconcile_locked(&mut record).await?;
+ Ok(Some(record.followup))
+ }
+
+ /// Persist an idempotent command, then finish its email effect under the lock.
+ pub async fn execute(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread: Uuid,
+ command: EmailFollowupCommand,
+ ) -> Result<EmailFollowup, ReminderError> {
+ let _guard = self.repo.lock_followup(&user, thread).await?;
+ self.execute_locked(user, thread, command).await
+ }
+
+ pub(crate) async fn execute_locked(
+ &self,
+ user: MacroUserIdStr<'static>,
+ thread: Uuid,
+ command: EmailFollowupCommand,
+ ) -> Result<EmailFollowup, ReminderError> {
+ let facts = self
+ .mailbox
+ .followup_thread(user.clone(), thread)
+ .await
+ .map_err(internal)?;
+ if let Some((reminder_id, previous)) = self
+ .repo
+ .previous_operation(&user, command.operation_id())
+ .await?
+ {
+ if previous != command {
+ return Err(conflict());
+ }
+ let mut record = self
+ .repo
+ .reminder_followup(&user, reminder_id)
+ .await?
+ .ok_or(ReminderError::NotFound)?;
+ if record.followup.thread_id != thread {
+ return Err(conflict());
+ }
+ self.reconcile_locked(&mut record).await?;
+ return Ok(record.followup);
+ }
+ let current = self.repo.thread_followup(&user, thread).await?;
+ let mut record = match &command {
+ EmailFollowupCommand::Set {
+ operation_id,
+ expected_revision,
+ remind_at,
+ condition,
+ } => {
+ let facts = facts
+ .as_ref()
+ .filter(|facts| !facts.unavailable)
+ .ok_or(ReminderError::EntityAccessDenied)?;
+ let now = self.clock.now();
+ // PostgreSQL timestamps retain microseconds, including seconds-only edits.
+ let remind_at = DateTime::from_timestamp_micros(remind_at.timestamp_micros())
+ .unwrap_or(*remind_at);
+ if remind_at <= now {
+ return Err(ReminderError::BadRequest(
+ "remindAt must be in the future".into(),
+ ));
+ }
+ if let Some(mut current) = current.filter(|record| record.followup.state.active()) {
+ if *expected_revision != Some(current.followup.revision) {
+ return Err(conflict());
+ }
+ if current.followup.state != FollowupState::Pending {
+ return Err(conflict());
+ }
+ current.followup.condition = *condition;
+ current.followup.remind_at = remind_at;
+ current.followup.revision = *operation_id;
+ // Editing the time doesn't redefine what counts as a reply.
+ current
+ } else {
+ if expected_revision.is_some() {
+ return Err(conflict());
+ }
+ FollowupRecord {
+ followup: EmailFollowup {
+ reminder_id: Uuid::now_v7(),
+ thread_id: thread,
+ link_id: facts.link_id,
+ condition: *condition,
+ remind_at,
+ revision: *operation_id,
+ state: FollowupState::Archiving,
+ },
+ user_id: user,
+ baseline: facts.baseline(now),
+ original_inbox_visible: facts.inbox_visible,
+ original_returned_at: facts.returned_at,
+ restore_original: false,
+ restore_inbox_visible: true,
+ cancel_on_restore: false,
+ }
+ }
+ }
+ EmailFollowupCommand::Remove {
+ operation_id,
+ expected_revision,
+ undo,
+ } => {
+ let mut current = current.ok_or(ReminderError::NotFound)?;
+ if current.followup.revision != *expected_revision {
+ return Err(conflict());
+ }
+ current.followup.revision = *operation_id;
+ current.followup.state = if current.followup.state.active()
+ && facts.as_ref().is_some_and(|facts| {
+ !facts.unavailable && facts.link_id == current.followup.link_id
+ }) {
+ FollowupState::Returning
+ } else {
+ FollowupState::Removed
+ };
+ current.cancel_on_restore = false;
+ current.restore_inbox_visible = !undo || current.original_inbox_visible;
+ current.restore_original = *undo;
+ current
+ }
+ };
+ let description = facts.as_ref().map(|facts| {
+ facts
+ .subject
+ .chars()
+ .take(super::super::models::MAX_DESCRIPTION_LEN)
+ .collect::<String>()
+ });
+ self.repo
+ .save_followup(&record, Some(&command), description.as_deref())
+ .await?;
+ if let Err(error) = self.reconcile_locked(&mut record).await {
+ if record.followup.state == FollowupState::Archiving {
+ record.followup.state = FollowupState::Returning;
+ record.restore_inbox_visible = record.original_inbox_visible;
+ record.restore_original = true;
+ self.repo.save_followup(&record, None, None).await?;
+ if let Err(restore_error) = self.reconcile_locked(&mut record).await {
+ tracing::error!(error = ?restore_error, reminder_id = %record.followup.reminder_id, "email reminder rollback will retry");
+ }
+ }
+ return Err(error);
+ }
+ Ok(record.followup)
+ }
+
+ /// Retire this exact owned reminder. Historical rows never mutate mail or
+ /// another follow-up; the caller retains the dispatch lock through retraction.
+ pub(crate) async fn retire_locked(
+ &self,
+ mut record: FollowupRecord,
+ ) -> Result<(), ReminderError> {
+ record.followup.revision = Uuid::now_v7();
+ record.cancel_on_restore = false;
+ record.restore_inbox_visible = true;
+ record.restore_original = false;
+ record.followup.state = if record.followup.state.active() {
+ FollowupState::Returning
+ } else {
+ FollowupState::Removed
+ };
+ self.repo.save_followup(&record, None, None).await?;
+ self.reconcile_locked(&mut record).await
+ }
+
+ /// Resume stored intent and cancel replied/inaccessible workflows. The caller
+ /// holds the user/thread lock until all changes have been persisted.
+ pub(crate) async fn reconcile_locked(
+ &self,
+ record: &mut FollowupRecord,
+ ) -> Result<(), ReminderError> {
+ if !record.followup.state.active() && record.followup.state != FollowupState::Returned {
+ return Ok(());
+ }
+ let facts = self
+ .mailbox
+ .followup_thread(record.user_id.clone(), record.followup.thread_id)
+ .await
+ .map_err(internal)?;
+ let Some(facts) =
+ facts.filter(|facts| !facts.unavailable && facts.link_id == record.followup.link_id)
+ else {
+ record.followup.state = FollowupState::Cancelled;
+ return self.repo.save_followup(record, None, None).await;
+ };
+ if matches!(
+ record.followup.state,
+ FollowupState::Archiving | FollowupState::Pending
+ ) && record.followup.condition == EmailReminderCondition::IfNoReply
+ && facts.has_reply(&record.baseline)
+ {
+ // A reply can arrive between the facts read and archive. Persist the
+ // restoration before touching mail, so a crash cannot strand that reply.
+ record.followup.state = FollowupState::Returning;
+ record.restore_inbox_visible = true;
+ record.cancel_on_restore = true;
+ record.restore_original = false;
+ self.repo.save_followup(record, None, None).await?;
+ }
+ let (visible, next) = match record.followup.state {
+ FollowupState::Archiving => (false, FollowupState::Pending),
+ FollowupState::Returning => (
+ record.restore_inbox_visible,
+ if record.cancel_on_restore {
+ FollowupState::Cancelled
+ } else {
+ FollowupState::Removed
+ },
+ ),
+ _ => return Ok(()),
+ };
+ self.mailbox
+ .set_followup_inbox(
+ record.user_id.clone(),
+ record.followup.thread_id,
+ record.followup.link_id,
+ visible,
+ if record.restore_original {
+ record.original_returned_at
+ } else {
+ visible.then(|| self.clock.now())
+ },
+ )
+ .await
+ .map_err(internal)?;
+ record.followup.state = next;
+ self.repo.save_followup(record, None, None).await
+ }
+
+ /// Durable reply cancellation and crash recovery, bounded in page size.
+ pub async fn reconcile(&self) -> Result<(), ReminderError> {
+ let mut after = None;
+ loop {
+ let records = self.repo.reconciliation_page(after, 100).await?;
+ if records.is_empty() {
+ return Ok(());
+ }
+ for record in records {
+ after = Some(record.followup.reminder_id);
+ let _guard = match self
+ .repo
+ .lock_followup(&record.user_id, record.followup.thread_id)
+ .await
+ {
+ Ok(guard) => guard,
+ Err(error) => {
+ tracing::error!(error = ?error, reminder_id = %record.followup.reminder_id, "email follow-up lock will retry");
+ continue;
+ }
+ };
+ let mut current = match self
+ .repo
+ .reminder_followup(&record.user_id, record.followup.reminder_id)
+ .await
+ {
+ Ok(Some(current)) => current,
+ Ok(None) => continue,
+ Err(error) => {
+ tracing::error!(error = ?error, reminder_id = %record.followup.reminder_id, "email follow-up read will retry");
+ continue;
+ }
+ };
+ if let Err(error) = self.reconcile_locked(&mut current).await {
+ tracing::error!(error = ?error, reminder_id = %current.followup.reminder_id, "email follow-up reconciliation will retry");
+ }
+ }
+ }
+ }
+
+ /// Return an eligible conversation before the existing persistent alert is sent.
+ /// Must run under the user/thread lock, retained through notification delivery.
+ pub(crate) async fn return_due_locked(
+ &self,
+ record: &mut FollowupRecord,
+ scheduled_for: DateTime<Utc>,
+ ) -> Result<bool, ReminderError> {
+ self.reconcile_locked(record).await?;
+ if record.followup.remind_at != scheduled_for {
+ return Ok(false);
+ }
+ if record.followup.state == FollowupState::Returned {
+ return Ok(true);
+ }
+ if record.followup.state != FollowupState::Pending {
+ return Ok(false);
+ }
+ // Reconciliation immediately above checked stable reply facts, trash,
+ // deletion and delegated access. Email repeats its access check on write.
+ self.mailbox
+ .set_followup_inbox(
+ record.user_id.clone(),
+ record.followup.thread_id,
+ record.followup.link_id,
+ true,
+ Some(self.clock.now()),
+ )
+ .await
+ .map_err(internal)?;
+ record.followup.state = FollowupState::Returned;
+ self.repo.save_followup(record, None, None).await?;
+ Ok(true)
+ }
+}
diff --git a/crates/reminders/src/domain/ports.rs b/crates/reminders/src/domain/ports.rs
index a48a96f211..a9eebefb44 100644
--- a/crates/reminders/src/domain/ports.rs
+++ b/crates/reminders/src/domain/ports.rs
@@ -297,6 +297,36 @@ pub trait ReminderDispatch: Send + Sync + 'static {
/// Inbound service port: the reminders API used by drivers (HTTP).
pub trait RemindersService: Send + Sync + 'static {
+ /// Read the email workflow when this service has email capabilities wired.
+ fn get_email_followup(
+ &self,
+ _user: MacroUserIdStr<'static>,
+ _thread: Uuid,
+ ) -> impl Future<Output = Result<Option<super::email_followup::EmailFollowup>, ReminderError>> + Send
+ {
+ async {
+ Err(ReminderError::BadRequest(
+ "Email reminders are unavailable".into(),
+ ))
+ }
+ }
+
+ /// Execute an idempotent email workflow command. Generic/AI-only services
+ /// deliberately do not gain inbox mutation capabilities by default.
+ fn execute_email_followup(
+ &self,
+ _user: MacroUserIdStr<'static>,
+ _thread: Uuid,
+ _command: super::email_followup::EmailFollowupCommand,
+ ) -> impl Future<Output = Result<super::email_followup::EmailFollowup, ReminderError>> + Send
+ {
+ async {
+ Err(ReminderError::BadRequest(
+ "Email reminders are unavailable".into(),
+ ))
+ }
+ }
+
/// Create a reminder for the user.
///
/// `entity_receipt` must be present whenever `request` names an entity, and
diff --git a/crates/reminders/src/domain/service.rs b/crates/reminders/src/domain/service.rs
index 7a72af92f7..e02d455068 100644
--- a/crates/reminders/src/domain/service.rs
+++ b/crates/reminders/src/domain/service.rs
@@ -198,7 +198,7 @@ fn resolve_entity(
/// holding proof for another. The repo stays user-scoped on top of this: the
/// receipt says who proved what, the `WHERE user_id` says what the query may
/// touch.
-fn receipt_owner_and_id(
+pub(crate) fn receipt_owner_and_id(
receipt: &EntityAccessReceipt<OwnerAccessLevel>,
) -> Result<(MacroUserIdStr<'static>, Uuid), ReminderError> {
let user_id = receipt
diff --git a/crates/reminders/src/inbound/axum_router.rs b/crates/reminders/src/inbound/axum_router.rs
index 8de8e70c8d..79f27d527d 100644
--- a/crates/reminders/src/inbound/axum_router.rs
+++ b/crates/reminders/src/inbound/axum_router.rs
@@ -7,7 +7,7 @@ use std::sync::Arc;
use axum::{
Json, Router,
- extract::{FromRef, State},
+ extract::{FromRef, Path, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, patch, post},
@@ -99,6 +99,11 @@ where
T: Send + Sync + 'static,
{
Router::new()
+ .route(
+ "/email/{thread_id}",
+ get(get_email_followup_handler::<S, Eas, Auth>)
+ .put(set_email_followup_handler::<S, Eas, Auth>),
+ )
.route("/", get(list_reminders_handler::<S, Eas, Auth>))
.route("/", post(create_reminder_handler::<S, Eas, Auth>))
.route("/{id}", get(get_reminder_handler::<S, Eas, Auth>))
@@ -514,3 +519,52 @@ impl IntoResponse for ReminderError {
.into_response()
}
}
+
+/// Read an email follow-up and reconcile inbound reply cancellation.
+#[utoipa::path(get, tag = "reminders", operation_id = "get_email_followup",
+ path = "/reminders/email/{thread_id}", params(("thread_id" = Uuid, Path)),
+ responses((status = 200, body = crate::domain::email_followup::EmailFollowupResponse),
+ (status = 403, body = ErrorResponse), (status = 500, body = ErrorResponse)))]
+pub async fn get_email_followup_handler<S, Eas, Auth>(
+ State(state): State<RemindersRouterState<S, Eas, Auth>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Path(thread_id): Path<Uuid>,
+) -> Result<Json<crate::domain::email_followup::EmailFollowupResponse>, ReminderError>
+where
+ S: RemindersService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ Ok(Json(crate::domain::email_followup::EmailFollowupResponse {
+ followup: state
+ .service
+ .get_email_followup(user.authorization.user.macro_user_id, thread_id)
+ .await?,
+ }))
+}
+
+/// Schedule, edit or remove one email follow-up as an idempotent operation.
+#[utoipa::path(put, tag = "reminders", operation_id = "set_email_followup",
+ path = "/reminders/email/{thread_id}", params(("thread_id" = Uuid, Path)),
+ request_body = crate::domain::email_followup::EmailFollowupCommand,
+ responses((status = 200, body = crate::domain::email_followup::EmailFollowup),
+ (status = 400, body = ErrorResponse), (status = 403, body = ErrorResponse),
+ (status = 500, body = ErrorResponse)))]
+pub async fn set_email_followup_handler<S, Eas, Auth>(
+ State(state): State<RemindersRouterState<S, Eas, Auth>>,
+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Path(thread_id): Path<Uuid>,
+ Json(command): Json<crate::domain::email_followup::EmailFollowupCommand>,
+) -> Result<Json<crate::domain::email_followup::EmailFollowup>, ReminderError>
+where
+ S: RemindersService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ Ok(Json(
+ state
+ .service
+ .execute_email_followup(user.authorization.user.macro_user_id, thread_id, command)
+ .await?,
+ ))
+}
diff --git a/crates/reminders/src/outbound/pg_reminders_repo.rs b/crates/reminders/src/outbound/pg_reminders_repo.rs
index badf87942f..ebfeb22db5 100644
--- a/crates/reminders/src/outbound/pg_reminders_repo.rs
+++ b/crates/reminders/src/outbound/pg_reminders_repo.rs
@@ -1,5 +1,6 @@
//! PostgreSQL implementation of the [`RemindersRepo`] port.
+mod email_followup;
#[cfg(test)]
mod test;
@@ -24,12 +25,29 @@ use crate::domain::ports::{ReminderDispatchRepo, RemindersRepo};
#[derive(Debug, Clone)]
pub struct PgRemindersRepo {
pool: PgPool,
+ followup_locks: PgPool,
}
impl PgRemindersRepo {
/// Create a repository backed by the provided pool.
pub fn new(pool: PgPool) -> Self {
- Self { pool }
+ Self::with_followup_lock_capacity(pool, 4)
+ }
+
+ /// Create a repository with a separate connection budget for concurrent
+ /// follow-up operations. HTTP and dispatch users should share this instance.
+ /// `lock_capacity` must be greater than zero.
+ pub fn with_followup_lock_capacity(pool: PgPool, lock_capacity: u32) -> Self {
+ // Lock holders span email operations. Keep their connections separate
+ // from the data pool; unsuccessful lock attempts release their connection
+ // before backoff so waiters do not occupy this pool either.
+ let followup_locks = sqlx::postgres::PgPoolOptions::new()
+ .max_connections(lock_capacity)
+ .connect_lazy_with(pool.connect_options().as_ref().clone());
+ Self {
+ pool,
+ followup_locks,
+ }
}
}
diff --git a/crates/reminders/src/outbound/pg_reminders_repo/email_followup.rs b/crates/reminders/src/outbound/pg_reminders_repo/email_followup.rs
new file mode 100644
index 0000000000..a50c6f7cda
--- /dev/null
+++ b/crates/reminders/src/outbound/pg_reminders_repo/email_followup.rs
@@ -0,0 +1,166 @@
+use super::PgRemindersRepo;
+use crate::domain::{
+ email_followup::{EmailFollowupCommand, EmailFollowupRepo, FollowupRecord, FollowupState},
+ models::ReminderError,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::{Postgres, Transaction, types::Json};
+use std::time::Duration;
+use uuid::Uuid;
+
+const LOCK_WAIT_TIMEOUT: Duration = Duration::from_secs(5);
+const LOCK_INITIAL_BACKOFF: Duration = Duration::from_millis(10);
+const LOCK_MAX_BACKOFF: Duration = Duration::from_millis(100);
+
+fn db(error: sqlx::Error) -> ReminderError {
+ ReminderError::Internal(rootcause::Report::new(error).into_dynamic())
+}
+
+impl EmailFollowupRepo for PgRemindersRepo {
+ type Guard = Transaction<'static, Postgres>;
+
+ async fn lock_followup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ thread: Uuid,
+ ) -> Result<Self::Guard, ReminderError> {
+ // The transaction exists only to hold the lock. Durable intent writes
+ // use their own transactions, so dropping/crashing this guard cannot
+ // roll back intent after an email side effect has committed.
+ let key = format!("{}:{thread}", user.as_ref());
+ tokio::time::timeout(LOCK_WAIT_TIMEOUT, async {
+ let mut backoff = LOCK_INITIAL_BACKOFF;
+ loop {
+ let mut guard = self.followup_locks.begin().await.map_err(db)?;
+ // The guard is deliberately idle during email/notification I/O.
+ // A deployment's idle transaction timeout must not release it.
+ sqlx::query!("SET LOCAL idle_in_transaction_session_timeout = 0")
+ .execute(&mut *guard)
+ .await
+ .map_err(db)?;
+ let locked = sqlx::query_scalar!(
+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 732849)) AS "locked!""#,
+ key
+ )
+ .fetch_one(&mut *guard)
+ .await
+ .map_err(db)?;
+ if locked {
+ return Ok(guard);
+ }
+ // Finish rollback before sleeping, returning the connection to
+ // the pool so unrelated threads can acquire their own locks.
+ guard.rollback().await.map_err(db)?;
+ tokio::time::sleep(backoff).await;
+ backoff = (backoff * 2).min(LOCK_MAX_BACKOFF);
+ }
+ })
+ .await
+ .map_err(|_| db(sqlx::Error::PoolTimedOut))?
+ }
+
+ async fn thread_followup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ thread: Uuid,
+ ) -> Result<Option<FollowupRecord>, ReminderError> {
+ Ok(sqlx::query_scalar!(
+ r#"SELECT payload AS "payload!: Json<FollowupRecord>" FROM reminder_email_followup
+ WHERE user_id = $1 AND thread_id = $2 ORDER BY created_at DESC, reminder_id DESC LIMIT 1"#,
+ user.as_ref(), thread,
+ ).fetch_optional(&self.pool).await.map_err(db)?.map(|record| record.0))
+ }
+
+ async fn reminder_followup(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ reminder: Uuid,
+ ) -> Result<Option<FollowupRecord>, ReminderError> {
+ Ok(sqlx::query_scalar!(
+ r#"SELECT payload AS "payload!: Json<FollowupRecord>" FROM reminder_email_followup
+ WHERE user_id = $1 AND reminder_id = $2"#,
+ user.as_ref(),
+ reminder,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(db)?
+ .map(|record| record.0))
+ }
+
+ async fn previous_operation(
+ &self,
+ user: &MacroUserIdStr<'_>,
+ operation: Uuid,
+ ) -> Result<Option<(Uuid, EmailFollowupCommand)>, ReminderError> {
+ Ok(sqlx::query!(
+ r#"SELECT reminder_id, request AS "request!: Json<EmailFollowupCommand>" FROM reminder_email_operation
+ WHERE user_id = $1 AND operation_id = $2"#,
+ user.as_ref(), operation,
+ ).fetch_optional(&self.pool).await.map_err(db)?.map(|row| (row.reminder_id, row.request.0)))
+ }
+
+ async fn save_followup(
+ &self,
+ record: &FollowupRecord,
+ command: Option<&EmailFollowupCommand>,
+ description: Option<&str>,
+ ) -> Result<(), ReminderError> {
+ let mut tx = self.pool.begin().await.map_err(db)?;
+ let f = &record.followup;
+ let enabled = matches!(f.state, FollowupState::Pending | FollowupState::Returned);
+ let completed = matches!(f.state, FollowupState::Cancelled | FollowupState::Removed);
+ let payload = Json(record);
+ sqlx::query!(
+ r#"INSERT INTO reminder (id, user_id, description, entity_type, entity_id, remind_at, next_run_at, enabled, completed_at)
+ VALUES ($1, $2, COALESCE($3, 'Email follow-up'), 'email_thread', $4, $5, $5, $6, CASE WHEN $7 THEN now() END)
+ ON CONFLICT (id) DO UPDATE SET remind_at = EXCLUDED.remind_at, next_run_at = EXCLUDED.next_run_at,
+ enabled = EXCLUDED.enabled, completed_at = EXCLUDED.completed_at, updated_at = now()
+ WHERE reminder.user_id = EXCLUDED.user_id"#,
+ f.reminder_id, record.user_id.as_ref(), description, f.thread_id, f.remind_at, enabled, completed,
+ ).execute(&mut *tx).await.map_err(db)?;
+ sqlx::query!(
+ r#"INSERT INTO reminder_email_followup (reminder_id, user_id, thread_id, link_id, state, payload)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (reminder_id) DO UPDATE SET state = EXCLUDED.state, payload = EXCLUDED.payload
+ WHERE reminder_email_followup.user_id = EXCLUDED.user_id"#,
+ f.reminder_id, record.user_id.as_ref(), f.thread_id, f.link_id, f.state.as_str(), payload as _,
+ ).execute(&mut *tx).await.map_err(db)?;
+ if let Some(command) = command {
+ let accepted = sqlx::query!(
+ r#"INSERT INTO reminder_email_operation (user_id, operation_id, thread_id, request, reminder_id)
+ VALUES ($1, $2, $3, $4, $5) ON CONFLICT (user_id, operation_id) DO NOTHING"#,
+ record.user_id.as_ref(), command.operation_id(), f.thread_id, Json(command) as _, f.reminder_id,
+ ).execute(&mut *tx).await.map_err(db)?;
+ if accepted.rows_affected() != 1 {
+ return Err(ReminderError::BadRequest(
+ "This request identity was already used for another email operation".into(),
+ ));
+ }
+ }
+ if !enabled {
+ // Same retraction semantics as ordinary reminder removal.
+ sqlx::query!(
+ r#"DELETE FROM notification WHERE event_item_id = $1 AND event_item_type = 'reminder'"#,
+ f.reminder_id.to_string(),
+ ).execute(&mut *tx).await.map_err(db)?;
+ }
+ tx.commit().await.map_err(db)
+ }
+
+ async fn reconciliation_page(
+ &self,
+ after: Option<Uuid>,
+ limit: i64,
+ ) -> Result<Vec<FollowupRecord>, ReminderError> {
+ Ok(sqlx::query_scalar!(
+ r#"SELECT payload AS "payload!: Json<FollowupRecord>" FROM reminder_email_followup
+ WHERE state IN ('archiving', 'pending', 'returning') AND ($1::uuid IS NULL OR reminder_id > $1)
+ ORDER BY reminder_id LIMIT $2"#,
+ after, limit,
+ ).fetch_all(&self.pool).await.map_err(db)?.into_iter().map(|record| record.0).collect())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs b/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs
new file mode 100644
index 0000000000..1530856b6f
--- /dev/null
+++ b/crates/reminders/src/outbound/pg_reminders_repo/email_followup/test.rs
@@ -0,0 +1,982 @@
+use super::*;
+use crate::domain::email_followup::{EmailReminderCondition, service::EmailFollowupService};
+use crate::domain::ports::{Clock, RemindersRepo};
+use crate::domain::{
+ email_followup::{dispatch::EmailReminderDispatch, reminder_service::EmailRemindersService},
+ models::{DeliveryOutcome, DueFiring, ReminderPatch, SweepSummary},
+ ports::{ReminderDispatch, RemindersService},
+ service::RemindersServiceImpl,
+};
+use chrono::{DateTime, Duration, Utc};
+use email::domain::{
+ followup::{EmailFollowupMailbox, FollowupMessage, FollowupThread},
+ models::EmailErr,
+};
+use entity_access::domain::models::{
+ AccessLevel, Entity as AccessEntity, EntityAccessReceipt, EntityPermission, OwnerAccessLevel,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use model_entity::EntityType;
+use sqlx::PgPool;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use tokio::sync::Notify;
+
+struct SweepProbe {
+ calls: Arc<AtomicUsize>,
+ fail: bool,
+}
+
+impl ReminderDispatch for SweepProbe {
+ async fn sweep(&self) -> Result<SweepSummary, ReminderError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ if self.fail {
+ Err(ReminderError::NotFound)
+ } else {
+ Ok(SweepSummary { dispatched: 7 })
+ }
+ }
+
+ async fn deliver(&self, _: DueFiring) -> Result<DeliveryOutcome, ReminderError> {
+ Ok(DeliveryOutcome::Gone)
+ }
+}
+
+fn owner_receipt(id: Uuid) -> EntityAccessReceipt<OwnerAccessLevel> {
+ EntityAccessReceipt::try_new_authenticated_user(
+ user(),
+ AccessEntity {
+ entity_id: id.to_string(),
+ entity_type: EntityType::Reminder,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
+ .unwrap()
+}
+
+struct PausedDelivery {
+ entered: Arc<Notify>,
+ release: Arc<Notify>,
+}
+
+impl ReminderDispatch for PausedDelivery {
+ async fn sweep(&self) -> Result<SweepSummary, ReminderError> {
+ Ok(SweepSummary::default())
+ }
+
+ async fn deliver(&self, _: DueFiring) -> Result<DeliveryOutcome, ReminderError> {
+ self.entered.notify_one();
+ self.release.notified().await;
+ Ok(DeliveryOutcome::Delivered)
+ }
+}
+
+const THREAD: Uuid = Uuid::from_u128(11);
+const LINK: Uuid = Uuid::from_u128(12);
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+#[derive(Clone)]
+struct FixedClock(DateTime<Utc>);
+impl Clock for FixedClock {
+ fn now(&self) -> DateTime<Utc> {
+ self.0
+ }
+}
+#[derive(Clone)]
+struct Mailbox(Arc<Mutex<Mail>>);
+struct Mail {
+ facts: Option<FollowupThread>,
+ archive_fails: bool,
+ return_fails: bool,
+ writes: usize,
+ reply_on_archive: Option<DateTime<Utc>>,
+}
+impl EmailFollowupMailbox for Mailbox {
+ async fn followup_thread(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ thread: Uuid,
+ ) -> Result<Option<FollowupThread>, EmailErr> {
+ if actor != user() || thread != THREAD {
+ return Ok(None);
+ }
+ Ok(self.0.lock().unwrap().facts.clone())
+ }
+ async fn set_followup_inbox(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ thread: Uuid,
+ link: Uuid,
+ visible: bool,
+ returned_at: Option<DateTime<Utc>>,
+ ) -> Result<(), EmailErr> {
+ assert_eq!(actor, user());
+ assert_eq!(thread, THREAD);
+ assert_eq!(link, LINK);
+ let mut mail = self.0.lock().unwrap();
+ if (visible && mail.return_fails) || (!visible && mail.archive_fails) {
+ return Err(EmailErr::ThreadEmpty);
+ }
+ if !visible && let Some(received_at) = mail.reply_on_archive.take() {
+ mail.facts.as_mut().unwrap().messages.push(FollowupMessage {
+ id: Uuid::now_v7(),
+ received_at: Some(received_at),
+ outgoing: false,
+ from_self: false,
+ });
+ }
+ mail.writes += 1;
+ mail.facts.as_mut().unwrap().inbox_visible = visible;
+ mail.facts.as_mut().unwrap().returned_at = if visible { returned_at } else { None };
+ Ok(())
+ }
+}
+async fn setup(pool: PgPool) -> EmailFollowupService<PgRemindersRepo, Mailbox, FixedClock> {
+ let owner = user();
+ sqlx::query!(r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, 'followup', '[email protected]', 'followup')"#, Uuid::now_v7()).execute(&pool).await.unwrap();
+ sqlx::query!(r#"INSERT INTO "User" (id, email, macro_user_id) SELECT $1, '[email protected]', id FROM macro_user WHERE email = '[email protected]'"#, owner.as_ref()).execute(&pool).await.unwrap();
+ sqlx::query!("INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider) VALUES ($1, $2, 'followup', '[email protected]', 'GMAIL')", LINK, owner.as_ref()).execute(&pool).await.unwrap();
+ sqlx::query!(
+ "INSERT INTO email_threads (id, link_id) VALUES ($1, $2)",
+ THREAD,
+ LINK
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ EmailFollowupService {
+ repo: PgRemindersRepo::new(pool),
+ clock: FixedClock(Utc::now()),
+ mailbox: Mailbox(Arc::new(Mutex::new(Mail {
+ facts: Some(FollowupThread {
+ link_id: LINK,
+ subject: "Waiting for a reply".into(),
+ inbox_visible: true,
+ returned_at: None,
+ unavailable: false,
+ messages: vec![],
+ }),
+ archive_fails: false,
+ return_fails: false,
+ writes: 0,
+ reply_on_archive: None,
+ }))),
+ }
+}
+fn set(at: DateTime<Utc>, condition: EmailReminderCondition) -> EmailFollowupCommand {
+ EmailFollowupCommand::Set {
+ operation_id: Uuid::now_v7(),
+ expected_revision: None,
+ remind_at: at,
+ condition,
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn retry_concurrency_and_stale_undo_do_not_duplicate_or_resurrect(pool: PgPool) {
+ let service = setup(pool).await;
+ let command = set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::IfNoReply,
+ );
+ let (first, retry) = tokio::join!(
+ service.execute(user(), THREAD, command.clone()),
+ service.execute(user(), THREAD, command.clone())
+ );
+ let first = first.unwrap();
+ assert_eq!(first, retry.unwrap());
+ assert_eq!(service.mailbox.0.lock().unwrap().writes, 1);
+ let mut edit = set(
+ service.clock.now() + Duration::hours(2),
+ EmailReminderCondition::Regardless,
+ );
+ if let EmailFollowupCommand::Set {
+ expected_revision, ..
+ } = &mut edit
+ {
+ *expected_revision = Some(first.revision);
+ }
+ let edited = service.execute(user(), THREAD, edit).await.unwrap();
+ let stale = EmailFollowupCommand::Remove {
+ operation_id: Uuid::now_v7(),
+ expected_revision: first.revision,
+ undo: true,
+ };
+ assert!(service.execute(user(), THREAD, stale).await.is_err());
+ let removed = service
+ .execute(
+ user(),
+ THREAD,
+ EmailFollowupCommand::Remove {
+ operation_id: Uuid::now_v7(),
+ expected_revision: edited.revision,
+ undo: false,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(removed.state, FollowupState::Removed);
+ assert_eq!(
+ service
+ .execute(user(), THREAD, command)
+ .await
+ .unwrap()
+ .state,
+ FollowupState::Removed
+ );
+ assert!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .inbox_visible
+ );
+ let reminder = service
+ .repo
+ .get_reminder(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!reminder.enabled);
+ assert!(reminder.completed_at.is_some());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reply_cancels_but_regardless_returns_sent_only_and_retry_is_idempotent(pool: PgPool) {
+ let service = setup(pool).await;
+ let first = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::IfNoReply,
+ ),
+ )
+ .await
+ .unwrap();
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_mut()
+ .unwrap()
+ .messages
+ .push(FollowupMessage {
+ id: Uuid::now_v7(),
+ received_at: Some(service.clock.now() + Duration::seconds(1)),
+ outgoing: false,
+ from_self: false,
+ });
+ service.reconcile().await.unwrap();
+ let mut record = service
+ .repo
+ .reminder_followup(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(record.followup.state, FollowupState::Cancelled);
+ assert!(
+ !service
+ .return_due_locked(&mut record, first.remind_at)
+ .await
+ .unwrap()
+ );
+ // A sent-only conversation has no inbound message requirement on this port.
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_mut()
+ .unwrap()
+ .messages
+ .clear();
+ let second = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(2),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_mut()
+ .unwrap()
+ .messages
+ .push(FollowupMessage {
+ id: Uuid::now_v7(),
+ received_at: Some(service.clock.now() + Duration::seconds(2)),
+ outgoing: false,
+ from_self: false,
+ });
+ let mut record = service
+ .repo
+ .reminder_followup(&user(), second.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ service.mailbox.0.lock().unwrap().return_fails = true;
+ assert!(
+ service
+ .return_due_locked(&mut record, second.remind_at)
+ .await
+ .is_err()
+ );
+ assert_eq!(record.followup.state, FollowupState::Pending);
+ service.mailbox.0.lock().unwrap().return_fails = false;
+ assert!(
+ service
+ .return_due_locked(&mut record, second.remind_at)
+ .await
+ .unwrap()
+ );
+ let writes = service.mailbox.0.lock().unwrap().writes;
+ assert!(
+ service
+ .return_due_locked(&mut record, second.remind_at)
+ .await
+ .unwrap()
+ );
+ assert_eq!(service.mailbox.0.lock().unwrap().writes, writes);
+ assert!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .inbox_visible
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn archive_failure_rolls_back_and_ineligible_mail_never_returns(pool: PgPool) {
+ let service = setup(pool).await;
+ service.mailbox.0.lock().unwrap().archive_fails = true;
+ assert!(
+ service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::IfNoReply
+ )
+ )
+ .await
+ .is_err()
+ );
+ service.mailbox.0.lock().unwrap().archive_fails = false;
+ service.reconcile().await.unwrap();
+ assert!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .inbox_visible
+ );
+ let first = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ let mut record = service
+ .repo
+ .reminder_followup(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ !service
+ .return_due_locked(&mut record, first.remind_at + Duration::minutes(1))
+ .await
+ .unwrap()
+ );
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_mut()
+ .unwrap()
+ .unavailable = true;
+ assert!(
+ !service
+ .return_due_locked(&mut record, first.remind_at)
+ .await
+ .unwrap()
+ );
+ sqlx::query!("DELETE FROM email_threads WHERE id = $1", THREAD)
+ .execute(&service.repo.pool)
+ .await
+ .unwrap();
+ assert!(
+ service
+ .repo
+ .reminder_followup(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .is_some(),
+ "deletion keeps the specialization tombstone"
+ );
+ service.mailbox.0.lock().unwrap().facts = None;
+ assert!(service.get(user(), THREAD).await.is_err());
+ assert!(
+ service
+ .execute(
+ user(),
+ Uuid::now_v7(),
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless
+ )
+ )
+ .await
+ .is_err()
+ );
+ let other = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ assert!(
+ service
+ .execute(
+ other,
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless
+ )
+ )
+ .await
+ .is_err()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reply_racing_archive_is_durably_restored(pool: PgPool) {
+ let service = setup(pool).await;
+ service.mailbox.0.lock().unwrap().reply_on_archive =
+ Some(service.clock.now() + Duration::seconds(1));
+ let created = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::IfNoReply,
+ ),
+ )
+ .await
+ .unwrap();
+ service.mailbox.0.lock().unwrap().return_fails = true;
+ service.reconcile().await.unwrap();
+ let restoring = service
+ .repo
+ .reminder_followup(&user(), created.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(restoring.followup.state, FollowupState::Returning);
+ assert!(restoring.cancel_on_restore);
+ service.mailbox.0.lock().unwrap().return_fails = false;
+ service.reconcile().await.unwrap();
+ assert_eq!(
+ service.get(user(), THREAD).await.unwrap().unwrap().state,
+ FollowupState::Cancelled
+ );
+ assert!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .inbox_visible
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn exact_seconds_and_removal_without_source_access(pool: PgPool) {
+ let service = setup(pool).await;
+ let requested = DateTime::from_timestamp_micros(
+ (service.clock.now() + Duration::seconds(10)).timestamp_micros(),
+ )
+ .unwrap();
+ let first = service
+ .execute(
+ user(),
+ THREAD,
+ set(requested, EmailReminderCondition::Regardless),
+ )
+ .await
+ .unwrap();
+ assert_eq!(first.remind_at, requested);
+ let edited = service
+ .execute(
+ user(),
+ THREAD,
+ EmailFollowupCommand::Set {
+ operation_id: Uuid::now_v7(),
+ expected_revision: Some(first.revision),
+ remind_at: requested + Duration::seconds(1),
+ condition: EmailReminderCondition::Regardless,
+ },
+ )
+ .await
+ .unwrap();
+ let mut record = service
+ .repo
+ .reminder_followup(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ !service
+ .return_due_locked(&mut record, first.remind_at)
+ .await
+ .unwrap()
+ );
+ service.mailbox.0.lock().unwrap().facts = None;
+ let writes = service.mailbox.0.lock().unwrap().writes;
+ let command = EmailFollowupCommand::Remove {
+ operation_id: Uuid::now_v7(),
+ expected_revision: edited.revision,
+ undo: false,
+ };
+ let removed = service
+ .execute(user(), THREAD, command.clone())
+ .await
+ .unwrap();
+ assert_eq!(removed.state, FollowupState::Removed);
+ assert_eq!(
+ service.execute(user(), THREAD, command).await.unwrap(),
+ removed
+ );
+ assert_eq!(service.mailbox.0.lock().unwrap().writes, writes);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn deleting_historical_followup_preserves_new_pending_followup(pool: PgPool) {
+ let service = setup(pool).await;
+ let first_command = set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ );
+ let first = service
+ .execute(user(), THREAD, first_command.clone())
+ .await
+ .unwrap();
+ let guard = service.repo.lock_followup(&user(), THREAD).await.unwrap();
+ let mut record = service
+ .repo
+ .reminder_followup(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ service
+ .return_due_locked(&mut record, first.remind_at)
+ .await
+ .unwrap()
+ );
+ drop(guard);
+ let second = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(2),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ let writes = service.mailbox.0.lock().unwrap().writes;
+ let reminders = EmailRemindersService::new(
+ RemindersServiceImpl::new(service.repo.clone()),
+ service.clone(),
+ );
+ reminders
+ .delete_reminder(owner_receipt(first.reminder_id))
+ .await
+ .unwrap();
+ assert_eq!(service.mailbox.0.lock().unwrap().writes, writes);
+ assert!(
+ !service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .inbox_visible
+ );
+ assert_eq!(service.get(user(), THREAD).await.unwrap(), Some(second));
+ assert_eq!(
+ service
+ .execute(user(), THREAD, first_command)
+ .await
+ .unwrap()
+ .state,
+ FollowupState::Removed
+ );
+ assert_eq!(service.mailbox.0.lock().unwrap().writes, writes);
+ let retired = service
+ .repo
+ .get_reminder(&user(), first.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!retired.enabled);
+ assert!(retired.completed_at.is_some());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn completion_waits_for_delivery_after_inbox_return(pool: PgPool) {
+ let service = setup(pool).await;
+ let created = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ let entered = Arc::new(Notify::new());
+ let release = Arc::new(Notify::new());
+ let dispatch = EmailReminderDispatch::new(
+ PausedDelivery {
+ entered: entered.clone(),
+ release: release.clone(),
+ },
+ service.clone(),
+ );
+ let delivery = tokio::spawn(async move {
+ dispatch
+ .deliver(DueFiring {
+ reminder_id: created.reminder_id,
+ scheduled_for: created.remind_at,
+ })
+ .await
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(5), entered.notified())
+ .await
+ .unwrap();
+ let returned = service
+ .repo
+ .reminder_followup(&user(), created.reminder_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(returned.followup.state, FollowupState::Returned);
+ let reminders = EmailRemindersService::new(
+ RemindersServiceImpl::new(service.repo.clone()),
+ service.clone(),
+ );
+ let completion = reminders.update_reminder(
+ owner_receipt(created.reminder_id),
+ ReminderPatch {
+ description: None,
+ schedule: None,
+ enabled: None,
+ completed: Some(true),
+ },
+ );
+ tokio::pin!(completion);
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(100), &mut completion)
+ .await
+ .is_err(),
+ "completion must wait while notification delivery owns the workflow lock"
+ );
+ release.notify_one();
+ assert_eq!(delivery.await.unwrap().unwrap(), DeliveryOutcome::Delivered);
+ let completed = tokio::time::timeout(std::time::Duration::from_secs(5), completion)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(completed.completed_at.is_some());
+ assert!(!completed.enabled);
+ assert_eq!(
+ service
+ .repo
+ .reminder_followup(&user(), created.reminder_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .followup
+ .state,
+ FollowupState::Removed
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn corrupt_email_reconciliation_does_not_suppress_generic_sweep(pool: PgPool) {
+ let service = setup(pool).await;
+ let created = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ sqlx::query!(
+ "UPDATE reminder_email_followup SET payload = '{}'::jsonb WHERE reminder_id = $1",
+ created.reminder_id,
+ )
+ .execute(&service.repo.pool)
+ .await
+ .unwrap();
+ assert!(
+ service.reconcile().await.is_err(),
+ "fixture must fail decoding"
+ );
+ let calls = Arc::new(AtomicUsize::new(0));
+ let dispatch = EmailReminderDispatch::new(
+ SweepProbe {
+ calls: calls.clone(),
+ fail: false,
+ },
+ service.clone(),
+ );
+ assert_eq!(dispatch.sweep().await.unwrap().dispatched, 7);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ let dispatch = EmailReminderDispatch::new(
+ SweepProbe {
+ calls: calls.clone(),
+ fail: true,
+ },
+ service,
+ );
+ assert!(matches!(
+ dispatch.sweep().await,
+ Err(ReminderError::NotFound)
+ ));
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn independent_followups_use_configured_pool_capacity(pool: PgPool) {
+ let repo = PgRemindersRepo::with_followup_lock_capacity(pool.clone(), 8);
+ let mut guards = Vec::new();
+ for _ in 0..8 {
+ guards.push(
+ tokio::time::timeout(
+ std::time::Duration::from_secs(1),
+ repo.lock_followup(&user(), Uuid::now_v7()),
+ )
+ .await
+ .expect("unrelated followups must use the configured concurrency budget")
+ .unwrap(),
+ );
+ }
+ // Saturated lock holders must still be able to perform their data writes.
+ let connection = tokio::time::timeout(std::time::Duration::from_secs(1), pool.acquire())
+ .await
+ .expect("lock holders must not consume the data pool")
+ .unwrap();
+ drop(connection);
+ for guard in guards {
+ guard.rollback().await.unwrap();
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn busy_thread_waiters_leave_lock_pool_available(pool: PgPool) {
+ // A different process owns the busy key. Four waiters used to occupy every
+ // connection in this process's lock pool while blocked inside PostgreSQL.
+ let holder = PgRemindersRepo::new(pool.clone());
+ let held = holder.lock_followup(&user(), THREAD).await.unwrap();
+ let repo = PgRemindersRepo::new(pool);
+ let mut waiters = Vec::new();
+ for _ in 0..4 {
+ let repo = repo.clone();
+ waiters.push(tokio::spawn(async move {
+ repo.lock_followup(&user(), THREAD).await
+ }));
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
+ assert!(waiters.iter().all(|waiter| !waiter.is_finished()));
+ let unrelated = tokio::time::timeout(
+ std::time::Duration::from_secs(1),
+ repo.lock_followup(&user(), Uuid::now_v7()),
+ )
+ .await
+ .expect("busy-thread waiters must not monopolize the lock pool")
+ .unwrap();
+ unrelated.rollback().await.unwrap();
+ for waiter in waiters {
+ waiter.abort();
+ let _ = waiter.await;
+ }
+ // The same busy key fails within the bounded acquisition deadline.
+ let result = tokio::time::timeout(
+ LOCK_WAIT_TIMEOUT + std::time::Duration::from_secs(1),
+ repo.lock_followup(&user(), THREAD),
+ )
+ .await
+ .expect("lock acquisition must have a bounded deadline");
+ assert!(result.is_err());
+ held.rollback().await.unwrap();
+ let recovered = repo.lock_followup(&user(), THREAD).await.unwrap();
+ recovered.rollback().await.unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn guard_survives_configured_idle_transaction_timeout(pool: PgPool) {
+ let mut repo = PgRemindersRepo::new(pool.clone());
+ repo.followup_locks = sqlx::postgres::PgPoolOptions::new()
+ .max_connections(1)
+ .connect_lazy_with(pool.connect_options().as_ref().clone());
+ sqlx::query!("SET idle_in_transaction_session_timeout = '50ms'")
+ .execute(&repo.followup_locks)
+ .await
+ .unwrap();
+ let guard = repo.lock_followup(&user(), THREAD).await.unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(150)).await;
+ let key = format!("{}:{THREAD}", user().as_ref());
+ let mut competing = pool.begin().await.unwrap();
+ let locked = sqlx::query_scalar!(
+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 732849)) AS "locked!""#,
+ key,
+ )
+ .fetch_one(&mut *competing)
+ .await
+ .unwrap();
+ assert!(
+ !locked,
+ "an idle guard must retain the lock across external I/O"
+ );
+ competing.rollback().await.unwrap();
+ guard.rollback().await.unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn undo_and_archive_rollback_restore_original_inbox_order(pool: PgPool) {
+ let service = setup(pool).await;
+ for original in [None, Some(service.clock.now() - Duration::days(1))] {
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_mut()
+ .unwrap()
+ .returned_at = original;
+ let created = service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless,
+ ),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .returned_at,
+ None
+ );
+ service
+ .execute(
+ user(),
+ THREAD,
+ EmailFollowupCommand::Remove {
+ operation_id: Uuid::now_v7(),
+ expected_revision: created.revision,
+ undo: true,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .returned_at,
+ original
+ );
+ service.mailbox.0.lock().unwrap().archive_fails = true;
+ assert!(
+ service
+ .execute(
+ user(),
+ THREAD,
+ set(
+ service.clock.now() + Duration::hours(1),
+ EmailReminderCondition::Regardless
+ )
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ service
+ .mailbox
+ .0
+ .lock()
+ .unwrap()
+ .facts
+ .as_ref()
+ .unwrap()
+ .returned_at,
+ original
+ );
+ service.mailbox.0.lock().unwrap().archive_fails = false;
+ }
+}
diff --git a/docs/AGENT_GUIDE/reminders.md b/docs/AGENT_GUIDE/reminders.md
index 55936d65d8..ec5c23439f 100644
--- a/docs/AGENT_GUIDE/reminders.md
+++ b/docs/AGENT_GUIDE/reminders.md
@@ -8,9 +8,13 @@ inspection.
## Create or edit a reminder
-The create dialog is titled **New reminder**. A standalone reminder requires the
-**Reminder description** field; an entity-attached reminder may derive its title
-from the source badge. The **When** field accepts date language such as
+**New reminder** opens **Remind me about…**, an entity picker with recent items.
+Search using **Search reminder items**, use Up/Down and Enter to select, or click
+an item. Selecting an email opens the conditional email follow-up flow below;
+selecting a task/document opens a time-first form with its title and icon.
+**Add a note** is optional; no duplicate title is required. **Change** returns to
+selection. **Write a reminder instead** opens the freeform form, where
+**Reminder description** is required. The **When** field accepts date language such as
`tomorrow 9am`, `in 30 minutes`, weekdays, and explicit dates. The resolved
weekday, date, time, and timezone appear in the **Scheduled:** preview before
saving.
@@ -35,6 +39,16 @@ The primary action reads **Set reminder** for create and **Save** for edit.
**Cancel** dismisses without saving. A description-only edit of an overdue
reminder keeps its old schedule instead of trying to reschedule it in the past.
+## Open or manage an attached reminder
+
+Attached rows lead with their source icon and current title. A personal note,
+when different, appears as secondary text. Click or Enter opens the email, task,
+or other source directly, including in Home and when opening a new split/tab.
+Freeform reminders open their editor. Use **Edit reminder** in the row menu to
+change the schedule or note of an attached reminder. Completion and removal
+still act on the reminder itself, not on its source. Inaccessible sources show
+an unavailable label rather than a cached private title.
+
## Verify save failure without changing dev data
Intercept `POST **/dss/reminders` and hold or reject the response. While held,
@@ -49,3 +63,35 @@ duplicate-safe.
After a confirmed response, the dialog closes and the success toast includes the
exact persisted time or recurrence. Only a confirmed create runs the invoking
surface's follow-up action.
+
+## Email follow-ups (H)
+
+On one selected email or an open conversation, **H**, **Remind me** in the menu,
+and the bell control open the same time-first picker. The subject is already
+known; the first field is **When**, with no required title. Bare H remains text
+inside reply, compose, search and other editable fields. Escape cancels without
+moving the conversation. Saving uses one server operation to schedule and move
+it out of the inbox; successful creation advances within the invoking list.
+
+**If no reply** is the default. A genuinely new inbound message after scheduling
+cancels it; drafts, outgoing mail (including provider SENT aliases), known own
+inbox senders, replays and historical backfill do not. **Regardless** survives a
+reply. Existing H opens the pending follow-up for editing or **Remove**. Remove
+returns the conversation to its inbox; **Undo** cancels a newly scheduled
+follow-up and restores its original inbox visibility. A stale undo cannot
+remove a newer edit. Generic reminders attached to the same thread remain
+separate reminders.
+
+The bell is accented for pending and returned reminders and its accessible label
+includes the pending time. Server dispatch returns eligible conversations to
+the top of the corresponding inbox, including sent-only conversations, then
+uses the existing persistent reminder alert. Trash, deleted and inaccessible
+conversations are not returned. The server sweep runs once a minute; this is
+not exact-second delivery, and it does not promise a closed-browser OS alert.
+Pending operations and replies reconcile without an open browser.
+
+Email writes use `PUT /dss/reminders/email/{threadId}` with a retained operation
+ID. Unlike generic creation, retrying the same email request cannot duplicate
+it. For failure verification, intercept that endpoint and verify the time and
+condition remain, no client archive request is sent, and no navigation occurs
+before the server confirms the operation.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 1489b4ba47..b9294a6460 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1897,3 +1897,13 @@ New conversations confirm selected model and effort settings before sending the
first message. If startup reports a rejected setting or timeout, the first prompt
has not been sent. See [effort capabilities](../AGENT_EFFORT.md) for the harness
contracts and test coverage.
+
+### Email reminders
+
+Use **H** on one selected email or its open conversation, **Remind me** in the
+menu, or the header bell. These share the email-specific, time-first workflow
+in [Reminders](reminders.md#email-follow-ups-h). A successful new reminder moves
+out of the inbox and advances within that surface's filtered list. Cancel and
+failed saves keep the current email. H on a pending follow-up edits it; Remove
+returns it to the inbox. The bell's label identifies pending time or returned
+status. Bare H in a reply or search field must remain ordinary typing.
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index 739ed09a25..6b3e5272ed 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, CommandFailure, CommandRejectedMetadata, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, CommandFailure, CommandRejectedMetadata, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index 5c1ca64a98..09186815fa 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, ServerSentEventsResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, AssignInitiativeTasksData, AssignInitiativeTasksErrors, AssignInitiativeTasksResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, UnassignInitiativeTaskData, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';
+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, AssignInitiativeTasksData, AssignInitiativeTasksErrors, AssignInitiativeTasksResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, UnassignInitiativeTaskData, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -2356,6 +2356,27 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Read an email follow-up and reconcile inbound reply cancellation.
+ */
+ public getEmailFollowup<ThrowOnError extends boolean = false>(options: Options<GetEmailFollowupData, ThrowOnError>): RequestResult<GetEmailFollowupResponses, GetEmailFollowupErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetEmailFollowupResponses, GetEmailFollowupErrors, ThrowOnError>({ url: '/reminders/email/{thread_id}', ...options });
+ }
+
+ /**
+ * Schedule, edit or remove one email follow-up as an idempotent operation.
+ */
+ public setEmailFollowup<ThrowOnError extends boolean = false>(options: Options<SetEmailFollowupData, ThrowOnError>): RequestResult<SetEmailFollowupResponses, SetEmailFollowupErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<SetEmailFollowupResponses, SetEmailFollowupErrors, ThrowOnError>({
+ url: '/reminders/email/{thread_id}',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Delete one of the caller's reminders.
*/
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 4d90bbee09..c880e0edf6 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -5489,6 +5489,89 @@ export type EmailFilters = {
shared?: SharedEmailFilter;
};
+/**
+ * Public status shown on email and in the Reminders editor.
+ */
+export type EmailFollowup = {
+ /**
+ * Condition, defaulting to no reply for new follow-ups.
+ */
+ condition: EmailReminderCondition;
+ /**
+ * Canonical owned/delegated inbox.
+ */
+ linkId: string;
+ /**
+ * Confirmed schedule.
+ */
+ remindAt: string;
+ /**
+ * Its ordinary reminder, used by the existing alert/management surfaces.
+ */
+ reminderId: string;
+ /**
+ * Last accepted operation; edits/removal compare this to prevent stale undo.
+ */
+ revision: string;
+ /**
+ * Durable lifecycle progress.
+ */
+ state: FollowupState;
+ /**
+ * Conversation identity.
+ */
+ threadId: string;
+};
+
+/**
+ * Idempotent email command. Reusing an operation ID with different data fails.
+ */
+export type EmailFollowupCommand = {
+ /**
+ * Reply condition.
+ */
+ condition: EmailReminderCondition;
+ /**
+ * None for creation, the current revision for edits.
+ */
+ expectedRevision?: string | null;
+ /**
+ * Unique request identity retained across network retries.
+ */
+ operationId: string;
+ /**
+ * One future instant; conditional recurrence is deliberately absent.
+ */
+ remindAt: string;
+ type: 'set';
+} | {
+ /**
+ * Reject removal if a newer edit has replaced this operation.
+ */
+ expectedRevision: string;
+ /**
+ * Unique request identity.
+ */
+ operationId: string;
+ type: 'remove';
+ /**
+ * Undo restores original visibility; ordinary Remove returns to inbox.
+ */
+ undo?: boolean;
+};
+
+/**
+ * Lookup response, including an email with no follow-up yet.
+ */
+export type EmailFollowupResponse = {
+ followup?: null | EmailFollowup;
+};
+
+/**
+ * When an email follow-up should return the conversation.
+ */
+export type EmailReminderCondition = 'if_no_reply' | 'regardless';
+
/**
* Empty response is required due to custom fetch forcing `response.json()`
*/
@@ -5901,6 +5984,11 @@ export type FolderItem = {
sha: string;
};
+/**
+ * Durable progress of an email operation.
+ */
+export type FollowupState = 'archiving' | 'pending' | 'returning' | 'returned' | 'cancelled' | 'removed';
+
/**
* A persisted mapping to an entity owned by an external system.
*/
@@ -17141,6 +17229,51 @@ export type CreateReminderResponses = {
export type CreateReminderResponse = CreateReminderResponses[keyof CreateReminderResponses];
+export type GetEmailFollowupData = {
+ body?: never;
+ path: {
+ thread_id: string;
+ };
+ query?: never;
+ url: '/reminders/email/{thread_id}';
+};
+
+export type GetEmailFollowupErrors = {
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type GetEmailFollowupError = GetEmailFollowupErrors[keyof GetEmailFollowupErrors];
+
+export type GetEmailFollowupResponses = {
+ 200: EmailFollowupResponse;
+};
+
+export type GetEmailFollowupResponse = GetEmailFollowupResponses[keyof GetEmailFollowupResponses];
+
+export type SetEmailFollowupData = {
+ body: EmailFollowupCommand;
+ path: {
+ thread_id: string;
+ };
+ query?: never;
+ url: '/reminders/email/{thread_id}';
+};
+
+export type SetEmailFollowupErrors = {
+ 400: ErrorResponse;
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type SetEmailFollowupError = SetEmailFollowupErrors[keyof SetEmailFollowupErrors];
+
+export type SetEmailFollowupResponses = {
+ 200: EmailFollowup;
+};
+
+export type SetEmailFollowupResponse = SetEmailFollowupResponses[keyof SetEmailFollowupResponses];
+
export type DeleteReminderData = {
body?: never;
path: {
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 7e0fbcf447..16630c62d9 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -14286,6 +14286,124 @@
}
}
},
+ "/reminders/email/{thread_id}": {
+ "get": {
+ "tags": ["reminders"],
+ "summary": "Read an email follow-up and reconcile inbound reply cancellation.",
+ "operationId": "get_email_followup",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EmailFollowupResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["reminders"],
+ "summary": "Schedule, edit or remove one email follow-up as an idempotent operation.",
+ "operationId": "set_email_followup",
+ "parameters": [
+ {
+ "name": "thread_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EmailFollowupCommand"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EmailFollowup"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/reminders/{id}": {
"get": {
"tags": ["reminders"],
@@ -23717,6 +23835,136 @@
}
}
},
+ "EmailFollowup": {
+ "type": "object",
+ "description": "Public status shown on email and in the Reminders editor.",
+ "required": [
+ "reminderId",
+ "threadId",
+ "linkId",
+ "condition",
+ "remindAt",
+ "revision",
+ "state"
+ ],
+ "properties": {
+ "condition": {
+ "$ref": "#/components/schemas/EmailReminderCondition",
+ "description": "Condition, defaulting to no reply for new follow-ups."
+ },
+ "linkId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Canonical owned/delegated inbox."
+ },
+ "remindAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Confirmed schedule."
+ },
+ "reminderId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Its ordinary reminder, used by the existing alert/management surfaces."
+ },
+ "revision": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Last accepted operation; edits/removal compare this to prevent stale undo."
+ },
+ "state": {
+ "$ref": "#/components/schemas/FollowupState",
+ "description": "Durable lifecycle progress."
+ },
+ "threadId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Conversation identity."
+ }
+ }
+ },
+ "EmailFollowupCommand": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "Create or edit one follow-up. An edit requires the displayed revision.",
+ "required": ["operationId", "remindAt", "condition", "type"],
+ "properties": {
+ "condition": {
+ "$ref": "#/components/schemas/EmailReminderCondition",
+ "description": "Reply condition."
+ },
+ "expectedRevision": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "None for creation, the current revision for edits."
+ },
+ "operationId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Unique request identity retained across network retries."
+ },
+ "remindAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "One future instant; conditional recurrence is deliberately absent."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["set"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "Cancel and restore the conversation without leaving a future alert.",
+ "required": ["operationId", "expectedRevision", "type"],
+ "properties": {
+ "expectedRevision": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Reject removal if a newer edit has replaced this operation."
+ },
+ "operationId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Unique request identity."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["remove"]
+ },
+ "undo": {
+ "type": "boolean",
+ "description": "Undo restores original visibility; ordinary Remove returns to inbox."
+ }
+ }
+ }
+ ],
+ "description": "Idempotent email command. Reusing an operation ID with different data fails."
+ },
+ "EmailFollowupResponse": {
+ "type": "object",
+ "description": "Lookup response, including an email with no follow-up yet.",
+ "properties": {
+ "followup": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EmailFollowup",
+ "description": "Most recent specialized follow-up, if any."
+ }
+ ]
+ }
+ }
+ },
+ "EmailReminderCondition": {
+ "type": "string",
+ "description": "When an email follow-up should return the conversation.",
+ "enum": ["if_no_reply", "regardless"]
+ },
"EmptyResponse": {
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
@@ -24777,6 +25025,18 @@
}
}
},
+ "FollowupState": {
+ "type": "string",
+ "description": "Durable progress of an email operation.",
+ "enum": [
+ "archiving",
+ "pending",
+ "returning",
+ "returned",
+ "cancelled",
+ "removed"
+ ]
+ },
"ForeignEntity": {
"type": "object",
"description": "A persisted mapping to an entity owned by an external system.",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index e2a8f2a59b..8d6ac7a605 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -356,6 +356,9 @@ export const storageExcluded = [
] as const satisfies readonly (keyof StorageSdk)[];
export const storageBacklog = [
+ // Email follow-ups are available through the generated client, like reminders.
+ 'getEmailFollowup',
+ 'setEmailFollowup',
'approveHarnessPairing',
'assignInitiativeTasks',
'claimHarnessPairing',
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 00165ecff5..fb154f4980 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -429,7 +429,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
entity_access_service.clone(),
document_tool_context.service.clone(),
chat_tool_context.service.clone(),
- user_email_service,
+ user_email_service.clone(),
);
let initiative_tool_context = ai_tools::build_initiative_tool_context(
@@ -466,6 +466,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
notification_tool_context: notification_tool_context.clone(),
reminders_tool_context: ai_tools::build_reminders_tool_context(
pool.clone(),
+ user_email_service.clone(),
entity_access_service.clone(),
),
import_tool_context: ai_tools::ToolImportToolContext::unwired(),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index f6ec037ed8..c9e8f8b2af 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -647,7 +647,7 @@ async fn main() -> anyhow::Result<()> {
entity_access_service.clone(),
document_tool_context.service.clone(),
chat_tool_context.service.clone(),
- user_email_service,
+ user_email_service.clone(),
);
let initiative_tool_context = ai_tools::build_initiative_tool_context(
@@ -685,6 +685,7 @@ async fn main() -> anyhow::Result<()> {
notification_tool_context: notification_tool_context.clone(),
reminders_tool_context: ai_tools::build_reminders_tool_context(
db.clone(),
+ user_email_service.clone(),
entity_access_service.clone(),
),
import_tool_context: import::inbound::toolset::ImportToolContext::wired(
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 989ff57559..9d456fb9b4 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -492,7 +492,13 @@ pub(crate) type DssUserApiKeyState =
UserApiKeyRouterState<UserApiKeyServiceType, AuthorizationService>;
/// Type alias for the reminders service.
-pub(crate) type RemindersServiceType = RemindersServiceImpl<PgRemindersRepo>;
+pub(crate) type RemindersServiceType =
+ reminders::domain::email_followup::reminder_service::EmailRemindersService<
+ RemindersServiceImpl<PgRemindersRepo>,
+ PgRemindersRepo,
+ DssEmailService,
+ reminders::domain::ports::SystemClock,
+ >;
/// Type alias for the reminders router state.
pub(crate) type DssRemindersState =
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 54e9961751..e8ac03c23b 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -387,6 +387,8 @@ use utoipa::OpenApi;
user_api_key::inbound::axum_router::delete_user_api_key_handler,
// reminders
+ reminders::inbound::axum_router::get_email_followup_handler,
+ reminders::inbound::axum_router::set_email_followup_handler,
reminders::inbound::axum_router::list_reminders_handler,
reminders::inbound::axum_router::create_reminder_handler,
reminders::inbound::axum_router::get_reminder_handler,
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 43a297326a..8b80e03b9c 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -1239,7 +1239,22 @@ async fn run() -> anyhow::Result<()> {
// Held by value here and behind an `Arc` in the router state: the impl is a
// pool handle, so cloning is cheap and `SoupImpl` needs an owned service.
- let reminders_service = RemindersServiceImpl::new(PgRemindersRepo::new(db.clone()));
+ // Additional connections for guards spanning email I/O. HTTP requests and
+ // dispatch share this budget, independently of the main data pool.
+ let followup_lock_capacity = match config.environment {
+ Environment::Production => 32,
+ Environment::Develop => 16,
+ Environment::Local => 8,
+ };
+ let email_followups = reminders::domain::email_followup::service::EmailFollowupService::new(
+ PgRemindersRepo::with_followup_lock_capacity(db.clone(), followup_lock_capacity),
+ email_service.clone(),
+ );
+ let reminders_service =
+ reminders::domain::email_followup::reminder_service::EmailRemindersService::new(
+ RemindersServiceImpl::new(PgRemindersRepo::new(db.clone())),
+ email_followups.clone(),
+ );
let document_creator = documents_hex::domain::create::DocumentCreator::new(
document_service.clone(),
@@ -1540,7 +1555,13 @@ async fn run() -> anyhow::Result<()> {
NotificationReminderNotifier::new((*notification_ingress_service).clone()),
queue.clone(),
);
- DispatchWorker::new(dispatch_service, queue)
+ DispatchWorker::new(
+ reminders::domain::email_followup::dispatch::EmailReminderDispatch::new(
+ dispatch_service,
+ email_followups.clone(),
+ ),
+ queue,
+ )
};
consumer_tracker.spawn({
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index bd4c2e7b84..d75d0c0688 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -376,7 +376,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
entity_access_service.clone(),
document_tool_context.service.clone(),
chat_tool_context.service.clone(),
- user_email_service,
+ user_email_service.clone(),
);
let search_service_client = Arc::new(search_service_client);
@@ -422,6 +422,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
notification_tool_context,
reminders_tool_context: ai_tools::build_reminders_tool_context(
db.clone(),
+ user_email_service.clone(),
entity_access_service.clone(),
),
import_tool_context: ToolImportToolContext::unwired(),