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(ai-tools): Email tools (#1796)

Evan Hutnik52862d9712b0
diff --git a/rust/cloud-storage/CLAUDE.md b/rust/cloud-storage/CLAUDE.md
index 2e0ea7d30c..8f028dba84 100644
--- a/rust/cloud-storage/CLAUDE.md
+++ b/rust/cloud-storage/CLAUDE.md
@@ -57,7 +57,7 @@ camelCased rather than snake_cased (use `/dump-schema` or check the migration fi
When a column is camelCased, you need to cast it as the snake_cased version when reading from the database. E.g.
`SELECT "userId" as "user_id" FROM "UserInsights"`.
Any time you make changes to the SQL code in rust, you need to run `just prepare_db` in
-`macro-api/cloud-storage/macro_db_client` to update the .sqlx.
+the root directory of the crate you made the changes in, to update the .sqlx directory.
## Development Commands
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index da8bffd93b..681f8de2d7 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3431,7 +3431,9 @@ dependencies = [
name = "email"
version = "0.1.0"
dependencies = [
+ "ai",
"anyhow",
+ "async-trait",
"authentication_service_client",
"axum",
"axum-extra",
@@ -3464,6 +3466,7 @@ dependencies = [
"thiserror 2.0.17",
"tokio",
"tracing",
+ "tracing-subscriber",
"utoipa",
"uuid",
]
diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.toml
index 9da6cd59ba..bd70d6356b 100644
--- a/rust/cloud-storage/deny.toml
+++ b/rust/cloud-storage/deny.toml
@@ -186,6 +186,7 @@ deny = [
"macro_aws_config",
], reason = "Use macro_aws_config for AWS configuration in workspace crates" },
{ crate = "tracing-subscriber", wrappers = [
+ "email", # Dev logging only
"lambda_runtime_api_client", # External crate allowed to use tracing-subscriber
"macro_entrypoint",
"notification_sandbox", # This is not production code its just tooling
diff --git a/rust/cloud-storage/email/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/email/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
new file mode 100644
index 0000000000..44d3a67e72
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json b/rust/cloud-storage/email/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
new file mode 100644
index 0000000000..60bfee0647
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json b/rust/cloud-storage/email/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
new file mode 100644
index 0000000000..58618b2697
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n -- CTE to recursively find all parent projects, starting from the given project.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project ID provided.\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n -- The hierarchy CTE includes the starting project, so this is all we need.\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n -- We only need to check ProjectPermission for the items in the hierarchy.\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json b/rust/cloud-storage/email/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
new file mode 100644
index 0000000000..524cc25ec7
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The chat itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-50318d6d13fb931307f2115b33d277b5298c45ed798719e792e722bd30615a95.json b/rust/cloud-storage/email/.sqlx/query-50318d6d13fb931307f2115b33d277b5298c45ed798719e792e722bd30615a95.json
new file mode 100644
index 0000000000..7a4d0490be
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-50318d6d13fb931307f2115b33d277b5298c45ed798719e792e722bd30615a95.json
@@ -0,0 +1,73 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, created_at, updated_at\n FROM email_links\n WHERE macro_id = $1\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 5,
+ "name": "is_sync_active",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "50318d6d13fb931307f2115b33d277b5298c45ed798719e792e722bd30615a95"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/email/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
new file mode 100644
index 0000000000..03a8dbf6bb
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/email/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
new file mode 100644
index 0000000000..655495fb29
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/email/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
new file mode 100644
index 0000000000..2bde15938f
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/email/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
new file mode 100644
index 0000000000..e42c9f2009
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json b/rust/cloud-storage/email/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
new file mode 100644
index 0000000000..2b67c5606d
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n -- CTE to recursively find all parent projects for the given email thread.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project directly associated with the thread.\n SELECT\n p.id as project_id\n FROM\n \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE\n etp.\"threadId\" = $1\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT\n parent.id as project_id\n FROM\n project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The thread ID itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json b/rust/cloud-storage/email/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json
new file mode 100644
index 0000000000..4c96ff0fd5
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE etp.\"threadId\" = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f"
+}
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 1b7b64223d..33501e32fb 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -5,7 +5,20 @@ publish = false
version = "0.1.0"
[features]
+all = [
+ "ai_tools",
+ "gmail_token",
+ "inbound",
+ "outbound",
+ "ports",
+]
ai_schema = ["dep:schemars"]
+ai_tools = [
+ "dep:ai",
+ "dep:async-trait",
+ "dep:schemars",
+ "ports",
+]
axum = [
"dep:axum",
"dep:axum-extra",
@@ -21,7 +34,9 @@ outbound = ["dep:sqlx", "ports"]
ports = ["dep:tokio", "frecency/ports"]
[dependencies]
+ai = { path = "../ai", optional = true }
anyhow = { workspace = true }
+async-trait = { workspace = true, optional = true }
base64 = { workspace = true }
entity_access = { path = "../entity_access" }
futures = { workspace = true }
@@ -57,5 +72,11 @@ utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
[dev-dependencies]
+frecency = { path = "../frecency", features = ["outbound", "postgres"] }
macro_db_migrator = { path = "../macro_db_migrator" }
serde_json = { workspace = true }
+tracing-subscriber = { workspace = true, features = ["env-filter"] }
+
+[[example]]
+name = "ai_tools_cli"
+required-features = ["all"]
diff --git a/rust/cloud-storage/email/examples/ai_tools_cli.rs b/rust/cloud-storage/email/examples/ai_tools_cli.rs
new file mode 100644
index 0000000000..df40e0d179
--- /dev/null
+++ b/rust/cloud-storage/email/examples/ai_tools_cli.rs
@@ -0,0 +1,114 @@
+//! CLI example for testing email AI tools interactively.
+//!
+//! This example creates a CLI interface to test the email toolset with real
+//! database connections and Gmail integration (for UpdateThreadLabels).
+//!
+//! # Usage
+//!
+//! ```bash
+//! DATABASE_URL=postgres://...
+//! ANTHROPIC_API_KEY=sk_abcdefl...
+//! LOCAL_USER_ID=macro|<email>
+//! REDIS_URL=redis://localhost:6379
+//! AUTHENTICATION_SERVICE_URL=http://...
+//! AUTHENTICATION_SERVICE_SECRET_KEY=...
+//! cargo run -p email --example ai_tools_cli --features all
+//! ```
+
+use ai::tool::tool_loop::cli::Cli;
+use ai::tool::types::RequestContext;
+use ai::types::Model;
+use email::domain::service::EmailServiceImpl;
+use email::inbound::toolset::{EmailToolContext, email_toolset};
+use email::outbound::{EmailPgRepo, GmailClientLabelModifier, GmailTokenProviderImpl};
+use frecency::domain::services::FrecencyQueryServiceImpl;
+use frecency::outbound::postgres::FrecencyPgStorage;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use std::sync::Arc;
+
+#[tokio::main]
+async fn main() {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("email=debug,ai=debug")),
+ )
+ .init();
+
+ let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
+ let usr = std::env::var("LOCAL_USER_ID").expect("LOCAL_USER_ID must be set");
+ let user_id: MacroUserIdStr<'static> = usr.try_into().expect("valid user id macro|<email>");
+ let redis_url =
+ std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6379".to_string());
+ let auth_service_url = std::env::var("AUTHENTICATION_SERVICE_URL")
+ .expect("AUTHENTICATION_SERVICE_URL must be set");
+ let auth_service_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY")
+ .expect("AUTHENTICATION_SERVICE_SECRET_KEY must be set");
+
+ println!(
+ "Running with\nuser [{}]\ndatabase [{}]\nredis [{}]\nauth_service [{}]",
+ user_id, database_url, redis_url, auth_service_url
+ );
+
+ let pool = PgPool::connect(&database_url)
+ .await
+ .expect("Failed to connect to database");
+
+ let redis_client = redis::Client::open(redis_url).expect("Failed to create redis client");
+ let redis_conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .expect("Failed to connect to redis");
+
+ let auth_service_client = Arc::new(authentication_service_client::AuthServiceClient::new(
+ auth_service_key,
+ auth_service_url,
+ ));
+
+ let gmail_token_provider =
+ Arc::new(GmailTokenProviderImpl::new(redis_conn, auth_service_client));
+ let gmail_client = Arc::new(gmail_client::GmailClient::new("unused".to_string()));
+ let gmail_label_modifier = GmailClientLabelModifier::new(gmail_client);
+
+ let frecency_storage = FrecencyPgStorage::new(pool.clone());
+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage);
+
+ let entity_access_service = Arc::new(
+ entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ ),
+ );
+
+ let email_repo = EmailPgRepo::new(pool);
+ let email_service = EmailServiceImpl::new(
+ email_repo,
+ frecency_service,
+ email::domain::ports::NoOpEnqueuer,
+ gmail_label_modifier,
+ 0,
+ );
+
+ let email_context = EmailToolContext::new(
+ Arc::new(email_service),
+ gmail_token_provider,
+ entity_access_service,
+ );
+ let toolset = email_toolset();
+
+ #[expect(deprecated)]
+ let context = RequestContext {
+ user_id: Arc::new(user_id),
+ jwt: Arc::new(String::new()),
+ };
+
+ let cli = Cli::new(
+ toolset,
+ email_context,
+ "You are an assistant that helps users manage their email. Use the available tools to list labels, add/remove labels from threads, create drafts, and read email threads.",
+ Model::Claude45Haiku,
+ move || context.clone(),
+ );
+
+ cli.run().await;
+}
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 2774313f4b..a0ba79b681 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -59,6 +59,11 @@ pub trait EmailRepo: Send + Sync + 'static {
provider: UserProvider,
) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
+ fn link_by_macro_id(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;
+
/// Fetch a thread by its database ID (without messages).
fn thread_by_id(
&self,
@@ -241,6 +246,12 @@ pub trait EmailService: Send + Sync + 'static {
macro_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
+ /// Fetch the email link for a user by their macro ID only.
+ fn get_link_by_macro_id(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;
+
/// Fetch a thread with paginated messages, verifying access via the provided receipt.
fn get_thread_with_messages(
&self,
@@ -311,6 +322,43 @@ pub trait GmailLabelModifier: Send + Sync + 'static {
) -> impl Future<Output = Result<(), EmailErr>> + Send;
}
+/// Port for fetching a Gmail access token for a given email link.
+///
+/// The domain service receives the token as an opaque `&str`. This trait
+/// allows the toolset layer to resolve tokens without depending on axum.
+pub trait GmailTokenProvider: Send + Sync + 'static {
+ /// Fetch a Gmail OAuth access token for the given email link.
+ fn fetch_gmail_access_token(
+ &self,
+ link: &Link,
+ ) -> impl Future<Output = Result<String, EmailErr>> + Send;
+
+ /// Fetch a Gmail OAuth access token directly from the auth service,
+ /// bypassing the Redis cache for reads but still caching the result.
+ fn fetch_gmail_access_token_no_cache(
+ &self,
+ link: &Link,
+ ) -> impl Future<Output = Result<String, EmailErr>> + Send;
+}
+
+/// No-op token provider for callers that don't need Gmail token resolution.
+#[derive(Clone)]
+pub struct NoOpGmailTokenProvider;
+
+impl GmailTokenProvider for NoOpGmailTokenProvider {
+ async fn fetch_gmail_access_token(&self, _link: &Link) -> Result<String, EmailErr> {
+ Err(EmailErr::ProviderErr(anyhow::anyhow!(
+ "Gmail token provider not configured"
+ )))
+ }
+
+ async fn fetch_gmail_access_token_no_cache(&self, _link: &Link) -> Result<String, EmailErr> {
+ Err(EmailErr::ProviderErr(anyhow::anyhow!(
+ "Gmail token provider not configured"
+ )))
+ }
+}
+
/// No-op label modifier for callers that don't need Gmail label operations.
#[derive(Clone)]
pub struct NoOpGmailLabelModifier;
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index a3d98a0de2..9c9e2dbdcd 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -77,6 +77,16 @@ where
.await
}
+ async fn get_link_by_macro_id(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Option<crate::domain::models::Link>, EmailErr> {
+ self.email_repo
+ .link_by_macro_id(macro_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
async fn get_thread_with_messages(
&self,
receipt: EntityAccessReceipt<ViewAccessLevel>,
diff --git a/rust/cloud-storage/email/src/inbound.rs b/rust/cloud-storage/email/src/inbound.rs
index a66cfff8b3..fedd10c42c 100644
--- a/rust/cloud-storage/email/src/inbound.rs
+++ b/rust/cloud-storage/email/src/inbound.rs
@@ -3,3 +3,6 @@ mod axum;
#[cfg(feature = "axum")]
pub use axum::*;
+
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
index 1f2132804a..30113f768f 100644
--- a/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/axum_impls.rs
@@ -1,7 +1,7 @@
use crate::{
domain::{
models::{EmailErr, Link, PreviewView},
- ports::EmailService,
+ ports::{EmailService, GmailTokenProvider},
},
inbound::{ApiSortMethod, EmailRouterState},
};
@@ -13,7 +13,6 @@ use axum::{
};
use axum_extra::extract::Cached;
use model_user::axum_extractor::{MacroUserExtractor, UserExtractorErr};
-use std::future::Future;
use std::sync::Arc;
use std::{marker::PhantomData, str::FromStr};
use thiserror::Error;
@@ -156,26 +155,6 @@ where
}
}
-/// Port for fetching a Gmail access token for a given link.
-///
-/// This is an inbound concern — the domain service receives the token as an
-/// opaque `&str`. The trait lives here (rather than in `domain::ports`)
-/// because only the axum extractor layer uses it.
-pub trait GmailTokenProvider: Send + Sync + 'static {
- /// Fetch a Gmail OAuth access token for the given email link.
- fn fetch_gmail_access_token(
- &self,
- link: &Link,
- ) -> impl Future<Output = Result<String, EmailErr>> + Send;
-
- /// Fetch a Gmail OAuth access token directly from the auth service,
- /// bypassing the Redis cache for reads but still caching the result.
- fn fetch_gmail_access_token_no_cache(
- &self,
- link: &Link,
- ) -> impl Future<Output = Result<String, EmailErr>> + Send;
-}
-
/// Axum state wrapper for a [`GmailTokenProvider`] implementation.
pub struct GmailTokenState<T> {
pub(crate) inner: Arc<T>,
diff --git a/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
index 6da2595d7a..b0db89237c 100644
--- a/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/thread_labels_router.rs
@@ -9,9 +9,12 @@ use model_error_response::ErrorResponse;
use thiserror::Error;
use uuid::Uuid;
-use crate::domain::{models::EmailErr, ports::EmailService};
+use crate::domain::{
+ models::EmailErr,
+ ports::{EmailService, GmailTokenProvider},
+};
-use super::{EmailRouterState, GmailAccessTokenExtractor, GmailTokenProvider, GmailTokenState};
+use super::{EmailRouterState, GmailAccessTokenExtractor, GmailTokenState};
/// Request body for updating a thread's labels.
#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
diff --git a/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs b/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
new file mode 100644
index 0000000000..683696cfc6
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/toolset/create_draft.rs
@@ -0,0 +1,144 @@
+//! CreateDraft tool for composing a new email draft.
+
+use crate::domain::{
+ models::{ContactInfo, CreateDraftInput},
+ ports::{EmailService, GmailTokenProvider},
+};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::EmailToolContext;
+
+/// A recipient for an email draft.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DraftRecipient {
+ /// The recipient's email address.
+ pub email: String,
+ /// The recipient's display name (optional).
+ #[serde(default)]
+ pub name: Option<String>,
+}
+
+impl From<DraftRecipient> for ContactInfo {
+ fn from(r: DraftRecipient) -> Self {
+ ContactInfo {
+ email: r.email,
+ name: r.name,
+ photo_url: None,
+ }
+ }
+}
+
+/// Create a new email draft. The draft is saved but NOT sent.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[schemars(
+ title = "CreateDraft",
+ description = "Create a new email draft that is saved but NOT sent. Use this to compose emails on behalf of the user. The user can review and send the draft themselves. To reply to an existing message, provide the replying_to_id. The body must be plain text only — do not use HTML, Markdown, or any formatting syntax (no **bold**, *italics*, headings, etc.). Just write natural prose with line breaks."
+)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateDraft {
+ /// The subject line of the email.
+ pub subject: String,
+ /// The plain text body of the email.
+ pub body: String,
+ /// The primary recipients (To field).
+ pub to: Vec<DraftRecipient>,
+ /// Carbon copy recipients (optional).
+ #[serde(default)]
+ pub cc: Vec<DraftRecipient>,
+ /// Blind carbon copy recipients (optional).
+ #[serde(default)]
+ pub bcc: Vec<DraftRecipient>,
+ /// The ID of a message to reply to (optional). When set, the draft is
+ /// created as a reply within the same thread.
+ #[serde(default)]
+ pub replying_to_id: Option<Uuid>,
+}
+
+/// Response from the CreateDraft tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateDraftResponse {
+ /// The database ID of the newly created draft.
+ pub draft_id: Uuid,
+ /// The thread ID the draft belongs to.
+ pub thread_id: Uuid,
+ /// A human-readable summary of the draft.
+ pub summary: String,
+}
+
+#[async_trait]
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for CreateDraft
+where
+ T: EmailService,
+ G: GmailTokenProvider,
+ E: EntityAccessService,
+{
+ type Output = CreateDraftResponse;
+
+ #[tracing::instrument(skip_all, fields(
+ user_id=?request_context.user_id,
+ subject=%self.subject,
+ to_count=%self.to.len(),
+ ), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<EmailToolContext<T, G, E>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("Create draft");
+
+ let link = service_context
+ .resolve_link((*request_context.user_id).clone())
+ .await?;
+
+ let input = CreateDraftInput {
+ db_id: None,
+ provider_id: None,
+ replying_to_id: self.replying_to_id,
+ provider_thread_id: None,
+ thread_db_id: None,
+ subject: self.subject.clone(),
+ to: self.to.iter().cloned().map(ContactInfo::from).collect(),
+ cc: self.cc.iter().cloned().map(ContactInfo::from).collect(),
+ bcc: self.bcc.iter().cloned().map(ContactInfo::from).collect(),
+ body_text: Some(self.body.clone()),
+ body_html: None,
+ body_macro: None,
+ headers_json: None,
+ send_time: None,
+ };
+
+ let created = service_context
+ .service
+ .create_draft(&link, input)
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to create draft: {e}"),
+ internal_error: e.into(),
+ })?;
+
+ let to_display: Vec<&str> = self.to.iter().map(|r| r.email.as_str()).collect();
+ let reply_note = if self.replying_to_id.is_some() {
+ " (reply)"
+ } else {
+ ""
+ };
+ let summary = format!(
+ "Draft{reply_note} created with subject \"{}\" to {}.",
+ self.subject,
+ to_display.join(", ")
+ );
+
+ Ok(CreateDraftResponse {
+ draft_id: created.db_id,
+ thread_id: created.thread_db_id,
+ summary,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs b/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs
new file mode 100644
index 0000000000..acbba3880f
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/toolset/get_thread.rs
@@ -0,0 +1,178 @@
+//! GetThread tool for retrieving an email thread with its messages.
+
+use crate::domain::{
+ models::{ContactInfo, ParsedMessage, ParsedThread},
+ ports::{EmailService, GmailTokenProvider},
+};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::{
+ models::{EntityType, ViewAccessLevel},
+ ports::EntityAccessService,
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::EmailToolContext;
+
+/// A simplified message for tool output.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolMessage {
+ /// The message's unique identifier.
+ pub id: Uuid,
+ /// The message subject.
+ pub subject: Option<String>,
+ /// The sender's email and name.
+ pub from: Option<ToolContact>,
+ /// The To recipients.
+ pub to: Vec<ToolContact>,
+ /// The Cc recipients.
+ pub cc: Vec<ToolContact>,
+ /// The parsed plaintext body (reply/forwarded content stripped, HTML converted).
+ pub body_parsed: Option<String>,
+ /// When the message was received/sent.
+ pub date: Option<String>,
+}
+
+/// A simplified contact for tool output.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolContact {
+ /// The contact's email address.
+ pub email: String,
+ /// The contact's display name.
+ pub name: Option<String>,
+}
+
+impl From<ContactInfo> for ToolContact {
+ fn from(c: ContactInfo) -> Self {
+ Self {
+ email: c.email,
+ name: c.name,
+ }
+ }
+}
+
+impl From<ParsedMessage> for ToolMessage {
+ fn from(m: ParsedMessage) -> Self {
+ Self {
+ id: m.db_id,
+ subject: m.subject,
+ from: m.from.map(ToolContact::from),
+ to: m.to.into_iter().map(ToolContact::from).collect(),
+ cc: m.cc.into_iter().map(ToolContact::from).collect(),
+ body_parsed: m.body_parsed,
+ date: m.internal_date_ts.map(|t| t.to_rfc3339()),
+ }
+ }
+}
+
+/// Response from the GetThread tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GetThreadResponse {
+ /// The thread's unique identifier.
+ pub thread_id: Uuid,
+ /// Whether the thread has been read.
+ pub is_read: bool,
+ /// The messages in the thread (most recent first).
+ pub messages: Vec<ToolMessage>,
+ /// A human-readable summary.
+ pub summary: String,
+}
+
+/// The default number of messages to retrieve.
+const DEFAULT_LIMIT: i64 = 10;
+
+/// Retrieve an email thread and its messages.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[schemars(
+ title = "GetThread",
+ description = "Retrieve an email thread and its messages. Returns the thread metadata and message contents including sender, recipients, subject, and body text. Use this to read the contents of a specific email conversation."
+)]
+#[serde(rename_all = "camelCase")]
+pub struct GetThread {
+ /// The ID of the email thread to retrieve.
+ pub thread_id: Uuid,
+ /// Maximum number of messages to return (default 10).
+ #[serde(default)]
+ pub limit: Option<i64>,
+}
+
+#[async_trait]
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for GetThread
+where
+ T: EmailService,
+ G: GmailTokenProvider,
+ E: EntityAccessService,
+{
+ type Output = GetThreadResponse;
+
+ #[tracing::instrument(skip_all, fields(
+ user_id=?request_context.user_id,
+ thread_id=%self.thread_id,
+ ), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<EmailToolContext<T, G, E>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("Get thread");
+
+ let receipt = service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &request_context.user_id,
+ None,
+ &self.thread_id.to_string(),
+ EntityType::EmailThread,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Access denied for thread: {e}"),
+ internal_error: e.into(),
+ })?;
+
+ let limit = self.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, 100);
+
+ let thread = service_context
+ .service
+ .get_thread_parsed(receipt, 0, limit)
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to get thread: {e}"),
+ internal_error: e.into(),
+ })?
+ .ok_or_else(|| ToolCallError {
+ description: "Thread not found.".to_string(),
+ internal_error: anyhow::anyhow!("Thread not found"),
+ })?;
+
+ let summary = build_summary(&thread);
+ let messages: Vec<ToolMessage> =
+ thread.messages.into_iter().map(ToolMessage::from).collect();
+
+ Ok(GetThreadResponse {
+ thread_id: thread.row.db_id,
+ is_read: thread.row.is_read,
+ messages,
+ summary,
+ })
+ }
+}
+
+fn build_summary(thread: &ParsedThread) -> String {
+ let msg_count = thread.messages.len();
+ let subject = thread
+ .messages
+ .first()
+ .and_then(|m| m.subject.as_deref())
+ .unwrap_or("(no subject)");
+
+ format!(
+ "Thread with {msg_count} message{} — subject: \"{subject}\".",
+ if msg_count == 1 { "" } else { "s" }
+ )
+}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
new file mode 100644
index 0000000000..92c9216683
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs
@@ -0,0 +1,124 @@
+//! ListLabels tool for listing a user's email labels.
+
+use crate::domain::{
+ models::{LabelType, LinkLabel},
+ ports::{EmailService, GmailTokenProvider},
+};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::EmailToolContext;
+
+/// A simplified label for tool output.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolLabel {
+ /// The label's unique identifier.
+ pub id: Uuid,
+ /// The display name of the label.
+ pub name: String,
+ /// Whether this is a "system" or "user" label.
+ #[serde(rename = "type")]
+ pub type_: String,
+}
+
+impl From<LinkLabel> for ToolLabel {
+ fn from(label: LinkLabel) -> Self {
+ let type_ = match label.type_ {
+ LabelType::System => "system".to_string(),
+ LabelType::User => "user".to_string(),
+ };
+ Self {
+ id: label.id,
+ name: label.name,
+ type_,
+ }
+ }
+}
+
+/// Response from the ListLabels tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListLabelsResponse {
+ /// The user's email labels.
+ pub labels: Vec<ToolLabel>,
+ /// A human-readable summary of the labels.
+ pub summary: String,
+}
+
+/// List the user's email labels (INBOX, SENT, custom labels, etc.).
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[schemars(
+ title = "ListLabels",
+ description = "List the user's email labels including system labels (INBOX, SENT, DRAFTS, etc.) and any custom user-created labels. Use this to understand how the user's email is organized before filtering or searching by label."
+)]
+pub struct ListLabels {}
+
+#[async_trait]
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for ListLabels
+where
+ T: EmailService,
+ G: GmailTokenProvider,
+ E: EntityAccessService,
+{
+ type Output = ListLabelsResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<EmailToolContext<T, G, E>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("List labels");
+
+ let link = service_context
+ .resolve_link((*request_context.user_id).clone())
+ .await?;
+
+ let labels = service_context
+ .service
+ .list_labels(&link)
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to list labels: {e}"),
+ internal_error: e.into(),
+ })?;
+
+ let tool_labels: Vec<ToolLabel> = labels.into_iter().map(ToolLabel::from).collect();
+ let summary = build_summary(&tool_labels);
+
+ Ok(ListLabelsResponse {
+ labels: tool_labels,
+ summary,
+ })
+ }
+}
+
+pub(super) fn build_summary(labels: &[ToolLabel]) -> String {
+ if labels.is_empty() {
+ return "No email labels found.".to_string();
+ }
+
+ let system_count = labels.iter().filter(|l| l.type_ == "system").count();
+ let user_count = labels.iter().filter(|l| l.type_ == "user").count();
+
+ let mut parts = Vec::new();
+ if system_count > 0 {
+ parts.push(format!(
+ "{system_count} system label{}",
+ if system_count == 1 { "" } else { "s" }
+ ));
+ }
+ if user_count > 0 {
+ parts.push(format!(
+ "{user_count} custom label{}",
+ if user_count == 1 { "" } else { "s" }
+ ));
+ }
+
+ format!("Found {}.", parts.join(" and "))
+}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/mod.rs b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..117f91f4a8
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/toolset/mod.rs
@@ -0,0 +1,108 @@
+//! Toolset inbound adapter for the Email service.
+
+mod create_draft;
+mod get_thread;
+mod list_labels;
+mod update_thread_labels;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ models::Link,
+ ports::{EmailService, GmailTokenProvider},
+};
+use ai::tool::{AsyncToolSet, ToolCallError};
+use entity_access::domain::ports::EntityAccessService;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Arc;
+
+pub use create_draft::{CreateDraft, CreateDraftResponse};
+pub use get_thread::{GetThread, GetThreadResponse};
+pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
+pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};
+
+/// Service context for email AI tools.
+pub struct EmailToolContext<
+ T: EmailService,
+ G: GmailTokenProvider = crate::domain::ports::NoOpGmailTokenProvider,
+ E: EntityAccessService = entity_access::domain::service::EntityAccessServiceImpl<
+ entity_access::outbound::PgAccessRepository,
+ >,
+> {
+ /// The email service instance.
+ pub service: Arc<T>,
+ /// The Gmail token provider for resolving OAuth access tokens.
+ pub token_provider: Arc<G>,
+ /// The entity access service for verifying thread access.
+ pub entity_access_service: Arc<E>,
+}
+
+impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> Clone
+ for EmailToolContext<T, G, E>
+{
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ token_provider: self.token_provider.clone(),
+ entity_access_service: self.entity_access_service.clone(),
+ }
+ }
+}
+
+impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> EmailToolContext<T, G, E> {
+ /// Create a new email tool context.
+ pub fn new(service: Arc<T>, token_provider: Arc<G>, entity_access_service: Arc<E>) -> Self {
+ Self {
+ service,
+ token_provider,
+ entity_access_service,
+ }
+ }
+
+ /// Resolve the user's email link from their macro ID.
+ ///
+ /// This is shared across all email tools that need an authenticated link.
+ pub async fn resolve_link(&self, macro_id: MacroUserIdStr<'_>) -> Result<Link, ToolCallError> {
+ self.service
+ .get_link_by_macro_id(macro_id)
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to resolve email link: {e}"),
+ internal_error: e.into(),
+ })?
+ .ok_or_else(|| ToolCallError {
+ description: "No email account linked for this user.".to_string(),
+ internal_error: anyhow::anyhow!("No email link found for user"),
+ })
+ }
+
+ /// Resolve a Gmail OAuth access token for the given link.
+ pub async fn resolve_access_token(&self, link: &Link) -> Result<String, ToolCallError> {
+ self.token_provider
+ .fetch_gmail_access_token(link)
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to fetch Gmail access token: {e}"),
+ internal_error: e.into(),
+ })
+ }
+}
+
+/// Create an email toolset.
+pub fn email_toolset<T, G, E>() -> AsyncToolSet<EmailToolContext<T, G, E>>
+where
+ T: EmailService,
+ G: GmailTokenProvider,
+ E: EntityAccessService,
+{
+ AsyncToolSet::new()
+ .add_tool::<ListLabels, EmailToolContext<T, G, E>>()
+ .expect("failed to add ListLabels tool")
+ .add_tool::<UpdateThreadLabels, EmailToolContext<T, G, E>>()
+ .expect("failed to add UpdateThreadLabels tool")
+ .add_tool::<CreateDraft, EmailToolContext<T, G, E>>()
+ .expect("failed to add CreateDraft tool")
+ .add_tool::<GetThread, EmailToolContext<T, G, E>>()
+ .expect("failed to add GetThread tool")
+}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/test.rs b/rust/cloud-storage/email/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..b5bc3ad310
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/toolset/test.rs
@@ -0,0 +1,116 @@
+use super::list_labels::build_summary;
+use super::*;
+use ai::generate_tool_input_schema;
+use ai::tool::types::tool_object::validate_tool_schema;
+
+#[test]
+fn test_list_labels_schema_validation() {
+ let schema = generate_tool_input_schema!(ListLabels);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "ListLabels",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("email labels"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_build_summary_empty() {
+ let summary = build_summary(&[]);
+ assert_eq!(summary, "No email labels found.");
+}
+
+#[test]
+fn test_build_summary_with_labels() {
+ let labels = vec![
+ ToolLabel {
+ id: uuid::Uuid::new_v4(),
+ name: "INBOX".to_string(),
+ type_: "system".to_string(),
+ },
+ ToolLabel {
+ id: uuid::Uuid::new_v4(),
+ name: "SENT".to_string(),
+ type_: "system".to_string(),
+ },
+ ToolLabel {
+ id: uuid::Uuid::new_v4(),
+ name: "Work".to_string(),
+ type_: "user".to_string(),
+ },
+ ];
+
+ let summary = build_summary(&labels);
+ assert!(summary.contains("2 system labels"));
+ assert!(summary.contains("1 custom label"));
+ assert!(summary.starts_with("Found"));
+}
+
+#[test]
+fn test_update_thread_labels_schema_validation() {
+ let schema = generate_tool_input_schema!(UpdateThreadLabels);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "UpdateThreadLabels",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("label"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_create_draft_schema_validation() {
+ let schema = generate_tool_input_schema!(CreateDraft);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "CreateDraft",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("draft"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_get_thread_schema_validation() {
+ let schema = generate_tool_input_schema!(GetThread);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "GetThread",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("thread"),
+ "Description should contain expected text"
+ );
+}
+
+// run `cargo test -p email inbound::toolset::test::print_input_schema -- --nocapture --include-ignored`
+#[test]
+#[ignore = "prints the input schema"]
+fn print_input_schema() {
+ let schema = generate_tool_input_schema!(ListLabels);
+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());
+}
diff --git a/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs
new file mode 100644
index 0000000000..748e5b2f46
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs
@@ -0,0 +1,101 @@
+//! UpdateThreadLabels tool for adding or removing a label from all messages in a thread.
+
+use crate::domain::ports::{EmailService, GmailTokenProvider};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::EmailToolContext;
+
+/// Add or remove a label from all messages in an email thread.
+#[derive(Debug, Deserialize, JsonSchema, Clone)]
+#[schemars(
+ title = "UpdateThreadLabels",
+ description = "Add or remove a label from all messages in an email thread. Use ListLabels first to get valid label IDs. Set `add` to true to apply the label, or false to remove it."
+)]
+pub struct UpdateThreadLabels {
+ /// The ID of the email thread to modify.
+ pub thread_id: Uuid,
+ /// The ID of the label to add or remove. Use ListLabels to get valid label IDs.
+ pub label_id: Uuid,
+ /// Whether to add (true) or remove (false) the label.
+ pub add: bool,
+}
+
+/// Response from the UpdateThreadLabels tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateThreadLabelsResponse {
+ /// The number of messages successfully updated.
+ pub successful_count: usize,
+ /// The number of messages that failed to update.
+ pub failed_count: usize,
+ /// A human-readable summary of the operation.
+ pub summary: String,
+}
+
+#[async_trait]
+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for UpdateThreadLabels
+where
+ T: EmailService,
+ G: GmailTokenProvider,
+ E: EntityAccessService,
+{
+ type Output = UpdateThreadLabelsResponse;
+
+ #[tracing::instrument(skip_all, fields(
+ user_id=?request_context.user_id,
+ thread_id=%self.thread_id,
+ label_id=%self.label_id,
+ add=%self.add,
+ ), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<EmailToolContext<T, G, E>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("Update thread labels");
+
+ let link = service_context
+ .resolve_link((*request_context.user_id).clone())
+ .await?;
+
+ let access_token = service_context.resolve_access_token(&link).await?;
+
+ let result = service_context
+ .service
+ .update_thread_labels(
+ &access_token,
+ &link,
+ self.thread_id,
+ self.label_id,
+ self.add,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to update thread labels: {e}"),
+ internal_error: e.into(),
+ })?;
+
+ let action = if self.add { "added to" } else { "removed from" };
+ let successful_count = result.successful_ids.len();
+ let failed_count = result.failed_ids.len();
+
+ let summary = if failed_count == 0 {
+ format!("Label successfully {action} {successful_count} message(s).")
+ } else {
+ format!(
+ "Label {action} {successful_count} message(s), but failed for {failed_count} message(s)."
+ )
+ };
+
+ Ok(UpdateThreadLabelsResponse {
+ successful_count,
+ failed_count,
+ summary,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
index e959ae9f27..45d9fe0d13 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/link.rs
@@ -36,3 +36,28 @@ pub(super) async fn link_by_fusionauth_and_macro_id(
.transpose()
.map_err(|e| sqlx::Error::Decode(Box::new(e)))
}
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn link_by_macro_id(
+ pool: &PgPool,
+ macro_id: MacroUserIdStr<'_>,
+) -> Result<Option<Link>, sqlx::Error> {
+ let db_link: Option<DbLink> = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
+ is_sync_active, created_at, updated_at
+ FROM email_links
+ WHERE macro_id = $1
+ LIMIT 1
+ "#,
+ macro_id.as_ref()
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ db_link
+ .map(|v: DbLink| v.try_into_model())
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
index 5e48568d38..3bf985c437 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs
@@ -74,6 +74,13 @@ impl EmailRepo for EmailPgRepo {
.await
}
+ async fn link_by_macro_id(
+ &self,
+ macro_id: MacroUserIdStr<'_>,
+ ) -> Result<Option<Link>, Self::Err> {
+ link::link_by_macro_id(&self.pool, macro_id).await
+ }
+
async fn thread_by_id(&self, thread_id: Uuid) -> Result<Option<ThreadRow>, Self::Err> {
thread::thread_by_id(&self.pool, thread_id).await
}
diff --git a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
index ad26c3f8ce..327172a180 100644
--- a/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
+++ b/rust/cloud-storage/email/src/outbound/gmail_token_provider.rs
@@ -6,7 +6,7 @@ use redis::aio::MultiplexedConnection;
use std::sync::Arc;
use crate::domain::models::{EmailErr, Link};
-use crate::inbound::GmailTokenProvider;
+use crate::domain::ports::GmailTokenProvider;
/// Ten minutes less than the hour the token is valid for, for long-running jobs.
static GMAIL_ACCESS_TOKEN_EXPIRY_SECONDS: u64 = 3000;
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs
index 9a03873ea1..19d6445300 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs
@@ -217,25 +217,14 @@ pub async fn add_message_labels(
})?;
}
- // conditionally update thread metadata, depending on the label getting added
- if provider_label_ids.iter().any(|provider_id|
- // marking a message as INBOX could change the latest_inbound_message_ts or inbox_visible status
- provider_id == service::label::system_labels::INBOX
- // marking a message as SPAM/TRASH could change the latest_non_spam_message_ts
- || provider_id == service::label::system_labels::SPAM
- || provider_id == service::label::system_labels::TRASH
- // marking as marking a message as unread could change thread's is_read
- || provider_id == service::label::system_labels::UNREAD)
- {
- update_thread_metadata(&mut tx, thread_db_id, link.id)
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to update thread metadata".to_string()),
- })
- })?;
- }
+ update_thread_metadata(&mut tx, thread_db_id, link.id)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to update thread metadata".to_string()),
+ })
+ })?;
Ok::<(), ProcessingError>(())
}
@@ -290,22 +279,14 @@ pub async fn remove_message_labels(
})?;
}
- // conditionally update thread metadata, depending on the label getting added
- if provider_label_ids.iter().any(|provider_id| {
- provider_id == service::label::system_labels::INBOX
- || provider_id == service::label::system_labels::SPAM
- || provider_id == service::label::system_labels::TRASH
- || provider_id == service::label::system_labels::UNREAD
- }) {
- update_thread_metadata(&mut tx, thread_db_id, link.id)
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to update thread metadata"),
- })
- })?;
- }
+ update_thread_metadata(&mut tx, thread_db_id, link.id)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to update thread metadata"),
+ })
+ })?;
Ok::<(), ProcessingError>(())
}
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index 63c4efef9b..01f7135b3e 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -47,6 +47,13 @@ impl EmailService for NoopEmailService {
Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
}
+ async fn get_link_by_macro_id(
+ &self,
+ _macro_id: MacroUserIdStr<'_>,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
+ }
+
async fn get_thread_with_messages(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index e43620b69c..b7d8d657d9 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -91,6 +91,13 @@ impl EmailService for MockEmail {
}))
}
+ async fn get_link_by_macro_id(
+ &self,
+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
async fn get_thread_with_messages(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -216,6 +223,13 @@ impl EmailService for MockEmailLinkResult {
(self.get_link_result)()
}
+ async fn get_link_by_macro_id(
+ &self,
+ _macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,
+ ) -> Result<Option<email::domain::models::Link>, email::domain::models::EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
async fn get_thread_with_messages(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,