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
import { DraftTransferAborted } from '@app/features/email-compose/context/compose-capabilities';
import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import { type Span, Telemetry } from '@macro-inc/observability';
import { invalidateAllSoup, refetchSoupEntity } from '@queries/soup/cache';
import { emailClient } from '@service-email/client';
import type {
ApiDraftInput,
CreateDraftResponse,
TransferDraftResponse,
} from '@service-email/generated/schemas';
import { getGraphqlCacheHost } from '@service-storage/graphql-soup';
import { useMutation } from '@tanstack/solid-query';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { refreshEmailThreadCache } from './cache-cleanup';
import { markThreadDraftSaved } from './draft-cache';
import { emailKeys } from './keys';
type CreateDraftParams = {
draft: ApiDraftInput;
/** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */
linkId?: string;
/** Skip updating soup when the thread will immediately be marked done. */
skipSoupRefetch?: boolean;
};
/**
* Mutation to save a new email draft.
*/
export function useSaveDraftMutation(
callbacks?: MutationCallbacks<CreateDraftResponse, Error, CreateDraftParams>
) {
return useMutation(() => ({
mutationFn: async (vars: CreateDraftParams) => {
return await throwOnErr(
async () =>
await emailClient.createDraft({ draft: vars.draft }, vars.linkId)
);
},
...withCallbacks<CreateDraftResponse, Error, CreateDraftParams>(
{
onError(error) {
console.error('Failed to save draft', error);
},
onSuccess(data, vars) {
try {
void queryClient
.invalidateQueries({
queryKey: emailKeys.previews._def,
})
.catch(Telemetry.error);
const threadId = data.draft.thread_db_id;
if (!threadId) return;
markThreadDraftSaved(threadId);
if (!vars.skipSoupRefetch) {
void refetchSoupEntity(threadId, 'emailThread').catch(
Telemetry.error
);
}
} catch (error) {
Telemetry.error(error);
}
},
},
callbacks
),
}));
}
type DeleteDraftParams = {
draftId: string;
draftGeneration?: number;
/** Thread the draft belonged to, refetched so it leaves the drafts tab. */
threadId?: string;
/** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */
linkId?: string;
/** Skip updating soup when the thread will immediately be marked done. */
skipSoupRefetch?: boolean;
};
/**
* Mutation to delete an email draft.
*/
export function useDeleteDraftMutation(
callbacks?: MutationCallbacks<void, Error, DeleteDraftParams>
) {
return useMutation(() => ({
mutationFn: async (vars: DeleteDraftParams) => {
await throwOnErr(
async () =>
await emailClient.deleteDraft(
{ id: vars.draftId, draftGeneration: vars.draftGeneration },
vars.linkId
)
);
},
...withCallbacks<void, Error, DeleteDraftParams>(
{
onError(error) {
console.error('Failed to delete draft', error);
},
async onSuccess(_data, vars) {
try {
if (vars.threadId) {
await refreshEmailThreadCache(vars.threadId);
}
void queryClient
.invalidateQueries({
queryKey: emailKeys.previews._def,
})
.catch(Telemetry.error);
if (vars.skipSoupRefetch) return;
// Refetch the thread (not the deleted draft) so its draft-derived
// fields settle. No-op for compose drafts, whose thread is deleted
// along with the draft, so the refetch finds nothing to update.
if (vars.threadId) {
void refetchSoupEntity(vars.threadId, 'emailThread').catch(
Telemetry.error
);
}
// Discarding a draft changes view membership — the thread leaves
// Signal/Drafts and a noise thread re-enters Noise — which a
// single-entity patch can't express, so the soup list queries must
// refetch. Mirrors the archive flow in EmailContext.
invalidateAllSoup();
} catch (error) {
Telemetry.error(error);
}
},
},
callbacks
),
}));
}
/** Moving creates a new server identity; old queued mutations retain their old target. */
export function transferEmailDraft(input: {
operationId: string;
draftId: string;
draftGeneration?: number;
sourceInboxId: string;
destinationInboxId: string;
}) {
return Telemetry.span('email.draft_transfer.request', async (span) => {
let result: TransferDraftResponse;
try {
result = await throwOnErr(() =>
emailClient.transferDraft(
input.draftId,
{
operation_id: input.operationId,
draft_generation: input.draftGeneration ?? 0,
destination_link_id: input.destinationInboxId,
},
input.sourceInboxId
)
);
span.setAttr('email.draft_transfer.committed_by', 'response');
} catch (originalError) {
const recovery = await span.span(
'email.draft_transfer.recover',
async (recover) => {
try {
return await throwOnErr(() =>
emailClient.recoverDraftTransfer(input.operationId)
);
} catch (error) {
recover.error('Draft transfer recovery failed');
span.error('Draft transfer recovery failed');
throw error;
}
}
);
if (!recovery.committed) {
span.error('Draft transfer aborted');
throw new DraftTransferAborted(
'The inbox change did not complete. Your original draft is preserved; you can edit it and try again.',
{ cause: originalError }
);
}
span.setAttr('email.draft_transfer.committed_by', 'recovery');
result = recovery.committed;
}
// Cache refresh errors must not turn a committed move into a failed write.
// The caller shows the moved draft first. Evicting the source thread
// replaces a route that still shows it with the not-found page.
fireAndForget(
span.span('email.draft_transfer.refresh', async (refresh) => {
try {
await refreshTransferredThreads(result, refresh);
} catch (error) {
refresh.error('Draft transfer refresh failed');
throw error;
}
}),
'email-draft-transfer'
);
return result;
});
}
async function refreshTransferredThreads(
result: TransferDraftResponse,
parent: Span
) {
await getGraphqlCacheHost()?.deleteRecords([
`GraphqlSoupEmailMessage:${result.source_id}`,
]);
await Promise.all([
parent.run(() => refreshEmailThreadCache(result.source_thread_id)),
parent.run(() => refreshEmailThreadCache(result.thread_id)),
]);
for (const threadId of [result.source_thread_id, result.thread_id]) {
await parent.run(() =>
queryClient.invalidateQueries({
queryKey: emailKeys.threadMessages(threadId).queryKey,
})
);
}
invalidateAllSoup();
}