Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): add project support for email threads (#2065)
Evan Hutnik6dda91d57fb2
diff --git a/js/app/bun.lock b/js/app/bun.lockindex 9a42aeaf60..53e01033e1 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -2783,7 +2783,7 @@"pathval": ["[email protected]", "", {}, "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts b/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.tsindex 39fdefa8a5..68f733770f 100644--- a/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts+++ b/js/app/packages/app/component/next-soup/actions/make-move-to-project-action.ts@@ -7,7 +7,7 @@ import { useMaybePreviewPanel } from '@app/component/PreviewPanel';export const makeMoveToProjectAction = () => {const canExecute = (entity: EntityData): boolean => {- return entity.type !== 'channel' && entity.type !== 'email';+ return entity.type !== 'channel';};const execute = async (entities: EntityData[]) => {diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsxindex 506ef4f160..d6308bdae4 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/filter-controls.tsx@@ -226,7 +226,7 @@ export const EntityTypeFilter = () => {);};-type FolderFilterTarget = 'chat' | 'document';+type FolderFilterTarget = 'chat' | 'document' | 'email';interface FolderFilterProps {target: FolderFilterTarget;@@ -254,7 +254,9 @@ export const FolderFilter = (props: FolderFilterProps) => {const projectIds =props.target === 'chat'? filters.chat_filters?.project_ids- : filters.document_filters?.project_ids;+ : props.target === 'email'+ ? filters.email_filters?.project_ids+ : filters.document_filters?.project_ids;if (!projectIds?.length) return [];@@ -279,6 +281,16 @@ export const FolderFilter = (props: FolderFilterProps) => {};}+ if (props.target === 'email') {+ return {+ ...prev,+ email_filters: {+ ...prev.email_filters,+ project_ids: newProjectIds,+ },+ };+ }+return {...prev,document_filters: {diff --git a/js/app/packages/block-project/component/Block.tsx b/js/app/packages/block-project/component/Block.tsxindex 7162cb45c2..6ffdb39779 100644--- a/js/app/packages/block-project/component/Block.tsx+++ b/js/app/packages/block-project/component/Block.tsx@@ -35,7 +35,7 @@ import { NIL_UUID } from '@app/component/next-soup/filters/query-filters';false && fileFolderDrop;false && fileSelector;-const PROJECT_ENTITY_TYPES = ['document', 'task', 'chat', 'project'];+const PROJECT_ENTITY_TYPES = ['document', 'task', 'chat', 'project', 'email'];const Block: Component = () => {useBlockEntityCommands();@@ -197,7 +197,7 @@ const ProjectEntityList = (props: {project_ids: [props.projectId],},email_filters: {- recipients: [NIL_UUID],+ project_ids: [props.projectId],},}}>diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.tsindex 2c4a705ee6..637e38a088 100644--- a/js/app/packages/core/component/FileList/itemOperations.ts+++ b/js/app/packages/core/component/FileList/itemOperations.ts@@ -3,6 +3,7 @@ import { isPaymentError } from '@core/util/handlePaymentError';import { isErr, isOk } from '@core/util/maybeResult';import { cognitionApiServiceClient } from '@service-cognition/client';import { commsServiceClient } from '@service-comms/client';+import { emailClient } from '@service-email/client';import { type ItemType, storageServiceClient } from '@service-storage/client';import {getDeletedTree,@@ -55,6 +56,15 @@ export async function getItemAccessLevel({return maybeChatMetadata[1].userAccessLevel;}break;+ case 'email':+ const maybeThread = await emailClient.getThread({+ thread_id: id,+ limit: 1,+ });+ if (isOk(maybeThread)) {+ return maybeThread[1].thread.access_level;+ }+ break;default:return;}@@ -226,6 +236,13 @@ export async function moveToFolder(args: {});break;}+ case 'email': {+ result = await emailClient.updateThreadProject({+ thread_id: id,+ projectId: folderId,+ });+ break;+ }default: {return false;}diff --git a/js/app/packages/entity/src/types/entity.ts b/js/app/packages/entity/src/types/entity.tsindex fb279d085c..90877b43e6 100644--- a/js/app/packages/entity/src/types/entity.ts+++ b/js/app/packages/entity/src/types/entity.ts@@ -87,6 +87,7 @@ export type EmailEntity = EntityBase & {snippet?: string;isImportant: boolean;done: boolean;+ projectId?: string;participants?: EmailThreadParticipants;senderEmail?: string;senderName?: string;diff --git a/js/app/packages/macro-entity/src/queries/dss.ts b/js/app/packages/macro-entity/src/queries/dss.tsindex b35ba61e90..5b7491d311 100644--- a/js/app/packages/macro-entity/src/queries/dss.ts+++ b/js/app/packages/macro-entity/src/queries/dss.ts@@ -175,7 +175,12 @@ export function createBulkCopyDssEntityMutation() {export function createBulkMoveToProjectDssEntityMutation() {const isUnsupportedEntity = (entity: EntityData) => {const type = entity.type;- return type !== 'chat' && type !== 'document' && type !== 'project';+ return (+ type !== 'chat' &&+ type !== 'document' &&+ type !== 'project' &&+ type !== 'email'+ );};return useMutation(() => ({@@ -193,7 +198,7 @@ export function createBulkMoveToProjectDssEntityMutation() {const results = await Promise.all(entities.map((entity) =>moveToFolder({- itemType: entity.type as 'document' | 'chat' | 'project',+ itemType: entity.type as 'document' | 'chat' | 'project' | 'email',id: entity.id,folderId: project.id,})@@ -215,13 +220,14 @@ export function createBulkMoveToProjectDssEntityMutation() {project: { id: string; name: string };}) => {const moveableEntities = entities.filter(- (e): e is typeof e & { type: 'document' | 'chat' } =>- e.type === 'document' || e.type === 'chat'+ (e): e is typeof e & { type: 'document' | 'chat' | 'email' } =>+ e.type === 'document' || e.type === 'chat' || e.type === 'email');return moveableEntities.map((e) => {const current = getSoupEntityById(e.id);+ const tag = e.type === 'email' ? 'emailThread' : e.type;return optimisticUpdateSoupEntity({- tag: e.type,+ tag,data: { id: e.id, projectId: project.id },frecency_score: current?.frecency_score ?? 0,});diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 6f5d6ba89f..23dee40e03 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -410,6 +410,7 @@ export const mapSoupPageToEntityList: (name: item.data.name || 'Email Thread',frecencyScore: item.frecency_score,viewedAt: item.data.viewedAt,+ projectId: item.data.projectId ?? undefined,participants,hasIcsAttachment,attachments,diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex 4718cdf5ae..8182fac070 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -137,6 +137,19 @@ export const emailClient = {(result) => result);},+ async updateThreadProject(args: {+ thread_id: string;+ projectId: string | null;+ }) {+ const { thread_id, projectId } = args;+ return emailFetch<{ oldProjectId: string | null }>(+ `/email/threads/${thread_id}/project`,+ {+ method: 'PATCH',+ body: JSON.stringify({ projectId }),+ }+ );+ },async flagArchived(args: { value: boolean; id: string }) {const { value, id } = args;return mapOk(diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex 35870b0130..f5e1f7b92d 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -45,6 +45,8 @@ import type {UpdateLabelBatchResponse,UpdateThreadLabelRequest,UpdateThreadLabelsResponse,+ UpdateThreadProjectRequest,+ UpdateThreadProjectResponse,UpsertScheduledRequest,UpsertScheduledResponse,} from './schemas';@@ -2384,6 +2386,73 @@ export const getThread = async (} as getThreadResponse;};+/**+ * @summary Update the project assignment for a thread.+ */+export type updateThreadProjectResponse200 = {+ data: UpdateThreadProjectResponse;+ status: 200;+};++export type updateThreadProjectResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type updateThreadProjectResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type updateThreadProjectResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type updateThreadProjectResponseSuccess =+ updateThreadProjectResponse200 & {+ headers: Headers;+ };+export type updateThreadProjectResponseError = (+ | updateThreadProjectResponse401+ | updateThreadProjectResponse404+ | updateThreadProjectResponse500+) & {+ headers: Headers;+};++export type updateThreadProjectResponse =+ | updateThreadProjectResponseSuccess+ | updateThreadProjectResponseError;++export const getUpdateThreadProjectUrl = (threadId: string) => {+ return `/email/threads/${threadId}/project`;+};++export const updateThreadProject = async (+ threadId: string,+ updateThreadProjectRequest: UpdateThreadProjectRequest,+ options?: RequestInit+): Promise<updateThreadProjectResponse> => {+ const res = await fetch(getUpdateThreadProjectUrl(threadId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(updateThreadProjectRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: updateThreadProjectResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as updateThreadProjectResponse;+};+/*** @summary Health check*/diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThread.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThread.tsindex e2ef7f7bb3..0acb752d70 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/apiThread.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThread.ts@@ -9,6 +9,7 @@ import type { ApiMessage } from './apiMessage';import type { ApiThreadLatestInboundMessageTs } from './apiThreadLatestInboundMessageTs';import type { ApiThreadLatestNonSpamMessageTs } from './apiThreadLatestNonSpamMessageTs';import type { ApiThreadLatestOutboundMessageTs } from './apiThreadLatestOutboundMessageTs';+import type { ApiThreadProjectId } from './apiThreadProjectId';import type { ApiThreadProviderId } from './apiThreadProviderId';/**@@ -25,6 +26,7 @@ export interface ApiThread {latest_outbound_message_ts?: ApiThreadLatestOutboundMessageTs;link_id: string;messages: ApiMessage[];+ project_id?: ApiThreadProjectId;provider_id?: ApiThreadProviderId;updated_at: string;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiThreadProjectId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadProjectId.tsnew file mode 100644index 0000000000..d19f562605--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiThreadProjectId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++export type ApiThreadProjectId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.tsindex 81e5df8009..d756e64dcd 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts@@ -115,6 +115,7 @@ export * from './apiThreadPreviewCursorInnerSenderName';export * from './apiThreadPreviewCursorInnerSenderPhotoUrl';export * from './apiThreadPreviewCursorInnerSnippet';export * from './apiThreadPreviewCursorInnerViewedAt';+export * from './apiThreadProjectId';export * from './apiThreadProviderId';export * from './archiveThreadRequest';export * from './attachment';@@ -240,6 +241,10 @@ export * from './updateLabelBatchRequest';export * from './updateLabelBatchResponse';export * from './updateThreadLabelRequest';export * from './updateThreadLabelsResponse';+export * from './updateThreadProjectRequest';+export * from './updateThreadProjectRequestProjectId';+export * from './updateThreadProjectResponse';+export * from './updateThreadProjectResponseOldProjectId';export * from './upsertScheduledRequest';export * from './upsertScheduledResponse';export * from './userProvider';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectRequest.tsnew file mode 100644index 0000000000..bda49203b1--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { UpdateThreadProjectRequestProjectId } from './updateThreadProjectRequestProjectId';++/**+ * Request body for updating a thread's project.+ */+export interface UpdateThreadProjectRequest {+ /** The project ID to assign to the thread, or null to remove from project. */+ projectId?: UpdateThreadProjectRequestProjectId;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectRequestProjectId.ts b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectRequestProjectId.tsnew file mode 100644index 0000000000..f7ca1958cb--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectRequestProjectId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The project ID to assign to the thread, or null to remove from project.+ */+export type UpdateThreadProjectRequestProjectId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectResponse.tsnew file mode 100644index 0000000000..fec750cd73--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { UpdateThreadProjectResponseOldProjectId } from './updateThreadProjectResponseOldProjectId';++/**+ * Response body for updating a thread's project.+ */+export interface UpdateThreadProjectResponse {+ /** The previous project ID of the thread. */+ oldProjectId?: UpdateThreadProjectResponseOldProjectId;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectResponseOldProjectId.ts b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectResponseOldProjectId.tsnew file mode 100644index 0000000000..952908be8f--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/updateThreadProjectResponseOldProjectId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The previous project ID of the thread.+ */+export type UpdateThreadProjectResponseOldProjectId = string | null;diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex e712b71392..3de73e3a01 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -2306,6 +2306,76 @@}}},+ "/email/threads/{thread_id}/project": {+ "patch": {+ "tags": ["Threads"],+ "summary": "Update the project assignment for a thread.",+ "operationId": "update_thread_project",+ "parameters": [+ {+ "name": "thread_id",+ "in": "path",+ "description": "Thread ID",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateThreadProjectRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateThreadProjectResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/health": {"get": {"tags": ["Health"],@@ -3114,6 +3184,9 @@"$ref": "#/components/schemas/ApiMessage"}},+ "project_id": {+ "type": ["string", "null"]+ },"provider_id": {"type": ["string", "null"]},@@ -4435,6 +4508,26 @@}}},+ "UpdateThreadProjectRequest": {+ "type": "object",+ "description": "Request body for updating a thread's project.",+ "properties": {+ "projectId": {+ "type": ["string", "null"],+ "description": "The project ID to assign to the thread, or null to remove from project."+ }+ }+ },+ "UpdateThreadProjectResponse": {+ "type": "object",+ "description": "Response body for updating a thread's project.",+ "properties": {+ "oldProjectId": {+ "type": ["string", "null"],+ "description": "The previous project ID of the thread."+ }+ }+ },"UpsertScheduledRequest": {"type": "object","required": ["send_time"],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.tsindex 2a76a24faf..5127ba1de3 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@@ -29,6 +29,8 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never apinclude_labels?: string[];/** Filter by email notification state. */notification_filters?: NotificationFilters;+ /** A list of project ids to search within. Empty to ignore project filtering. */+ project_ids?: string[];/** Email Recipient addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by Recipient. */recipients?: string[];/** Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders. */diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex cbefa936df..f08e7183a7 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -922,6 +922,13 @@"$ref": "#/components/schemas/NotificationFilters","description": "Filter by email notification state."},+ "project_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "A list of project ids to search within. Empty to ignore project filtering."+ },"recipients": {"type": "array","items": {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.tsindex 1e8063291c..0254d1d07d 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@@ -29,6 +29,8 @@ Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never apinclude_labels?: string[];/** Filter by email notification state. */notification_filters?: NotificationFilters;+ /** A list of project ids to search within. Empty to ignore project filtering. */+ project_ids?: string[];/** Email Recipient addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by Recipient. */recipients?: string[];/** Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders. */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.tsindex f79ac72070..43284f607d 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@@ -541,6 +541,7 @@ export * from './soupDocumentSubTypeProperty';export * from './soupDocumentViewedAt';export * from './soupEmailThreadPreview';export * from './soupEmailThreadPreviewName';+export * from './soupEmailThreadPreviewProjectId';export * from './soupEmailThreadPreviewProviderId';export * from './soupEmailThreadPreviewSenderEmail';export * from './soupEmailThreadPreviewSenderName';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreview.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreview.tsindex 728d6a4f6c..fc3f571d5a 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreview.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreview.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { SoupEmailThreadPreviewName } from './soupEmailThreadPreviewName';+import type { SoupEmailThreadPreviewProjectId } from './soupEmailThreadPreviewProjectId';import type { SoupEmailThreadPreviewProviderId } from './soupEmailThreadPreviewProviderId';import type { SoupEmailThreadPreviewSenderEmail } from './soupEmailThreadPreviewSenderEmail';import type { SoupEmailThreadPreviewSenderName } from './soupEmailThreadPreviewSenderName';@@ -21,6 +22,7 @@ export interface SoupEmailThreadPreview {isRead: boolean;name?: SoupEmailThreadPreviewName;ownerId: string;+ projectId?: SoupEmailThreadPreviewProjectId;providerId?: SoupEmailThreadPreviewProviderId;senderEmail?: SoupEmailThreadPreviewSenderEmail;senderName?: SoupEmailThreadPreviewSenderName;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreviewProjectId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreviewProjectId.tsnew file mode 100644index 0000000000..555550efeb--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupEmailThreadPreviewProjectId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type SoupEmailThreadPreviewProjectId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 23737d7576..7324105760 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -3694,6 +3694,7 @@ export const getItemsSoupResponse = zod.object({isRead: zod.boolean(),name: zod.string().nullish(),ownerId: zod.string(),+ projectId: zod.string().nullish(),providerId: zod.string().nullish(),senderEmail: zod.string().nullish(),senderName: zod.string().nullish(),@@ -4320,6 +4321,12 @@ export const postItemsSoupBody = zod}).optional().describe('Notification-level filters that apply to an entity type.'),+ project_ids: zod+ .array(zod.string())+ .optional()+ .describe(+ 'A list of project ids to search within. Empty to ignore project filtering.'+ ),recipients: zod.array(zod.string()).optional()@@ -5279,6 +5286,7 @@ export const postItemsSoupResponse = zod.object({isRead: zod.boolean(),name: zod.string().nullish(),ownerId: zod.string(),+ projectId: zod.string().nullish(),providerId: zod.string().nullish(),senderEmail: zod.string().nullish(),senderName: zod.string().nullish(),diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 9a530ee3d8..d06ff712a0 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -6942,6 +6942,13 @@"$ref": "#/components/schemas/NotificationFilters","description": "Filter by email notification state."},+ "project_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "A list of project ids to search within. Empty to ignore project filtering."+ },"recipients": {"type": "array","items": {@@ -9971,6 +9978,9 @@"ownerId": {"type": "string"},+ "projectId": {+ "type": ["string", "null"]+ },"providerId": {"type": ["string", "null"]},diff --git a/rust/cloud-storage/email/.sqlx/query-0e0422c73b3bdb5c60680cec7581ac905f34c70bd295694a120e8dd7891e3853.json b/rust/cloud-storage/email/.sqlx/query-0e0422c73b3bdb5c60680cec7581ac905f34c70bd295694a120e8dd7891e3853.jsonnew file mode 100644index 0000000000..625a77c4c3--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-0e0422c73b3bdb5c60680cec7581ac905f34c70bd295694a120e8dd7891e3853.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_threads\n SET project_id = $2, updated_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "0e0422c73b3bdb5c60680cec7581ac905f34c70bd295694a120e8dd7891e3853"+}diff --git a/rust/cloud-storage/email/.sqlx/query-1b6de2ef7fb060a48639ccdae7a8de85596b43caad2085e6dc9e3c6c3430e5c1.json b/rust/cloud-storage/email/.sqlx/query-1b6de2ef7fb060a48639ccdae7a8de85596b43caad2085e6dc9e3c6c3430e5c1.jsondeleted file mode 100644index 263aaa963a..0000000000--- a/rust/cloud-storage/email/.sqlx/query-1b6de2ef7fb060a48639ccdae7a8de85596b43caad2085e6dc9e3c6c3430e5c1.json+++ /dev/null@@ -1,111 +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.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 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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- null,- null,- null,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "1b6de2ef7fb060a48639ccdae7a8de85596b43caad2085e6dc9e3c6c3430e5c1"-}diff --git a/rust/cloud-storage/email/.sqlx/query-c00b010b70c1314694f0aa9f47c3ed778531e5d06c0f0436f63858281fd682e3.json b/rust/cloud-storage/email/.sqlx/query-26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f.jsonsimilarity index 85%rename from rust/cloud-storage/email/.sqlx/query-c00b010b70c1314694f0aa9f47c3ed778531e5d06c0f0436f63858281fd682e3.jsonrename to rust/cloud-storage/email/.sqlx/query-26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f.jsonindex c89b3838f6..2acef5cef5 100644--- a/rust/cloud-storage/email/.sqlx/query-c00b010b70c1314694f0aa9f47c3ed778531e5d06c0f0436f63858281fd682e3.json+++ b/rust/cloud-storage/email/.sqlx/query-26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f.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 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 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 ","describe": {"columns": [{@@ -40,41 +40,46 @@},{"ordinal": 7,+ "name": "project_id",+ "type_info": "Text"+ },+ {+ "ordinal": 8,"name": "viewed_at?","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 9,"name": "is_draft!","type_info": "Bool"},{- "ordinal": 9,+ "ordinal": 10,"name": "is_important!","type_info": "Bool"},{- "ordinal": 10,+ "ordinal": 11,"name": "name?","type_info": "Text"},{- "ordinal": 11,+ "ordinal": 12,"name": "snippet?","type_info": "Text"},{- "ordinal": 12,+ "ordinal": 13,"name": "sender_email?","type_info": "Varchar"},{- "ordinal": 13,+ "ordinal": 14,"name": "sender_name?","type_info": "Varchar"},{- "ordinal": 14,+ "ordinal": 15,"name": "sender_photo_url?","type_info": "Text"}@@ -96,6 +101,7 @@null,null,null,+ true,false,null,null,@@ -106,5 +112,5 @@true]},- "hash": "c00b010b70c1314694f0aa9f47c3ed778531e5d06c0f0436f63858281fd682e3"+ "hash": "26c62e1a9f613757fd03b3dc854b887587fdefd328e8c5d1b51838a634b16f1f"}diff --git a/rust/cloud-storage/email/.sqlx/query-292a3b8e05a93f73487443c08b705736e45e0800075902bb4a660c2e39988302.json b/rust/cloud-storage/email/.sqlx/query-292a3b8e05a93f73487443c08b705736e45e0800075902bb4a660c2e39988302.jsondeleted file mode 100644index 944498eb78..0000000000--- a/rust/cloud-storage/email/.sqlx/query-292a3b8e05a93f73487443c08b705736e45e0800075902bb4a660c2e39988302.json+++ /dev/null@@ -1,110 +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.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 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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- null,- null,- null,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "292a3b8e05a93f73487443c08b705736e45e0800075902bb4a660c2e39988302"-}diff --git a/rust/cloud-storage/email/.sqlx/query-4d652400e96ad57cb53adcedd99748bd8f44753a5511d83d99e6124ec31a00eb.json b/rust/cloud-storage/email/.sqlx/query-4d652400e96ad57cb53adcedd99748bd8f44753a5511d83d99e6124ec31a00eb.jsondeleted file mode 100644index 35485b3de2..0000000000--- a/rust/cloud-storage/email/.sqlx/query-4d652400e96ad57cb53adcedd99748bd8f44753a5511d83d99e6124ec31a00eb.json+++ /dev/null@@ -1,110 +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.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 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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- null,- null,- null,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "4d652400e96ad57cb53adcedd99748bd8f44753a5511d83d99e6124ec31a00eb"-}diff --git a/rust/cloud-storage/email/.sqlx/query-6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd.json b/rust/cloud-storage/email/.sqlx/query-6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd.jsonnew file mode 100644index 0000000000..bdf82a2be9--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-6308825c9185249f0d2345b2f3e3276c8e153fe60dc2dd19545ac7de17e816dd.json@@ -0,0 +1,116 @@+{+ "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.jsonnew file mode 100644index 0000000000..e4dfeb53f0--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-6fd1d9664bdbb6711f66cbb95e6703cbf3b285f97593dfd0eeecdbb474987074.json@@ -0,0 +1,116 @@+{+ "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-7794d9a18fedeb8c4bfe541f01e690007beef397f2a772d2e2a8ace54b04a321.json b/rust/cloud-storage/email/.sqlx/query-7794d9a18fedeb8c4bfe541f01e690007beef397f2a772d2e2a8ace54b04a321.jsondeleted file mode 100644index 1778fc94e9..0000000000--- a/rust/cloud-storage/email/.sqlx/query-7794d9a18fedeb8c4bfe541f01e690007beef397f2a772d2e2a8ace54b04a321.json+++ /dev/null@@ -1,110 +0,0 @@-{- "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.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.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 ",- "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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- null,- true,- true,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "7794d9a18fedeb8c4bfe541f01e690007beef397f2a772d2e2a8ace54b04a321"-}diff --git a/rust/cloud-storage/email/.sqlx/query-7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122.json b/rust/cloud-storage/email/.sqlx/query-7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122.jsonnew file mode 100644index 0000000000..2c35794f0f--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-7a2801aee37ec03a99a8b2b69c3ab70d8d4fdf952f6643589fdf253d6ae32122.json@@ -0,0 +1,116 @@+{+ "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-83dea9ffef9207e919ec708a6570c6f4090dbdbbb9f5f609edbad91becbc1bb4.json b/rust/cloud-storage/email/.sqlx/query-83dea9ffef9207e919ec708a6570c6f4090dbdbbb9f5f609edbad91becbc1bb4.jsonnew file mode 100644index 0000000000..1290218ff1--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-83dea9ffef9207e919ec708a6570c6f4090dbdbbb9f5f609edbad91becbc1bb4.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT project_id\n FROM email_threads\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "project_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "83dea9ffef9207e919ec708a6570c6f4090dbdbbb9f5f609edbad91becbc1bb4"+}diff --git a/rust/cloud-storage/email/.sqlx/query-8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4.json b/rust/cloud-storage/email/.sqlx/query-8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4.jsonnew file mode 100644index 0000000000..93205a125b--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-8457904f1747277abd3cc4e70ff28194f32c3ae2d6e67a392e679fd48aaab3f4.json@@ -0,0 +1,117 @@+{+ "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-8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574.json b/rust/cloud-storage/email/.sqlx/query-8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574.jsonnew file mode 100644index 0000000000..07ea7f8528--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574.json@@ -0,0 +1,116 @@+{+ "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 ",+ "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": "8928f4d015d60dc8ece8cb8665023ff9b779b876e032342c950cdb5a8c7f5574"+}diff --git a/rust/cloud-storage/email/.sqlx/query-b7e8f8ed8fecd120039ab8aad1373e90b280626bd7f4d164c04e814b947d4927.json b/rust/cloud-storage/email/.sqlx/query-b7e8f8ed8fecd120039ab8aad1373e90b280626bd7f4d164c04e814b947d4927.jsondeleted file mode 100644index fb767f941a..0000000000--- a/rust/cloud-storage/email/.sqlx/query-b7e8f8ed8fecd120039ab8aad1373e90b280626bd7f4d164c04e814b947d4927.json+++ /dev/null@@ -1,110 +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.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.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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- null,- true,- true,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "b7e8f8ed8fecd120039ab8aad1373e90b280626bd7f4d164c04e814b947d4927"-}diff --git a/rust/cloud-storage/email/.sqlx/query-bd3a03ee24e9b8a52d0dabc3872920624891977d33df5052d070a8019a864060.json b/rust/cloud-storage/email/.sqlx/query-bd3a03ee24e9b8a52d0dabc3872920624891977d33df5052d070a8019a864060.jsondeleted file mode 100644index 61ce1d3daa..0000000000--- a/rust/cloud-storage/email/.sqlx/query-bd3a03ee24e9b8a52d0dabc3872920624891977d33df5052d070a8019a864060.json+++ /dev/null@@ -1,110 +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.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.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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- null,- true,- true,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "bd3a03ee24e9b8a52d0dabc3872920624891977d33df5052d070a8019a864060"-}diff --git a/rust/cloud-storage/email/.sqlx/query-c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141.json b/rust/cloud-storage/email/.sqlx/query-c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141.jsonnew file mode 100644index 0000000000..64f269cefe--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-c3822d7dd145de025543eb4adaeba0bee0a970d6111ac2fc44049cbb0843e141.json@@ -0,0 +1,116 @@+{+ "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.jsonnew file mode 100644index 0000000000..86523dc51a--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-d8232849be1f6ec23537bb317cdf15e29ccdaf5ebee894e07dad1f8ca9b6b061.json@@ -0,0 +1,116 @@+{+ "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/.sqlx/query-0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23.json b/rust/cloud-storage/email/.sqlx/query-d9956cd2e52cda4f0e7c080058d33f2bbf35c99b29e7482f198d592ff435cf28.jsonsimilarity index 81%rename from rust/cloud-storage/email/.sqlx/query-0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23.jsonrename to rust/cloud-storage/email/.sqlx/query-d9956cd2e52cda4f0e7c080058d33f2bbf35c99b29e7482f198d592ff435cf28.jsonindex 1d88eeb713..6790b93ff8 100644--- a/rust/cloud-storage/email/.sqlx/query-0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23.json+++ b/rust/cloud-storage/email/.sqlx/query-d9956cd2e52cda4f0e7c080058d33f2bbf35c99b29e7482f198d592ff435cf28.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT t.id, t.provider_id, t.link_id, t.inbox_visible, t.is_read,\n t.latest_inbound_message_ts, t.latest_outbound_message_ts,\n t.latest_non_spam_message_ts, t.created_at, t.updated_at\n FROM email_threads t\n WHERE t.id = $1\n ",+ "query": "\n SELECT t.id, t.provider_id, t.link_id, t.inbox_visible, t.is_read,\n t.latest_inbound_message_ts, t.latest_outbound_message_ts,\n t.latest_non_spam_message_ts, t.created_at, t.updated_at,\n t.project_id\n FROM email_threads t\n WHERE t.id = $1\n ","describe": {"columns": [{@@ -52,6 +52,11 @@"ordinal": 9,"name": "updated_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "project_id",+ "type_info": "Text"}],"parameters": {@@ -69,8 +74,9 @@true,true,false,- false+ false,+ true]},- "hash": "0fa68fc475c11aef694e24ffa9db39d6823782c2a53f7fb0944f2d5720371b23"+ "hash": "d9956cd2e52cda4f0e7c080058d33f2bbf35c99b29e7482f198d592ff435cf28"}diff --git a/rust/cloud-storage/email/.sqlx/query-fe3861aa924320e57d72dbd209973c71c70608af0e34c5c530c31d4b99286b15.json b/rust/cloud-storage/email/.sqlx/query-fe3861aa924320e57d72dbd209973c71c70608af0e34c5c530c31d4b99286b15.jsondeleted file mode 100644index 096d4ee68e..0000000000--- a/rust/cloud-storage/email/.sqlx/query-fe3861aa924320e57d72dbd209973c71c70608af0e34c5c530c31d4b99286b15.json+++ /dev/null@@ -1,110 +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.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.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": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 11,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 13,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 14,- "name": "sender_photo_url?",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- null,- false,- null,- true,- true,- false,- true,- true,- false,- null,- false,- null,- true- ]- },- "hash": "fe3861aa924320e57d72dbd209973c71c70608af0e34c5c530c31d4b99286b15"-}diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query.sqlindex 0ad4f50bb1..eaf5cae952 100644--- a/rust/cloud-storage/email/fixtures/email_dynamic_query.sql+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query.sql@@ -1,6 +1,19 @@-- Fixture for testing dynamic email query builder-- Sets up threads, messages, contacts, recipients, labels for comprehensive testing+-- Insert test user for project ownership+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)+VALUES ('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_user1');++INSERT INTO "User" (id, email, name, macro_user_id)+VALUES ('macro|[email protected]', '[email protected]', 'Test User 1', 'a1111111-1111-1111-1111-111111111111');++-- Insert test projects+INSERT INTO "Project" (id, name, "userId", "createdAt", "updatedAt")+VALUES+ ('proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Project Alpha', 'macro|[email protected]', NOW(), NOW()),+ ('proj-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Project Beta', 'macro|[email protected]', NOW(), NOW());+-- Insert test linkINSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)VALUES@@ -36,27 +49,27 @@ INSERT INTO email_threads (created_at, updated_at)VALUES- -- Thread 1: Inbox, from [email protected]+ -- Thread 1: Inbox, from [email protected], in Project Alpha('20000001-0000-0000-0000-000000000001', 'thread1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',true, false, '2024-01-15 10:00:00+00', NULL, '2024-01-15 10:00:00+00', NOW(), NOW()),- -- Thread 2: Sent, to [email protected]+ -- Thread 2: Sent, to [email protected], in Project Alpha('20000002-0000-0000-0000-000000000002', 'thread2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false, true, NULL, '2024-01-14 09:00:00+00', '2024-01-14 09:00:00+00', NOW(), NOW()),- -- Thread 3: Draft from [email protected]+ -- Thread 3: Draft from [email protected] (no project)('20000003-0000-0000-0000-000000000003', 'thread3', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false, false, NULL, NULL, '2024-01-13 08:00:00+00', NOW(), NOW()),- -- Thread 4: Starred, from [email protected]+ -- Thread 4: Starred, from [email protected] (no project)('20000004-0000-0000-0000-000000000004', 'thread4', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',true, false, '2024-01-12 07:00:00+00', NULL, '2024-01-12 07:00:00+00', NOW(), NOW()),- -- Thread 5: Important inbox from [email protected]+ -- Thread 5: Important inbox from [email protected], in Project Alpha('20000005-0000-0000-0000-000000000005', 'thread5', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',true, false, '2024-01-11 06:00:00+00', NULL, '2024-01-11 06:00:00+00', NOW(), NOW()),- -- Thread 6: User label "Work", from [email protected]+ -- Thread 6: User label "Work", from [email protected], in Project Beta('20000006-0000-0000-0000-000000000006', 'thread6', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false, false, NULL, NULL, '2024-01-10 05:00:00+00', NOW(), NOW()),@@ -80,6 +93,14 @@ VALUES('20000011-0000-0000-0000-000000000011', 'thread11', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false, false, NULL, NULL, '2024-01-05 00:00:00+00', NOW(), NOW());+-- Assign threads to projects+UPDATE email_threads SET project_id = 'proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa' WHERE id IN (+ '20000001-0000-0000-0000-000000000001',+ '20000002-0000-0000-0000-000000000002',+ '20000005-0000-0000-0000-000000000005'+);+UPDATE email_threads SET project_id = 'proj-bbbb-bbbb-bbbb-bbbbbbbbbbbb' WHERE id = '20000006-0000-0000-0000-000000000006';+-- Insert test messagesINSERT INTO email_messages (id, thread_id, link_id, provider_id, from_contact_id,diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rsindex 219b737c85..98b476d07e 100644--- a/rust/cloud-storage/email/src/domain/models/error.rs+++ b/rust/cloud-storage/email/src/domain/models/error.rs@@ -38,4 +38,10 @@ pub enum EmailErr {/// No messages found for thread.#[error("No messages found for thread")]ThreadEmpty,+ /// Thread not found.+ #[error("Thread not found")]+ ThreadNotFound,+ /// The caller does not have permission to perform this action.+ #[error("You do not have permission to perform this action")]+ Unauthorized,}diff --git a/rust/cloud-storage/email/src/domain/models/preview.rs b/rust/cloud-storage/email/src/domain/models/preview.rsindex 20473ccd2b..5ea6ff1101 100644--- a/rust/cloud-storage/email/src/domain/models/preview.rs+++ b/rust/cloud-storage/email/src/domain/models/preview.rs@@ -86,6 +86,7 @@ pub struct EmailThreadPreview {pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,pub viewed_at: Option<DateTime<Utc>>,+ pub project_id: Option<String>,}#[non_exhaustive]diff --git a/rust/cloud-storage/email/src/domain/models/thread.rs b/rust/cloud-storage/email/src/domain/models/thread.rsindex ea158a3418..be643209f5 100644--- a/rust/cloud-storage/email/src/domain/models/thread.rs+++ b/rust/cloud-storage/email/src/domain/models/thread.rs@@ -25,6 +25,8 @@ pub struct ThreadRow {pub created_at: DateTime<Utc>,/// When the thread was last updated.pub updated_at: DateTime<Utc>,+ /// The project this thread belongs to, if any.+ pub project_id: Option<String>,}/// A fully assembled email thread with paginated messages.diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rsindex aebdb3d79f..2774313f4b 100644--- a/rust/cloud-storage/email/src/domain/ports.rs+++ b/rust/cloud-storage/email/src/domain/ports.rs@@ -6,7 +6,7 @@ use crate::domain::models::{SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult, UpsertedContacts, UserProvider,};use chrono::{DateTime, Utc};-use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{PaginatedCursor, SimpleSortMethod};use std::collections::HashMap;@@ -208,6 +208,20 @@ pub trait EmailRepo: Send + Sync + 'static {message_ids: &[Uuid],link_id: Uuid,) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Update the project assignment for a thread. Pass `None` to remove from project.+ /// Returns `false` if the thread was not found.+ fn update_thread_project(+ &self,+ thread_id: Uuid,+ project_id: Option<&str>,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Get the current project_id for a thread.+ fn get_thread_project_id(+ &self,+ thread_id: Uuid,+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;}pub trait EmailService: Send + Sync + 'static {@@ -272,6 +286,17 @@ pub trait EmailService: Send + Sync + 'static {label_id: Uuid,add: bool,) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send;++ /// Update the project assignment for a thread. Returns the old project_id.+ ///+ /// `thread_receipt` proves the caller has edit access to the thread.+ /// `project_receipt` proves the caller has edit access to the target project.+ /// Pass `None` to remove the thread from its current project.+ fn update_thread_project(+ &self,+ thread_receipt: EntityAccessReceipt<EditAccessLevel>,+ project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,+ ) -> impl Future<Output = Result<Option<String>, EmailErr>> + Send;}/// Port for modifying Gmail message labels via the provider API.diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rsindex f68d652e28..50682fb6a2 100644--- a/rust/cloud-storage/email/src/domain/service/draft.rs+++ b/rust/cloud-storage/email/src/domain/service/draft.rs@@ -225,6 +225,7 @@ wherelatest_non_spam_message_ts: None,created_at: now,updated_at: now,+ project_id: None,};let thread_db_id = thread.db_id;diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rsindex bf206edde2..a3d98a0de2 100644--- a/rust/cloud-storage/email/src/domain/service/mod.rs+++ b/rust/cloud-storage/email/src/domain/service/mod.rs@@ -11,7 +11,9 @@ use crate::domain::{},ports::{EmailMessageEnqueuer, EmailRepo, EmailService, GmailLabelModifier},};-use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};+use entity_access::domain::models::{+ AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, ViewAccessLevel,+};use frecency::domain::ports::FrecencyQueryService;use models_pagination::{PaginatedCursor, SimpleSortMethod};use uuid::Uuid;@@ -128,4 +130,46 @@ whereself.update_thread_labels_impl(access_token, link, thread_id, label_id, add).await}++ async fn update_thread_project(+ &self,+ thread_receipt: EntityAccessReceipt<EditAccessLevel>,+ project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,+ ) -> Result<Option<String>, EmailErr> {+ let is_owner = matches!(+ thread_receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner+ }+ );++ if !is_owner {+ return Err(EmailErr::Unauthorized);+ }++ let thread_id = Uuid::parse_str(&thread_receipt.entity().entity_id)+ .map_err(|e| EmailErr::RepoErr(anyhow::anyhow!("invalid thread id: {}", e)))?;++ let project_id = project_receipt+ .as_ref()+ .map(|r| r.entity().entity_id.as_str());++ let old_project_id = self+ .email_repo+ .get_thread_project_id(thread_id)+ .await+ .map_err(|e| EmailErr::RepoErr(e.into()))?;++ let updated = self+ .email_repo+ .update_thread_project(thread_id, project_id)+ .await+ .map_err(|e| EmailErr::RepoErr(e.into()))?;++ if !updated {+ return Err(EmailErr::ThreadNotFound);+ }++ Ok(old_project_id)+ }}diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rsindex 094cb2010e..a300c41e7f 100644--- a/rust/cloud-storage/email/src/inbound/axum.rs+++ b/rust/cloud-storage/email/src/inbound/axum.rs@@ -6,6 +6,7 @@ mod list_labels_router;mod previews_router;mod send_router;mod thread_labels_router;+mod thread_project_router;pub use api_types::*;pub use axum_impls::*;@@ -15,3 +16,4 @@ pub use list_labels_router::*;pub use previews_router::*;pub use send_router::*;pub use thread_labels_router::*;+pub use thread_project_router::*;diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rsindex dfa64181c7..586546ceea 100644--- a/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rs+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/thread.rs@@ -40,6 +40,7 @@ pub struct ApiThread {pub latest_non_spam_message_ts: Option<DateTime<Utc>>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,+ pub project_id: Option<String>,pub messages: Vec<ApiMessage>,}@@ -57,6 +58,7 @@ impl ApiThread {latest_non_spam_message_ts: t.row.latest_non_spam_message_ts,created_at: t.row.created_at,updated_at: t.row.updated_at,+ project_id: t.row.project_id,messages: t.messages.into_iter().map(ApiMessage::from).collect(),}}diff --git a/rust/cloud-storage/email/src/inbound/axum/thread_project_router.rs b/rust/cloud-storage/email/src/inbound/axum/thread_project_router.rsnew file mode 100644index 0000000000..e45d71bd08--- /dev/null+++ b/rust/cloud-storage/email/src/inbound/axum/thread_project_router.rs@@ -0,0 +1,125 @@+use axum::{+ Json, Router, extract::State, http::StatusCode, response::IntoResponse, routing::patch,+};+use entity_access::domain::models::EditAccessLevel;+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::{+ ProjectBodyAccessLevelExtractor, ThreadAccessLevelExtractor,+};+use model_error_response::ErrorResponse;+use thiserror::Error;++use crate::domain::{models::EmailErr, ports::EmailService};++use super::EmailThreadRouterState;++/// Request body for updating a thread's project.+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct UpdateThreadProjectRequest {+ /// The project ID to assign to the thread, or null to remove from project.+ pub project_id: Option<String>,+}++/// Response body for updating a thread's project.+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct UpdateThreadProjectResponse {+ /// The previous project ID of the thread.+ pub old_project_id: Option<String>,+}++/// Errors from the update thread project handler.+#[derive(Debug, Error)]+pub enum UpdateThreadProjectError {+ /// Thread not found.+ #[error("Thread not found")]+ NotFound,+ /// Unauthorized.+ #[error("{0}")]+ Unauthorized(String),+ /// Internal error.+ #[error("Internal error")]+ Internal(EmailErr),+}++impl IntoResponse for UpdateThreadProjectError {+ fn into_response(self) -> axum::response::Response {+ if matches!(self, UpdateThreadProjectError::Internal(_)) {+ tracing::error!(error=?self, "update thread project error");+ }++ let status = match &self {+ UpdateThreadProjectError::NotFound => StatusCode::NOT_FOUND,+ UpdateThreadProjectError::Unauthorized(_) => StatusCode::UNAUTHORIZED,+ UpdateThreadProjectError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = self.to_string();+ (status, Json(ErrorResponse { message: &message })).into_response()+ }+}++impl From<EmailErr> for UpdateThreadProjectError {+ fn from(err: EmailErr) -> Self {+ match err {+ EmailErr::ThreadNotFound => UpdateThreadProjectError::NotFound,+ EmailErr::Unauthorized => UpdateThreadProjectError::Unauthorized(err.to_string()),+ other => UpdateThreadProjectError::Internal(other),+ }+ }+}++/// Create the thread project router with a `PATCH /{thread_id}/project` handler.+pub fn thread_project_router<S, T, Svc>(state: EmailThreadRouterState<T, Svc>) -> Router<S>+where+ S: Send + Sync + 'static,+ T: EmailService,+ Svc: EntityAccessService,+{+ Router::new()+ .route(+ "/{thread_id}/project",+ patch(update_thread_project_handler::<T, Svc>),+ )+ .with_state(state)+}++/// Update the project assignment for a thread.+#[utoipa::path(+ patch,+ tag = "Threads",+ path = "/email/threads/{thread_id}/project",+ operation_id = "update_thread_project",+ request_body = UpdateThreadProjectRequest,+ params(+ ("thread_id" = String, Path, description = "Thread ID"),+ ),+ responses(+ (status = 200, body = UpdateThreadProjectResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip(state, access, project))]+pub async fn update_thread_project_handler<T: EmailService, Svc: EntityAccessService>(+ State(state): State<EmailThreadRouterState<T, Svc>>,+ access: ThreadAccessLevelExtractor<EditAccessLevel, Svc>,+ project: ProjectBodyAccessLevelExtractor<EditAccessLevel, UpdateThreadProjectRequest, Svc>,+) -> Result<Json<UpdateThreadProjectResponse>, UpdateThreadProjectError> {+ let project_receipt = match project {+ ProjectBodyAccessLevelExtractor::FoundProject {+ entity_access_receipt,+ ..+ } => Some(entity_access_receipt),+ ProjectBodyAccessLevelExtractor::ProjectNotInBody { .. } => None,+ };++ let old_project_id = state+ .service+ .update_thread_project(access.entity_access_receipt, project_receipt)+ .await?;++ Ok(Json(UpdateThreadProjectResponse { old_project_id }))+}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.rsindex a6d96ae107..4fbe23f227 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@@ -43,6 +43,7 @@ pub struct ThreadPreviewCursorDbRow {pub viewed_at: Option<DateTime<Utc>>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,+ pub project_id: Option<String>,}#[derive(Debug, sqlx::Type, Clone, Copy, PartialEq, Eq, Doppleganger)]@@ -110,6 +111,7 @@ impl ThreadPreviewCursorDbRow {viewed_at,created_at,updated_at,+ project_id,} = self;EmailThreadPreview {@@ -129,6 +131,7 @@ impl ThreadPreviewCursorDbRow {created_at,updated_at,viewed_at,+ project_id,}}}@@ -164,6 +167,7 @@ pub struct DbThreadRow {pub latest_non_spam_message_ts: Option<DateTime<Utc>>,pub created_at: chrono::DateTime<Utc>,pub updated_at: chrono::DateTime<Utc>,+ pub project_id: Option<String>,}impl From<DbThreadRow> for ThreadRow {@@ -179,6 +183,7 @@ impl From<DbThreadRow> for ThreadRow {latest_non_spam_message_ts: row.latest_non_spam_message_ts,created_at: row.created_at,updated_at: row.updated_at,+ project_id: row.project_id,}}}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.rsindex c7c98c00a0..3c839bfe05 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@@ -8,7 +8,9 @@ pub(super) fn has_thread_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(_)) => true,+ filter_ast::ExprFrame::Literal(EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_)) => {+ true+ }filter_ast::ExprFrame::Literal(_) => false,})}@@ -17,7 +19,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(_)) => false,+ filter_ast::ExprFrame::Literal(EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_)) => {+ false+ }filter_ast::ExprFrame::Literal(_) => true,})}@@ -54,7 +58,9 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmenfilter_ast::ExprFrame::Or(a, b) => SqlFragment::or(a, b),filter_ast::ExprFrame::Not(a) => SqlFragment::not(a),- filter_ast::ExprFrame::Literal(EmailLiteral::ThreadId(_)) => SqlFragment::raw("TRUE"),+ filter_ast::ExprFrame::Literal(+ EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_),+ ) => SqlFragment::raw("TRUE"),filter_ast::ExprFrame::Literal(EmailLiteral::Sender(email)) => build_email_match(r#"EXISTS (@@ -159,6 +165,12 @@ pub(super) fn build_thread_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmentf}+ filter_ast::ExprFrame::Literal(EmailLiteral::ProjectId(id)) => {+ let mut f = SqlFragment::raw("t.project_id = ");+ f.extend(SqlFragment::bind_string(id));+ f+ }+filter_ast::ExprFrame::Literal(EmailLiteral::Sender(_)| EmailLiteral::Cc(_)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.rsindex a1761bd8df..f78befd5c6 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@@ -40,6 +40,7 @@ fn build_query(t.created_at,t.updated_at,t.viewed_at,+ t.project_id,lmp.subject AS name,lmp.snippet,lmp.is_draft,@@ -74,6 +75,7 @@ fn build_query(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,"#,);@@ -268,6 +270,7 @@ pub(crate) async fn dynamic_email_thread_cursor(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")?,})}).fetch_all(pool)diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rsindex 2c08610c51..816fd11d0e 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs@@ -392,6 +392,90 @@ fn test_has_both_literals_in_combined_ast() {assert!(has_message_literals(&expr));}+#[test]+fn test_build_thread_email_filter_single_project_id() {+ let expr = Expr::Literal(EmailLiteral::ProjectId("project-123".to_string()));+ let result = build_thread_email_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("t.project_id = "));+ assert!(result.has_bind_string("project-123"));+ assert!(result.has_no_raw_containing("project-123"));+}++#[test]+fn test_build_thread_email_filter_multiple_project_ids() {+ let expr = Expr::or(+ Expr::Literal(EmailLiteral::ProjectId("project-1".to_string())),+ Expr::Literal(EmailLiteral::ProjectId("project-2".to_string())),+ );+ let result = build_thread_email_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("OR"));+ assert!(result.has_bind_string("project-1"));+ assert!(result.has_bind_string("project-2"));+ assert!(result.has_no_raw_containing("project-1"));+ assert!(result.has_no_raw_containing("project-2"));+}++#[test]+fn test_build_message_email_filter_maps_project_id_to_true() {+ let expr = Expr::Literal(EmailLiteral::ProjectId("project-123".to_string()));+ let result = build_message_email_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("TRUE"));+ assert!(!debug.contains("project_id"));+}++#[test]+fn test_has_thread_literals_true_when_project_id_present() {+ let expr = Expr::Literal(EmailLiteral::ProjectId("project-123".to_string()));+ assert!(has_thread_literals(&expr));+}++#[test]+fn test_has_message_literals_false_when_only_project_id() {+ let expr = Expr::Literal(EmailLiteral::ProjectId("project-123".to_string()));+ assert!(!has_message_literals(&expr));+}++#[test]+fn test_combined_project_id_and_sender_splits_correctly() {+ let email = Email::Complete(+ EmailStr::parse_from_str("[email protected]")+ .unwrap()+ .into_owned(),+ );+ let expr = Expr::and(+ Expr::Literal(EmailLiteral::ProjectId("project-123".to_string())),+ Expr::Literal(EmailLiteral::Sender(email)),+ );++ let thread_result = build_thread_email_filter(&expr);+ let thread_debug = thread_result.to_debug_sql();+ assert!(thread_debug.contains("t.project_id = "));+ assert!(thread_result.has_bind_string("project-123"));+ assert!(!thread_debug.contains("from_contact_id"));++ let message_result = build_message_email_filter(&expr);+ let message_debug = message_result.to_debug_sql();+ assert!(message_debug.contains("from_contact_id"));+ assert!(message_result.has_bind_string("[email protected]"));+ assert!(!message_result.has_bind_string("project-123"));+}++#[test]+fn test_sql_injection_project_id_not_in_raw_sql() {+ let expr = Expr::Literal(EmailLiteral::ProjectId("'; DROP TABLE--".to_string()));+ let result = build_thread_email_filter(&expr);++ assert!(result.has_bind_string("'; DROP TABLE--"));+ assert!(result.has_no_raw_containing("DROP"));+ assert!(result.has_no_raw_containing("';"));+}+#[test]fn test_sql_injection_email_not_in_raw_sql() {let malicious = Email::Complete(EmailStr::parse_from_str("[email protected]").unwrap().into_owned());diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rsindex 3764e844db..5e48568d38 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs@@ -237,4 +237,16 @@ impl EmailRepo for EmailPgRepo {) -> Result<(), Self::Err> {label::delete_scheduled_messages_batch(&self.pool, message_ids, link_id).await}++ async fn update_thread_project(+ &self,+ thread_id: Uuid,+ project_id: Option<&str>,+ ) -> Result<bool, Self::Err> {+ thread::update_thread_project(&self.pool, thread_id, project_id).await+ }++ async fn get_thread_project_id(&self, thread_id: Uuid) -> Result<Option<String>, Self::Err> {+ thread::get_thread_project_id(&self.pool, thread_id).await+ }}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.rsindex 1fc23b3c8d..aa26890dd1 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@@ -39,6 +39,7 @@ pub(crate) async fn all_mail_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -62,6 +63,7 @@ pub(crate) async fn all_mail_preview_cursor(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,t.latest_non_spam_message_ts AS created_at,t.latest_non_spam_message_ts AS updated_at,uh.updated_at AS viewed_at,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.rsindex a81a078143..2dc5c39a6a 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@@ -28,6 +28,7 @@ pub(crate) async fn drafts_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -55,6 +56,7 @@ pub(crate) async fn drafts_preview_cursor(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,ldpt.latest_draft_ts AS created_at,ldpt.latest_draft_ts AS updated_at,uh.updated_at AS viewed_at,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.rsindex 88c2cc7f6f..c36f705d67 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@@ -132,6 +132,7 @@ pub(crate) async fn important_preview_cursor(isk.effective_ts as "sort_ts!",isk.created_at as "created_at!",isk.updated_at as "updated_at!",+ t.project_id,isk.viewed_at as "viewed_at?",isk.is_draft as "is_draft!",-- It's the important view - all threads here are importantdiff --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.rsindex 460dcf7a9b..75790ad9c6 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@@ -35,6 +35,7 @@ pub(crate) async fn new_inbox_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -57,6 +58,7 @@ pub(crate) async fn new_inbox_preview_cursor(t.provider_id,t.link_id,t.is_read,+ t.project_id,t.latest_inbound_message_ts AS created_at,t.latest_inbound_message_ts AS updated_at,uh.updated_at AS viewed_at,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.rsindex 5b95a881d4..f7ba604798 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@@ -28,6 +28,7 @@ pub(crate) async fn other_inbox_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -55,6 +56,7 @@ pub(crate) async fn other_inbox_preview_cursor(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,t.latest_non_spam_message_ts AS created_at,t.latest_non_spam_message_ts AS updated_at,uh.updated_at AS viewed_at,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.rsindex 4dc4f98ca5..f7d5d0735b 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@@ -29,6 +29,7 @@ pub(crate) async fn sent_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -56,6 +57,7 @@ pub(crate) async fn sent_preview_cursor(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,t.latest_outbound_message_ts AS created_at,t.latest_outbound_message_ts AS updated_at,uh.updated_at AS viewed_at,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.rsindex af69236ff4..b9f377c058 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@@ -29,6 +29,7 @@ pub(crate) async fn starred_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -56,6 +57,7 @@ pub(crate) async fn starred_preview_cursor(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,lspt.latest_starred_ts AS created_at,lspt.latest_starred_ts AS updated_at,uh.updated_at AS viewed_at,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.rsindex 502b325b5c..79e1c5c230 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@@ -30,6 +30,7 @@ pub(crate) async fn user_label_preview_cursor(t.effective_ts AS "sort_ts!",t.created_at AS "created_at!",t.updated_at AS "updated_at!",+ t.project_id,t.viewed_at AS "viewed_at?",lmp.subject AS "name?",lmp.snippet AS "snippet?",@@ -57,6 +58,7 @@ pub(crate) async fn user_label_preview_cursor(t.link_id,t.inbox_visible,t.is_read,+ t.project_id,llpt.latest_labeled_ts AS created_at,llpt.latest_labeled_ts AS updated_at,uh.updated_at AS viewed_at,diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rsindex a9f5cd12f9..770cbf9207 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs@@ -459,6 +459,7 @@ async fn test_insert_draft_message_with_new_thread(pool: Pool<Postgres>) -> anyhlatest_non_spam_message_ts: None,created_at: Utc::now(),updated_at: Utc::now(),+ project_id: None,};repo.insert_message(&input, &contacts, link_id, Some(new_thread), true)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.rsindex 0703051cf7..412a9cf9c8 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@@ -634,6 +634,153 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhOk(())}+// ── Project ID filter tests ──────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_dynamic_query_with_single_project_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;++ // Filter for threads in Project Alpha+ let filter = Arc::new(Expr::Literal(EmailLiteral::ProjectId(+ "proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),+ )));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ 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");++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ assert!(result_ids.contains("20000001-0000-0000-0000-000000000001"));+ assert!(result_ids.contains("20000002-0000-0000-0000-000000000002"));+ assert!(result_ids.contains("20000005-0000-0000-0000-000000000005"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_dynamic_query_with_multiple_project_ids(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;++ // Filter for threads in Project Alpha OR Project Beta+ let filter = Arc::new(Expr::or(+ Expr::Literal(EmailLiteral::ProjectId(+ "proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),+ )),+ Expr::Literal(EmailLiteral::ProjectId(+ "proj-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),+ )),+ ));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;++ // Threads 1, 2, 5 (Alpha) + Thread 6 (Beta)+ assert_eq!(+ results.len(),+ 4,+ "Should return 4 threads across both projects"+ );++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ assert!(result_ids.contains("20000006-0000-0000-0000-000000000006"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_dynamic_query_project_id_with_sender_filter(+ 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;++ // Filter for threads in Project Alpha AND from [email protected]+ // Threads 1 and 5 are in Alpha and from john; thread 2 is in Alpha but from john (sent)+ let filter = Arc::new(Expr::and(+ Expr::Literal(EmailLiteral::ProjectId(+ "proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),+ )),+ Expr::Literal(EmailLiteral::Sender(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))),+ ));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ 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 {+ if let Some(sender) = &result.sender_email {+ assert_eq!(sender, "[email protected]");+ }+ }+ assert!(+ results.len() >= 2,+ "Should return threads in Project Alpha from john"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_dynamic_query_project_id_with_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 50;++ // Filter for inbox threads in Project Alpha+ // Thread 1 and 5 are inbox + Alpha; thread 2 is Alpha but not inbox+ let filter = Arc::new(Expr::Literal(EmailLiteral::ProjectId(+ "proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string(),+ )));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;++ assert_eq!(+ results.len(),+ 2,+ "Should return 2 inbox threads in Project Alpha"+ );++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ assert!(result_ids.contains("20000001-0000-0000-0000-000000000001"));+ assert!(result_ids.contains("20000005-0000-0000-0000-000000000005"));+ // Thread 2 is in Alpha but not inbox+ assert!(!result_ids.contains("20000002-0000-0000-0000-000000000002"));++ Ok(())+}+// Inbox view + importance=false: the "Other" toggle in the UI.// Thread 6 (CATEGORY_UPDATES) has importance=false but inbox_visible=false → excluded by Inbox view.// Thread 7 (CATEGORY_PROMOTIONS) has importance=false AND inbox_visible=true → included.diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rsindex 7aa6d1d62f..987ae94d71 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs@@ -218,6 +218,7 @@ async fn test_insert_thread_new(pool: Pool<Postgres>) -> anyhow::Result<()> {latest_non_spam_message_ts: None,created_at: now,updated_at: now,+ project_id: None,};let mut tx = pool.begin().await?;@@ -259,6 +260,7 @@ async fn test_insert_thread_conflict_with_provider_id(pool: Pool<Postgres>) -> alatest_non_spam_message_ts: None,created_at: now,updated_at: now,+ project_id: None,};let mut tx = pool.begin().await?;diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rsindex 5dda3003bb..40f69947f5 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs@@ -11,12 +11,13 @@ pub(super) async fn thread_by_id(pool: &PgPool,thread_id: Uuid,) -> Result<Option<ThreadRow>, sqlx::Error> {- let row = sqlx::query_as!(+ let row: Option<DbThreadRow> = sqlx::query_as!(DbThreadRow,r#"SELECT t.id, t.provider_id, t.link_id, t.inbox_visible, t.is_read,t.latest_inbound_message_ts, t.latest_outbound_message_ts,- t.latest_non_spam_message_ts, t.created_at, t.updated_at+ t.latest_non_spam_message_ts, t.created_at, t.updated_at,+ t.project_idFROM email_threads tWHERE t.id = $1"#,@@ -356,6 +357,48 @@ async fn update_db_thread_metadata(Ok(())}+/// Update the project assignment for a thread. Returns `false` if the thread was not found.+#[tracing::instrument(err, skip(pool))]+pub(super) async fn update_thread_project(+ pool: &PgPool,+ thread_id: Uuid,+ project_id: Option<&str>,+) -> Result<bool, sqlx::Error> {+ let result = sqlx::query!(+ r#"+ UPDATE email_threads+ SET project_id = $2, updated_at = NOW()+ WHERE id = $1+ "#,+ thread_id,+ project_id,+ )+ .execute(pool)+ .await?;++ Ok(result.rows_affected() > 0)+}++/// Get the current project_id for a thread.+#[tracing::instrument(err, skip(pool))]+pub(super) async fn get_thread_project_id(+ pool: &PgPool,+ thread_id: Uuid,+) -> Result<Option<String>, sqlx::Error> {+ let row: Option<Option<String>> = sqlx::query_scalar!(+ r#"+ SELECT project_id+ FROM email_threads+ WHERE id = $1+ "#,+ thread_id,+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.flatten())+}+/// Upsert user history for thread interaction tracking.pub(super) async fn upsert_user_history(tx: &mut sqlx::PgConnection,diff --git a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/mod.rsindex 8da43f5c16..3d689e99c7 100644--- a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs@@ -44,8 +44,12 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {email::outbound::GmailTokenProviderImpl,>();+ let hex_thread_project_routes =+ email::inbound::thread_project_router(state.email_thread_state.clone());+Router::new().merge(required_link_routes).merge(hex_thread_routes).merge(hex_thread_labels_routes)+ .merge(hex_thread_project_routes)}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex a5dc0ba6ea..7da958f283 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -27,7 +27,10 @@ use ::email::inbound::{CreateDraftResponse as HexCreateDraftResponse, GetPreviewsCursorParams, GetThreadResponse,SendMessageRequest as HexSendMessageRequest, SendMessageResponse as HexSendMessageResponse,};-use ::email::inbound::{UpdateThreadLabelRequest, UpdateThreadLabelsResponse};+use ::email::inbound::{+ UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectRequest,+ UpdateThreadProjectResponse,+};use model::response::EmptyResponse;use models_email::api::settings::Settings;use models_email::email::service;@@ -72,6 +75,7 @@ use utoipa::OpenApi;inbound::update_thread_labels_handler,inbound::cursor_handler,inbound::get_thread_handler,+ inbound::update_thread_project_handler,email::links::list::list_links_handler,email::labels::create::handler,email::labels::delete::handler,@@ -118,6 +122,8 @@ use utoipa::OpenApi;ArchiveThreadRequest,UpdateThreadLabelRequest,UpdateThreadLabelsResponse,+ UpdateThreadProjectRequest,+ UpdateThreadProjectResponse,ThreadPreviewCursor,GetThreadResponse,ApiThread,diff --git a/rust/cloud-storage/entity_access/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json b/rust/cloud-storage/entity_access/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.jsonnew file mode 100644index 0000000000..83caec4173--- /dev/null+++ b/rust/cloud-storage/entity_access/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $2\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055"+}diff --git a/rust/cloud-storage/entity_access/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json b/rust/cloud-storage/entity_access/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.jsondeleted file mode 100644index 2b67c5606d..0000000000--- a/rust/cloud-storage/entity_access/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n -- CTE to recursively find all parent projects for the given email thread.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project directly associated with the thread.\n SELECT\n p.id as project_id\n FROM\n \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE\n etp.\"threadId\" = $1\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT\n parent.id as project_id\n FROM\n project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The thread ID itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0"-}diff --git a/rust/cloud-storage/entity_access/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json b/rust/cloud-storage/entity_access/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.jsonnew file mode 100644index 0000000000..6ef8856744--- /dev/null+++ b/rust/cloud-storage/entity_access/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $3 AND item_id IN (\n SELECT $2 -- The thread ID as text\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $2\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed"+}diff --git a/rust/cloud-storage/entity_access/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json b/rust/cloud-storage/entity_access/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.jsondeleted file mode 100644index 4c96ff0fd5..0000000000--- a/rust/cloud-storage/entity_access/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE etp.\"threadId\" = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f"-}diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rsindex 7ba1ae8414..7a90ba98a3 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs@@ -42,32 +42,23 @@ pub async fn get_thread_access(let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(r#"- -- CTE to recursively find all parent projects for the given email thread.WITH RECURSIVE project_hierarchy AS (- -- Base case: Start with the project directly associated with the thread.- SELECT- p.id as project_id- FROM- "EmailThreadPermission" etp- JOIN "Project" p ON etp."projectId" = p.id AND p."deletedAt" IS NULL- WHERE- etp."threadId" = $1+ SELECT p.id as project_id+ FROM email_threads t+ JOIN "Project" p ON t.project_id = p.id AND p."deletedAt" IS NULL+ WHERE t.id = $1UNION ALL- -- Recursive case: Find the parent of the project from the previous step.- SELECT- parent.id as project_id- FROM- project_hierarchy ph+ SELECT parent.id as project_id+ FROM project_hierarchy phJOIN "Project" parent ON parent.id = (SELECT "parentId" FROM "Project" WHERE id = ph.project_id AND "parentId" IS NOT NULL AND "deletedAt" IS NULL))- -- The subquery now gathers all levels as plain text.SELECT access_level FROM (-- Source 1: Cast the AccessLevel enum to text.SELECT access_level::text FROM "UserItemAccess"- WHERE user_id = $2 AND item_id IN (- SELECT $1 -- The thread ID itself+ WHERE user_id = $3 AND item_id IN (+ SELECT $2 -- The thread ID as textUNIONSELECT project_id FROM project_hierarchy -- All parent projects)@@ -76,12 +67,13 @@ pub async fn get_thread_access(SELECT "publicAccessLevel" as access_levelFROM "SharePermission"WHERE "isPublic" = true AND "publicAccessLevel" IS NOT NULL AND id IN (- SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $1+ SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $2UNIONSELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" IN (SELECT project_id FROM project_hierarchy))) as all_levels"#,+ thread_uuid,thread_id,user_id)diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rsindex 9c1d5c6767..b87f34f9e6 100644--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rs+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_users.rs@@ -1,6 +1,7 @@//! Query for users with access to an email thread via UserItemAccess.use sqlx::PgPool;+use uuid::Uuid;/// Get all user IDs that have access to an email thread via `UserItemAccess`.///@@ -8,13 +9,15 @@ use sqlx::PgPool;/// to any parent project in the hierarchy.#[tracing::instrument(err, skip(pool))]pub async fn get_thread_users(pool: &PgPool, thread_id: &str) -> Result<Vec<String>, sqlx::Error> {+ let thread_uuid = Uuid::parse_str(thread_id).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;+let users: Vec<String> = sqlx::query_scalar!(r#"WITH RECURSIVE project_hierarchy AS (SELECT p.id as project_id- FROM "EmailThreadPermission" etp- JOIN "Project" p ON etp."projectId" = p.id AND p."deletedAt" IS NULL- WHERE etp."threadId" = $1+ FROM email_threads t+ JOIN "Project" p ON t.project_id = p.id AND p."deletedAt" IS NULL+ WHERE t.id = $1UNION ALLSELECT parent.id as project_idFROM project_hierarchy ph@@ -24,11 +27,12 @@ pub async fn get_thread_users(pool: &PgPool, thread_id: &str) -> Result<Vec<Stri)SELECT DISTINCT user_id FROM "UserItemAccess"WHERE item_id IN (- SELECT $1+ SELECT $2UNIONSELECT project_id FROM project_hierarchy)"#,+ thread_uuid,thread_id).fetch_all(pool)diff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rsindex a986dcaf17..8b5323022a 100644--- a/rust/cloud-storage/item_filters/src/ast/email.rs+++ b/rust/cloud-storage/item_filters/src/ast/email.rs@@ -27,6 +27,8 @@ pub enum EmailLiteral {Recipient(Email),/// This value filters by email thread IDThreadId(Uuid),+ /// This value filters by project ID+ ProjectId(String),/// This node value filters by email importance. false short-circuits to match nothing.Importance(bool),/// This node value filters by notification done state for emails.@@ -44,6 +46,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {bcc,recipients,email_thread_ids,+ project_ids,importance,notification_filters,include_labels: _,@@ -79,6 +82,10 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {.map(|s| Uuid::parse_str(s)).try_expand(|r| r.map(EmailLiteral::ThreadId), Expr::or)?;+ let project_id_nodes = project_ids+ .into_iter()+ .expand(EmailLiteral::ProjectId, Expr::or);+let importance_node = importance.map(|imp| Expr::Literal(EmailLiteral::Importance(imp)));let notification_done_node = notification_filters.done@@ -93,6 +100,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {bcc_nodes,recipient_nodes,thread_id_nodes,+ project_id_nodes,importance_node,notification_done_node,notification_seen_node,diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 604b81758f..b8dde15d46 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -197,6 +197,10 @@ pub struct EmailFilters {#[serde(default, skip_serializing_if = "Vec::is_empty")]pub email_thread_ids: Vec<String>,+ /// A list of project ids to search within. Empty to ignore project filtering.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub project_ids: Vec<String>,+/// Filter by email importance. None to not filter. True to show only important emails/// (drafts, personal, sent, or uncategorized). False to show only unimportant emails/// (those categorized as promotions, social, updates, or forums).@@ -226,6 +230,7 @@ impl IsEmpty for EmailFilters {bcc,recipients,email_thread_ids,+ project_ids,importance,notification_filters,include_labels,@@ -236,6 +241,7 @@ impl IsEmpty for EmailFilters {&& bcc.is_empty()&& recipients.is_empty()&& email_thread_ids.is_empty()+ && project_ids.is_empty()&& importance.is_none()&& notification_filters.is_empty()&& include_labels.is_empty()diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.jsonnew file mode 100644index 0000000000..d2b084cf10--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.jsonnew file mode 100644index 0000000000..6d97183829--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.jsonnew file mode 100644index 0000000000..9d717fa5f9--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "values",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7.json b/rust/cloud-storage/macro_db_client/.sqlx/query-cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7.jsonnew file mode 100644index 0000000000..9dc9838dc0--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity_properties\n SET values = $2\n WHERE entity_id = $1;\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "cf71680da3444f573f4cddf66b6269bfe31aeee4bbec34b7e6067a855e28f2b7"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.jsonnew file mode 100644index 0000000000..182e0858ba--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"+}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260319232323_add_project_id_to_email_threads.sql b/rust/cloud-storage/macro_db_client/migrations/20260319232323_add_project_id_to_email_threads.sqlnew file mode 100644index 0000000000..28133aa992--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260319232323_add_project_id_to_email_threads.sql@@ -0,0 +1,8 @@+ALTER TABLE email_threads ADD COLUMN project_id text;++ALTER TABLE email_threads+ ADD CONSTRAINT email_threads_project_id_fkey+ FOREIGN KEY (project_id) REFERENCES "Project"(id)+ ON UPDATE CASCADE ON DELETE SET NULL;++CREATE INDEX idx_email_threads_project_id ON email_threads USING btree (project_id);diff --git a/rust/cloud-storage/models_soup/src/email_thread.rs b/rust/cloud-storage/models_soup/src/email_thread.rsindex ad5397f278..914fe3cb91 100644--- a/rust/cloud-storage/models_soup/src/email_thread.rs+++ b/rust/cloud-storage/models_soup/src/email_thread.rs@@ -105,6 +105,7 @@ pub struct SoupEmailThreadPreview {pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,pub viewed_at: Option<DateTime<Utc>>,+ pub project_id: Option<String>,}#[derive(Debug, Serialize, Deserialize)]diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 5edf42d1ee..63c4efef9b 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -98,6 +98,16 @@ impl EmailService for NoopEmailService {) -> Result<email::domain::models::UpdateThreadLabelsResult, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))}++ async fn update_thread_project(+ &self,+ _thread_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ _project_receipt: Option<+ EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ >,+ ) -> Result<Option<String>, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))+ }}struct NoopCommsService;diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex a7c5ec12d7..e43620b69c 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -142,6 +142,16 @@ impl EmailService for MockEmail {) -> Result<email::domain::models::UpdateThreadLabelsResult, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}++ async fn update_thread_project(+ &self,+ _thread_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ _project_receipt: Option<+ EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ >,+ ) -> Result<Option<String>, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }}fn mock_router() -> Router {@@ -257,6 +267,16 @@ impl EmailService for MockEmailLinkResult {) -> Result<email::domain::models::UpdateThreadLabelsResult, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}++ async fn update_thread_project(+ &self,+ _thread_receipt: EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ _project_receipt: Option<+ EntityAccessReceipt<entity_access::domain::models::EditAccessLevel>,+ >,+ ) -> Result<Option<String>, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }}#[tokio::test]