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): Forwarding message attachments (#1505)
Evan Hutnik0dea2c0f97c3
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex ae099e984f..2de4193b90 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -105,7 +105,9 @@ import {} from './EmailContext';import { getOrInitEmailFormContext } from './EmailFormContext';import {+ useAddForwardedAttachmentsMutation,useRemoveDraftAttachmentMutation,+ useRemoveForwardedAttachmentMutation,useUploadDraftAttachmentsMutation,} from '@queries/email/attachment';import { EmailAttachmentPill } from '@block-email/component/AttachmentPill';@@ -392,6 +394,7 @@ export function BaseInput(props: {});const uploadAttachmentMutation = useUploadDraftAttachmentsMutation();+ const addForwardedAttachmentsMutation = useAddForwardedAttachmentsMutation();const saveDraftMutation = useSaveDraftMutation();const deleteDraftMutation = useDeleteDraftMutation();@@ -568,6 +571,23 @@ export function BaseInput(props: {}}+ // Sync forwarded attachments+ const forwardedAttachments = form()+ .attachments.list()+ .filter((a) => a.type === 'forwarded') as Extract<+ DraftFormAttachment,+ { type: 'forwarded' }+ >[];++ if (forwardedAttachments.length) {+ await addForwardedAttachmentsMutation.mutateAsync({+ draftID: draftId,+ attachments: forwardedAttachments.map((a) => ({+ attachmentID: a.attachmentID,+ })),+ });+ }+setSavedDraftId(draftId);refetchThreadMessages();return draftId;@@ -941,10 +961,14 @@ export function BaseInput(props: {};const removeAttachmentMutation = useRemoveDraftAttachmentMutation();+ const removeForwardedAttachmentMutation =+ useRemoveForwardedAttachmentMutation();const handleRemoveAttachment = (attachment: DraftFormAttachment) => {if (attachment.type === 'local') {form().attachments.removeByFile(attachment.file);+ } else if (attachment.type === 'forwarded') {+ form().attachments.removeForwarded(attachment.attachmentID);} else {form().attachments.removeByID(attachment.attachmentID);}@@ -953,10 +977,17 @@ export function BaseInput(props: {if (!currentDraftID || !attachment.attachmentID) return;- removeAttachmentMutation.mutate({- draftID: currentDraftID,- attachmentID: attachment.attachmentID,- });+ if (attachment.type === 'forwarded') {+ removeForwardedAttachmentMutation.mutate({+ draftID: currentDraftID,+ attachmentID: attachment.attachmentID,+ });+ } else {+ removeAttachmentMutation.mutate({+ draftID: currentDraftID,+ attachmentID: attachment.attachmentID,+ });+ }};const unscheduleMessageMutation = useUnscheduleMessageMutation({@@ -1289,6 +1320,18 @@ export function BaseInput(props: {/>)}</Match>+ <Match when={attachment.type === 'forwarded' && attachment}>+ {(attachment) => (+ <EmailAttachmentPill+ attachment={{+ fileName: attachment().fileName,+ mimeType: attachment().mimeType,+ }}+ removable+ onRemove={() => handleRemoveAttachment(attachment())}+ />+ )}+ </Match></Switch>)}</For>diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex bb6f754974..4d80d64c07 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -61,6 +61,7 @@ import {} from '@queries/email/draft';import {useRemoveDraftAttachmentMutation,+ useRemoveForwardedAttachmentMutation,useUploadDraftAttachmentsMutation,} from '@queries/email/attachment';import { MACRO_EMAIL_SIGNATURE } from '@block-email/constants';@@ -278,10 +279,14 @@ export function EmailCompose(props: EmailComposeProps) {};const removeAttachmentMutation = useRemoveDraftAttachmentMutation();+ const removeForwardedAttachmentMutation =+ useRemoveForwardedAttachmentMutation();const handleRemoveAttachment = (attachment: DraftFormAttachment) => {if (attachment.type === 'local') {form.attachments.removeByFile(attachment.file);+ } else if (attachment.type === 'forwarded') {+ form.attachments.removeForwarded(attachment.attachmentID);} else {form.attachments.removeByID(attachment.attachmentID);}@@ -290,10 +295,17 @@ export function EmailCompose(props: EmailComposeProps) {if (!savedDraftID || !attachment.attachmentID) return;- removeAttachmentMutation.mutate({- draftID: savedDraftID,- attachmentID: attachment.attachmentID,- });+ if (attachment.type === 'forwarded') {+ removeForwardedAttachmentMutation.mutate({+ draftID: savedDraftID,+ attachmentID: attachment.attachmentID,+ });+ } else {+ removeAttachmentMutation.mutate({+ draftID: savedDraftID,+ attachmentID: attachment.attachmentID,+ });+ }};// We are consuming the first change, because it is the initial valuediff --git a/js/app/packages/block-email/component/ComposeEmailInput.tsx b/js/app/packages/block-email/component/ComposeEmailInput.tsxindex eef1c3dd74..df12770c3f 100644--- a/js/app/packages/block-email/component/ComposeEmailInput.tsx+++ b/js/app/packages/block-email/component/ComposeEmailInput.tsx@@ -277,6 +277,18 @@ export function ComposeEmailInput(props: ComposeEmailInputProps) {/>)}</Match>+ <Match when={attachment.type === 'forwarded' && attachment}>+ {(attachment) => (+ <EmailAttachmentPill+ attachment={{+ fileName: attachment().fileName,+ mimeType: attachment().mimeType,+ }}+ removable+ onRemove={handleRemoveAttachment}+ />+ )}+ </Match></Switch>);}}diff --git a/js/app/packages/block-email/component/MessageContainer.tsx b/js/app/packages/block-email/component/MessageContainer.tsxindex 6a88dded9c..17e436ccf9 100644--- a/js/app/packages/block-email/component/MessageContainer.tsx+++ b/js/app/packages/block-email/component/MessageContainer.tsx@@ -139,6 +139,10 @@ export function MessageContainer(props: MessageContainerProps) {return props.message.attachments_draft ?? [];});+ const forwardedAttachments = createMemo(() => {+ return props.message.attachments_forwarded ?? [];+ });+const onClickAttachment = async (event: MouseEvent,attachment: Attachment,@@ -290,7 +294,12 @@ export function MessageContainer(props: MessageContainerProps) {</Show>{/* Draft attachments. Needed to display attachments of sent messages before they actually get sent (undo window). */}- <Show when={draftAttachments().length > 0}>+ <Show+ when={+ draftAttachments().length > 0 ||+ forwardedAttachments().length > 0+ }+ ><div class="flex flex-row overflow-x-scroll mt-2 gap-2"><For each={draftAttachments()}>{(attachment) => (@@ -302,6 +311,16 @@ export function MessageContainer(props: MessageContainerProps) {/>)}</For>+ <For each={forwardedAttachments()}>+ {(attachment) => (+ <EmailAttachmentPill+ attachment={{+ fileName: attachment.filename ?? '',+ mimeType: attachment.mime_type ?? undefined,+ }}+ />+ )}+ </For></div></Show></Message>diff --git a/js/app/packages/block-email/component/createEmailFormState.ts b/js/app/packages/block-email/component/createEmailFormState.tsindex 3f20c17e99..b664318677 100644--- a/js/app/packages/block-email/component/createEmailFormState.ts+++ b/js/app/packages/block-email/component/createEmailFormState.ts@@ -33,6 +33,13 @@ export type DraftFormAttachment =contentType: string;attachmentID: string;fileSize: number;+ }+ | {+ type: 'forwarded';+ attachmentID: string;+ fileName: string;+ mimeType: string;+ fileSize: number;};export interface EmailFormStateOptions {@@ -165,16 +172,23 @@ export function createEmailFormState(// TODO: Replace this signal with a memo deriving the attachments from the draft data// and a temporary queue to track attachments to be uploaded on draft save- const [attachments, setAttachments] = createSignal<DraftFormAttachment[]>(- draft?.attachments_draft.map((a) => ({- type: 'remote',+ const [attachments, setAttachments] = createSignal<DraftFormAttachment[]>([+ ...(draft?.attachments_draft.map((a) => ({+ type: 'remote' as const,attachmentID: a.id,contentType: a.content_type,fileName: a.file_name,url: a.s3_key,fileSize: a.size,- })) ?? []- );+ })) ?? []),+ ...(draft?.attachments_forwarded.map((a) => ({+ type: 'forwarded' as const,+ attachmentID: a.attachment_id,+ fileName: a.filename ?? 'attachment',+ mimeType: a.mime_type ?? 'application/octet-stream',+ fileSize: a.size_bytes ?? 0,+ })) ?? []),+ ]);const setRecipients = (field: keyof EmailFormRecipients,@@ -197,6 +211,10 @@ export function createEmailFormState(setState('replyType', next);const rt = state.replyType;const msg = replyingTo;++ // Clear forwarded attachments when switching away from forward+ setAttachments((prev) => prev.filter((a) => a.type !== 'forwarded'));+if (msg) {let calculated: EmailFormRecipients = { to: [], cc: [], bcc: [] };@@ -223,6 +241,18 @@ export function createEmailFormState(replyType: rt,visible: true,});++ // Populate forwarded attachments from original message (skip inline images)+ const fwdAttachments: DraftFormAttachment[] = (msg.attachments ?? [])+ .filter((a) => !a.content_id)+ .map((a) => ({+ type: 'forwarded' as const,+ attachmentID: a.db_id,+ fileName: a.filename ?? 'attachment',+ mimeType: a.mime_type ?? 'application/octet-stream',+ fileSize: a.size_bytes ?? 0,+ }));+ setAttachments((prev) => [...prev, ...fwdAttachments]);}}@@ -324,6 +354,13 @@ export function createEmailFormState());},+ removeForwarded: (attachmentID: string) => {+ setAttachments((p) =>+ p.filter(+ (a) => a.type !== 'forwarded' || a.attachmentID !== attachmentID+ )+ );+ },},};diff --git a/js/app/packages/queries/email/attachment.ts b/js/app/packages/queries/email/attachment.tsindex f82a524c42..b81836f47d 100644--- a/js/app/packages/queries/email/attachment.ts+++ b/js/app/packages/queries/email/attachment.ts@@ -132,3 +132,63 @@ export const useRemoveDraftAttachmentMutation = (),}));};++type AddForwardedAttachmentsParams = {+ draftID: string;+ attachments: { attachmentID: string }[];+};++export const useAddForwardedAttachmentsMutation = (+ callbacks?: MutationCallbacks<void, Error, AddForwardedAttachmentsParams>+) => {+ return useMutation(() => ({+ mutationFn: async (params: AddForwardedAttachmentsParams) => {+ for (const att of params.attachments) {+ await throwOnErr(+ async () =>+ await emailClient.addForwardedAttachment({+ draftID: params.draftID,+ attachmentID: att.attachmentID,+ })+ );+ }+ },+ ...withCallbacks<void, Error, AddForwardedAttachmentsParams>(+ {+ onError() {+ toast.failure('Failed to add forwarded attachments');+ },+ },+ callbacks+ ),+ }));+};++type RemoveForwardedAttachmentParams = {+ draftID: string;+ attachmentID: string;+};++export const useRemoveForwardedAttachmentMutation = (+ callbacks?: MutationCallbacks<void, Error, RemoveForwardedAttachmentParams>+) => {+ return useMutation(() => ({+ mutationFn: async (params: RemoveForwardedAttachmentParams) => {+ await throwOnErr(+ async () =>+ await emailClient.removeForwardedAttachment({+ draftID: params.draftID,+ attachmentID: params.attachmentID,+ })+ );+ },+ ...withCallbacks<void, Error, RemoveForwardedAttachmentParams>(+ {+ onError() {+ toast.failure('Failed to remove forwarded attachment');+ },+ },+ callbacks+ ),+ }));+};diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex 0805f67af1..76369627ca 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -265,6 +265,37 @@ export const emailClient = {(result) => result);},+ async addForwardedAttachment(args: {+ draftID: string;+ attachmentID: string;+ }) {+ return mapOk(+ await emailFetch<{+ attachment_id: string;+ filename: string | null;+ mime_type: string | null;+ size_bytes: number | null;+ }>(`/email/drafts/${args.draftID}/forwarded-attachments`, {+ method: 'POST',+ body: JSON.stringify({ attachment_id: args.attachmentID }),+ }),+ (result) => result+ );+ },+ async removeForwardedAttachment(args: {+ draftID: string;+ attachmentID: string;+ }) {+ return mapOk(+ await emailFetch<EmptyResponse>(+ `/email/drafts/${args.draftID}/forwarded-attachments/${args.attachmentID}`,+ {+ method: 'DELETE',+ }+ ),+ (result) => result+ );+ },async markThreadAsSeen(args: { thread_id: string }) {const { thread_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 e669dfc1e5..d847c87470 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -7,6 +7,8 @@import type {AddDraftAttachmentRequest,AddDraftAttachmentResponse,+ AddForwardedAttachmentRequest,+ AddForwardedAttachmentResponse,ApiPaginatedThreadCursor,ArchiveThreadRequest,CancelBackfillParams,@@ -920,6 +922,129 @@ export const removeDraftAttachment = async (} as removeDraftAttachmentResponse;};+/**+ * @summary Add a forwarded attachment to a draft.+ */+export type addForwardedAttachmentResponse201 = {+ data: AddForwardedAttachmentResponse;+ status: 201;+};++export type addForwardedAttachmentResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type addForwardedAttachmentResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type addForwardedAttachmentResponseSuccess =+ addForwardedAttachmentResponse201 & {+ headers: Headers;+ };+export type addForwardedAttachmentResponseError = (+ | addForwardedAttachmentResponse404+ | addForwardedAttachmentResponse500+) & {+ headers: Headers;+};++export type addForwardedAttachmentResponse =+ | addForwardedAttachmentResponseSuccess+ | addForwardedAttachmentResponseError;++export const getAddForwardedAttachmentUrl = (id: string) => {+ return `/email/drafts/${id}/forwarded-attachments`;+};++export const addForwardedAttachment = async (+ id: string,+ addForwardedAttachmentRequest: AddForwardedAttachmentRequest,+ options?: RequestInit+): Promise<addForwardedAttachmentResponse> => {+ const res = await fetch(getAddForwardedAttachmentUrl(id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(addForwardedAttachmentRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: addForwardedAttachmentResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as addForwardedAttachmentResponse;+};++/**+ * @summary Remove a forwarded attachment from a draft.+ */+export type removeForwardedAttachmentResponse204 = {+ data: void;+ status: 204;+};++export type removeForwardedAttachmentResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type removeForwardedAttachmentResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type removeForwardedAttachmentResponseSuccess =+ removeForwardedAttachmentResponse204 & {+ headers: Headers;+ };+export type removeForwardedAttachmentResponseError = (+ | removeForwardedAttachmentResponse404+ | removeForwardedAttachmentResponse500+) & {+ headers: Headers;+};++export type removeForwardedAttachmentResponse =+ | removeForwardedAttachmentResponseSuccess+ | removeForwardedAttachmentResponseError;++export const getRemoveForwardedAttachmentUrl = (+ id: string,+ attachmentId: string+) => {+ return `/email/drafts/${id}/forwarded-attachments/${attachmentId}`;+};++export const removeForwardedAttachment = async (+ id: string,+ attachmentId: string,+ options?: RequestInit+): Promise<removeForwardedAttachmentResponse> => {+ const res = await fetch(getRemoveForwardedAttachmentUrl(id, attachmentId), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: removeForwardedAttachmentResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as removeForwardedAttachmentResponse;+};+/*** @summary Initialize email functionality for the user. Populates initial threads and enables inbox syncing.*/diff --git a/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentRequest.tsnew file mode 100644index 0000000000..002f14682c--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentRequest.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++export interface AddForwardedAttachmentRequest {+ /** The ID of the original attachment to forward. */+ attachment_id: string;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponse.tsnew file mode 100644index 0000000000..a65e36e77a--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponse.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { AddForwardedAttachmentResponseFilename } from './addForwardedAttachmentResponseFilename';+import type { AddForwardedAttachmentResponseMimeType } from './addForwardedAttachmentResponseMimeType';+import type { AddForwardedAttachmentResponseSizeBytes } from './addForwardedAttachmentResponseSizeBytes';++export interface AddForwardedAttachmentResponse {+ /** The ID of the original attachment. */+ attachment_id: string;+ /** Original file name of the attachment. */+ filename?: AddForwardedAttachmentResponseFilename;+ /** MIME type of the attachment. */+ mime_type?: AddForwardedAttachmentResponseMimeType;+ /** File size in bytes. */+ size_bytes?: AddForwardedAttachmentResponseSizeBytes;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseFilename.ts b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseFilename.tsnew file mode 100644index 0000000000..c1b20847c2--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseFilename.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Original file name of the attachment.+ */+export type AddForwardedAttachmentResponseFilename = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseMimeType.ts b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseMimeType.tsnew file mode 100644index 0000000000..9ff54bd51b--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseMimeType.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * MIME type of the attachment.+ */+export type AddForwardedAttachmentResponseMimeType = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseSizeBytes.ts b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseSizeBytes.tsnew file mode 100644index 0000000000..f0124782f3--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/addForwardedAttachmentResponseSizeBytes.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * File size in bytes.+ */+export type AddForwardedAttachmentResponseSizeBytes = number | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwarded.ts b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwarded.tsnew file mode 100644index 0000000000..13b196eddb--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwarded.ts@@ -0,0 +1,31 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { AttachmentForwardedFilename } from './attachmentForwardedFilename';+import type { AttachmentForwardedMimeType } from './attachmentForwardedMimeType';+import type { AttachmentForwardedProviderAttachmentId } from './attachmentForwardedProviderAttachmentId';+import type { AttachmentForwardedSizeBytes } from './attachmentForwardedSizeBytes';++/**+ * A forwarded attachment linking a draft to an original message's attachment.+Data is fetched from Gmail at send time rather than stored in S3.+ */+export interface AttachmentForwarded {+ /** The UUID of the original attachment in email_attachments. */+ attachment_id: string;+ /** The ID of the draft message this forwarded attachment belongs to. */+ draft_id: string;+ /** Original file name of the attachment. */+ filename?: AttachmentForwardedFilename;+ /** The Gmail message ID of the original message containing the attachment. */+ message_provider_id: string;+ /** MIME type of the attachment. */+ mime_type?: AttachmentForwardedMimeType;+ /** The Gmail attachment ID for fetching data from Gmail API. */+ provider_attachment_id?: AttachmentForwardedProviderAttachmentId;+ /** File size in bytes. */+ size_bytes?: AttachmentForwardedSizeBytes;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedFilename.ts b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedFilename.tsnew file mode 100644index 0000000000..766967c65c--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedFilename.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Original file name of the attachment.+ */+export type AttachmentForwardedFilename = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedMimeType.ts b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedMimeType.tsnew file mode 100644index 0000000000..97dc19602d--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedMimeType.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * MIME type of the attachment.+ */+export type AttachmentForwardedMimeType = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedProviderAttachmentId.ts b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedProviderAttachmentId.tsnew file mode 100644index 0000000000..11ffc102d5--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedProviderAttachmentId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The Gmail attachment ID for fetching data from Gmail API.+ */+export type AttachmentForwardedProviderAttachmentId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedSizeBytes.ts b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedSizeBytes.tsnew file mode 100644index 0000000000..57bb9e94b1--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/attachmentForwardedSizeBytes.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * File size in bytes.+ */+export type AttachmentForwardedSizeBytes = number | 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 8d91b1a030..c6f4d8a7bc 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@@ -8,6 +8,11 @@export * from './accessLevel';export * from './addDraftAttachmentRequest';export * from './addDraftAttachmentResponse';+export * from './addForwardedAttachmentRequest';+export * from './addForwardedAttachmentResponse';+export * from './addForwardedAttachmentResponseFilename';+export * from './addForwardedAttachmentResponseMimeType';+export * from './addForwardedAttachmentResponseSizeBytes';export * from './aPIThread';export * from './aPIThreadLatestInboundMessageTs';export * from './aPIThreadLatestNonSpamMessageTs';@@ -47,6 +52,11 @@ export * from './attachmentContentId';export * from './attachmentDataUrl';export * from './attachmentDraft';export * from './attachmentFilename';+export * from './attachmentForwarded';+export * from './attachmentForwardedFilename';+export * from './attachmentForwardedMimeType';+export * from './attachmentForwardedProviderAttachmentId';+export * from './attachmentForwardedSizeBytes';export * from './attachmentMimeType';export * from './attachmentProviderId';export * from './attachmentSfsId';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/message.ts b/js/app/packages/service-clients/service-email/generated/schemas/message.tsindex f0718d1b18..0c46695d43 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/message.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/message.ts@@ -6,6 +6,7 @@*/import type { Attachment } from './attachment';import type { AttachmentDraft } from './attachmentDraft';+import type { AttachmentForwarded } from './attachmentForwarded';import type { ContactInfo } from './contactInfo';import type { Label } from './label';import type { MessageBodyHtmlSanitized } from './messageBodyHtmlSanitized';@@ -29,6 +30,8 @@ export interface Message {attachments: Attachment[];/** Uploaded file attachments for the message, if it is a draft */attachments_draft: AttachmentDraft[];+ /** Forwarded attachments from original messages, if it is a draft */+ attachments_forwarded: AttachmentForwarded[];bcc: ContactInfo[];body_html_sanitized?: MessageBodyHtmlSanitized;body_macro?: MessageBodyMacro;diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex ad44270ed0..1925a2a50b 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -870,6 +870,121 @@}}},+ "/email/drafts/{id}/forwarded-attachments": {+ "post": {+ "tags": ["Drafts"],+ "summary": "Add a forwarded attachment to a draft.",+ "operationId": "add_forwarded_attachment",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The ID of the draft to add the forwarded attachment to.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AddForwardedAttachmentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "201": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AddForwardedAttachmentResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/email/drafts/{id}/forwarded-attachments/{attachment_id}": {+ "delete": {+ "tags": ["Drafts"],+ "summary": "Remove a forwarded attachment from a draft.",+ "operationId": "remove_forwarded_attachment",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "The ID of the draft to remove the forwarded attachment from.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "attachment_id",+ "in": "path",+ "description": "The ID of the forwarded attachment to remove.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/email/init": {"post": {"tags": ["Init"],@@ -2078,6 +2193,41 @@}}},+ "AddForwardedAttachmentRequest": {+ "type": "object",+ "required": ["attachment_id"],+ "properties": {+ "attachment_id": {+ "type": "string",+ "format": "uuid",+ "description": "The ID of the original attachment to forward."+ }+ }+ },+ "AddForwardedAttachmentResponse": {+ "type": "object",+ "required": ["attachment_id"],+ "properties": {+ "attachment_id": {+ "type": "string",+ "format": "uuid",+ "description": "The ID of the original attachment."+ },+ "filename": {+ "type": ["string", "null"],+ "description": "Original file name of the attachment."+ },+ "mime_type": {+ "type": ["string", "null"],+ "description": "MIME type of the attachment."+ },+ "size_bytes": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "File size in bytes."+ }+ }+ },"ApiAttachment": {"type": "object","required": ["id", "messageId", "createdAt"],@@ -2401,6 +2551,44 @@}}},+ "AttachmentForwarded": {+ "type": "object",+ "description": "A forwarded attachment linking a draft to an original message's attachment.\nData is fetched from Gmail at send time rather than stored in S3.",+ "required": ["attachment_id", "draft_id", "message_provider_id"],+ "properties": {+ "attachment_id": {+ "type": "string",+ "format": "uuid",+ "description": "The UUID of the original attachment in email_attachments."+ },+ "draft_id": {+ "type": "string",+ "format": "uuid",+ "description": "The ID of the draft message this forwarded attachment belongs to."+ },+ "filename": {+ "type": ["string", "null"],+ "description": "Original file name of the attachment."+ },+ "message_provider_id": {+ "type": "string",+ "description": "The Gmail message ID of the original message containing the attachment."+ },+ "mime_type": {+ "type": ["string", "null"],+ "description": "MIME type of the attachment."+ },+ "provider_attachment_id": {+ "type": ["string", "null"],+ "description": "The Gmail attachment ID for fetching data from Gmail API."+ },+ "size_bytes": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "File size in bytes."+ }+ }+ },"AttachmentToSend": {"type": "object","description": "The attachment data we need to include when sending a message to a provider.",@@ -2908,6 +3096,7 @@"labels","attachments","attachments_draft",+ "attachments_forwarded","created_at","updated_at"],@@ -2925,6 +3114,13 @@},"description": "Uploaded file attachments for the message, if it is a draft"},+ "attachments_forwarded": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/AttachmentForwarded"+ },+ "description": "Forwarded attachments from original messages, if it is a draft"+ },"bcc": {"type": "array","items": {diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a786348f9b..d008d2b870 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3187,6 +3187,7 @@ dependencies = ["ammonia","anyhow","authentication_service_client",+ "aws-config","aws-sdk-s3","aws-sdk-secretsmanager","aws-sdk-sqs",diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c.json b/rust/cloud-storage/email_db_client/.sqlx/query-020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c.jsonnew file mode 100644index 0000000000..3b06227108--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c.json@@ -0,0 +1,59 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n eaf.attachment_id,\n eaf.message_id AS draft_id,\n ea.provider_attachment_id,\n orig_msg.provider_id AS \"message_provider_id!\",\n ea.filename,\n ea.mime_type,\n ea.size_bytes\n FROM email_attachments_fwd eaf\n JOIN email_messages draft_msg ON eaf.message_id = draft_msg.id\n JOIN email_attachments ea ON eaf.attachment_id = ea.id\n JOIN email_messages orig_msg ON ea.message_id = orig_msg.id\n WHERE eaf.message_id = $1 AND draft_msg.link_id = $2\n ORDER BY ea.filename ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "attachment_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "draft_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "provider_attachment_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "message_provider_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "filename",+ "type_info": "Varchar"+ },+ {+ "ordinal": 5,+ "name": "mime_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 6,+ "name": "size_bytes",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "020ad49dd342e529563c91a7d2403de9196482e24765f4b2c93d2da50273d69c"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-63eecd3605682482786210e65ac14cd04b67b741bac7bac67471bcfe21205d80.json b/rust/cloud-storage/email_db_client/.sqlx/query-63eecd3605682482786210e65ac14cd04b67b741bac7bac67471bcfe21205d80.jsonnew file mode 100644index 0000000000..8437d9133a--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-63eecd3605682482786210e65ac14cd04b67b741bac7bac67471bcfe21205d80.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n eaf.attachment_id,\n eaf.message_id AS draft_id,\n ea.provider_attachment_id,\n orig_msg.provider_id AS \"message_provider_id!\",\n ea.filename,\n ea.mime_type,\n ea.size_bytes\n FROM email_attachments_fwd eaf\n JOIN email_attachments ea ON eaf.attachment_id = ea.id\n JOIN email_messages orig_msg ON ea.message_id = orig_msg.id\n WHERE eaf.message_id = ANY($1)\n ORDER BY eaf.message_id, ea.filename ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "attachment_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "draft_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "provider_attachment_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "message_provider_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "filename",+ "type_info": "Varchar"+ },+ {+ "ordinal": 5,+ "name": "mime_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 6,+ "name": "size_bytes",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "63eecd3605682482786210e65ac14cd04b67b741bac7bac67471bcfe21205d80"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-8b8194993cc2ec93b2db6104da98fe3569d973d3d2a3f723c70414c04cc574ef.json b/rust/cloud-storage/email_db_client/.sqlx/query-8b8194993cc2ec93b2db6104da98fe3569d973d3d2a3f723c70414c04cc574ef.jsonnew file mode 100644index 0000000000..e065f0dc6a--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-8b8194993cc2ec93b2db6104da98fe3569d973d3d2a3f723c70414c04cc574ef.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_attachments_fwd (message_id, attachment_id)\n SELECT $1, $2\n FROM email_messages m\n WHERE m.id = $1 AND m.link_id = $3\n ON CONFLICT DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "8b8194993cc2ec93b2db6104da98fe3569d973d3d2a3f723c70414c04cc574ef"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-f61e5ffbf5f10d3989640c3f1b70bbe79c9e1b2e6d2e6925bdf89df1a07ead5d.json b/rust/cloud-storage/email_db_client/.sqlx/query-f61e5ffbf5f10d3989640c3f1b70bbe79c9e1b2e6d2e6925bdf89df1a07ead5d.jsonnew file mode 100644index 0000000000..b75c335b28--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-f61e5ffbf5f10d3989640c3f1b70bbe79c9e1b2e6d2e6925bdf89df1a07ead5d.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM email_attachments_fwd eaf\n USING email_messages m\n WHERE eaf.message_id = m.id\n AND eaf.message_id = $1 AND eaf.attachment_id = $2 AND m.link_id = $3\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "f61e5ffbf5f10d3989640c3f1b70bbe79c9e1b2e6d2e6925bdf89df1a07ead5d"+}diff --git a/rust/cloud-storage/email_db_client/fixtures/forwarded_attachments.sql b/rust/cloud-storage/email_db_client/fixtures/forwarded_attachments.sqlnew file mode 100644index 0000000000..73a18f3fe4--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/forwarded_attachments.sql@@ -0,0 +1,132 @@+-- SQL fixture for forwarded_attachments tests+-- Tests insert, fetch, delete operations for forwarded attachment links++------------------------------------------------------------+-- User Link+------------------------------------------------------------++INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000f01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000f01',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++-- Second link for testing cross-link access prevention+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000f02', 'macro|[email protected]', '00000000-0000-0000-0000-000000000f02',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++------------------------------------------------------------+-- Contact+------------------------------------------------------------++INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000cf001',+ '00000000-0000-0000-0000-000000000f01',+ '[email protected]',+ NOW(), NOW());++------------------------------------------------------------+-- Thread+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000f201',+ '00000000-0000-0000-0000-000000000f01',+ true, false, NOW(), NOW());++------------------------------------------------------------+-- Original Message (the one being forwarded, has attachments)+------------------------------------------------------------++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000f301',+ '00000000-0000-0000-0000-00000000f201',+ '00000000-0000-0000-0000-000000000f01',+ 'gmail-original-msg-001',+ TRUE,+ '00000000-0000-0000-0000-0000000cf001',+ '2025-01-05 10:00:00 +00:00',+ true, true, false, false, NOW(), NOW());++-- Original message attachments (in email_attachments table)+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, created_at)+VALUES ('00000000-0000-0000-0000-0000000fa001',+ '00000000-0000-0000-0000-00000000f301',+ 'gmail-att-id-001',+ 'report.pdf',+ 'application/pdf',+ 50000,+ NOW());++INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, created_at)+VALUES ('00000000-0000-0000-0000-0000000fa002',+ '00000000-0000-0000-0000-00000000f301',+ 'gmail-att-id-002',+ 'photo.jpg',+ 'image/jpeg',+ 120000,+ NOW());++INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, created_at)+VALUES ('00000000-0000-0000-0000-0000000fa003',+ '00000000-0000-0000-0000-00000000f301',+ 'gmail-att-id-003',+ 'notes.txt',+ 'text/plain',+ 500,+ NOW());++------------------------------------------------------------+-- Draft Message 1: Has forwarded attachments (for fetch and delete tests)+------------------------------------------------------------++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000f501',+ '00000000-0000-0000-0000-00000000f201',+ '00000000-0000-0000-0000-000000000f01',+ 'provider-fwd-draft-501',+ FALSE,+ '00000000-0000-0000-0000-0000000cf001',+ '2025-01-05 11:00:00 +00:00',+ true, false, false, true, NOW(), NOW());++-- Link draft 1 to two original attachments+INSERT INTO email_attachments_fwd (message_id, attachment_id)+VALUES ('00000000-0000-0000-0000-00000000f501', '00000000-0000-0000-0000-0000000fa001');++INSERT INTO email_attachments_fwd (message_id, attachment_id)+VALUES ('00000000-0000-0000-0000-00000000f501', '00000000-0000-0000-0000-0000000fa002');++------------------------------------------------------------+-- Draft Message 2: Empty draft (no forwarded attachments, for insert test)+------------------------------------------------------------++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000f502',+ '00000000-0000-0000-0000-00000000f201',+ '00000000-0000-0000-0000-000000000f01',+ 'provider-fwd-draft-502',+ FALSE,+ '00000000-0000-0000-0000-0000000cf001',+ '2025-01-05 12:00:00 +00:00',+ false, false, false, true, NOW(), NOW());++------------------------------------------------------------+-- Draft Message 3: Single forwarded attachment (for delete test)+------------------------------------------------------------++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000f503',+ '00000000-0000-0000-0000-00000000f201',+ '00000000-0000-0000-0000-000000000f01',+ 'provider-fwd-draft-503',+ FALSE,+ '00000000-0000-0000-0000-0000000cf001',+ '2025-01-05 13:00:00 +00:00',+ true, false, false, true, NOW(), NOW());++INSERT INTO email_attachments_fwd (message_id, attachment_id)+VALUES ('00000000-0000-0000-0000-00000000f503', '00000000-0000-0000-0000-0000000fa003');diff --git a/rust/cloud-storage/email_db_client/src/attachments/forwarded/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/forwarded/mod.rsnew file mode 100644index 0000000000..18f7ec10f5--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/forwarded/mod.rs@@ -0,0 +1,151 @@+use models_email::{db, service};+use sqlx::types::Uuid;+use sqlx::{Executor, PgPool, Postgres};++#[cfg(test)]+mod test;++/// Inserts a forwarded attachment link between a draft and an original message's attachment.+/// Uses a subquery to verify the draft belongs to the given link_id.+/// ON CONFLICT DO NOTHING makes this idempotent.+#[tracing::instrument(skip(executor), err)]+pub async fn insert_forwarded_attachment<'e, E>(+ executor: E,+ link_id: Uuid,+ draft_id: Uuid,+ attachment_id: Uuid,+) -> anyhow::Result<()>+where+ E: Executor<'e, Database = Postgres>,+{+ sqlx::query!(+ r#"+ INSERT INTO email_attachments_fwd (message_id, attachment_id)+ SELECT $1, $2+ FROM email_messages m+ WHERE m.id = $1 AND m.link_id = $3+ ON CONFLICT DO NOTHING+ "#,+ draft_id,+ attachment_id,+ link_id,+ )+ .execute(executor)+ .await?;++ Ok(())+}++/// Deletes a forwarded attachment link. Verifies draft ownership via link_id.+#[tracing::instrument(skip(executor), err)]+pub async fn delete_forwarded_attachment<'e, E>(+ executor: E,+ link_id: Uuid,+ draft_id: Uuid,+ attachment_id: Uuid,+) -> anyhow::Result<u64>+where+ E: Executor<'e, Database = Postgres>,+{+ let result = sqlx::query!(+ r#"+ DELETE FROM email_attachments_fwd eaf+ USING email_messages m+ WHERE eaf.message_id = m.id+ AND eaf.message_id = $1 AND eaf.attachment_id = $2 AND m.link_id = $3+ "#,+ draft_id,+ attachment_id,+ link_id,+ )+ .execute(executor)+ .await?;++ Ok(result.rows_affected())+}++/// Fetches all forwarded attachments for a given draft, joining email_attachments+/// for metadata and email_messages for the original message's provider_id.+#[tracing::instrument(skip(pool), err)]+pub async fn fetch_forwarded_attachments_by_draft_id(+ pool: &PgPool,+ link_id: Uuid,+ draft_id: Uuid,+) -> anyhow::Result<Vec<service::attachment::AttachmentForwarded>> {+ let db_attachments = sqlx::query_as!(+ db::attachment::AttachmentForwarded,+ r#"+ SELECT+ eaf.attachment_id,+ eaf.message_id AS draft_id,+ ea.provider_attachment_id,+ orig_msg.provider_id AS "message_provider_id!",+ ea.filename,+ ea.mime_type,+ ea.size_bytes+ FROM email_attachments_fwd eaf+ JOIN email_messages draft_msg ON eaf.message_id = draft_msg.id+ JOIN email_attachments ea ON eaf.attachment_id = ea.id+ JOIN email_messages orig_msg ON ea.message_id = orig_msg.id+ WHERE eaf.message_id = $1 AND draft_msg.link_id = $2+ ORDER BY ea.filename ASC+ "#,+ draft_id,+ link_id,+ )+ .fetch_all(pool)+ .await?;++ let service_attachments = db_attachments+ .into_iter()+ .map(service::attachment::AttachmentForwarded::from)+ .collect();++ Ok(service_attachments)+}++/// Fetches forwarded attachments for multiple draft IDs and returns a map keyed by draft_id.+#[tracing::instrument(skip(pool), err)]+pub async fn fetch_forwarded_attachments_in_bulk(+ pool: &PgPool,+ draft_ids: &[Uuid],+) -> anyhow::Result<std::collections::HashMap<Uuid, Vec<db::attachment::AttachmentForwarded>>> {+ if draft_ids.is_empty() {+ return Ok(std::collections::HashMap::new());+ }++ let results = sqlx::query_as!(+ db::attachment::AttachmentForwarded,+ r#"+ SELECT+ eaf.attachment_id,+ eaf.message_id AS draft_id,+ ea.provider_attachment_id,+ orig_msg.provider_id AS "message_provider_id!",+ ea.filename,+ ea.mime_type,+ ea.size_bytes+ FROM email_attachments_fwd eaf+ JOIN email_attachments ea ON eaf.attachment_id = ea.id+ JOIN email_messages orig_msg ON ea.message_id = orig_msg.id+ WHERE eaf.message_id = ANY($1)+ ORDER BY eaf.message_id, ea.filename ASC+ "#,+ draft_ids,+ )+ .fetch_all(pool)+ .await?;++ let mut attachments_map: std::collections::HashMap<+ Uuid,+ Vec<db::attachment::AttachmentForwarded>,+ > = std::collections::HashMap::new();+ for attachment in results {+ attachments_map+ .entry(attachment.draft_id)+ .or_default()+ .push(attachment);+ }++ Ok(attachments_map)+}diff --git a/rust/cloud-storage/email_db_client/src/attachments/forwarded/test.rs b/rust/cloud-storage/email_db_client/src/attachments/forwarded/test.rsnew file mode 100644index 0000000000..72838a2d11--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/forwarded/test.rs@@ -0,0 +1,247 @@+use crate::attachments::forwarded::{+ delete_forwarded_attachment, fetch_forwarded_attachments_by_draft_id,+ fetch_forwarded_attachments_in_bulk, insert_forwarded_attachment,+};+use anyhow::Result;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::types::Uuid;+use sqlx::{Pool, Postgres};++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn fetch_forwarded_attachments_returns_attachments_ordered_by_filename(+ pool: Pool<Postgres>,+) -> Result<()> {+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?;++ let res = fetch_forwarded_attachments_by_draft_id(&pool, link_id, draft_id).await?;++ assert_eq!(res.len(), 2);++ // Verify ordering by filename ASC+ assert_eq!(res[0].filename, Some("photo.jpg".to_string()));+ assert_eq!(res[1].filename, Some("report.pdf".to_string()));++ // Verify other fields+ assert_eq!(res[0].mime_type, Some("image/jpeg".to_string()));+ assert_eq!(res[0].size_bytes, Some(120000));+ assert_eq!(+ res[0].provider_attachment_id,+ Some("gmail-att-id-002".to_string())+ );+ assert_eq!(res[0].message_provider_id, "gmail-original-msg-001");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn fetch_forwarded_attachments_returns_empty_for_wrong_link_id(+ pool: Pool<Postgres>,+) -> Result<()> {+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f02")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?;++ let res = fetch_forwarded_attachments_by_draft_id(&pool, wrong_link_id, draft_id).await?;++ assert_eq!(res.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn insert_forwarded_attachment_creates_new_link(pool: Pool<Postgres>) -> Result<()> {+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f502")?;+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000fa001")?;++ // Verify no forwarded attachments before insert+ let before = fetch_forwarded_attachments_by_draft_id(&pool, link_id, draft_id).await?;+ assert_eq!(before.len(), 0);++ insert_forwarded_attachment(&pool, link_id, draft_id, attachment_id).await?;++ // Verify attachment was linked+ let after = fetch_forwarded_attachments_by_draft_id(&pool, link_id, draft_id).await?;+ assert_eq!(after.len(), 1);+ assert_eq!(after[0].attachment_id, attachment_id);+ assert_eq!(after[0].filename, Some("report.pdf".to_string()));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn insert_forwarded_attachment_is_idempotent(pool: Pool<Postgres>) -> Result<()> {+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?;+ // This attachment is already linked to this draft in the fixture+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000fa001")?;++ // Should not error on duplicate+ insert_forwarded_attachment(&pool, link_id, draft_id, attachment_id).await?;++ let res = fetch_forwarded_attachments_by_draft_id(&pool, link_id, draft_id).await?;+ assert_eq!(res.len(), 2); // Still 2, not 3++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn insert_forwarded_attachment_does_nothing_for_wrong_link_id(+ pool: Pool<Postgres>,+) -> Result<()> {+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f02")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f502")?;+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000fa001")?;++ insert_forwarded_attachment(&pool, wrong_link_id, draft_id, attachment_id).await?;++ // Verify nothing was inserted with the correct link_id+ let correct_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let attachments =+ fetch_forwarded_attachments_by_draft_id(&pool, correct_link_id, draft_id).await?;+ assert_eq!(attachments.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn delete_forwarded_attachment_removes_link(pool: Pool<Postgres>) -> Result<()> {+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f503")?;+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000fa003")?;++ // Verify attachment exists before delete+ let before = fetch_forwarded_attachments_by_draft_id(&pool, link_id, draft_id).await?;+ assert_eq!(before.len(), 1);++ let rows_affected =+ delete_forwarded_attachment(&pool, link_id, draft_id, attachment_id).await?;++ assert_eq!(rows_affected, 1);++ // Verify attachment is deleted+ let after = fetch_forwarded_attachments_by_draft_id(&pool, link_id, draft_id).await?;+ assert_eq!(after.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn delete_forwarded_attachment_returns_zero_for_wrong_link_id(+ pool: Pool<Postgres>,+) -> Result<()> {+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f02")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f503")?;+ let attachment_id = Uuid::parse_str("00000000-0000-0000-0000-0000000fa003")?;++ let rows_affected =+ delete_forwarded_attachment(&pool, wrong_link_id, draft_id, attachment_id).await?;++ assert_eq!(rows_affected, 0);++ // Verify attachment still exists with correct link_id+ let correct_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let attachments =+ fetch_forwarded_attachments_by_draft_id(&pool, correct_link_id, draft_id).await?;+ assert_eq!(attachments.len(), 1);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn delete_forwarded_attachment_returns_zero_for_nonexistent(+ pool: Pool<Postgres>,+) -> Result<()> {+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;+ let draft_id = Uuid::parse_str("00000000-0000-0000-0000-00000000f503")?;+ let nonexistent_id = Uuid::parse_str("00000000-0000-0000-0000-0000000fffff")?;++ let rows_affected =+ delete_forwarded_attachment(&pool, link_id, draft_id, nonexistent_id).await?;++ assert_eq!(rows_affected, 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn fetch_forwarded_attachments_in_bulk_returns_grouped_by_draft_id(+ pool: Pool<Postgres>,+) -> Result<()> {+ let draft_id_1 = Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?;+ let draft_id_3 = Uuid::parse_str("00000000-0000-0000-0000-00000000f503")?;++ let result = fetch_forwarded_attachments_in_bulk(&pool, &[draft_id_1, draft_id_3]).await?;++ assert_eq!(result.len(), 2);++ // Draft 1 should have 2 forwarded attachments+ let draft_1_attachments = result.get(&draft_id_1).unwrap();+ assert_eq!(draft_1_attachments.len(), 2);++ // Draft 3 should have 1 forwarded attachment+ let draft_3_attachments = result.get(&draft_id_3).unwrap();+ assert_eq!(draft_3_attachments.len(), 1);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn fetch_forwarded_attachments_in_bulk_returns_empty_for_empty_input(+ pool: Pool<Postgres>,+) -> Result<()> {+ let result = fetch_forwarded_attachments_in_bulk(&pool, &[]).await?;++ assert!(result.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("forwarded_attachments"))+)]+async fn fetch_forwarded_attachments_in_bulk_excludes_drafts_without_attachments(+ pool: Pool<Postgres>,+) -> Result<()> {+ let draft_with = Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?;+ let draft_without = Uuid::parse_str("00000000-0000-0000-0000-00000000f502")?;++ let result = fetch_forwarded_attachments_in_bulk(&pool, &[draft_with, draft_without]).await?;++ assert_eq!(result.len(), 1);+ assert!(result.contains_key(&draft_with));+ assert!(!result.contains_key(&draft_without));++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/attachments/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/mod.rsindex 17a6730fba..93dcb049f9 100644--- a/rust/cloud-storage/email_db_client/src/attachments/mod.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/mod.rs@@ -1,3 +1,4 @@pub mod draft;+pub mod forwarded;pub mod provider;pub mod sfs;diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rsindex 4d5f165318..b221e23a3b 100644--- a/rust/cloud-storage/email_db_client/src/messages/get.rs+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs@@ -542,6 +542,7 @@ pub async fn convert_db_messages_to_service_concurrent(labels_map,attachments_map,draft_attachments_map,+ forwarded_attachments_map,) = tokio::try_join!(contacts::get::fetch_senders_by_message_ids(pool, &message_ids),contacts::get::fetch_db_recipients_in_bulk(pool, &message_ids),@@ -549,6 +550,7 @@ pub async fn convert_db_messages_to_service_concurrent(labels::get::fetch_message_labels_in_bulk(pool, &message_ids),attachments::provider::fetch_db_attachments_in_bulk(pool, &message_ids_with_attachments),attachments::draft::fetch_db_draft_attachments_in_bulk(pool, &draft_message_ids),+ attachments::forwarded::fetch_forwarded_attachments_in_bulk(pool, &draft_message_ids),)?;// Build service messages concurrently by looking up data from the hashmaps@@ -568,6 +570,10 @@ pub async fn convert_db_messages_to_service_concurrent(.get(&message_id).cloned().unwrap_or_default();+ let forwarded_attachments = forwarded_attachments_map+ .get(&message_id)+ .cloned()+ .unwrap_or_default();async move {// Build the service message without attachments first@@ -580,6 +586,7 @@ pub async fn convert_db_messages_to_service_concurrent(service_message,attachments,draft_attachments,+ forwarded_attachments,)}});diff --git a/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs b/rust/cloud-storage/email_db_client/src/parse/db_to_service.rsindex 569ae4b30c..c04bc5de40 100644--- a/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs+++ b/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs@@ -87,6 +87,7 @@ pub fn map_db_message_attachments_to_service(mut service_message: message::Message,attachments_res: Vec<db::attachment::Attachment>,draft_attachments_res: Vec<db::attachment::AttachmentDraft>,+ forwarded_attachments_res: Vec<db::attachment::AttachmentForwarded>,) -> anyhow::Result<message::Message> {service_message.attachments = map_db_attachments_to_service(attachments_res);@@ -95,6 +96,11 @@ pub fn map_db_message_attachments_to_service(.map(|a| a.into()).collect();+ service_message.attachments_forwarded = forwarded_attachments_res+ .into_iter()+ .map(|a| a.into())+ .collect();+Ok(service_message)}@@ -183,6 +189,7 @@ pub fn map_attachmentless_db_message_to_service(body_macro: db_message.body_macro,attachments: Vec::new(),attachments_draft: Vec::new(),+ attachments_forwarded: Vec::new(),headers_json: db_message.headers_jsonb,created_at: db_message.created_at,updated_at: db_message.updated_at,diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/add_forwarded_attachment.rs b/rust/cloud-storage/email_service/src/api/email/drafts/add_forwarded_attachment.rsnew file mode 100644index 0000000000..b2aa04e59c--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/drafts/add_forwarded_attachment.rs@@ -0,0 +1,123 @@+use crate::api::context::ApiContext;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::{Extension, Json};+use model::response::ErrorResponse;+use models_email::service::link::Link;+use strum_macros::AsRefStr;+use thiserror::Error;+use utoipa::{IntoParams, ToSchema};+use uuid::Uuid;++#[derive(Debug, Error, AsRefStr)]+pub enum AddForwardedAttachmentError {+ #[error("Draft not found")]+ DraftNotFound,++ #[error("Attachment not found")]+ AttachmentNotFound,++ #[error("Internal error")]+ InternalError(#[from] anyhow::Error),+}++impl IntoResponse for AddForwardedAttachmentError {+ fn into_response(self) -> Response {+ let status_code = match &self {+ AddForwardedAttachmentError::DraftNotFound+ | AddForwardedAttachmentError::AttachmentNotFound => StatusCode::NOT_FOUND,+ AddForwardedAttachmentError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (+ status_code,+ Json(ErrorResponse {+ message: self.to_string().as_str(),+ }),+ )+ .into_response()+ }+}++#[derive(serde::Serialize, serde::Deserialize, Debug, IntoParams)]+pub struct PathParams {+ /// The ID of the draft to add the forwarded attachment to.+ pub id: Uuid,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct AddForwardedAttachmentRequest {+ /// The ID of the original attachment to forward.+ pub attachment_id: Uuid,+}++#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct AddForwardedAttachmentResponse {+ /// The ID of the original attachment.+ pub attachment_id: Uuid,+ /// Original file name of the attachment.+ pub filename: Option<String>,+ /// MIME type of the attachment.+ pub mime_type: Option<String>,+ /// File size in bytes.+ pub size_bytes: Option<i64>,+}++/// Add a forwarded attachment to a draft.+#[utoipa::path(+ post,+ tag = "Drafts",+ path = "/email/drafts/{id}/forwarded-attachments",+ operation_id = "add_forwarded_attachment",+ params(PathParams),+ request_body = AddForwardedAttachmentRequest,+ responses(+ (status = 201, body = AddForwardedAttachmentResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx), err)]+pub async fn handler(+ State(ctx): State<ApiContext>,+ link: Extension<Link>,+ Path(PathParams { id: draft_id }): Path<PathParams>,+ Json(req): Json<AddForwardedAttachmentRequest>,+) -> Result<(StatusCode, Json<AddForwardedAttachmentResponse>), AddForwardedAttachmentError> {+ // Ensure draft exists and belongs to this link+ if !email_db_client::messages::get::draft_exists_with_id(&ctx.db, link.id, draft_id).await? {+ return Err(AddForwardedAttachmentError::DraftNotFound);+ }++ // Verify the attachment exists in email_attachments and belongs to this link+ let result = email_db_client::attachments::provider::fetch_attachment_by_id(+ &ctx.db,+ req.attachment_id,+ link.id,+ )+ .await?;++ let Some((attachment, _message_provider_id)) = result else {+ return Err(AddForwardedAttachmentError::AttachmentNotFound);+ };++ // Insert the forwarded attachment link+ email_db_client::attachments::forwarded::insert_forwarded_attachment(+ &ctx.db,+ link.id,+ draft_id,+ req.attachment_id,+ )+ .await?;++ Ok((+ StatusCode::CREATED,+ Json(AddForwardedAttachmentResponse {+ attachment_id: attachment.db_id,+ filename: attachment.filename,+ mime_type: attachment.mime_type,+ size_bytes: attachment.size_bytes,+ }),+ ))+}diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rsindex 460bbe2b99..29c053aae0 100644--- a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs@@ -1,7 +1,9 @@pub(crate) mod add_attachment;+pub(crate) mod add_forwarded_attachment;pub(crate) mod create;pub(crate) mod delete;pub(crate) mod remove_attachment;+pub(crate) mod remove_forwarded_attachment;pub(crate) mod scheduled;use crate::api::ApiContext;@@ -18,6 +20,14 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {"/:id/attachments/:attachment_id",delete(remove_attachment::handler),)+ .route(+ "/:id/forwarded-attachments",+ post(add_forwarded_attachment::handler),+ )+ .route(+ "/:id/forwarded-attachments/:attachment_id",+ delete(remove_forwarded_attachment::handler),+ ).layer(axum::middleware::from_fn_with_state(state.email_service,crate::api::middleware::link::attach_link_context,diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/remove_forwarded_attachment.rs b/rust/cloud-storage/email_service/src/api/email/drafts/remove_forwarded_attachment.rsnew file mode 100644index 0000000000..4790717ea6--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/drafts/remove_forwarded_attachment.rs@@ -0,0 +1,91 @@+use crate::api::context::ApiContext;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::{Extension, Json};+use model::response::ErrorResponse;+use models_email::service::link::Link;+use strum_macros::AsRefStr;+use thiserror::Error;+use utoipa::IntoParams;+use uuid::Uuid;++#[derive(Debug, Error, AsRefStr)]+pub enum RemoveForwardedAttachmentError {+ #[error("Draft not found")]+ DraftNotFound,++ #[error("Attachment not found")]+ AttachmentNotFound,++ #[error("Internal error")]+ InternalError(#[from] anyhow::Error),+}++impl IntoResponse for RemoveForwardedAttachmentError {+ fn into_response(self) -> Response {+ let status_code = match &self {+ RemoveForwardedAttachmentError::DraftNotFound+ | RemoveForwardedAttachmentError::AttachmentNotFound => StatusCode::NOT_FOUND,+ RemoveForwardedAttachmentError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (+ status_code,+ Json(ErrorResponse {+ message: self.to_string().as_str(),+ }),+ )+ .into_response()+ }+}++#[derive(serde::Serialize, serde::Deserialize, Debug, IntoParams)]+pub struct PathParams {+ /// The ID of the draft to remove the forwarded attachment from.+ pub id: Uuid,+ /// The ID of the forwarded attachment to remove.+ pub attachment_id: Uuid,+}++/// Remove a forwarded attachment from a draft.+#[utoipa::path(+ delete,+ tag = "Drafts",+ path = "/email/drafts/{id}/forwarded-attachments/{attachment_id}",+ operation_id = "remove_forwarded_attachment",+ params(PathParams),+ responses(+ (status = 204),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx), err)]+pub async fn handler(+ State(ctx): State<ApiContext>,+ link: Extension<Link>,+ Path(PathParams {+ id: draft_id,+ attachment_id,+ }): Path<PathParams>,+) -> Result<impl IntoResponse, RemoveForwardedAttachmentError> {+ // Ensure draft exists+ if !email_db_client::messages::get::draft_exists_with_id(&ctx.db, link.id, draft_id).await? {+ return Err(RemoveForwardedAttachmentError::DraftNotFound);+ }++ let rows_affected = email_db_client::attachments::forwarded::delete_forwarded_attachment(+ &ctx.db,+ link.id,+ draft_id,+ attachment_id,+ )+ .await?;++ if rows_affected == 0 {+ return Err(RemoveForwardedAttachmentError::AttachmentNotFound);+ }++ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex d420c54565..00ae650e8c 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -6,6 +6,9 @@ use crate::api::email::contacts::list::ListContactsResponse;use crate::api::email::drafts::add_attachment::{AddDraftAttachmentRequest, AddDraftAttachmentResponse,};+use crate::api::email::drafts::add_forwarded_attachment::{+ AddForwardedAttachmentRequest, AddForwardedAttachmentResponse,+};use crate::api::email::drafts::create::{CreateDraftRequest, CreateDraftResponse};use crate::api::email::init::InitResponse;use crate::api::email::labels::create::CreateLabelRequest;@@ -52,6 +55,8 @@ use utoipa::OpenApi;email::drafts::scheduled::upsert::handler,email::drafts::add_attachment::handler,email::drafts::remove_attachment::handler,+ email::drafts::add_forwarded_attachment::handler,+ email::drafts::remove_forwarded_attachment::handler,email::messages::get::handler,email::messages::get::batch_handler,email::messages::labels::handler,@@ -82,6 +87,8 @@ use utoipa::OpenApi;CreateDraftResponse,AddDraftAttachmentRequest,AddDraftAttachmentResponse,+ AddForwardedAttachmentRequest,+ AddForwardedAttachmentResponse,// Init typesInitResponse,// Label typesdiff --git a/rust/cloud-storage/email_service/src/convert/message.rs b/rust/cloud-storage/email_service/src/convert/message.rsindex 1451f170d4..613ac75d2c 100644--- a/rust/cloud-storage/email_service/src/convert/message.rs+++ b/rust/cloud-storage/email_service/src/convert/message.rs@@ -99,6 +99,7 @@ pub fn map_message_resource_to_service(body_macro: None,attachments,attachments_draft: Vec::new(),+ attachments_forwarded: Vec::new(),headers_json: Some(serde_json::to_value(parsed_payload.all_headers)?),created_at: Utc::now(), // Omitted - set default/ignoredupdated_at: Utc::now(), // Omitted - set default/ignoreddiff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rsindex 4212df93d7..e0f91c91ee 100644--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs@@ -1,7 +1,8 @@use crate::pubsub::scheduled::context::ScheduledContext;use crate::util::gmail::auth::fetch_gmail_access_token_from_link;use crate::util::gmail::send::{- cleanup_draft_attachments, fetch_and_attach_draft_attachments, generate_email_threading_headers,+ cleanup_draft_attachments, fetch_and_attach_draft_attachments,+ fetch_and_attach_forwarded_attachments, generate_email_threading_headers,};use anyhow::Context;use chrono::Utc;@@ -127,7 +128,7 @@ async fn process_scheduled_message_inner(generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, data.link_id).await;- // Include attachments for message+ // Include draft attachments (user-uploaded files from S3)let db_attachments = fetch_and_attach_draft_attachments(&ctx.db,&ctx.s3_client,@@ -137,6 +138,16 @@ async fn process_scheduled_message_inner().await?;+ // Include forwarded attachments (fetched from Gmail at send time)+ fetch_and_attach_forwarded_attachments(+ &ctx.db,+ &ctx.gmail_client,+ &gmail_access_token,+ &link,+ &mut message_to_send,+ )+ .await?;+// send message to gmail apictx.gmail_client.send_message(diff --git a/rust/cloud-storage/email_service/src/util/gmail/send.rs b/rust/cloud-storage/email_service/src/util/gmail/send.rsindex ad701b807f..e7f0d08dde 100644--- a/rust/cloud-storage/email_service/src/util/gmail/send.rs+++ b/rust/cloud-storage/email_service/src/util/gmail/send.rs@@ -1,4 +1,5 @@use anyhow::Context;+use gmail_client::GmailClient;use models_email::service::attachment::{AttachmentDraft, AttachmentToSend};use models_email::service::link::Link;use models_email::service::message;@@ -104,6 +105,65 @@ pub async fn fetch_and_attach_draft_attachments(Ok(None)}+/// Fetch forwarded attachments from Gmail and attach them to the message being sent.+/// Forwarded attachments reference original Gmail attachments, so their data is fetched+/// from Gmail at send time rather than from S3.+#[tracing::instrument(+ skip(db, gmail_client, access_token, message_to_send),+ fields(message_db_id = ?message_to_send.db_id), err+)]+pub async fn fetch_and_attach_forwarded_attachments(+ db: &PgPool,+ gmail_client: &GmailClient,+ access_token: &str,+ link: &Link,+ message_to_send: &mut message::MessageToSend,+) -> anyhow::Result<()> {+ let Some(db_id) = message_to_send.db_id else {+ return Ok(());+ };++ let fwd_attachments =+ email_db_client::attachments::forwarded::fetch_forwarded_attachments_by_draft_id(+ db, link.id, db_id,+ )+ .await+ .context("unable to fetch forwarded attachments from database")?;++ if fwd_attachments.is_empty() {+ return Ok(());+ }++ let fetch_futures = fwd_attachments.iter().map(|fwd_att| async move {+ let provider_att_id = fwd_att.provider_attachment_id.as_deref().unwrap_or_default();++ let data = gmail_client+ .get_attachment_data(access_token, &fwd_att.message_provider_id, provider_att_id)+ .await+ .with_context(|| {+ format!(+ "Failed to fetch forwarded attachment from Gmail (message: {}, attachment: {:?})",+ fwd_att.message_provider_id, fwd_att.provider_attachment_id+ )+ })?;++ Ok::<AttachmentToSend, anyhow::Error>(AttachmentToSend {+ file_name: fwd_att.filename.clone().unwrap_or_default(),+ content_type: fwd_att.mime_type.clone().unwrap_or_else(|| "application/octet-stream".to_string()),+ data,+ })+ });++ let forwarded_to_send = futures::future::try_join_all(fetch_futures).await?;++ match &mut message_to_send.attachments {+ Some(existing) => existing.extend(forwarded_to_send),+ None => message_to_send.attachments = Some(forwarded_to_send),+ }++ Ok(())+}+#[tracing::instrument(skip(db, s3_client))]pub async fn cleanup_draft_attachments(db: sqlx::PgPool,diff --git a/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs b/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rsindex 69f4bd95ad..d6a06a4b63 100644--- a/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs+++ b/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs@@ -144,6 +144,7 @@ mod tests {body_text: None,attachments: vec![],attachments_draft: vec![],+ attachments_forwarded: vec![],headers_json: None,created_at: Default::default(),labels: vec![],diff --git a/rust/cloud-storage/macro_db_client/migrations/20260212192413_email_attachments_fwd.sql b/rust/cloud-storage/macro_db_client/migrations/20260212192413_email_attachments_fwd.sqlnew file mode 100644index 0000000000..d55b58ec56--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260212192413_email_attachments_fwd.sql@@ -0,0 +1,7 @@+CREATE TABLE email_attachments_fwd (+ message_id UUID NOT NULL REFERENCES email_messages(id) ON DELETE CASCADE,+ attachment_id UUID NOT NULL REFERENCES email_attachments(id) ON DELETE CASCADE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ UNIQUE(message_id, attachment_id)+);+CREATE INDEX idx_email_attachments_fwd_attachment_id ON email_attachments_fwd(attachment_id);diff --git a/rust/cloud-storage/models_email/src/email/db/attachment.rs b/rust/cloud-storage/models_email/src/email/db/attachment.rsindex 52e120eac9..e10e2f36e2 100644--- a/rust/cloud-storage/models_email/src/email/db/attachment.rs+++ b/rust/cloud-storage/models_email/src/email/db/attachment.rs@@ -67,3 +67,23 @@ impl From<crate::service::attachment::AttachmentDraft> for AttachmentDraft {}}}++/// A forwarded attachment linking a draft to an original message's attachment.+/// Data is fetched from Gmail at send time rather than stored in S3.+#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]+pub struct AttachmentForwarded {+ /// The UUID of the original attachment in email_attachments.+ pub attachment_id: Uuid,+ /// The ID of the draft message this forwarded attachment belongs to.+ pub draft_id: Uuid,+ /// The Gmail attachment ID for fetching data from Gmail API.+ pub provider_attachment_id: Option<String>,+ /// The Gmail message ID of the original message containing the attachment.+ pub message_provider_id: String,+ /// Original file name of the attachment.+ pub filename: Option<String>,+ /// MIME type of the attachment.+ pub mime_type: Option<String>,+ /// File size in bytes.+ pub size_bytes: Option<i64>,+}diff --git a/rust/cloud-storage/models_email/src/email/service/attachment.rs b/rust/cloud-storage/models_email/src/email/service/attachment.rsindex 63531a6d82..04dbdda389 100644--- a/rust/cloud-storage/models_email/src/email/service/attachment.rs+++ b/rust/cloud-storage/models_email/src/email/service/attachment.rs@@ -104,6 +104,40 @@ impl From<crate::db::attachment::AttachmentDraft> for AttachmentDraft {}}+/// A forwarded attachment linking a draft to an original message's attachment.+/// Data is fetched from Gmail at send time rather than stored in S3.+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct AttachmentForwarded {+ /// The UUID of the original attachment in email_attachments.+ pub attachment_id: Uuid,+ /// The ID of the draft message this forwarded attachment belongs to.+ pub draft_id: Uuid,+ /// The Gmail attachment ID for fetching data from Gmail API.+ pub provider_attachment_id: Option<String>,+ /// The Gmail message ID of the original message containing the attachment.+ pub message_provider_id: String,+ /// Original file name of the attachment.+ pub filename: Option<String>,+ /// MIME type of the attachment.+ pub mime_type: Option<String>,+ /// File size in bytes.+ pub size_bytes: Option<i64>,+}++impl From<crate::db::attachment::AttachmentForwarded> for AttachmentForwarded {+ fn from(db: crate::db::attachment::AttachmentForwarded) -> Self {+ Self {+ attachment_id: db.attachment_id,+ draft_id: db.draft_id,+ provider_attachment_id: db.provider_attachment_id,+ message_provider_id: db.message_provider_id,+ filename: db.filename,+ mime_type: db.mime_type,+ size_bytes: db.size_bytes,+ }+ }+}+/// The attachment data we need to include when sending a message to a provider.#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]pub struct AttachmentToSend {diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rsindex e524d80991..247881fdf9 100644--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs+++ b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs@@ -116,6 +116,7 @@ mod tests {body_text: None,attachments: vec![],attachments_draft: vec![],+ attachments_forwarded: vec![],headers_json: None,created_at: Default::default(),labels: vec![],diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rsindex ed62ece8f4..4c58ed35d8 100644--- a/rust/cloud-storage/models_email/src/email/service/message.rs+++ b/rust/cloud-storage/models_email/src/email/service/message.rs@@ -2,7 +2,7 @@ use crate::db;use crate::email::service::address::ContactInfo;use crate::email::service::attachment::Attachment;use crate::email::service::label::{LabelInfo, system_labels};-use crate::service::attachment::{AttachmentDraft, AttachmentToSend};+use crate::service::attachment::{AttachmentDraft, AttachmentForwarded, AttachmentToSend};use crate::service::body_parsing::body_parsed::{get_body_parsed_for_message, get_body_parsed_linkless_for_message,};@@ -88,6 +88,8 @@ pub struct Message {pub attachments: Vec<Attachment>,/// Uploaded file attachments for the message, if it is a draftpub attachments_draft: Vec<AttachmentDraft>,+ /// Forwarded attachments from original messages, if it is a draft+ pub attachments_forwarded: Vec<AttachmentForwarded>,pub headers_json: Option<JsonValue>,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,