Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(search, multi-inbox): hook up search with multi-inbox in backend and email view (#3882)
gbirman16875f677cf7
diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.tsindex 55cc782e35..12a9a95a95 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts@@ -48,13 +48,15 @@ function filterDataToQueryFilters(data: QueryState): EntityFilters {include.threadId?.length ||include.emailSender?.length ||include.emailShared ||- include.emailImportance !== undefined+ include.emailImportance !== undefined ||+ include.emailLinkId?.length) {filters.email_filters = {email_thread_ids: include.threadId,senders: include.emailSender,shared: include.emailShared,importance: include.emailImportance,+ link_ids: include.emailLinkId,};}diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsxindex e18ac5269b..eef83e3dd8 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx@@ -10,6 +10,7 @@ import type { FilterContext } from '@app/component/next-soup/filters/configs/';import {compileToAst,NIL_UUID,+ type QueryState,} from '@app/component/next-soup/filters/filter-store';import type { SetPredicatesInput } from '@app/component/next-soup/filters/filter-store/predicates-store';import {@@ -272,18 +273,21 @@ export const SoupViewContextProvider: FlowComponent<}});- const soupBody = createMemo(() => {+ const applyInboxFilter = (state: QueryState): QueryState => {const inboxes = inboxFilter();- if (inboxes === undefined) return queryFilters.compile();- const state = queryFilters.state;- return compileToAst({+ if (inboxes === undefined) return state;+ return {...state,include: {...state.include,emailLinkId: inboxes.length ? inboxes : [NIL_UUID],},- });- });+ };+ };++ const soupBody = createMemo(() =>+ compileToAst(applyInboxFilter(queryFilters.state))+ );const [searchText, setSearchText] = useEntryState<string>('search.text', {default: props.initialSearchText ?? '',@@ -291,7 +295,7 @@ export const SoupViewContextProvider: FlowComponent<const search = createSearchState({soup,- filters: () => queryFilters.state,+ filters: () => applyInboxFilter(queryFilters.state),assignees: assigneeFilter,disableLocalSearch: props.disableLocalSearch,searchPaused,diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 279ce425d3..0e058050ae 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -348,6 +348,7 @@ export const useSearchResponseItemMapper = () => {id: result.thread_id,name,ownerId: result.owner_id,+ linkId: result.link_id,createdAt: result.created_at,updatedAt: result.updated_at,viewedAt: result.viewed_at,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex f38dcdfd15..c7c5224872 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -211,6 +211,7 @@ export const SearchToolResponse = z.object({is_draft: z.boolean(),is_important: z.boolean(),is_read: z.boolean(),+ link_id: z.string().uuid(),name: z.union([z.string(), z.null()]).optional(),owner_id: z.string(),participants: z.array(diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 09b5373b2a..7f856ee31b 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -1002,6 +1002,11 @@ export interface EmailSearchResponseItemWithMetadata {is_draft: boolean;is_important: boolean;is_read: boolean;+ /**+ * The inbox that owns the thread. Drives the multi-inbox indicator+ * when the caller has more than one inbox.+ */+ link_id: string;/*** Subject of the email thread*/diff --git a/js/app/packages/service-clients/service-search/generated/models/emailSearchResponseItem.ts b/js/app/packages/service-clients/service-search/generated/models/emailSearchResponseItem.tsindex c0520358fa..9387ba9f01 100644--- a/js/app/packages/service-clients/service-search/generated/models/emailSearchResponseItem.ts+++ b/js/app/packages/service-clients/service-search/generated/models/emailSearchResponseItem.ts@@ -21,6 +21,9 @@ This may be empty if the search result match was on the email subject only */These field names are being aligned across all item typesfor consistency in our data model. */id: string;+ /** The inbox that owns the thread. Drives the multi-inbox indicator+when the caller has more than one inbox. */+ link_id: string;/** Subject of the email thread */name?: EmailSearchResponseItemName;owner_id: string;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 93679f7145..caf00c05aa 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1388,6 +1388,7 @@"owner_id","thread_id","user_id",+ "link_id","email_message_search_results","participants"],@@ -1404,6 +1405,11 @@"format": "uuid","description": "Standardized fields that all item types will share.\nThese field names are being aligned across all item types\nfor consistency in our data model."},+ "link_id": {+ "type": "string",+ "format": "uuid",+ "description": "The inbox that owns the thread. Drives the multi-inbox indicator\nwhen the caller has more than one inbox."+ },"name": {"type": ["string", "null"],"description": "Subject of the email thread"diff --git a/rust/cloud-storage/.sqlx/query-039dd65419a635365c37d46699bf115e771ceae4526e0a13928152e2bb1bb9b3.json b/rust/cloud-storage/.sqlx/query-039dd65419a635365c37d46699bf115e771ceae4526e0a13928152e2bb1bb9b3.jsonnew file mode 100644index 0000000000..887d1272a9--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-039dd65419a635365c37d46699bf115e771ceae4526e0a13928152e2bb1bb9b3.json@@ -0,0 +1,107 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n t.id as thread_id,\n -- Return timestamps from the chosen messages directly\n COALESCE(earliest_msg.sent_at, earliest_msg.updated_at) as \"first_message_ts!\",\n COALESCE(latest_msg.sent_at, latest_msg.updated_at) as \"last_message_ts!\",\n -- Last time user viewed this thread\n uh.updated_at as \"viewed_at?\",\n latest_msg.snippet,\n earliest_msg.subject as \"subject?\",\n l.macro_id,\n t.link_id,\n latest_msg.sender as sender,\n latest_msg.pretty_sender as \"pretty_sender!\",\n latest_msg.trash_label as trash_label,\n (\n SELECT m_latest.is_draft\n FROM email_messages m_latest\n WHERE m_latest.thread_id = t.id\n AND m_latest.link_id = t.link_id\n ORDER BY m_latest.internal_date_ts DESC NULLS LAST\n LIMIT 1\n ) AS \"is_draft!\",\n t.is_read,\n t.inbox_visible,\n (\n SELECT 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 email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.link_id = t.link_id\n AND l.name = 'IMPORTANT'\n )\n ) AS \"is_important!\"\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 LEFT JOIN email_links l ON l.id = t.link_id\n -- LATERAL join for LATEST message\n -- JOIN (Inner) acts as a filter to ensure we only return threads that actually have messages\n JOIN LATERAL (\n SELECT\n m2.snippet,\n m2.sent_at,\n m2.updated_at,\n c.email_address as sender,\n COALESCE(c.name, c.email_address) as pretty_sender,\n EXISTS(\n SELECT 1 \n FROM email_message_labels eml \n JOIN email_labels el ON el.id = eml.label_id \n WHERE eml.message_id = m2.id \n AND el.provider_label_id = 'TRASH'\n ) as trash_label\n FROM email_messages m2\n LEFT JOIN email_contacts c ON c.id = m2.from_contact_id\n WHERE m2.thread_id = t.id\n AND m2.link_id = t.link_id\n ORDER BY\n (CASE WHEN m2.is_draft = false AND m2.sent_at IS NOT NULL THEN 0 ELSE 1 END) ASC,\n COALESCE(m2.sent_at, m2.updated_at) DESC NULLS LAST\n LIMIT 1\n ) latest_msg ON true\n -- LATERAL join for EARLIEST message\n LEFT JOIN LATERAL (\n SELECT\n m3.subject,\n m3.sent_at,\n m3.updated_at\n FROM email_messages m3\n WHERE m3.thread_id = t.id\n AND m3.link_id = t.link_id\n ORDER BY\n -- 1. Priority: Non-drafts with valid sent_at come first (0), everything else is fallback (1)\n (CASE WHEN m3.is_draft = false AND m3.sent_at IS NOT NULL THEN 0 ELSE 1 END) ASC,\n -- 2. Sort by time (Oldest first)\n COALESCE(m3.sent_at, m3.updated_at) ASC NULLS LAST\n LIMIT 1\n ) earliest_msg ON true\n WHERE t.id = ANY($2)\n AND t.link_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "first_message_ts!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "last_message_ts!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "viewed_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "snippet",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "subject?",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "macro_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 8,+ "name": "sender",+ "type_info": "Varchar"+ },+ {+ "ordinal": 9,+ "name": "pretty_sender!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 10,+ "name": "trash_label",+ "type_info": "Bool"+ },+ {+ "ordinal": 11,+ "name": "is_draft!",+ "type_info": "Bool"+ },+ {+ "ordinal": 12,+ "name": "is_read",+ "type_info": "Bool"+ },+ {+ "ordinal": 13,+ "name": "inbox_visible",+ "type_info": "Bool"+ },+ {+ "ordinal": 14,+ "name": "is_important!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ false,+ true,+ true,+ false,+ false,+ false,+ null,+ null,+ null,+ false,+ false,+ null+ ]+ },+ "hash": "039dd65419a635365c37d46699bf115e771ceae4526e0a13928152e2bb1bb9b3"+}diff --git a/rust/cloud-storage/.sqlx/query-c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932.json b/rust/cloud-storage/.sqlx/query-0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa.jsonsimilarity index 85%rename from rust/cloud-storage/.sqlx/query-c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932.jsonrename to rust/cloud-storage/.sqlx/query-0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa.jsonindex 7291ffb268..d80c3a400a 100644--- a/rust/cloud-storage/.sqlx/query-c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932.json+++ b/rust/cloud-storage/.sqlx/query-0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n m.id as message_id,\n c.email_address as \"sender!\",\n COALESCE(c.name, c.email_address) as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.id = ANY($1)\n AND m.link_id = $2\n ",+ "query": "\n SELECT\n m.id as message_id,\n c.email_address as \"sender!\",\n COALESCE(c.name, c.email_address) as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.id = ANY($1)\n AND m.link_id = ANY($2)\n ","describe": {"columns": [{@@ -22,14 +22,14 @@"parameters": {"Left": ["UuidArray",- "Uuid"+ "UuidArray"]},"nullable": [false,- false,+ true,null]},- "hash": "c4a1f6b77f876941ec74751bb5813c1328a3716c1d7adc6464b60ff6a3c3e932"+ "hash": "0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa"}diff --git a/rust/cloud-storage/.sqlx/query-86d971ef2350eb0120ca72cf4a7ecfd8ac7a04922066909603459467ace0788a.json b/rust/cloud-storage/.sqlx/query-86d971ef2350eb0120ca72cf4a7ecfd8ac7a04922066909603459467ace0788a.jsondeleted file mode 100644index 77306de147..0000000000--- a/rust/cloud-storage/.sqlx/query-86d971ef2350eb0120ca72cf4a7ecfd8ac7a04922066909603459467ace0788a.json+++ /dev/null@@ -1,101 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n t.id as thread_id,\n -- Return timestamps from the chosen messages directly\n COALESCE(earliest_msg.sent_at, earliest_msg.updated_at) as \"first_message_ts!\",\n COALESCE(latest_msg.sent_at, latest_msg.updated_at) as \"last_message_ts!\",\n -- Last time user viewed this thread\n uh.updated_at as \"viewed_at?\",\n latest_msg.snippet,\n earliest_msg.subject as \"subject?\",\n l.macro_id,\n latest_msg.sender as sender,\n latest_msg.pretty_sender as \"pretty_sender!\",\n latest_msg.trash_label as trash_label,\n (\n SELECT m_latest.is_draft\n FROM email_messages m_latest\n WHERE m_latest.thread_id = t.id\n AND m_latest.link_id = $1\n ORDER BY m_latest.internal_date_ts DESC NULLS LAST\n LIMIT 1\n ) AS \"is_draft!\",\n t.is_read,\n t.inbox_visible,\n (\n SELECT 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 email_labels l ON ml.label_id = l.id\n WHERE m_imp.thread_id = t.id\n AND l.link_id = t.link_id\n AND l.name = 'IMPORTANT'\n )\n ) AS \"is_important!\"\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1\n LEFT JOIN email_links l ON l.id = t.link_id\n -- LATERAL join for LATEST message\n -- JOIN (Inner) acts as a filter to ensure we only return threads that actually have messages\n JOIN LATERAL (\n SELECT\n m2.snippet,\n m2.sent_at,\n m2.updated_at,\n c.email_address as sender,\n COALESCE(c.name, c.email_address) as pretty_sender,\n EXISTS(\n SELECT 1 \n FROM email_message_labels eml \n JOIN email_labels el ON el.id = eml.label_id \n WHERE eml.message_id = m2.id \n AND el.provider_label_id = 'TRASH'\n ) as trash_label\n FROM email_messages m2\n LEFT JOIN email_contacts c ON c.id = m2.from_contact_id\n WHERE m2.thread_id = t.id\n AND m2.link_id = $1\n ORDER BY\n (CASE WHEN m2.is_draft = false AND m2.sent_at IS NOT NULL THEN 0 ELSE 1 END) ASC,\n COALESCE(m2.sent_at, m2.updated_at) DESC NULLS LAST\n LIMIT 1\n ) latest_msg ON true\n -- LATERAL join for EARLIEST message\n LEFT JOIN LATERAL (\n SELECT\n m3.subject,\n m3.sent_at,\n m3.updated_at\n FROM email_messages m3\n WHERE m3.thread_id = t.id\n AND m3.link_id = $1\n ORDER BY\n -- 1. Priority: Non-drafts with valid sent_at come first (0), everything else is fallback (1)\n (CASE WHEN m3.is_draft = false AND m3.sent_at IS NOT NULL THEN 0 ELSE 1 END) ASC,\n -- 2. Sort by time (Oldest first)\n COALESCE(m3.sent_at, m3.updated_at) ASC NULLS LAST\n LIMIT 1\n ) earliest_msg ON true\n WHERE t.id = ANY($2)\n AND t.link_id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "thread_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "first_message_ts!",- "type_info": "Timestamptz"- },- {- "ordinal": 2,- "name": "last_message_ts!",- "type_info": "Timestamptz"- },- {- "ordinal": 3,- "name": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 4,- "name": "snippet",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "subject?",- "type_info": "Text"- },- {- "ordinal": 6,- "name": "macro_id",- "type_info": "Text"- },- {- "ordinal": 7,- "name": "sender",- "type_info": "Varchar"- },- {- "ordinal": 8,- "name": "pretty_sender!",- "type_info": "Varchar"- },- {- "ordinal": 9,- "name": "trash_label",- "type_info": "Bool"- },- {- "ordinal": 10,- "name": "is_draft!",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_read",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "inbox_visible",- "type_info": "Bool"- },- {- "ordinal": 13,- "name": "is_important!",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "UuidArray"- ]- },- "nullable": [- false,- null,- null,- false,- true,- true,- false,- false,- null,- null,- null,- false,- false,- null- ]- },- "hash": "86d971ef2350eb0120ca72cf4a7ecfd8ac7a04922066909603459467ace0788a"-}diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rsindex e934b56512..bbe071e73c 100644--- a/rust/cloud-storage/email_db_client/src/messages/get.rs+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs@@ -18,7 +18,7 @@ use sqlx::types::Uuid;#[tracing::instrument(skip(pool), err)]pub async fn get_message_sender_and_pretty_sender(pool: &PgPool,- link_id: Uuid,+ link_ids: &[Uuid],message_ids: &[Uuid],) -> anyhow::Result<HashMap<Uuid, MessageSenderInfo>> {// TODO: use NonEmpty@@ -35,10 +35,10 @@ pub async fn get_message_sender_and_pretty_sender(FROM email_messages mLEFT JOIN email_contacts c ON c.id = m.from_contact_idWHERE m.id = ANY($1)- AND m.link_id = $2+ AND m.link_id = ANY($2)"#,message_ids,- link_id+ link_ids).fetch_all(pool).await?;diff --git a/rust/cloud-storage/email_db_client/src/user_history/mod.rs b/rust/cloud-storage/email_db_client/src/user_history/mod.rsindex a0ab4f77fd..33fe590b21 100644--- a/rust/cloud-storage/email_db_client/src/user_history/mod.rs+++ b/rust/cloud-storage/email_db_client/src/user_history/mod.rs@@ -52,7 +52,7 @@ where#[tracing::instrument(skip(pool), err)]pub async fn get_thread_summary_info(pool: &PgPool,- link_id: Uuid,+ link_ids: &[Uuid],thread_ids: &[Uuid],) -> anyhow::Result<HashMap<Uuid, ThreadHistoryInfo>> {if thread_ids.is_empty() {@@ -71,6 +71,7 @@ pub async fn get_thread_summary_info(latest_msg.snippet,earliest_msg.subject as "subject?",l.macro_id,+ t.link_id,latest_msg.sender as sender,latest_msg.pretty_sender as "pretty_sender!",latest_msg.trash_label as trash_label,@@ -78,7 +79,7 @@ pub async fn get_thread_summary_info(SELECT m_latest.is_draftFROM email_messages m_latestWHERE m_latest.thread_id = t.id- AND m_latest.link_id = $1+ AND m_latest.link_id = t.link_idORDER BY m_latest.internal_date_ts DESC NULLS LASTLIMIT 1) AS "is_draft!",@@ -96,7 +97,7 @@ pub async fn get_thread_summary_info()) AS "is_important!"FROM email_threads t- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_idLEFT JOIN email_links l ON l.id = t.link_id-- LATERAL join for LATEST message-- JOIN (Inner) acts as a filter to ensure we only return threads that actually have messages@@ -117,7 +118,7 @@ pub async fn get_thread_summary_info(FROM email_messages m2LEFT JOIN email_contacts c ON c.id = m2.from_contact_idWHERE m2.thread_id = t.id- AND m2.link_id = $1+ AND m2.link_id = t.link_idORDER BY(CASE WHEN m2.is_draft = false AND m2.sent_at IS NOT NULL THEN 0 ELSE 1 END) ASC,COALESCE(m2.sent_at, m2.updated_at) DESC NULLS LAST@@ -131,7 +132,7 @@ pub async fn get_thread_summary_info(m3.updated_atFROM email_messages m3WHERE m3.thread_id = t.id- AND m3.link_id = $1+ AND m3.link_id = t.link_idORDER BY-- 1. Priority: Non-drafts with valid sent_at come first (0), everything else is fallback (1)(CASE WHEN m3.is_draft = false AND m3.sent_at IS NOT NULL THEN 0 ELSE 1 END) ASC,@@ -140,9 +141,9 @@ pub async fn get_thread_summary_info(LIMIT 1) earliest_msg ON trueWHERE t.id = ANY($2)- AND t.link_id = $1+ AND t.link_id = ANY($1)"#,- link_id,+ link_ids,thread_ids).fetch_all(pool)@@ -160,6 +161,7 @@ pub async fn get_thread_summary_info(let summary_info = ThreadHistoryInfo {item_id: row.thread_id,user_id: row.macro_id,+ link_id: row.link_id,subject: row.subject,snippet: row.snippet,created_at: row.first_message_ts,diff --git a/rust/cloud-storage/email_db_client/src/user_history/test.rs b/rust/cloud-storage/email_db_client/src/user_history/test.rsindex 9136d7404c..a102132e08 100644--- a/rust/cloud-storage/email_db_client/src/user_history/test.rs+++ b/rust/cloud-storage/email_db_client/src/user_history/test.rs@@ -14,7 +14,7 @@ async fn get_thread_summary_info_all_non_drafts_with_sent_at(pool: Pool<Postgreslet link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000301")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -44,7 +44,7 @@ async fn get_thread_summary_info_all_drafts_fallback_to_updated_at(let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000302")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -74,7 +74,7 @@ async fn get_thread_summary_info_mixed_drafts_ignores_draft_timestamps(let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000303")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -108,7 +108,7 @@ async fn get_thread_summary_info_single_message_same_first_and_last(let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000305")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -136,7 +136,7 @@ async fn get_thread_summary_info_partial_sent_at_prefers_sent_at_over_updated_atlet link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000306")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -173,7 +173,7 @@ async fn get_thread_summary_info_multiple_threads(pool: Pool<Postgres>) -> ResulUuid::parse_str("00000000-0000-0000-0000-000000000305")?,];- let result = get_thread_summary_info(&pool, link_id, &thread_ids).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &thread_ids).await?;// Should return info for all 3 threadsassert_eq!(result.len(), 3);@@ -196,7 +196,7 @@ async fn get_thread_summary_info_empty_thread_ids_returns_empty(let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_ids: Vec<Uuid> = vec![];- let result = get_thread_summary_info(&pool, link_id, &thread_ids).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &thread_ids).await?;assert_eq!(result.len(), 0);@@ -213,7 +213,7 @@ async fn get_thread_summary_info_viewed_at_logic(pool: Pool<Postgres>) -> Resultlet link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000301")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -238,7 +238,7 @@ async fn get_thread_summary_info_subject_is_from_earliest_message(let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000307")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert_eq!(result.len(), 1);let info = result.get(&thread_id).unwrap();@@ -265,7 +265,7 @@ async fn get_thread_summary_info_filter_out_trash(pool: Pool<Postgres>) -> Resullet link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000308")?;- let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;+ let result = get_thread_summary_info(&pool, &[link_id], &[thread_id]).await?;assert!(result.is_empty());diff --git a/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rs b/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rsindex 004c833558..937c916efc 100644--- a/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rs+++ b/rust/cloud-storage/email_service/src/api/internal/get_message_senders.rs@@ -49,7 +49,7 @@ pub async fn handler(let sender_map = email_db_client::messages::get::get_message_sender_and_pretty_sender(&ctx.db,- link.id,+ &[link.id],&req_body.message_ids,).await?;diff --git a/rust/cloud-storage/email_service/src/api/internal/get_thread_histories.rs b/rust/cloud-storage/email_service/src/api/internal/get_thread_histories.rsindex 2f0afe94b2..5a19a6603e 100644--- a/rust/cloud-storage/email_service/src/api/internal/get_thread_histories.rs+++ b/rust/cloud-storage/email_service/src/api/internal/get_thread_histories.rs@@ -49,7 +49,7 @@ pub async fn handler(let history_map = email_db_client::user_history::get_thread_summary_info(&ctx.db,- link.id,+ &[link.id],&req_body.thread_ids,).await?;diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rsindex 3f4120ef14..83d81c791b 100644--- a/rust/cloud-storage/models_email/src/email/service/message.rs+++ b/rust/cloud-storage/models_email/src/email/service/message.rs@@ -345,6 +345,8 @@ pub struct ThreadHistoryInfo {pub viewed_at: Option<DateTime<Utc>>,pub snippet: Option<String>,pub user_id: String,+ /// The inbox that owns this thread.+ pub link_id: Uuid,pub subject: Option<String>,/// The sender of the latest email in the thread.pub sender: String,diff --git a/rust/cloud-storage/models_search/src/email.rs b/rust/cloud-storage/models_search/src/email.rsindex 56f83a1a56..88e60b1bcc 100644--- a/rust/cloud-storage/models_search/src/email.rs+++ b/rust/cloud-storage/models_search/src/email.rs@@ -62,6 +62,9 @@ pub struct EmailSearchResponseItem {pub thread_id: uuid::Uuid,/// The id of the owner of the email threadpub user_id: String,+ /// The inbox that owns the thread. Drives the multi-inbox indicator+ /// when the caller has more than one inbox.+ pub link_id: uuid::Uuid,/// The search results for the document/// This may be empty if the search result match was on the email subject onlypub email_message_search_results: Vec<EmailSearchResult>,diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rsindex 2e2b37e315..db4e4555a4 100644--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs@@ -115,6 +115,10 @@ pub struct SearchQueryBuilder<T: SearchQueryConfig> {pub page_size: u32,/// The user id to search forpub user_id: String,+ /// Additional user ids to filter access by. When non-empty the access+ /// filter matches any of these (terms) instead of the single `user_id`.+ /// Used for multi-inbox email search across delegated inboxes.+ pub user_ids: Vec<String>,/// Whether to collapse the results to be a single result per ID_KEY/// Defaults to false.pub collapse: bool,@@ -136,6 +140,7 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {page: 0,page_size: 10,user_id: String::new(),+ user_ids: Vec::new(),collapse: false,ids_only: false,ids: Vec::new(),@@ -169,6 +174,11 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {self}+ pub fn user_ids(mut self, user_ids: Vec<String>) -> Self {+ self.user_ids = user_ids;+ self+ }+pub fn collapse(mut self, collapse: bool) -> Self {self.collapse = collapse;self@@ -200,7 +210,11 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {} else {let user_id_key =user_id_key.ok_or(OpensearchClientError::UserIdKeyRequired(T::ENTITY_INDEX))?;- let user_id_query = QueryType::term(user_id_key.to_string(), self.user_id.clone());+ let user_id_query = if self.user_ids.is_empty() {+ QueryType::term(user_id_key.to_string(), self.user_id.clone())+ } else {+ QueryType::terms(user_id_key.to_string(), self.user_ids.clone())+ };// If there are no ids provided we can return only the user id query to filter overif self.ids.is_empty() {@@ -216,10 +230,7 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {filter_bool_query.should(QueryType::terms(T::ID_KEY.to_string(), self.ids.to_vec()));- filter_bool_query.should(QueryType::term(- user_id_key.to_string(),- self.user_id.clone(),- ));+ filter_bool_query.should(user_id_query);Ok(filter_bool_query.build().into())}diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex 63c46fd974..8c4a2d159a 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -136,6 +136,7 @@ impl EmailQueryBuilder {fn page(page: u32) -> Self;fn page_size(page_size: u32) -> Self;fn user_id(user_id: &str) -> Self;+ fn user_ids(user_ids: Vec<String>) -> Self;fn collapse(collapse: bool) -> Self;fn ids(ids: Vec<String>) -> Self;fn ids_only(ids_only: bool) -> Self;@@ -346,6 +347,7 @@ pub(crate) struct EmailIndex {pub struct EmailSearchArgs {pub terms: Vec<String>,pub user_id: String,+ pub user_ids: Vec<String>,pub thread_ids: Vec<String>,pub link_ids: Vec<String>,pub sender: Vec<String>,@@ -370,6 +372,7 @@ impl From<EmailSearchArgs> for EmailQueryBuilder {.page_size(args.page_size).page(args.page).user_id(&args.user_id)+ .user_ids(args.user_ids).ids(args.thread_ids).link_ids(args.link_ids).sender(args.sender)diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex 32df382619..078f25a420 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -97,6 +97,7 @@ fn test_email_search_args_quoted_phrase_uses_phrase_query_in_sqs() -> anyhow::Relet builder: EmailQueryBuilder = EmailSearchArgs {terms: vec!["reply test".to_string()],user_id: "macro|[email protected]".to_string(),+ user_ids: vec![],thread_ids: vec![],link_ids: vec![],sender: vec![],@@ -133,6 +134,7 @@ fn test_email_search_args_build_injects_simple_query_string() -> anyhow::Result<let builder: EmailQueryBuilder = EmailSearchArgs {terms: vec!["hello".to_string(), "test".to_string()],user_id: "macro|[email protected]".to_string(),+ user_ids: vec![],thread_ids: vec![],link_ids: vec![],sender: vec![],diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 22242bfcd7..bf1513f081 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -86,6 +86,7 @@ impl From<UnifiedSearchArgs> for EmailSearchArgs {EmailSearchArgs {terms: args.email_search_args.terms,user_id: args.user_id,+ user_ids: args.email_search_args.user_ids,page: args.page,page_size: args.page_size,match_type: args.match_type,@@ -175,6 +176,7 @@ pub struct UnifiedDocumentSearchArgs {#[derive(Debug, Default, Clone)]pub struct UnifiedEmailSearchArgs {pub terms: Vec<String>,+ pub user_ids: Vec<String>,pub thread_ids: Vec<String>,pub link_ids: Vec<String>,pub sender: Vec<String>,diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rsindex e2844e8e6f..4d2b35ae34 100644--- a/rust/cloud-storage/search_service/src/api/search/email.rs+++ b/rust/cloud-storage/search_service/src/api/search/email.rs@@ -27,18 +27,22 @@ pub(in crate::api::search) async fn enrich_emails(return Ok(vec![]);}- // Get the email link for this user- let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, user_id)+ // Resolve every inbox the user can access (their own + delegated) so hits+ // from delegated inboxes are enriched rather than dropped.+ let inboxes = email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, user_id).await- .map_err(SearchError::InternalError)?- .ok_or_else(|| SearchError::InternalError(anyhow::anyhow!("Link not found for user")))?;+ .map_err(SearchError::InternalError)?;+ if inboxes.is_empty() {+ return Ok(vec![]);+ }+ let link_ids: Vec<Uuid> = inboxes.iter().map(|l| l.id).collect();// Extract thread IDs from resultslet thread_ids: Vec<Uuid> = results.iter().map(|r| r.entity_id).collect();// Fetch email thread metadata directly from DBlet thread_histories =- email_db_client::user_history::get_thread_summary_info(&ctx.db, link.id, &thread_ids)+ email_db_client::user_history::get_thread_summary_info(&ctx.db, &link_ids, &thread_ids).await.map_err(SearchError::InternalError)?;@@ -60,7 +64,7 @@ pub(in crate::api::search) async fn enrich_emails(let (message_senders_map, contacts_map) = tokio::try_join!(email_db_client::messages::get::get_message_sender_and_pretty_sender(&ctx.db,- link.id,+ &link_ids,&message_ids,),email_db_client::contacts::get::fetch_contacts_by_thread_ids(&ctx.db, &thread_ids),@@ -169,6 +173,7 @@ pub fn construct_search_result(thread_id: entity_id,owner_id: info.user_id.clone(),user_id: info.user_id,+ link_id: info.link_id,name: info.subject.clone(),subject: info.subject,email_message_search_results: hits,diff --git a/rust/cloud-storage/search_service/src/api/search/email/test.rs b/rust/cloud-storage/search_service/src/api/search/email/test.rsindex 9581151570..1e98088313 100644--- a/rust/cloud-storage/search_service/src/api/search/email/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/email/test.rs@@ -14,6 +14,7 @@ fn create_email_history(thread_id: &str) -> models_email::service::message::Threviewed_at: None,snippet: None,user_id: "user1".to_string(),+ link_id: Uuid::new_v4(),subject: Some("subject".to_string()),sender: "[email protected]".to_string(),pretty_sender: "Pretty Sender".to_string(),diff --git a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs b/rust/cloud-storage/search_service/src/api/search/simple/filter.rsindex 48ba29b6de..99f811bf36 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs@@ -167,6 +167,7 @@ impl FilterVariantToSearchArgs for item_filters::EmailFilters {cc: self.cc.clone(),bcc: self.bcc.clone(),recipients: self.recipients.clone(),+ link_ids: self.link_ids.clone(),include_labels: self.include_labels.clone(),exclude_labels: self.exclude_labels.clone(),importance: self.importance,diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rsindex a52ca3be42..3bec891c7c 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs@@ -220,6 +220,22 @@ pub(in crate::api::search) async fn perform_unified_search(filter_email_response.terms = email_terms.clone();filter_call_record_response.terms = split_search_terms(&terms);+ // Widen the email access filter to every inbox the caller can reach (their+ // own plus delegated). Connected secondary inboxes share the owner's+ // user_id; delegated inboxes index under their own, so collect the+ // distinct macro_ids the caller can search.+ if should_include_emails {+ let inboxes =+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, user_id.as_ref())+ .await+ .map_err(SearchError::InternalError)?;+ let mut email_user_ids: Vec<String> =+ inboxes.iter().map(|l| l.macro_id.to_string()).collect();+ email_user_ids.sort();+ email_user_ids.dedup();+ filter_email_response.user_ids = email_user_ids;+ }+// Clone terms for use in name searcheslet name_search_term = terms[0].clone();diff --git a/rust/cloud-storage/search_service/src/api/search/unified/test.rs b/rust/cloud-storage/search_service/src/api/search/unified/test.rsindex ac5ecb79cc..ab6655011c 100644--- a/rust/cloud-storage/search_service/src/api/search/unified/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified/test.rs@@ -83,6 +83,7 @@ fn test_sort_unified_search_results() {subject: Some("Email Subject".to_string()),thread_id: email_id,user_id: "user1".to_string(),+ link_id: email_id,email_message_search_results: vec![],participants: vec![],},