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): send X-Email-Link-Id on compose/reply mutations for non-primary inboxes (#3689)
gbirman40adc8c42f49
diff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex d936d8945d..2c4f93f9b9 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -68,7 +68,10 @@ import {useSaveDraftMutation,} from '@queries/email/draft';import { emailKeys } from '@queries/email/keys';-import { useEmailLinksQuery } from '@queries/email/link';+import {+ useEmailLinksQuery,+ useNonPrimaryEmailLinkIdHeader,+} from '@queries/email/link';import {useSendMessageMutation,useUnscheduleMessageMutation,@@ -429,6 +432,14 @@ export function BaseInput(props: {const blockId = useBlockId();const emailLinksQuery = useEmailLinksQuery();+ const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();+ // The inbox this input acts in: the open thread's inbox, else the default+ // inbox for a new message. Mutations send it as X-Email-Link-Id when it's a+ // non-primary inbox so the draft/send targets the right account.+ const activeLinkId = () =>+ ctx.thread()?.link_id ?? emailLinksQuery.data?.links[0]?.id;+ const headerLinkId = () => toHeaderLinkId(activeLinkId());+const [bodyMacro, setBodyMacro] = createSignal<string>('');const [expandedRecipientsRef, setExpandedRecipientsRef] =createSignal<HTMLDivElement>();@@ -691,7 +702,10 @@ export function BaseInput(props: {if (!draftToSave) {const draftId = savedDraftId();if (draftId) {- await deleteDraftMutation.mutateAsync({ draftId });+ await deleteDraftMutation.mutateAsync({+ draftId,+ linkId: headerLinkId(),+ });refetchThreadMessages();}setSavedDraftId(undefined);@@ -721,6 +735,7 @@ export function BaseInput(props: {provider_thread_id: currentThread?.provider_id,thread_db_id: currentThread?.db_id,},+ linkId: headerLinkId(),});const draftId = draftResponse.draft.db_id;@@ -739,6 +754,7 @@ export function BaseInput(props: {const uploaded = await uploadAttachmentMutation.mutateAsync({draftID: draftId,attachments: attachments.map((a) => a.file),+ linkId: headerLinkId(),});// Assign the attachment ids to attachments for later use@@ -764,6 +780,7 @@ export function BaseInput(props: {attachments: forwardedAttachments.map((a) => ({attachmentID: a.attachmentID,})),+ linkId: headerLinkId(),});}@@ -1007,6 +1024,7 @@ export function BaseInput(props: {thread_db_id: currentThread?.db_id,to,},+ linkId: toHeaderLinkId(linkId),});// Block any save scheduled by reset side effects (form().reset() callDirty,@@ -1047,7 +1065,10 @@ export function BaseInput(props: {const draftId = savedDraftId();try {if (draftId) {- await deleteDraftMutation.mutateAsync({ draftId });+ await deleteDraftMutation.mutateAsync({+ draftId,+ linkId: headerLinkId(),+ });refetchThreadMessages();}resetState();@@ -1246,11 +1267,13 @@ export function BaseInput(props: {removeForwardedAttachmentMutation.mutate({draftID: currentDraftID,attachmentID: attachment.attachmentID,+ linkId: headerLinkId(),});} else {removeAttachmentMutation.mutate({draftID: currentDraftID,attachmentID: attachment.attachmentID,+ linkId: headerLinkId(),});}};@@ -1272,6 +1295,7 @@ export function BaseInput(props: {if (!date && currentSendTime && currentDraft) {unscheduleMessageMutation.mutate({draftID: currentDraft,+ linkId: headerLinkId(),});form().setSendTime(date);return;@@ -1289,15 +1313,21 @@ export function BaseInput(props: {return;}- await emailClient.scheduleMessage({- draftID,- send_time: date.toISOString(),- });+ await emailClient.scheduleMessage(+ {+ draftID,+ send_time: date.toISOString(),+ },+ headerLinkId()+ );// Mark the thread as doneconst threadID = ctx.thread()?.db_id;if (threadID) {- await emailClient.flagArchived({ id: threadID, value: true });+ await emailClient.flagArchived(+ { id: threadID, value: true },+ headerLinkId()+ );}}};diff --git a/js/app/packages/block-email/component/Block.tsx b/js/app/packages/block-email/component/Block.tsxindex 54f664354d..104c2b7687 100644--- a/js/app/packages/block-email/component/Block.tsx+++ b/js/app/packages/block-email/component/Block.tsx@@ -39,6 +39,7 @@ export default function BlockEmail() {<EmailDebouncedReadMarkernotificationSource={notificationSource}threadId={id()}+ linkId={threadQuery.data?.thread?.link_id}debounceTime={isPreview ? 1_500 : 100}/><Suspense>diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsxindex 7d7d42f148..28f4b9f015 100644--- a/js/app/packages/block-email/component/EmailContext.tsx+++ b/js/app/packages/block-email/component/EmailContext.tsx@@ -21,6 +21,7 @@ import { whenSettled } from '@core/util/whenSettled';import { createEffectOnEntityTypeNotification } from '@notifications';import { queryClient } from '@queries/client';import { emailKeys } from '@queries/email/keys';+import { useNonPrimaryEmailLinkIdHeader } from '@queries/email/link';import {blockSenderWithToast,markSenderNoiseWithToast,@@ -330,6 +331,8 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {},});+ const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();+const archiveThread = () => {const thread = threadQuery.data;@@ -338,6 +341,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {archiveMutation.mutate({threadId: thread.db_id,archive: thread.inbox_visible,+ linkId: toHeaderLinkId(thread.link_id),});if (!props) return false;@@ -354,6 +358,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {archiveMutation.mutate({threadId: thread.db_id,archive: thread.inbox_visible,+ linkId: toHeaderLinkId(thread.link_id),});}@@ -375,7 +380,7 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {if (!senderEmail) return false;- blockSenderWithToast(senderEmail);+ blockSenderWithToast(senderEmail, toHeaderLinkId(thread.link_id));return true;};diff --git a/js/app/packages/block-email/component/compose/Compose.tsx b/js/app/packages/block-email/component/compose/Compose.tsxindex 6a2e512ee6..579823d48c 100644--- a/js/app/packages/block-email/component/compose/Compose.tsx+++ b/js/app/packages/block-email/component/compose/Compose.tsx@@ -49,7 +49,10 @@ import {useSaveDraftMutation,} from '@queries/email/draft';import { emailKeys } from '@queries/email/keys';-import { useEmailLinksQuery } from '@queries/email/link';+import {+ useEmailLinksQuery,+ useNonPrimaryEmailLinkIdHeader,+} from '@queries/email/link';import {useSendMessageMutation,useUnscheduleMessageMutation,@@ -102,6 +105,11 @@ export function EmailCompose(props: EmailComposeProps) {return undefined;});+ const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();+ // Scope writes to the inbox this compose sends from (its X-Email-Link-Id+ // header), so a non-primary "from" inbox drafts/sends from the right account.+ const headerLinkId = () => toHeaderLinkId(link()?.id);+const hasLinkError = createMemo(() => {if (emailLinksQuery.isPending) return false;return (@@ -190,7 +198,10 @@ export function EmailCompose(props: EmailComposeProps) {if (!draftToSave) {const draftID = currentDraftID();if (draftID) {- await deleteDraftMutation.mutateAsync({ draftId: draftID });+ await deleteDraftMutation.mutateAsync({+ draftId: draftID,+ linkId: headerLinkId(),+ });}setCurrentDraftID(undefined);return;@@ -201,6 +212,7 @@ export function EmailCompose(props: EmailComposeProps) {...draftToSave,db_id: currentDraftID(),},+ linkId: headerLinkId(),});const draftId = draftResponse.draft.db_id;@@ -216,6 +228,7 @@ export function EmailCompose(props: EmailComposeProps) {const uploaded = await uploadAttachmentMutation.mutateAsync({draftID: draftId,attachments: attachments.map((a) => a.file),+ linkId: headerLinkId(),});for (const attachment of uploaded.attachments) {@@ -264,11 +277,13 @@ export function EmailCompose(props: EmailComposeProps) {removeForwardedAttachmentMutation.mutate({draftID: savedDraftID,attachmentID: attachment.attachmentID,+ linkId: headerLinkId(),});} else {removeAttachmentMutation.mutate({draftID: savedDraftID,attachmentID: attachment.attachmentID,+ linkId: headerLinkId(),});}};@@ -294,7 +309,7 @@ export function EmailCompose(props: EmailComposeProps) {const undoSend = async (draftId: string) => {try {- await emailClient.unscheduleMessage({ draftID: draftId });+ await emailClient.unscheduleMessage({ draftID: draftId }, headerLinkId());queryClient.invalidateQueries({queryKey: emailKeys.previews._def,});@@ -437,6 +452,7 @@ export function EmailCompose(props: EmailComposeProps) {body_macro: bodyMacro,db_id: currentDraftID(),},+ linkId: headerLinkId(),});cleanupWatermark();@@ -461,6 +477,7 @@ export function EmailCompose(props: EmailComposeProps) {if (!date && currentSendTime && currentDraft) {unscheduleMessageMutation.mutate({draftID: currentDraft,+ linkId: headerLinkId(),});form.setSendTime(date);return;@@ -477,14 +494,20 @@ export function EmailCompose(props: EmailComposeProps) {return;}- await emailClient.scheduleMessage({- draftID,- send_time: date.toISOString(),- });+ await emailClient.scheduleMessage(+ {+ draftID,+ send_time: date.toISOString(),+ },+ headerLinkId()+ );const threadID = saveDraftMutation.data?.draft.thread_db_id;if (threadID) {- await emailClient.flagArchived({ id: threadID, value: true });+ await emailClient.flagArchived(+ { id: threadID, value: true },+ headerLinkId()+ );}}};@@ -518,7 +541,10 @@ export function EmailCompose(props: EmailComposeProps) {const deleteDraftAndReset = async () => {const draftId = currentDraftID();if (draftId) {- await deleteDraftMutation.mutateAsync({ draftId });+ await deleteDraftMutation.mutateAsync({+ draftId,+ linkId: headerLinkId(),+ });}resetState();};diff --git a/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx b/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsxindex d44cfab81d..e436089018 100644--- a/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx+++ b/js/app/packages/notifications/components/DebouncedNotificationReadMarker.tsx@@ -1,4 +1,5 @@import type { Entity } from '@core/types';+import { useNonPrimaryEmailLinkIdHeader } from '@queries/email/link';import { useMarkThreadAsSeenMutation } from '@queries/email/thread';import { debounce } from '@solid-primitives/scheduled';import { onMount } from 'solid-js';@@ -129,8 +130,11 @@ export function EmailDebouncedReadMarker(props: {notificationSource: NotificationSource;debounceTime?: number;threadId: string;+ /** The inbox the thread belongs to; scopes mark-as-seen to a non-primary inbox. */+ linkId?: string;}) {const markSeenMutation = useMarkThreadAsSeenMutation();+ const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();return (<DebouncedMarker@@ -140,7 +144,10 @@ export function EmailDebouncedReadMarker(props: {type: 'email_thread',id: props.threadId,});- markSeenMutation.mutate({ threadId: props.threadId });+ markSeenMutation.mutate({+ threadId: props.threadId,+ linkId: toHeaderLinkId(props.linkId),+ });}}/>);diff --git a/js/app/packages/queries/email/attachment.ts b/js/app/packages/queries/email/attachment.tsindex fc3208ceb6..dfa6ca110e 100644--- a/js/app/packages/queries/email/attachment.ts+++ b/js/app/packages/queries/email/attachment.ts@@ -9,6 +9,8 @@ import { useMutation } from '@tanstack/solid-query';type UploadDraftAttachmentsParams = {draftID: string;attachments: File[];+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;};type UploadDraftAttachmentsReturn = {@@ -42,14 +44,17 @@ export const useUploadDraftAttachmentsMutation = (const result = await throwOnErr(async () =>- await emailClient.addDraftAttachment({- draftID: params.draftID,- attachment: {- file_name: attachment.name,- size: attachment.size,- sha,+ await emailClient.addDraftAttachment(+ {+ draftID: params.draftID,+ attachment: {+ file_name: attachment.name,+ size: attachment.size,+ sha,+ },},- })+ params.linkId+ ));uploadedAttachments.push({@@ -91,10 +96,13 @@ export const useUploadDraftAttachmentsMutation = (async onError(error, variables) {if (error instanceof UploadDraftAttachmentError) {try {- await emailClient.removeDraftAttachment({- draftID: variables.draftID,- attachmentID: error.context.attachmentID,- });+ await emailClient.removeDraftAttachment(+ {+ draftID: variables.draftID,+ attachmentID: error.context.attachmentID,+ },+ variables.linkId+ );} catch {console.error('Unable to remove draft attachment after failure');}@@ -110,6 +118,8 @@ export const useUploadDraftAttachmentsMutation = (type RemoveDraftAttachmentParams = {draftID: string;attachmentID: string;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;};export const useRemoveDraftAttachmentMutation = (@@ -119,10 +129,13 @@ export const useRemoveDraftAttachmentMutation = (mutationFn: async (params: RemoveDraftAttachmentParams) => {await throwOnErr(async () =>- await emailClient.removeDraftAttachment({- draftID: params.draftID,- attachmentID: params.attachmentID,- })+ await emailClient.removeDraftAttachment(+ {+ draftID: params.draftID,+ attachmentID: params.attachmentID,+ },+ params.linkId+ ));},...withCallbacks<void, Error, RemoveDraftAttachmentParams>(@@ -139,6 +152,8 @@ export const useRemoveDraftAttachmentMutation = (type AddForwardedAttachmentsParams = {draftID: string;attachments: { attachmentID: string }[];+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;};export const useAddForwardedAttachmentsMutation = (@@ -149,10 +164,13 @@ export const useAddForwardedAttachmentsMutation = (for (const att of params.attachments) {await throwOnErr(async () =>- await emailClient.addForwardedAttachment({- draftID: params.draftID,- attachmentID: att.attachmentID,- })+ await emailClient.addForwardedAttachment(+ {+ draftID: params.draftID,+ attachmentID: att.attachmentID,+ },+ params.linkId+ ));}},@@ -170,6 +188,8 @@ export const useAddForwardedAttachmentsMutation = (type RemoveForwardedAttachmentParams = {draftID: string;attachmentID: string;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;};export const useRemoveForwardedAttachmentMutation = (@@ -179,10 +199,13 @@ export const useRemoveForwardedAttachmentMutation = (mutationFn: async (params: RemoveForwardedAttachmentParams) => {await throwOnErr(async () =>- await emailClient.removeForwardedAttachment({- draftID: params.draftID,- attachmentID: params.attachmentID,- })+ await emailClient.removeForwardedAttachment(+ {+ draftID: params.draftID,+ attachmentID: params.attachmentID,+ },+ params.linkId+ ));},...withCallbacks<void, Error, RemoveForwardedAttachmentParams>(diff --git a/js/app/packages/queries/email/draft.ts b/js/app/packages/queries/email/draft.tsindex 2cc295eeff..7dcb49c551 100644--- a/js/app/packages/queries/email/draft.ts+++ b/js/app/packages/queries/email/draft.ts@@ -14,6 +14,8 @@ import { emailKeys } from './keys';type CreateDraftParams = {draft: ApiDraftInput;sendTime?: Date | null;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;};/**@@ -26,10 +28,13 @@ export function useSaveDraftMutation(mutationFn: async (vars: CreateDraftParams) => {return await throwOnErr(async () =>- await emailClient.createDraft({- draft: vars.draft,- send_time: vars.sendTime?.toISOString() ?? null,- })+ await emailClient.createDraft(+ {+ draft: vars.draft,+ send_time: vars.sendTime?.toISOString() ?? null,+ },+ vars.linkId+ ));},...withCallbacks<CreateDraftResponse, Error, CreateDraftParams>(@@ -54,6 +59,8 @@ export function useSaveDraftMutation(type DeleteDraftParams = {draftId: string;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;};/**@@ -65,7 +72,8 @@ export function useDeleteDraftMutation(return useMutation(() => ({mutationFn: async (vars: DeleteDraftParams) => {await throwOnErr(- async () => await emailClient.deleteDraft({ id: vars.draftId })+ async () =>+ await emailClient.deleteDraft({ id: vars.draftId }, vars.linkId));},...withCallbacks<void, Error, DeleteDraftParams>(diff --git a/js/app/packages/queries/email/link.ts b/js/app/packages/queries/email/link.tsindex 6813dd88a7..4c0bff8c3f 100644--- a/js/app/packages/queries/email/link.ts+++ b/js/app/packages/queries/email/link.ts@@ -1,7 +1,9 @@+import { useEmail } from '@core/context/user';import { throwOnErr } from '@core/util/result';import { queryClient } from '@queries/client';import { emailClient } from '@service-email/client';import { useQuery } from '@tanstack/solid-query';+import { createMemo } from 'solid-js';import { emailKeys } from './keys';const LINK_STALE_TIME = 5 * 60 * 1000;@@ -15,6 +17,35 @@ export function useEmailLinksQuery() {}));}+/**+ * The link id of the user's primary inbox — the linked inbox whose address+ * matches the account email. `undefined` until links/email load or if none match.+ */+export function usePrimaryEmailLinkId() {+ const linksQuery = useEmailLinksQuery();+ const email = useEmail();+ return createMemo(() => {+ const primaryEmail = email()?.toLowerCase();+ if (!primaryEmail) return undefined;+ return linksQuery.data?.links.find(+ (link) => link.email_address.toLowerCase() === primaryEmail+ )?.id;+ });+}++/**+ * Returns a mapper from a target inbox link id to the `X-Email-Link-Id` value a+ * mutation should send: the link id when it targets a non-primary inbox, or+ * `undefined` for the primary inbox (the backend defaults to primary when the+ * header is absent). Use at mutation call sites to scope writes to the inbox the+ * user is acting in.+ */+export function useNonPrimaryEmailLinkIdHeader() {+ const primaryLinkId = usePrimaryEmailLinkId();+ return (linkId: string | undefined | null): string | undefined =>+ !linkId || linkId === primaryLinkId() ? undefined : linkId;+}+export function invalidateEmailLinks() {queryClient.cancelQueries({ queryKey: emailKeys.links.queryKey });queryClient.invalidateQueries({diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.tsindex cb2efb3b7f..4eeca53807 100644--- a/js/app/packages/queries/email/thread.ts+++ b/js/app/packages/queries/email/thread.ts@@ -151,7 +151,11 @@ export function useThreadQuery<Options extends UseThreadQueryOptions>(}));}-type MarkThreadAsSeenParams = { threadId: string };+type MarkThreadAsSeenParams = {+ threadId: string;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;+};/*** Optimistically update soup queries when marking as seen.@@ -177,7 +181,10 @@ export function useMarkThreadAsSeenMutation(return useMutation(() => ({mutationFn: async (params: MarkThreadAsSeenParams) => {await throwOnErr(() =>- emailClient.markThreadAsSeen({ thread_id: params.threadId })+ emailClient.markThreadAsSeen(+ { thread_id: params.threadId },+ params.linkId+ ));},...withCallbacks<void, Error, MarkThreadAsSeenParams>(@@ -192,7 +199,12 @@ export function useMarkThreadAsSeenMutation(}));}-type ArchiveThreadParams = { threadId: string; archive: boolean };+type ArchiveThreadParams = {+ threadId: string;+ archive: boolean;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;+};type ArchiveThreadContext = {previousData: InfiniteData<Thread, number> | undefined;};@@ -238,10 +250,13 @@ export function useArchiveThreadMutation(mutationFn: async (params: ArchiveThreadParams) =>void throwOnErr(async () =>- await emailClient.flagArchived({- id: params.threadId,- value: params.archive,- })+ await emailClient.flagArchived(+ {+ id: params.threadId,+ value: params.archive,+ },+ params.linkId+ )),...withCallbacks<void, Error, ArchiveThreadParams, ArchiveThreadContext>({@@ -266,7 +281,11 @@ export function useArchiveThreadMutation(}));}-type SendMessageParams = { message: ApiDraftInput };+type SendMessageParams = {+ message: ApiDraftInput;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;+};/*** Mutation to send an email message.@@ -279,7 +298,8 @@ export function useSendMessageMutation(return useMutation(() => ({mutationFn: async (vars: SendMessageParams) =>await throwOnErr(- async () => await emailClient.sendMessage({ message: vars.message })+ async () =>+ await emailClient.sendMessage({ message: vars.message }, vars.linkId)),...withCallbacks<SendMessageResponse, Error, SendMessageParams>({@@ -344,7 +364,11 @@ function _useScheduleMessageMutation(}));}-type UnscheduleMessageParams = { draftID: string };+type UnscheduleMessageParams = {+ draftID: string;+ /** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */+ linkId?: string;+};/*** Mutation to send an email message.@@ -356,9 +380,12 @@ export function useUnscheduleMessageMutation(mutationFn: async (vars: UnscheduleMessageParams) => {await throwOnErr(async () =>- await emailClient.unscheduleMessage({- draftID: vars.draftID,- })+ await emailClient.unscheduleMessage(+ {+ draftID: vars.draftID,+ },+ vars.linkId+ ));},...withCallbacks<void, Error, UnscheduleMessageParams>(@@ -378,10 +405,16 @@ export function useUnscheduleMessageMutation(* Blocks a sender and shows appropriate toasts with undo support.* Shared by the email thread view and soup context menu.*/-export async function blockSenderWithToast(senderEmail: string) {- const result = await emailClient.blockSender({- email_address: senderEmail,- });+export async function blockSenderWithToast(+ senderEmail: string,+ linkId?: string+) {+ const result = await emailClient.blockSender(+ {+ email_address: senderEmail,+ },+ linkId+ );if (result.isErr()) {toast.failure('Failed to block sender', { subtext: senderEmail });@@ -395,9 +428,12 @@ export async function blockSenderWithToast(senderEmail: string) {label: 'Undo',icon: ArrowCounterClockwise,onClick: async () => {- const undoResult = await emailClient.unblockSender({- email_address: senderEmail,- });+ const undoResult = await emailClient.unblockSender(+ {+ email_address: senderEmail,+ },+ linkId+ );if (undoResult.isErr()) {toast.failure('Failed to unblock sender', { subtext: senderEmail });} else {diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.tsindex 86f2e5cd23..f9133856d9 100644--- a/js/app/packages/service-clients/service-email/client.ts+++ b/js/app/packages/service-clients/service-email/client.ts@@ -35,6 +35,16 @@ import type { EmptyResponse } from './generated/schemas/emptyResponse';const emailHost: string = SERVER_HOSTS['email-service'];+/**+ * Header that scopes a mutating email request to a specific inbox. Omitted for+ * the primary inbox (the backend defaults to it when the header is absent).+ */+const EMAIL_LINK_ID_HEADER = 'X-Email-Link-Id';++function emailLinkHeaders(linkId?: string): Record<string, string> | undefined {+ return linkId ? { [EMAIL_LINK_ID_HEADER]: linkId } : undefined;+}+function emailFetch(url: string,init?: SafeFetchInit@@ -147,12 +157,13 @@ export const emailClient = {});},- async flagArchived(args: { value: boolean; id: string }) {+ async flagArchived(args: { value: boolean; id: string }, linkId?: string) {const { value, id } = args;return (await emailFetch<EmptyResponse>(`/email/threads/${id}/archived`, {method: 'PATCH',body: JSON.stringify({ value }),+ headers: emailLinkHeaders(linkId),})).map((result) => result);},@@ -171,16 +182,20 @@ export const emailClient = {).map((result) => result);},- async sendMessage(args: SendMessageRequest) {+ async sendMessage(args: SendMessageRequest, linkId?: string) {return (await emailFetch<SendMessageResponse>('/email/messages', {method: 'POST',body: JSON.stringify(args),+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async scheduleMessage(args: { draftID: string } & UpsertScheduledRequest) {+ async scheduleMessage(+ args: { draftID: string } & UpsertScheduledRequest,+ linkId?: string+ ) {const { draftID, ...rest } = args;return (await emailFetch<UpsertScheduledResponse>(@@ -188,17 +203,19 @@ export const emailClient = {{method: 'PUT',body: JSON.stringify(rest),+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async unscheduleMessage(args: { draftID: string }) {+ async unscheduleMessage(args: { draftID: string }, linkId?: string) {return (await emailFetch<EmptyResponse>(`/email/drafts/scheduled/${args.draftID}`,{method: 'DELETE',+ headers: emailLinkHeaders(linkId),})).map((result) => result);@@ -262,50 +279,63 @@ export const emailClient = {)).map((result) => result);},- async createDraft(args: CreateDraftRequest) {+ async createDraft(args: CreateDraftRequest, linkId?: string) {return (await emailFetch<CreateDraftResponse>('/email/drafts', {method: 'POST',body: JSON.stringify(args),+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async deleteDraft(args: { id: string }) {+ async deleteDraft(args: { id: string }, linkId?: string) {const { id } = args;return (await emailFetch<EmptyResponse>(`/email/drafts/${id}`, {method: 'DELETE',+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async addDraftAttachment(args: {- draftID: string;- attachment: AddDraftAttachmentRequest;- }) {+ async addDraftAttachment(+ args: {+ draftID: string;+ attachment: AddDraftAttachmentRequest;+ },+ linkId?: string+ ) {return (await emailFetch<AddDraftAttachmentResponse>(`/email/drafts/${args.draftID}/attachments`,{method: 'POST',body: JSON.stringify(args.attachment),+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async removeDraftAttachment(args: { draftID: string; attachmentID: string }) {+ async removeDraftAttachment(+ args: { draftID: string; attachmentID: string },+ linkId?: string+ ) {return (await emailFetch<EmptyResponse>(`/email/drafts/${args.draftID}/attachments/${args.attachmentID}`,{method: 'DELETE',+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async addForwardedAttachment(args: {- draftID: string;- attachmentID: string;- }) {+ async addForwardedAttachment(+ args: {+ draftID: string;+ attachmentID: string;+ },+ linkId?: string+ ) {return (await emailFetch<{attachment_id: string;@@ -315,40 +345,48 @@ export const emailClient = {}>(`/email/drafts/${args.draftID}/forwarded-attachments`, {method: 'POST',body: JSON.stringify({ attachment_id: args.attachmentID }),+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async removeForwardedAttachment(args: {- draftID: string;- attachmentID: string;- }) {+ async removeForwardedAttachment(+ args: {+ draftID: string;+ attachmentID: string;+ },+ linkId?: string+ ) {return (await emailFetch<EmptyResponse>(`/email/drafts/${args.draftID}/forwarded-attachments/${args.attachmentID}`,{method: 'DELETE',+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async markThreadAsSeen(args: { thread_id: string }) {+ async markThreadAsSeen(args: { thread_id: string }, linkId?: string) {const { thread_id } = args;return (await emailFetch<EmptyResponse>(`/email/threads/${thread_id}/seen`, {method: 'POST',+ headers: emailLinkHeaders(linkId),})).map((result) => result);},- async blockSender(args: { email_address: string }) {+ async blockSender(args: { email_address: string }, linkId?: string) {return emailFetch('/email/contacts/block', {method: 'POST',body: JSON.stringify({ email_address: args.email_address }),+ headers: emailLinkHeaders(linkId),});},- async unblockSender(args: { email_address: string }) {+ async unblockSender(args: { email_address: string }, linkId?: string) {return emailFetch('/email/contacts/unblock', {method: 'POST',body: JSON.stringify({ email_address: args.email_address }),+ headers: emailLinkHeaders(linkId),});},async listEmailFilters() {