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(soup): add shared email thread filtering (#2091)

Evan Hutnik0072a19f035f
diff --git a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts b/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts
index 7dc73de2b6..18a85aa3f5 100644
--- a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts
+++ b/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts
@@ -9,6 +9,7 @@ import {
} from '@app/component/next-soup/filters/inbox-query-filters';
import type { ListView } from '@app/constants/list-views';
import type { SoupBody } from '@queries/soup/items';
+import { SharedEmailFilter } from '@service-storage/generated/schemas';
export type SoupFiltersPreset = {
queryFilters: SoupBody;
@@ -39,27 +40,42 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {
inbox: {
default: 'signal',
tabs: {
- signal: () => ({
- queryFilters: {
- ...applyInboxQueryFilters({
- document_filters: { is_email_attachment: false },
- }),
- emailView: 'inbox',
- },
- clientFilters: { and: ['signal', 'not-done'] },
- }),
- noise: () => ({
- queryFilters: {
- ...applyOtherQueryFilters({
- document_filters: { is_email_attachment: false },
- }),
- emailView: 'inbox',
- },
- clientFilters: { and: ['noise', 'not-done'] },
- }),
+ signal: () => {
+ const filters = applyInboxQueryFilters({
+ document_filters: { is_email_attachment: false },
+ });
+ return {
+ queryFilters: {
+ ...filters,
+ email_filters: {
+ ...filters.email_filters,
+ shared: SharedEmailFilter.exclude,
+ },
+ emailView: 'inbox',
+ },
+ clientFilters: { and: ['signal', 'not-done'] },
+ };
+ },
+ noise: () => {
+ const filters = applyOtherQueryFilters({
+ document_filters: { is_email_attachment: false },
+ });
+ return {
+ queryFilters: {
+ ...filters,
+ email_filters: {
+ ...filters.email_filters,
+ shared: SharedEmailFilter.exclude,
+ },
+ emailView: 'inbox',
+ },
+ clientFilters: { and: ['noise', 'not-done'] },
+ };
+ },
all: () => ({
queryFilters: {
document_filters: { is_email_attachment: false },
+ email_filters: { shared: SharedEmailFilter.include },
emailView: 'all',
},
clientFilters: { and: ['explicit-noise'] },
@@ -95,20 +111,27 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {
important: () => ({
queryFilters: {
...QUERY_FILTERS.email,
- email_filters: { importance: true },
+ email_filters: {
+ importance: true,
+ shared: SharedEmailFilter.exclude,
+ },
},
clientFilters: { and: ['email', 'no-drafts'] },
}),
noise: () => ({
queryFilters: {
...QUERY_FILTERS.email,
- email_filters: { importance: false },
+ email_filters: {
+ importance: false,
+ shared: SharedEmailFilter.exclude,
+ },
},
clientFilters: { and: ['email', 'no-drafts'] },
}),
drafts: () => ({
queryFilters: {
...QUERY_FILTERS.email,
+ email_filters: { shared: SharedEmailFilter.exclude },
emailView: 'drafts',
},
clientFilters: { and: ['email-drafts'] },
@@ -118,12 +141,23 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {
return {
queryFilters: {
...QUERY_FILTERS.email,
- email_filters: { senders: [ctx.email] },
+ email_filters: {
+ senders: [ctx.email],
+ shared: SharedEmailFilter.exclude,
+ },
emailView: 'sent',
},
clientFilters: { and: ['email', 'no-drafts'] },
};
},
+ shared: () => ({
+ queryFilters: {
+ ...QUERY_FILTERS.email,
+ email_filters: { shared: SharedEmailFilter.only },
+ emailView: 'all',
+ },
+ clientFilters: { and: ['email'] },
+ }),
},
},
documents: {
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx
index 9896f9786c..505ea1ab16 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx
@@ -155,6 +155,7 @@ const MailTabs = () => {
{ value: 'noise', label: 'Noise' },
{ value: 'drafts', label: 'Drafts' },
{ value: 'sent', label: 'Sent' },
+ { value: 'shared', label: 'Shared' },
]}
value={activeTab()}
defaultValue={VIEW_TAB_PRESETS.mail.default}
diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsx
index 6ffdb39779..07978d0329 100644
--- a/js/app/packages/block-project/component/Block.tsx
+++ b/js/app/packages/block-project/component/Block.tsx
@@ -30,6 +30,7 @@ import {
import { SoupViewContextProvider } from '@app/component/next-soup/soup-view/soup-view-context';
import { SoupViewList } from '@app/component/next-soup/soup-view/soup-view';
import { NIL_UUID } from '@app/component/next-soup/filters/query-filters';
+import { SharedEmailFilter } from '@service-storage/generated/schemas';
// HACK: prevent lint error on custom directive
false && fileFolderDrop;
@@ -198,6 +199,7 @@ const ProjectEntityList = (props: {
},
email_filters: {
project_ids: [props.projectId],
+ shared: SharedEmailFilter.include,
},
}}
>
diff --git a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts b/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts
index 5127ba1de3..06f1d5a957 100644
--- a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts
@@ -6,6 +6,7 @@
*/
import type { EmailFiltersImportance } from './emailFiltersImportance';
import type { NotificationFilters } from './notificationFilters';
+import type { SharedEmailFilter } from './sharedEmailFilter';
/**
* The email filters used to filter down what emails you search over.
@@ -35,4 +36,7 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never ap
recipients?: string[];
/** Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders. */
senders?: string[];
+ /** Controls whether shared email threads are included in results.
+Defaults to "exclude" (only the user's own threads). */
+ shared?: SharedEmailFilter;
}
diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.ts
index 8aad9ac225..0d3db333c2 100644
--- a/js/app/packages/service-clients/service-search/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts
@@ -130,6 +130,7 @@ export * from './searchHighlightSender';
export * from './searchHighlightUserId';
export * from './searchOn';
export * from './searchResponse';
+export * from './sharedEmailFilter';
export * from './simpleChannelSearchReponseBaseItem';
export * from './simpleChannelSearchReponseBaseItemHumanReadableTimestamp';
export * from './simpleChannelSearchReponseBaseItemHumanReadableTimestampOrgId';
diff --git a/js/app/packages/service-clients/service-search/generated/models/sharedEmailFilter.ts b/js/app/packages/service-clients/service-search/generated/models/sharedEmailFilter.ts
new file mode 100644
index 0000000000..678255f59d
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/sharedEmailFilter.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Controls whether shared email threads are included in results.
+ */
+export type SharedEmailFilter =
+ (typeof SharedEmailFilter)[keyof typeof SharedEmailFilter];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const SharedEmailFilter = {
+ exclude: 'exclude',
+ include: 'include',
+ only: 'only',
+} as const;
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index f08e7183a7..2eb4fb53cb 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -942,6 +942,10 @@
"type": "string"
},
"description": "Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders."
+ },
+ "shared": {
+ "$ref": "#/components/schemas/SharedEmailFilter",
+ "description": "Controls whether shared email threads are included in results.\nDefaults to \"exclude\" (only the user's own threads)."
}
}
},
@@ -1916,6 +1920,11 @@
}
}
},
+ "SharedEmailFilter": {
+ "type": "string",
+ "description": "Controls whether shared email threads are included in results.",
+ "enum": ["exclude", "include", "only"]
+ },
"SimpleChannelSearchReponseBaseItem": {
"type": "object",
"required": [
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts
index 0254d1d07d..76e35ef332 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts
@@ -6,6 +6,7 @@
*/
import type { EmailFiltersImportance } from './emailFiltersImportance';
import type { NotificationFilters } from './notificationFilters';
+import type { SharedEmailFilter } from './sharedEmailFilter';
/**
* The email filters used to filter down what emails you search over.
@@ -35,4 +36,7 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never ap
recipients?: string[];
/** Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders. */
senders?: string[];
+ /** Controls whether shared email threads are included in results.
+Defaults to "exclude" (only the user's own threads). */
+ shared?: SharedEmailFilter;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index d52a41c00c..d15a215b93 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -503,6 +503,7 @@ export * from './setPropertyValueOneOfSevenType';
export * from './setPropertyValueOneOfThree';
export * from './setPropertyValueOneOfThreeType';
export * from './setPropertyValueOneOfType';
+export * from './sharedEmailFilter';
export * from './sharePermissionV2';
export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2PublicAccessLevel';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/sharedEmailFilter.ts b/js/app/packages/service-clients/service-storage/generated/schemas/sharedEmailFilter.ts
new file mode 100644
index 0000000000..f82f9fd7f8
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/sharedEmailFilter.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Controls whether shared email threads are included in results.
+ */
+export type SharedEmailFilter =
+ (typeof SharedEmailFilter)[keyof typeof SharedEmailFilter];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const SharedEmailFilter = {
+ exclude: 'exclude',
+ include: 'include',
+ only: 'only',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 3c25f0c1f3..edca7774e7 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -4363,6 +4363,12 @@ export const postItemsSoupBody = zod
.describe(
"Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders."
),
+ shared: zod
+ .enum(['exclude', 'include', 'only'])
+ .optional()
+ .describe(
+ 'Controls whether shared email threads are included in results.'
+ ),
})
.optional()
.describe(
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index b349af0d6d..509b6ab4ec 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6976,6 +6976,10 @@
"type": "string"
},
"description": "Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders."
+ },
+ "shared": {
+ "$ref": "#/components/schemas/SharedEmailFilter",
+ "description": "Controls whether shared email threads are included in results.\nDefaults to \"exclude\" (only the user's own threads)."
}
}
},
@@ -9653,6 +9657,11 @@
}
}
},
+ "SharedEmailFilter": {
+ "type": "string",
+ "description": "Controls whether shared email threads are included in results.",
+ "enum": ["exclude", "include", "only"]
+ },
"ShortIdResponse": {
"type": "object",
"description": "Short ID response.",
diff --git a/rust/cloud-storage/email/.sqlx/query-03313f689cbc216503f0372eca83b82f58a55d5c030892b6889eb77e76dbae2e.json b/rust/cloud-storage/email/.sqlx/query-03313f689cbc216503f0372eca83b82f58a55d5c030892b6889eb77e76dbae2e.json
new file mode 100644
index 0000000000..d852429fbd
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-03313f689cbc216503f0372eca83b82f58a55d5c030892b6889eb77e76dbae2e.json
@@ -0,0 +1,122 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Find the latest starred timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n lspt.latest_starred_ts AS created_at,\n lspt.latest_starred_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest starred timestamp for every thread.\n SELECT m.thread_id, MAX(m.internal_date_ts) as latest_starred_ts\n FROM email_messages m\n WHERE m.link_id = $1 AND m.is_starred = TRUE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = $1\n )\n GROUP BY m.thread_id\n ) lspt\n JOIN email_threads t ON lspt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest starred message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_starred = TRUE\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "03313f689cbc216503f0372eca83b82f58a55d5c030892b6889eb77e76dbae2e"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-60fe557b143af00c5ddce77735e8b629dcce80126672a6c1d6bb9d2677976c75.json b/rust/cloud-storage/email/.sqlx/query-60fe557b143af00c5ddce77735e8b629dcce80126672a6c1d6bb9d2677976c75.json
new file mode 100644
index 0000000000..68fd6aefaa
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-60fe557b143af00c5ddce77735e8b629dcce80126672a6c1d6bb9d2677976c75.json
@@ -0,0 +1,122 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Find the latest draft timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results. This is the core optimization.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n ldpt.latest_draft_ts AS created_at,\n ldpt.latest_draft_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest draft timestamp for every thread.\n SELECT m.thread_id, MAX(m.updated_at) as latest_draft_ts\n FROM email_messages m\n -- we only display macro drafts, not drafts created in gmail\n WHERE m.link_id = $1 AND m.is_draft = TRUE AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = $1\n )\n GROUP BY m.thread_id\n ) ldpt\n JOIN email_threads t ON ldpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest draft.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = TRUE\n -- we only display macro drafts, not drafts created in gmail\n AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.updated_at DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "60fe557b143af00c5ddce77735e8b629dcce80126672a6c1d6bb9d2677976c75"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd.json b/rust/cloud-storage/email/.sqlx/query-6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd.json
deleted file mode 100644
index bdf82a2be9..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_outbound_message_ts AS created_at,\n t.latest_outbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.latest_outbound_message_ts IS NOT NULL\n \n -- Cursor logic moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest SENT, non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_sent = TRUE -- This condition is specific to the \"Sent\" view\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- true,
- true,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true
- ]
- },
- "hash": "6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-6fd1d9664bdbb6711f66cbb95e6703cbf3b285f97593dfd0eeecdbb474987074.json b/rust/cloud-storage/email/.sqlx/query-6fd1d9664bdbb6711f66cbb95e6703cbf3b285f97593dfd0eeecdbb474987074.json
deleted file mode 100644
index e4dfeb53f0..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-6fd1d9664bdbb6711f66cbb95e6703cbf3b285f97593dfd0eeecdbb474987074.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n -- A thread in \"Other\" can still be \"Important\", so we must perform the check.\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 c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the \"Other\" inbox.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.latest_non_spam_message_ts IS NOT NULL\n -- Inclusion Criteria: Must have a category label.\n AND EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n -- ****** CORRECTED EXCLUSION CRITERIA ******\n -- This now matches the logic of your original query, which did NOT filter out 'INBOX' or 'IMPORTANT'.\n AND NOT EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH', 'DRAFT')\n )\n \n AND (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-spam/trash message for the preview.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH')\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- true,
- true,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true
- ]
- },
- "hash": "6fd1d9664bdbb6711f66cbb95e6703cbf3b285f97593dfd0eeecdbb474987074"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f.json b/rust/cloud-storage/email/.sqlx/query-714f90b277b3e53e84688fbe6b573cd622f5c320c33ab43c3c952aa9c12199b3.json
similarity index 90%
rename from rust/cloud-storage/email/.sqlx/query-26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f.json
rename to rust/cloud-storage/email/.sqlx/query-714f90b277b3e53e84688fbe6b573cd622f5c320c33ab43c3c952aa9c12199b3.json
index 2acef5cef5..ed19453502 100644
--- a/rust/cloud-storage/email/.sqlx/query-26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f.json
+++ b/rust/cloud-storage/email/.sqlx/query-714f90b277b3e53e84688fbe6b573cd622f5c320c33ab43c3c952aa9c12199b3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH ApplicableLabelIDs AS (\n SELECT id\n FROM email_labels\n WHERE link_id = $1\n AND (name = 'INBOX')\n ),\n QualifyingMessages AS (\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = $1\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = $1\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'IMPORTANT'\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN ApplicableLabelIDs ali ON ml.label_id = ali.id\n WHERE ml.message_id = m.id\n )\n\n UNION ALL\n\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = $1\n AND m.is_draft = TRUE\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = $1\n )\n ),\n AllImportantThreads AS (\n -- From all qualifying messages, get the single most recent one per thread.\n SELECT DISTINCT ON (thread_id)\n thread_id,\n internal_date_ts,\n fallback_ts,\n is_draft,\n subject,\n snippet,\n from_contact_id,\n from_name\n FROM QualifyingMessages\n ORDER BY thread_id, COALESCE(internal_date_ts, fallback_ts) DESC\n ),\n ImportantWithSortKey AS (\n -- Join with user_history to calculate the final effective sort key.\n SELECT\n ait.thread_id,\n ait.internal_date_ts,\n ait.fallback_ts,\n ait.is_draft,\n ait.subject,\n ait.snippet,\n ait.from_contact_id,\n ait.from_name,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as created_at,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as updated_at,\n uh.updated_at as viewed_at,\n -- This CASE statement dynamically selects the correct timestamp for sorting.\n -- For 'updated_at' and 'created_at', we use the important message timestamp\n -- For 'viewed_at', we use the history timestamp.\n -- For 'viewed_updated', we use the history timestamp if it exists, otherwise the important message timestamp.\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, COALESCE(ait.internal_date_ts, ait.fallback_ts))\n ELSE COALESCE(ait.internal_date_ts, ait.fallback_ts)\n END AS effective_ts\n FROM AllImportantThreads ait\n -- This has to be a left join to support all sort methods.\n LEFT JOIN email_user_history uh ON uh.thread_id = ait.thread_id AND uh.link_id = $1\n )\n SELECT\n isk.thread_id as \"id!\",\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n isk.effective_ts as \"sort_ts!\",\n isk.created_at as \"created_at!\",\n isk.updated_at as \"updated_at!\",\n t.project_id,\n isk.viewed_at as \"viewed_at?\",\n isk.is_draft as \"is_draft!\",\n -- It's the important view - all threads here are important\n true as \"is_important!\",\n isk.subject as \"name?\",\n isk.snippet as \"snippet?\",\n c.email_address AS \"sender_email?\",\n COALESCE(isk.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM ImportantWithSortKey isk\n JOIN email_threads t ON isk.thread_id = t.id\n LEFT JOIN email_contacts c ON isk.from_contact_id = c.id\n WHERE\n ($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)\n ORDER BY isk.effective_ts DESC, isk.thread_id DESC\n LIMIT $2\n ",
+ "query": "\n WITH ApplicableLabelIDs AS (\n SELECT id\n FROM email_labels\n WHERE link_id = $1\n AND (name = 'INBOX')\n ),\n QualifyingMessages AS (\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = $1\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = $1\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'IMPORTANT'\n )\n AND EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN ApplicableLabelIDs ali ON ml.label_id = ali.id\n WHERE ml.message_id = m.id\n )\n\n UNION ALL\n\n SELECT m.thread_id,\n m.internal_date_ts,\n m.created_at AS fallback_ts,\n m.is_draft,\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.link_id = $1\n AND m.is_draft = TRUE\n AND NOT EXISTS (\n SELECT 1\n FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id\n AND l.name = 'TRASH'\n AND l.link_id = $1\n )\n ),\n AllImportantThreads AS (\n -- From all qualifying messages, get the single most recent one per thread.\n SELECT DISTINCT ON (thread_id)\n thread_id,\n internal_date_ts,\n fallback_ts,\n is_draft,\n subject,\n snippet,\n from_contact_id,\n from_name\n FROM QualifyingMessages\n ORDER BY thread_id, COALESCE(internal_date_ts, fallback_ts) DESC\n ),\n ImportantWithSortKey AS (\n -- Join with user_history to calculate the final effective sort key.\n SELECT\n ait.thread_id,\n ait.internal_date_ts,\n ait.fallback_ts,\n ait.is_draft,\n ait.subject,\n ait.snippet,\n ait.from_contact_id,\n ait.from_name,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as created_at,\n COALESCE(ait.internal_date_ts, ait.fallback_ts) as updated_at,\n uh.updated_at as viewed_at,\n -- This CASE statement dynamically selects the correct timestamp for sorting.\n -- For 'updated_at' and 'created_at', we use the important message timestamp\n -- For 'viewed_at', we use the history timestamp.\n -- For 'viewed_updated', we use the history timestamp if it exists, otherwise the important message timestamp.\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, COALESCE(ait.internal_date_ts, ait.fallback_ts))\n ELSE COALESCE(ait.internal_date_ts, ait.fallback_ts)\n END AS effective_ts\n FROM AllImportantThreads ait\n -- This has to be a left join to support all sort methods.\n LEFT JOIN email_user_history uh ON uh.thread_id = ait.thread_id AND uh.link_id = $1\n )\n SELECT\n isk.thread_id as \"id!\",\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n isk.effective_ts as \"sort_ts!\",\n isk.created_at as \"created_at!\",\n isk.updated_at as \"updated_at!\",\n t.project_id,\n isk.viewed_at as \"viewed_at?\",\n isk.is_draft as \"is_draft!\",\n -- It's the important view - all threads here are important\n true as \"is_important!\",\n isk.subject as \"name?\",\n isk.snippet as \"snippet?\",\n c.email_address AS \"sender_email?\",\n COALESCE(isk.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM ImportantWithSortKey isk\n JOIN email_threads t ON isk.thread_id = t.id\n LEFT JOIN email_contacts c ON isk.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n WHERE\n ($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)\n ORDER BY isk.effective_ts DESC, isk.thread_id DESC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -82,6 +82,11 @@
"ordinal": 15,
"name": "sender_photo_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
}
],
"parameters": {
@@ -109,8 +114,9 @@
null,
false,
null,
- true
+ true,
+ false
]
},
- "hash": "26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f"
+ "hash": "714f90b277b3e53e84688fbe6b573cd622f5c320c33ab43c3c952aa9c12199b3"
}
diff --git a/rust/cloud-storage/email/.sqlx/query-7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122.json b/rust/cloud-storage/email/.sqlx/query-7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122.json
deleted file mode 100644
index 2c35794f0f..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH trash_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'TRASH'\n ),\n important_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n TRUE AS \"inbox_visible!\",\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n WHERE m_imp.thread_id = t.id\n AND ml.label_id = (SELECT id FROM important_label)\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery is fast as it only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.is_read,\n t.project_id,\n t.latest_inbound_message_ts AS created_at,\n t.latest_inbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.inbox_visible = TRUE\n AND t.latest_inbound_message_ts IS NOT NULL\n \n -- The cursor logic is moved inside this subquery for maximum efficiency.\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n WHERE ml.message_id = m.id\n AND ml.label_id = (SELECT id FROM trash_label)\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible!",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- null,
- false,
- null,
- true,
- true,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true
- ]
- },
- "hash": "7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-82301526394304e59946caa3c724c377fa46ad214834bc1a876d39ad29ad92ac.json b/rust/cloud-storage/email/.sqlx/query-82301526394304e59946caa3c724c377fa46ad214834bc1a876d39ad29ad92ac.json
new file mode 100644
index 0000000000..37446ebe78
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-82301526394304e59946caa3c724c377fa46ad214834bc1a876d39ad29ad92ac.json
@@ -0,0 +1,122 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_outbound_message_ts AS created_at,\n t.latest_outbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.latest_outbound_message_ts IS NOT NULL\n \n -- Cursor logic moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_outbound_message_ts)\n ELSE t.latest_outbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest SENT, non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_sent = TRUE -- This condition is specific to the \"Sent\" view\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "82301526394304e59946caa3c724c377fa46ad214834bc1a876d39ad29ad92ac"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4.json b/rust/cloud-storage/email/.sqlx/query-8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4.json
deleted file mode 100644
index 93205a125b..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4.json
+++ /dev/null
@@ -1,117 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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 c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Find the latest labeled message timestamp for each thread,\n -- calculate the effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n llpt.latest_labeled_ts AS created_at,\n llpt.latest_labeled_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest timestamp for every thread\n -- that has at least one message with the specified label.\n SELECT\n m.thread_id,\n MAX(m.internal_date_ts) as latest_labeled_ts\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.link_id = $1 AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = $1\n )\n GROUP BY m.thread_id\n ) llpt\n JOIN email_threads t ON llpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest message with that specific label.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND m.is_draft = FALSE AND l.link_id = t.link_id AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- null,
- null,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true
- ]
- },
- "hash": "8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-8519d142dcd5c9c6b60b9c61c24eca0b0c860eee7227124be31b2fcbff39e2bd.json b/rust/cloud-storage/email/.sqlx/query-8519d142dcd5c9c6b60b9c61c24eca0b0c860eee7227124be31b2fcbff39e2bd.json
new file mode 100644
index 0000000000..14e048261e
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-8519d142dcd5c9c6b60b9c61c24eca0b0c860eee7227124be31b2fcbff39e2bd.json
@@ -0,0 +1,122 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH trash_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'TRASH'\n ),\n important_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n TRUE AS \"inbox_visible!\",\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n WHERE m_imp.thread_id = t.id\n AND ml.label_id = (SELECT id FROM important_label)\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.\n -- This subquery is fast as it only touches `threads` and `user_history`.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.is_read,\n t.project_id,\n t.latest_inbound_message_ts AS created_at,\n t.latest_inbound_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.inbox_visible = TRUE\n AND t.latest_inbound_message_ts IS NOT NULL\n \n -- The cursor logic is moved inside this subquery for maximum efficiency.\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_inbound_message_ts)\n ELSE t.latest_inbound_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-trashed message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n WHERE ml.message_id = m.id\n AND ml.label_id = (SELECT id FROM trash_label)\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n -- Final ordering is preserved because the input `t` is already sorted.\n ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ null,
+ false,
+ null,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "8519d142dcd5c9c6b60b9c61c24eca0b0c860eee7227124be31b2fcbff39e2bd"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-8b647d9753ba2b63ba9cc0057e0b71c87592c3e3983205d6969e0b3f1dbdb74b.json b/rust/cloud-storage/email/.sqlx/query-8b647d9753ba2b63ba9cc0057e0b71c87592c3e3983205d6969e0b3f1dbdb74b.json
new file mode 100644
index 0000000000..1e10ec0e6e
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-8b647d9753ba2b63ba9cc0057e0b71c87592c3e3983205d6969e0b3f1dbdb74b.json
@@ -0,0 +1,123 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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 c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Find the latest labeled message timestamp for each thread,\n -- calculate the effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n llpt.latest_labeled_ts AS created_at,\n llpt.latest_labeled_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest timestamp for every thread\n -- that has at least one message with the specified label.\n SELECT\n m.thread_id,\n MAX(m.internal_date_ts) as latest_labeled_ts\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.link_id = $1 AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = $1\n )\n GROUP BY m.thread_id\n ) llpt\n JOIN email_threads t ON llpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $6 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, llpt.latest_labeled_ts)\n ELSE llpt.latest_labeled_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest message with that specific label.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n JOIN email_message_labels ml ON m.id = ml.message_id\n JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND m.is_draft = FALSE AND l.link_id = t.link_id AND l.name = $5\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml2\n JOIN email_labels l2 ON ml2.label_id = l2.id\n WHERE ml2.message_id = m.id AND l2.name = 'TRASH' AND l2.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "8b647d9753ba2b63ba9cc0057e0b71c87592c3e3983205d6969e0b3f1dbdb74b"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574.json b/rust/cloud-storage/email/.sqlx/query-a2c42d1ef0b78555844e0feddc14956117973fadd5565af9a2c48c7d2230e05f.json
similarity index 50%
rename from rust/cloud-storage/email/.sqlx/query-8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574.json
rename to rust/cloud-storage/email/.sqlx/query-a2c42d1ef0b78555844e0feddc14956117973fadd5565af9a2c48c7d2230e05f.json
index 07ea7f8528..df027cb4f4 100644
--- a/rust/cloud-storage/email/.sqlx/query-8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574.json
+++ b/rust/cloud-storage/email/.sqlx/query-a2c42d1ef0b78555844e0feddc14956117973fadd5565af9a2c48c7d2230e05f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH spam_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'SPAM'\n ),\n trash_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'TRASH'\n ),\n important_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n WHERE m_imp.thread_id = t.id\n AND ml.label_id = (SELECT id FROM important_label)\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads.\n -- This subquery only touches `threads` and `user_history`, making it very fast.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.latest_non_spam_message_ts IS NOT NULL\n \n -- Cursor logic is moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n WHERE ml.message_id = m.id\n AND ml.label_id = (SELECT id FROM spam_label)\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n WHERE ml.message_id = m.id\n AND ml.label_id = (SELECT id FROM trash_label)\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "query": "\n WITH spam_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'SPAM'\n ),\n trash_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'TRASH'\n ),\n important_label AS (\n SELECT id FROM email_labels WHERE link_id = $1 AND name = 'IMPORTANT'\n )\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_labels ml ON m_imp.id = ml.message_id\n WHERE m_imp.thread_id = t.id\n AND ml.label_id = (SELECT id FROM important_label)\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads.\n -- This subquery only touches `threads` and `user_history`, making it very fast.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.latest_non_spam_message_ts IS NOT NULL\n \n -- Cursor logic is moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n WHERE ml.message_id = m.id\n AND ml.label_id = (SELECT id FROM spam_label)\n )\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n WHERE ml.message_id = m.id\n AND ml.label_id = (SELECT id FROM trash_label)\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
"describe": {
"columns": [
{
@@ -82,6 +82,11 @@
"ordinal": 15,
"name": "sender_photo_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
}
],
"parameters": {
@@ -109,8 +114,9 @@
null,
false,
null,
- true
+ true,
+ false
]
},
- "hash": "8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574"
+ "hash": "a2c42d1ef0b78555844e0feddc14956117973fadd5565af9a2c48c7d2230e05f"
}
diff --git a/rust/cloud-storage/email/.sqlx/query-a774adbda891d81dd017de5b0b50f41a5a1da6e4c5a81e51eb3cb267f10ef1fc.json b/rust/cloud-storage/email/.sqlx/query-a774adbda891d81dd017de5b0b50f41a5a1da6e4c5a81e51eb3cb267f10ef1fc.json
new file mode 100644
index 0000000000..ca7b895e22
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-a774adbda891d81dd017de5b0b50f41a5a1da6e4c5a81e51eb3cb267f10ef1fc.json
@@ -0,0 +1,122 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n -- A thread in \"Other\" can still be \"Important\", so we must perform the check.\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 c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the \"Other\" inbox.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = $1\n AND t.latest_non_spam_message_ts IS NOT NULL\n -- Inclusion Criteria: Must have a category label.\n AND EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')\n )\n -- ****** CORRECTED EXCLUSION CRITERIA ******\n -- This now matches the logic of your original query, which did NOT filter out 'INBOX' or 'IMPORTANT'.\n AND NOT EXISTS (\n SELECT 1 FROM email_messages m JOIN email_message_labels ml ON m.id = ml.message_id JOIN email_labels l ON ml.label_id = l.id\n WHERE m.thread_id = t.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH', 'DRAFT')\n )\n \n AND (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-spam/trash message for the preview.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.link_id = t.link_id AND l.name IN ('SPAM', 'TRASH')\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "inbox_visible",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "sort_ts!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "viewed_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "snippet?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "is_important!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 13,
+ "name": "sender_email?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 14,
+ "name": "sender_name?",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 15,
+ "name": "sender_photo_url?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "owner_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Timestamptz",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ null,
+ true,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ null,
+ false,
+ null,
+ true,
+ false
+ ]
+ },
+ "hash": "a774adbda891d81dd017de5b0b50f41a5a1da6e4c5a81e51eb3cb267f10ef1fc"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141.json b/rust/cloud-storage/email/.sqlx/query-c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141.json
deleted file mode 100644
index 64f269cefe..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Find the latest draft timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results. This is the core optimization.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n ldpt.latest_draft_ts AS created_at,\n ldpt.latest_draft_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest draft timestamp for every thread.\n SELECT m.thread_id, MAX(m.updated_at) as latest_draft_ts\n FROM email_messages m\n -- we only display macro drafts, not drafts created in gmail\n WHERE m.link_id = $1 AND m.is_draft = TRUE AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = $1\n )\n GROUP BY m.thread_id\n ) ldpt\n JOIN email_threads t ON ldpt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, ldpt.latest_draft_ts)\n ELSE ldpt.latest_draft_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest draft.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_draft = TRUE\n -- we only display macro drafts, not drafts created in gmail\n AND m.internal_date_ts IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.updated_at DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- null,
- null,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true
- ]
- },
- "hash": "c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-d8232849be1f6ec23537bb317cdf15e29ccdaf5ebee894e07dad1f8ca9b6b061.json b/rust/cloud-storage/email/.sqlx/query-d8232849be1f6ec23537bb317cdf15e29ccdaf5ebee894e07dad1f8ca9b6b061.json
deleted file mode 100644
index 86523dc51a..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-d8232849be1f6ec23537bb317cdf15e29ccdaf5ebee894e07dad1f8ca9b6b061.json
+++ /dev/null
@@ -1,116 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n (\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.name = 'IMPORTANT'\n AND l.link_id = t.link_id\n )\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\"\n FROM (\n -- Step 1: Find the latest starred timestamp for each thread, calculate the\n -- effective sort key, then sort and limit the results.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.project_id,\n lspt.latest_starred_ts AS created_at,\n lspt.latest_starred_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END AS effective_ts\n FROM (\n -- This sub-subquery efficiently finds the latest starred timestamp for every thread.\n SELECT m.thread_id, MAX(m.internal_date_ts) as latest_starred_ts\n FROM email_messages m\n WHERE m.link_id = $1 AND m.is_starred = TRUE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = $1\n )\n GROUP BY m.thread_id\n ) lspt\n JOIN email_threads t ON lspt.thread_id = t.id\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n (($3::timestamptz IS NULL) OR (\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, lspt.latest_starred_ts)\n ELSE lspt.latest_starred_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find the full details of its latest starred message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.from_contact_id,\n m.from_name,\n m.is_draft\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND m.is_starred = TRUE\n AND m.is_draft = FALSE\n AND NOT EXISTS (\n SELECT 1 FROM email_message_labels ml\n JOIN email_labels l ON ml.label_id = l.id\n WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id\n )\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "provider_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "inbox_visible",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "is_read",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "viewed_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "snippet?",
- "type_info": "Text"
- },
- {
- "ordinal": 11,
- "name": "is_draft",
- "type_info": "Bool"
- },
- {
- "ordinal": 12,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "sender_email?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 14,
- "name": "sender_name?",
- "type_info": "Varchar"
- },
- {
- "ordinal": 15,
- "name": "sender_photo_url?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Int8",
- "Timestamptz",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- null,
- null,
- null,
- true,
- false,
- true,
- true,
- false,
- null,
- false,
- null,
- true
- ]
- },
- "hash": "d8232849be1f6ec23537bb317cdf15e29ccdaf5ebee894e07dad1f8ca9b6b061"
-}
diff --git a/rust/cloud-storage/email/fixtures/email_shared_threads.sql b/rust/cloud-storage/email/fixtures/email_shared_threads.sql
new file mode 100644
index 0000000000..955b80e3c2
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_shared_threads.sql
@@ -0,0 +1,104 @@
+-- Fixture for testing shared email thread filtering.
+-- Builds on email_dynamic_query fixture by adding a second user with their own
+-- email threads, some of which are shared with user1 via UserItemAccess or project membership.
+
+-- == Second user ==
+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
+VALUES ('b2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'stripe_user2');
+
+INSERT INTO "User" (id, email, name, macro_user_id)
+VALUES ('macro|[email protected]', '[email protected]', 'Test User 2', 'b2222222-2222-2222-2222-222222222222');
+
+-- Second user's email link
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'macro|[email protected]', 'user2', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Contacts for user2's link
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ ('40000005-0000-0000-0000-000000000005', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '[email protected]', 'External Person', NOW(), NOW());
+
+-- Labels for user2's link
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('10000101-0000-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('10000101-0000-0000-0000-000000000006', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW());
+
+-- == Shared project: user1 has access to this project owned by user2 ==
+INSERT INTO "Project" (id, name, "userId", "createdAt", "updatedAt")
+VALUES ('proj-cccc-cccc-cccc-cccccccccccc', 'Shared Project', 'macro|[email protected]', NOW(), NOW());
+
+-- Grant user1 access to the shared project
+INSERT INTO "UserItemAccess" (id, user_id, item_id, item_type, access_level, created_at, updated_at)
+VALUES ('acc00000-0000-0000-0000-000000000001', 'macro|[email protected]', 'proj-cccc-cccc-cccc-cccccccccccc', 'project', 'view', NOW(), NOW());
+
+-- == User2's email threads ==
+
+-- Thread 101: Directly shared with user1 via UserItemAccess (not in any shared project)
+INSERT INTO email_threads (
+ id, provider_id, link_id, inbox_visible, is_read,
+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,
+ created_at, updated_at
+)
+VALUES
+ ('20000101-0000-0000-0000-000000000101', 'shared_thread1', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ true, false, '2024-02-01 10:00:00+00', NULL, '2024-02-01 10:00:00+00', NOW(), NOW());
+
+-- Thread 102: Lives in the shared project (inherited access via project membership)
+INSERT INTO email_threads (
+ id, provider_id, link_id, inbox_visible, is_read,
+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,
+ created_at, updated_at, project_id
+)
+VALUES
+ ('20000102-0000-0000-0000-000000000102', 'shared_thread2', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ true, false, '2024-02-02 10:00:00+00', NULL, '2024-02-02 10:00:00+00', NOW(), NOW(),
+ 'proj-cccc-cccc-cccc-cccccccccccc');
+
+-- Thread 103: User2's thread NOT shared with user1 (should never appear)
+INSERT INTO email_threads (
+ id, provider_id, link_id, inbox_visible, is_read,
+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,
+ created_at, updated_at
+)
+VALUES
+ ('20000103-0000-0000-0000-000000000103', 'not_shared_thread', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ true, false, '2024-02-03 10:00:00+00', NULL, '2024-02-03 10:00:00+00', NOW(), NOW());
+
+-- Direct share: thread 101 shared with user1
+INSERT INTO "UserItemAccess" (id, user_id, item_id, item_type, access_level, created_at, updated_at)
+VALUES ('acc00000-0000-0000-0000-000000000002', 'macro|[email protected]', '20000101-0000-0000-0000-000000000101', 'thread', 'view', NOW(), NOW());
+
+-- == Messages for user2's threads ==
+INSERT INTO email_messages (
+ id, thread_id, link_id, provider_id, from_contact_id,
+ subject, snippet, internal_date_ts,
+ is_draft, is_sent, is_starred, is_read,
+ created_at, updated_at
+)
+VALUES
+ -- Message for directly shared thread 101
+ ('30000101-0000-0000-0000-000000000101', '20000101-0000-0000-0000-000000000101',
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'shared_msg1', '40000005-0000-0000-0000-000000000005',
+ 'Shared Thread Direct', 'This thread is directly shared', '2024-02-01 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ -- Message for project-shared thread 102
+ ('30000102-0000-0000-0000-000000000102', '20000102-0000-0000-0000-000000000102',
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'shared_msg2', '40000005-0000-0000-0000-000000000005',
+ 'Shared Thread Project', 'This thread is shared via project', '2024-02-02 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ -- Message for NOT shared thread 103
+ ('30000103-0000-0000-0000-000000000103', '20000103-0000-0000-0000-000000000103',
+ 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'not_shared_msg', '40000005-0000-0000-0000-000000000005',
+ 'Not Shared Thread', 'This thread should not be visible', '2024-02-03 10:00:00+00',
+ false, false, false, false, NOW(), NOW());
+
+-- Message labels for user2's threads
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('30000101-0000-0000-0000-000000000101', '10000101-0000-0000-0000-000000000001'),
+ ('30000102-0000-0000-0000-000000000102', '10000101-0000-0000-0000-000000000001'),
+ ('30000103-0000-0000-0000-000000000103', '10000101-0000-0000-0000-000000000001');
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
index 4fbe23f227..ac24338c9d 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs
@@ -44,6 +44,8 @@ pub struct ThreadPreviewCursorDbRow {
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
pub project_id: Option<String>,
+ /// The macro user ID of the thread owner, resolved from email_links.
+ pub owner_id: String,
}
#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq, Doppleganger)]
@@ -94,7 +96,7 @@ pub struct LabelDbRow {
}
impl ThreadPreviewCursorDbRow {
- pub fn with_user_id(self, owner_id: MacroUserIdStr<'_>) -> EmailThreadPreview {
+ pub fn into_preview(self) -> EmailThreadPreview {
let ThreadPreviewCursorDbRow {
id,
provider_id,
@@ -112,12 +114,15 @@ impl ThreadPreviewCursorDbRow {
created_at,
updated_at,
project_id,
+ owner_id,
} = self;
EmailThreadPreview {
id,
provider_id,
- owner_id: owner_id.into_owned(),
+ owner_id: MacroUserIdStr::parse_from_str(&owner_id)
+ .expect("invalid macro_id in email_links")
+ .into_owned(),
inbox_visible,
is_read,
is_draft,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
index 3c839bfe05..17de34c75a 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
@@ -11,6 +11,7 @@ pub(super) fn has_thread_literals(ast: &Expr<EmailLiteral>) -> bool {
filter_ast::ExprFrame::Literal(EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_)) => {
true
}
+ filter_ast::ExprFrame::Literal(EmailLiteral::Shared(_)) => false,
filter_ast::ExprFrame::Literal(_) => false,
})
}
@@ -19,9 +20,9 @@ pub(super) fn has_message_literals(ast: &Expr<EmailLiteral>) -> bool {
ast.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) | filter_ast::ExprFrame::Or(a, b) => a || b,
filter_ast::ExprFrame::Not(a) => a,
- filter_ast::ExprFrame::Literal(EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_)) => {
- false
- }
+ filter_ast::ExprFrame::Literal(
+ EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_) | EmailLiteral::Shared(_),
+ ) => false,
filter_ast::ExprFrame::Literal(_) => true,
})
}
@@ -147,6 +148,7 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmen
filter_ast::ExprFrame::Literal(EmailLiteral::NotificationSeen(_)) => {
SqlFragment::raw("TRUE")
}
+ filter_ast::ExprFrame::Literal(EmailLiteral::Shared(_)) => SqlFragment::raw("TRUE"),
});
fragment.with_and_prefix()
@@ -178,7 +180,8 @@ pub(super) fn build_thread_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragment
| EmailLiteral::Recipient(_)
| EmailLiteral::Importance(_)
| EmailLiteral::NotificationDone(_)
- | EmailLiteral::NotificationSeen(_),
+ | EmailLiteral::NotificationSeen(_)
+ | EmailLiteral::Shared(_),
) => SqlFragment::raw("TRUE"),
});
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
index f78befd5c6..507c84ce89 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/query.rs
@@ -3,8 +3,10 @@ use crate::domain::models::{PreviewView, PreviewViewStandardLabel};
use crate::outbound::email_pg_repo::db_types::*;
use chrono::{DateTime, Utc};
use filter_ast::Expr;
+use item_filters::SharedEmailFilter;
use item_filters::ast::email::EmailLiteral;
use models_pagination::{Query, SimpleSortMethod};
+use recursion::CollapsibleExt;
use sqlx::{PgPool, Postgres, QueryBuilder, Row};
use std::sync::Arc;
use uuid::Uuid;
@@ -16,6 +18,8 @@ struct QueryParams {
cursor_timestamp: Option<DateTime<Utc>>,
cursor_id_str: Option<String>,
is_important: bool,
+ shared: SharedEmailFilter,
+ user_id: String,
}
/// Builds a dynamic email thread query with filters applied.
@@ -29,7 +33,49 @@ fn build_query(
let view_thread_filter = build_view_thread_filter(view);
let view_message_filter = build_view_message_filter(view);
- let mut builder = sqlx::QueryBuilder::new(
+ let needs_shared_cte = !matches!(params.shared, SharedEmailFilter::Exclude);
+
+ let mut builder = if needs_shared_cte {
+ let mut b = sqlx::QueryBuilder::new(
+ r#"
+ WITH RECURSIVE ProjectHierarchy AS (
+ SELECT p.id, uia.access_level
+ FROM "Project" p
+ JOIN "UserItemAccess" uia ON p.id = uia.item_id AND uia.item_type = 'project'
+ WHERE uia.user_id = "#,
+ );
+ b.push_bind(params.user_id.clone());
+ b.push(
+ r#" AND p."deletedAt" IS NULL
+ UNION ALL
+ SELECT p.id, ph.access_level
+ FROM "Project" p
+ JOIN ProjectHierarchy ph ON p."parentId" = ph.id
+ WHERE p."deletedAt" IS NULL
+ ),
+ SharedEmailThreads AS (
+ SELECT item_id::uuid AS thread_id
+ FROM "UserItemAccess"
+ WHERE user_id = "#,
+ );
+ b.push_bind(params.user_id.clone());
+ b.push(
+ r#" AND item_type = 'thread'
+ UNION
+ -- Find threads living in accessible projects.
+ -- project_id is text, ProjectHierarchy.id is uuid, so cast to text for comparison.
+ SELECT t.id AS thread_id
+ FROM email_threads t
+ WHERE t.project_id = ANY(ARRAY(SELECT id::text FROM ProjectHierarchy))
+ )
+ "#,
+ );
+ b
+ } else {
+ sqlx::QueryBuilder::new("")
+ };
+
+ builder.push(
r#"
SELECT
t.id,
@@ -66,7 +112,8 @@ fn build_query(
END AS is_important,
c.email_address AS sender_email,
c.name AS sender_name,
- c.sfs_photo_url as sender_photo_url
+ c.sfs_photo_url as sender_photo_url,
+ el.macro_id AS owner_id
FROM (
-- Step 1: Efficiently find and sort candidate threads
SELECT
@@ -100,11 +147,24 @@ fn build_query(
FROM email_threads t
LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
WHERE
- t.link_id = "#,
+ "#,
sort_ts_field, sort_ts_field
));
- builder.push_bind(params.link_id);
+ match params.shared {
+ SharedEmailFilter::Exclude => {
+ builder.push("t.link_id = ");
+ builder.push_bind(params.link_id);
+ }
+ SharedEmailFilter::Include => {
+ builder.push("(t.link_id = ");
+ builder.push_bind(params.link_id);
+ builder.push(" OR t.id IN (SELECT thread_id FROM SharedEmailThreads))");
+ }
+ SharedEmailFilter::Only => {
+ builder.push("t.id IN (SELECT thread_id FROM SharedEmailThreads)");
+ }
+ }
// Add view-specific thread filters
if !view_thread_filter.is_empty() {
@@ -187,6 +247,8 @@ fn build_query(
) AS lmp
-- Step 3: Join to get the sender's details
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ -- Step 4: Join to get the thread owner's macro user ID
+ JOIN email_links el ON t.link_id = el.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
);
@@ -194,6 +256,20 @@ fn build_query(
builder
}
+/// Extracts the [SharedEmailFilter] from the email filter AST, defaulting to Exclude.
+fn extract_shared_filter(ast: &Expr<EmailLiteral>) -> SharedEmailFilter {
+ ast.collapse_frames(
+ |frame: filter_ast::ExprFrame<SharedEmailFilter, EmailLiteral>| match frame {
+ filter_ast::ExprFrame::Literal(EmailLiteral::Shared(s)) => s,
+ filter_ast::ExprFrame::And(a, b) | filter_ast::ExprFrame::Or(a, b) => {
+ if !a.is_default() { a } else { b }
+ }
+ filter_ast::ExprFrame::Not(a) => a,
+ _ => SharedEmailFilter::Exclude,
+ },
+ )
+}
+
/// Fetches a paginated list of thread previews with dynamic filtering based on EmailLiteral AST.
/// This function provides a flexible alternative to the hardcoded view-specific queries,
/// combining view-specific filters (Inbox, Sent, Drafts, etc.) with custom email filters
@@ -226,6 +302,7 @@ pub(crate) async fn dynamic_email_thread_cursor(
limit: u32,
view: &PreviewView,
query: Query<Uuid, SimpleSortMethod, Arc<Expr<EmailLiteral>>>,
+ user_id: &str,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
let query_limit = limit as i64;
let sort_method_str = query.sort_method().to_string();
@@ -234,13 +311,14 @@ pub(crate) async fn dynamic_email_thread_cursor(
// Extract email filter from query
let email_filter = query.filter();
+ let shared = extract_shared_filter(email_filter);
let is_important = matches!(
view,
PreviewView::StandardLabel(PreviewViewStandardLabel::Important)
);
- build_query(
+ let mut qb = build_query(
view,
email_filter,
QueryParams {
@@ -250,29 +328,32 @@ pub(crate) async fn dynamic_email_thread_cursor(
cursor_timestamp: cursor_timestamp.copied(),
cursor_id_str,
is_important,
+ shared,
+ user_id: user_id.to_string(),
},
- )
- .build()
- .try_map(|row| {
- Ok(ThreadPreviewCursorDbRow {
- id: row.try_get("id")?,
- provider_id: row.try_get("provider_id")?,
- inbox_visible: row.try_get("inbox_visible")?,
- is_read: row.try_get("is_read")?,
- is_draft: row.try_get("is_draft")?,
- is_important: row.try_get("is_important")?,
- sort_ts: row.try_get("sort_ts")?,
- name: row.try_get("name")?,
- snippet: row.try_get("snippet")?,
- sender_email: row.try_get("sender_email")?,
- sender_name: row.try_get("sender_name")?,
- sender_photo_url: row.try_get("sender_photo_url")?,
- viewed_at: row.try_get("viewed_at")?,
- created_at: row.try_get("created_at")?,
- updated_at: row.try_get("updated_at")?,
- project_id: row.try_get("project_id")?,
+ );
+ qb.build()
+ .try_map(|row| {
+ Ok(ThreadPreviewCursorDbRow {
+ id: row.try_get("id")?,
+ provider_id: row.try_get("provider_id")?,
+ inbox_visible: row.try_get("inbox_visible")?,
+ is_read: row.try_get("is_read")?,
+ is_draft: row.try_get("is_draft")?,
+ is_important: row.try_get("is_important")?,
+ sort_ts: row.try_get("sort_ts")?,
+ name: row.try_get("name")?,
+ snippet: row.try_get("snippet")?,
+ sender_email: row.try_get("sender_email")?,
+ sender_name: row.try_get("sender_name")?,
+ sender_photo_url: row.try_get("sender_photo_url")?,
+ viewed_at: row.try_get("viewed_at")?,
+ created_at: row.try_get("created_at")?,
+ updated_at: row.try_get("updated_at")?,
+ project_id: row.try_get("project_id")?,
+ owner_id: row.try_get("owner_id")?,
+ })
})
- })
- .fetch_all(pool)
- .await
+ .fetch_all(pool)
+ .await
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs
index 19a7219750..d35a1228d0 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview.rs
@@ -27,8 +27,15 @@ pub(super) async fn previews_for_view_cursor(
Ok(match (view, query) {
(view, Either::Right(dynamic_query)) => {
- super::dynamic::dynamic_email_thread_cursor(pool, &link_id, limit, &view, dynamic_query)
- .await?
+ super::dynamic::dynamic_email_thread_cursor(
+ pool,
+ &link_id,
+ limit,
+ &view,
+ dynamic_query,
+ user_id.as_ref(),
+ )
+ .await?
}
(PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox), Either::Left(query)) => {
super::preview_views::new_inbox::new_inbox_preview_cursor(pool, &link_id, limit, &query)
@@ -71,7 +78,7 @@ pub(super) async fn previews_for_view_cursor(
}
}
.into_iter()
- .map(|row: ThreadPreviewCursorDbRow| row.with_user_id(user_id.clone()))
+ .map(|row: ThreadPreviewCursorDbRow| row.into_preview())
.collect())
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
index aa26890dd1..b43709321a 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/all_mail.rs
@@ -53,7 +53,8 @@ pub(crate) async fn all_mail_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Efficiently find, sort, and limit the top N+1 threads.
-- This subquery only touches `threads` and `user_history`, making it very fast.
@@ -115,6 +116,7 @@ pub(crate) async fn all_mail_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details for the final result set.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
link_id, // $1
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
index 2dc5c39a6a..971f715ef1 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/draft.rs
@@ -46,7 +46,8 @@ pub(crate) async fn drafts_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Find the latest draft timestamp for each thread, calculate the
-- effective sort key, then sort and limit the results. This is the core optimization.
@@ -114,6 +115,7 @@ pub(crate) async fn drafts_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
link_id, // $1
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
index c36f705d67..657825ad43 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/important.rs
@@ -141,10 +141,12 @@ pub(crate) async fn important_preview_cursor(
isk.snippet as "snippet?",
c.email_address AS "sender_email?",
COALESCE(isk.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM ImportantWithSortKey isk
JOIN email_threads t ON isk.thread_id = t.id
LEFT JOIN email_contacts c ON isk.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
WHERE
($3::timestamptz IS NULL) OR (isk.effective_ts, isk.thread_id) < ($3::timestamptz, $4::uuid)
ORDER BY isk.effective_ts DESC, isk.thread_id DESC
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
index 75790ad9c6..ce07425dfc 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/new_inbox.rs
@@ -49,7 +49,8 @@ pub(crate) async fn new_inbox_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
-- This subquery is fast as it only touches `threads` and `user_history`.
@@ -106,6 +107,7 @@ pub(crate) async fn new_inbox_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details for the final result set.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
-- Final ordering is preserved because the input `t` is already sorted.
ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
"#,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
index f7ba604798..7ba209bd89 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/other_inbox.rs
@@ -47,7 +47,8 @@ pub(crate) async fn other_inbox_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Efficiently find, sort, and limit the top N+1 threads that qualify for the "Other" inbox.
SELECT
@@ -112,6 +113,7 @@ pub(crate) async fn other_inbox_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
link_id, // $1
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
index f7d5d0735b..3003325556 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/sent.rs
@@ -47,7 +47,8 @@ pub(crate) async fn sent_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Efficiently find and sort ONLY the top N+1 candidate threads.
-- This subquery only touches `threads` and `user_history`.
@@ -104,6 +105,7 @@ pub(crate) async fn sent_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details for the final result set.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
-- Final ordering is preserved because the input `t` is already sorted.
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
index b9f377c058..b49e0b0632 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/starred.rs
@@ -47,7 +47,8 @@ pub(crate) async fn starred_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Find the latest starred timestamp for each thread, calculate the
-- effective sort key, then sort and limit the results.
@@ -113,6 +114,7 @@ pub(crate) async fn starred_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
link_id, // $1
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
index 79e1c5c230..280351d254 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/preview_views/user_label.rs
@@ -48,7 +48,8 @@ pub(crate) async fn user_label_preview_cursor(
) AS "is_important!",
c.email_address AS "sender_email?",
COALESCE(lmp.from_name, c.name) AS "sender_name?",
- c.sfs_photo_url as "sender_photo_url?"
+ c.sfs_photo_url as "sender_photo_url?",
+ el.macro_id AS "owner_id!"
FROM (
-- Step 1: Find the latest labeled message timestamp for each thread,
-- calculate the effective sort key, then sort and limit the results.
@@ -119,6 +120,7 @@ pub(crate) async fn user_label_preview_cursor(
) AS lmp
-- Step 3: Join to get the sender's details.
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ JOIN email_links el ON t.link_id = el.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
link_id, // $1
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
index 412a9cf9c8..3c2ab58c98 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
@@ -15,7 +15,7 @@ async fn test_dynamic_query_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<(
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get inbox messages (threads 1, 4, 5, 7)
assert_eq!(
@@ -49,7 +49,7 @@ async fn test_dynamic_query_sent_view(pool: Pool<Postgres>) -> anyhow::Result<()
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get sent messages (thread 2)
assert_eq!(results.len(), 1, "Sent view should return 1 thread");
@@ -75,7 +75,7 @@ async fn test_dynamic_query_drafts_view(pool: Pool<Postgres>) -> anyhow::Result<
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get draft messages (threads 3 and 8)
assert_eq!(results.len(), 2, "Drafts view should return 2 threads");
@@ -101,7 +101,7 @@ async fn test_dynamic_query_starred_view(pool: Pool<Postgres>) -> anyhow::Result
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get starred messages (thread 4)
assert_eq!(results.len(), 1, "Starred view should return 1 thread");
@@ -127,7 +127,7 @@ async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Resu
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get important messages and drafts (threads 3, 5, and 8)
assert_eq!(results.len(), 3, "Important view should return 3 threads");
@@ -205,7 +205,7 @@ async fn test_dynamic_query_user_label_view(pool: Pool<Postgres>) -> anyhow::Res
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get messages with "Work" label (thread 6)
assert_eq!(results.len(), 1, "User label view should return 1 thread");
@@ -233,7 +233,7 @@ async fn test_dynamic_query_with_sender_filter(pool: Pool<Postgres>) -> anyhow::
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get messages from [email protected] (threads 1, 2, 5)
assert!(
@@ -267,7 +267,7 @@ async fn test_dynamic_query_with_partial_sender_filter(pool: Pool<Postgres>) ->
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get all messages since all contacts are from example.com
assert!(
@@ -294,7 +294,7 @@ async fn test_dynamic_query_with_recipient_filter(pool: Pool<Postgres>) -> anyho
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get messages to [email protected] (threads 1, 3, 5, 7)
assert!(
@@ -321,7 +321,7 @@ async fn test_dynamic_query_with_cc_filter(pool: Pool<Postgres>) -> anyhow::Resu
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get messages with [email protected] in CC (thread 7)
assert_eq!(results.len(), 1, "Should return 1 thread with CC to bob");
@@ -349,7 +349,7 @@ async fn test_dynamic_query_inbox_with_sender_filter(pool: Pool<Postgres>) -> an
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get inbox messages from [email protected] (threads 1, 5)
assert_eq!(
@@ -387,7 +387,7 @@ async fn test_dynamic_query_drafts_with_recipient_filter(
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get draft messages to [email protected] (threads 3 and 8)
assert_eq!(
@@ -421,7 +421,7 @@ async fn test_dynamic_query_with_and_filter(pool: Pool<Postgres>) -> anyhow::Res
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get messages from john to alice (threads 1, 5)
assert!(
@@ -453,7 +453,7 @@ async fn test_dynamic_query_with_or_filter(pool: Pool<Postgres>) -> anyhow::Resu
let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Should get messages from john or jane
assert!(
@@ -479,7 +479,7 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<(
))));
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter1);
let first_page =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
assert_eq!(first_page.len(), 2, "Should return 2 results");
@@ -506,7 +506,7 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<(
};
let query2 = Query::new(Some(cursor), SimpleSortMethod::UpdatedAt, filter3);
let second_page =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query2).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query2, "").await?;
assert!(
second_page.len() > 0,
@@ -550,7 +550,7 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyh
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Threads 1 (CATEGORY_PERSONAL), 2 (SENT), 3 (DRAFT), 4 (no depriority), 5 (no depriority), 8 (DRAFT overrides depriority)
assert_eq!(
@@ -604,7 +604,7 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyh
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Threads 6 (CATEGORY_UPDATES) and 7 (CATEGORY_PROMOTIONS)
// Thread 8 has CATEGORY_UPDATES but is excluded because DRAFT is a priority label
@@ -652,7 +652,7 @@ async fn test_dynamic_query_with_single_project_id(pool: Pool<Postgres>) -> anyh
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Threads 1, 2, 5 are in Project Alpha
assert_eq!(results.len(), 3, "Should return 3 threads in Project Alpha");
@@ -688,7 +688,7 @@ async fn test_dynamic_query_with_multiple_project_ids(pool: Pool<Postgres>) -> a
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Threads 1, 2, 5 (Alpha) + Thread 6 (Beta)
assert_eq!(
@@ -729,7 +729,7 @@ async fn test_dynamic_query_project_id_with_sender_filter(
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// All results should be in Project Alpha and from john
for result in &results {
@@ -762,7 +762,7 @@ async fn test_dynamic_query_project_id_with_inbox_view(pool: Pool<Postgres>) ->
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
assert_eq!(
results.len(),
@@ -799,7 +799,7 @@ async fn test_dynamic_query_inbox_view_with_importance_false(
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
// Only thread 7: inbox_visible=true AND importance=false
assert_eq!(
@@ -839,7 +839,7 @@ async fn test_dynamic_query_with_single_thread_id(pool: Pool<Postgres>) -> anyho
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
assert_eq!(results.len(), 1);
assert_eq!(results[0].id, thread_id);
@@ -875,7 +875,7 @@ async fn test_dynamic_query_thread_id_with_sender_filter(
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
assert_eq!(results.len(), 1);
assert_eq!(results[0].id, id1);
@@ -902,7 +902,7 @@ async fn test_importance_true_includes_drafts_with_depriority_label(
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
let result_ids: std::collections::HashSet<String> =
results.iter().map(|r| r.id.to_string()).collect();
@@ -938,7 +938,7 @@ async fn test_importance_true_excludes_trashed_drafts(pool: Pool<Postgres>) -> a
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
let result_ids: std::collections::HashSet<String> =
results.iter().map(|r| r.id.to_string()).collect();
@@ -979,7 +979,7 @@ async fn test_importance_false_excludes_drafts(pool: Pool<Postgres>) -> anyhow::
let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
let results =
- dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
let result_ids: std::collections::HashSet<String> =
results.iter().map(|r| r.id.to_string()).collect();
@@ -1142,3 +1142,217 @@ async fn test_static_user_label_excludes_trashed(pool: Pool<Postgres>) -> anyhow
Ok(())
}
+
+// === Shared email thread tests ===
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads")
+ )
+)]
+async fn test_shared_exclude_returns_only_own_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Exclude,
+ )));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &link_id,
+ limit,
+ &view,
+ query,
+ )
+ .await?;
+
+ let result_ids: std::collections::HashSet<String> =
+ results.iter().map(|r| r.id.to_string()).collect();
+
+ // Should NOT include any of user2's threads
+ assert!(
+ !result_ids.contains("20000101-0000-0000-0000-000000000101"),
+ "Exclude mode should not return directly shared thread"
+ );
+ assert!(
+ !result_ids.contains("20000102-0000-0000-0000-000000000102"),
+ "Exclude mode should not return project-shared thread"
+ );
+ assert!(
+ !result_ids.contains("20000103-0000-0000-0000-000000000103"),
+ "Exclude mode should not return unshared thread from other user"
+ );
+
+ // Should include user1's own threads
+ assert!(
+ !results.is_empty(),
+ "Exclude mode should still return user's own threads"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads")
+ )
+)]
+async fn test_shared_only_returns_only_shared_threads(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Only,
+ )));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &link_id,
+ limit,
+ &view,
+ query,
+ )
+ .await?;
+
+ let result_ids: std::collections::HashSet<String> =
+ results.iter().map(|r| r.id.to_string()).collect();
+
+ // Should include directly shared thread
+ assert!(
+ result_ids.contains("20000101-0000-0000-0000-000000000101"),
+ "Only mode should return directly shared thread 101"
+ );
+
+ // Should include project-shared thread
+ assert!(
+ result_ids.contains("20000102-0000-0000-0000-000000000102"),
+ "Only mode should return project-shared thread 102"
+ );
+
+ // Should NOT include unshared thread from user2
+ assert!(
+ !result_ids.contains("20000103-0000-0000-0000-000000000103"),
+ "Only mode should not return unshared thread 103"
+ );
+
+ // Should NOT include any of user1's own threads
+ assert!(
+ !result_ids.contains("20000001-0000-0000-0000-000000000001"),
+ "Only mode should not return user's own threads"
+ );
+
+ assert_eq!(
+ results.len(),
+ 2,
+ "Only mode should return exactly 2 shared threads"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads")
+ )
+)]
+async fn test_shared_include_returns_own_and_shared_threads(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Include,
+ )));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &link_id,
+ limit,
+ &view,
+ query,
+ )
+ .await?;
+
+ let result_ids: std::collections::HashSet<String> =
+ results.iter().map(|r| r.id.to_string()).collect();
+
+ // Should include user1's own threads
+ assert!(
+ result_ids.contains("20000001-0000-0000-0000-000000000001"),
+ "Include mode should return user's own thread 1"
+ );
+
+ // Should include directly shared thread
+ assert!(
+ result_ids.contains("20000101-0000-0000-0000-000000000101"),
+ "Include mode should return directly shared thread 101"
+ );
+
+ // Should include project-shared thread
+ assert!(
+ result_ids.contains("20000102-0000-0000-0000-000000000102"),
+ "Include mode should return project-shared thread 102"
+ );
+
+ // Should NOT include unshared thread from user2
+ assert!(
+ !result_ids.contains("20000103-0000-0000-0000-000000000103"),
+ "Include mode should not return unshared thread 103"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_shared_threads")
+ )
+)]
+async fn test_shared_only_returns_correct_owner_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Shared(
+ item_filters::SharedEmailFilter::Only,
+ )));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results = dynamic::dynamic_email_thread_cursor(
+ &pool,
+ &link_id,
+ limit,
+ &view,
+ query,
+ )
+ .await?;
+
+ // All shared threads should have user2's macro_id as owner
+ for result in &results {
+ assert_eq!(
+ result.owner_id.as_str(),
+ "Shared threads should have user2 as owner, got {:?} for thread {}",
+ result.owner_id,
+ result.id
+ );
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rs
index 8b5323022a..2082c343a6 100644
--- a/rust/cloud-storage/item_filters/src/ast/email.rs
+++ b/rust/cloud-storage/item_filters/src/ast/email.rs
@@ -3,7 +3,7 @@ use macro_user_id::{cowlike::CowLike, email::EmailStr};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-use crate::{EmailFilters, ast::ExpandErr};
+use crate::{EmailFilters, SharedEmailFilter, ast::ExpandErr};
/// Possible email values in the ast
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -35,6 +35,8 @@ pub enum EmailLiteral {
NotificationDone(bool),
/// This node value filters by notification seen state for emails.
NotificationSeen(bool),
+ /// Controls whether shared email threads are included in results.
+ Shared(SharedEmailFilter),
}
impl ExpandFrame<EmailLiteral> for EmailFilters {
@@ -51,6 +53,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
notification_filters,
include_labels: _,
exclude_labels: _,
+ shared,
} = input;
fn map_email(s: String) -> Email {
@@ -93,6 +96,11 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
let notification_seen_node = notification_filters
.seen
.map(|seen| Expr::Literal(EmailLiteral::NotificationSeen(seen)));
+ let shared_node = if shared.is_default() {
+ None
+ } else {
+ Some(Expr::Literal(EmailLiteral::Shared(shared)))
+ };
Ok([
sender_nodes,
@@ -104,6 +112,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {
importance_node,
notification_done_node,
notification_seen_node,
+ shared_node,
]
.into_iter()
.fold_with(Expr::and))
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index b8dde15d46..51bea9e2fa 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -176,6 +176,27 @@ impl IsEmpty for ChatFilters {
}
}
+/// Controls whether shared email threads are included in results.
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone, Copy)]
+#[serde(rename_all = "snake_case")]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
+pub enum SharedEmailFilter {
+ /// Only show the user's own threads (default)
+ #[default]
+ Exclude,
+ /// Show both own and shared threads
+ Include,
+ /// Show only threads shared with the user
+ Only,
+}
+
+impl SharedEmailFilter {
+ /// Returns true if this is the default (Exclude) variant.
+ pub fn is_default(&self) -> bool {
+ matches!(self, SharedEmailFilter::Exclude)
+ }
+}
+
/// The email filters used to filter down what emails you search over.
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
@@ -220,6 +241,11 @@ pub struct EmailFilters {
/// Note: SPAM and TRASH emails are not indexed in OpenSearch, so they are already excluded by default.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exclude_labels: Vec<String>,
+
+ /// Controls whether shared email threads are included in results.
+ /// Defaults to "exclude" (only the user's own threads).
+ #[serde(default, skip_serializing_if = "SharedEmailFilter::is_default")]
+ pub shared: SharedEmailFilter,
}
impl IsEmpty for EmailFilters {
@@ -235,6 +261,7 @@ impl IsEmpty for EmailFilters {
notification_filters,
include_labels,
exclude_labels,
+ shared,
} = self;
senders.is_empty()
&& cc.is_empty()
@@ -246,6 +273,7 @@ impl IsEmpty for EmailFilters {
&& notification_filters.is_empty()
&& include_labels.is_empty()
&& exclude_labels.is_empty()
+ && shared.is_default()
}
}