Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): assign draft attachment ids before the content upload (#6112)

gbirmanf204397d4e03
diff --git a/apps/web/src/features/block-email/component/BaseInput.tsx b/apps/web/src/features/block-email/component/BaseInput.tsx
index 2a6dc32523..cc7061a3c5 100644
--- a/apps/web/src/features/block-email/component/BaseInput.tsx
+++ b/apps/web/src/features/block-email/component/BaseInput.tsx
@@ -782,6 +782,12 @@ export function BaseInput(props: {
};
}
+ // Content uploads still in flight, including ones started by earlier saves.
+ // attachmentID only proves the draft record exists, and the send path treats
+ // a resolved save as "attachments ready", so a save must not resolve while
+ // any of these are pending.
+ const inFlightAttachmentUploads = new Set<Promise<void>>();
+
async function executeSaveDraft(skipSoupRefetch = false) {
if (sendMutation.isPending || pendingDeletion || pendingSend) {
return;
@@ -841,21 +847,30 @@ export function BaseInput(props: {
{ type: 'local' }
>[];
+ let uploadRun: Promise<void> | undefined;
if (attachments.length) {
- const uploaded = await uploadAttachmentMutation.mutateAsync({
+ uploadRun = uploadAttachmentMutation.mutateAsync({
draftID: draftId,
attachments: attachments.map((a) => a.file),
linkId: headerLinkId(),
+ onAttachmentAdded: (file, attachmentID) =>
+ form().attachments.assignAttachmentID(file, attachmentID),
+ onAttachmentUploadFailed: (file) =>
+ form().attachments.clearAttachmentID(file),
});
+ const tracked = uploadRun.then(
+ () => undefined,
+ () => undefined
+ );
+ inFlightAttachmentUploads.add(tracked);
+ tracked.then(() => inFlightAttachmentUploads.delete(tracked));
+ }
- // Assign the attachment ids to attachments for later use
- for (const attachment of uploaded.attachments) {
- form().attachments.assignAttachmentID(
- attachment.file,
- attachment.attachmentID
- );
- }
+ while (inFlightAttachmentUploads.size) {
+ await Promise.all([...inFlightAttachmentUploads]);
}
+ // Settled by the drain above, this only rethrows this save's own failure
+ if (uploadRun) await uploadRun;
// Sync forwarded attachments
const forwardedAttachments = form()
diff --git a/apps/web/src/features/block-email/component/compose/Compose.tsx b/apps/web/src/features/block-email/component/compose/Compose.tsx
index 7170c3f028..fb09205344 100644
--- a/apps/web/src/features/block-email/component/compose/Compose.tsx
+++ b/apps/web/src/features/block-email/component/compose/Compose.tsx
@@ -267,6 +267,12 @@ export function EmailCompose(props: EmailComposeProps) {
};
}
+ // Content uploads still in flight, including ones started by earlier saves.
+ // attachmentID only proves the draft record exists, and the send path treats
+ // a resolved save as "attachments ready", so a save must not resolve while
+ // any of these are pending.
+ const inFlightAttachmentUploads = new Set<Promise<void>>();
+
async function executeSaveDraft() {
if (sendMutation.isPending) {
return;
@@ -310,20 +316,28 @@ export function EmailCompose(props: EmailComposeProps) {
{ type: 'local' }
>[];
+ let uploadRun: Promise<void> | undefined;
if (attachments.length) {
- const uploaded = await uploadAttachmentMutation.mutateAsync({
+ uploadRun = uploadAttachmentMutation.mutateAsync({
draftID: draftId,
attachments: attachments.map((a) => a.file),
linkId: headerLinkId(),
+ onAttachmentAdded: form.attachments.assignAttachmentID,
+ onAttachmentUploadFailed: form.attachments.clearAttachmentID,
});
+ const tracked = uploadRun.then(
+ () => undefined,
+ () => undefined
+ );
+ inFlightAttachmentUploads.add(tracked);
+ tracked.then(() => inFlightAttachmentUploads.delete(tracked));
+ }
- for (const attachment of uploaded.attachments) {
- form.attachments.assignAttachmentID(
- attachment.file,
- attachment.attachmentID
- );
- }
+ while (inFlightAttachmentUploads.size) {
+ await Promise.all([...inFlightAttachmentUploads]);
}
+ // Settled by the drain above, this only rethrows this save's own failure
+ if (uploadRun) await uploadRun;
setCurrentDraftID(draftId);
return draftId;
diff --git a/apps/web/src/features/block-email/component/createEmailFormState.ts b/apps/web/src/features/block-email/component/createEmailFormState.ts
index 9421becf52..4c307c7346 100644
--- a/apps/web/src/features/block-email/component/createEmailFormState.ts
+++ b/apps/web/src/features/block-email/component/createEmailFormState.ts
@@ -409,6 +409,15 @@ export function createEmailFormState(
)
);
},
+ clearAttachmentID: (file: File) => {
+ setAttachments((p) =>
+ p.map((a) =>
+ a.type === 'local' && a.file === file
+ ? { ...a, attachmentID: undefined }
+ : a
+ )
+ );
+ },
removeByFile: (file: File) => {
setAttachments((p) =>
p.filter((a) => a.type !== 'local' || a.file !== file)
diff --git a/apps/web/src/lib/queries/email/attachment.test.tsx b/apps/web/src/lib/queries/email/attachment.test.tsx
new file mode 100644
index 0000000000..e21ef0cbdd
--- /dev/null
+++ b/apps/web/src/lib/queries/email/attachment.test.tsx
@@ -0,0 +1,184 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { err, ok, type Result } from 'neverthrow';
+import type { JSX } from 'solid-js';
+import { render } from 'solid-js/web';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useUploadDraftAttachmentsMutation } from './attachment';
+
+const addDraftAttachmentMock = vi.hoisted(() => vi.fn());
+const removeDraftAttachmentMock = vi.hoisted(() => vi.fn());
+const uploadToPresignedUrlMock = vi.hoisted(() => vi.fn());
+const toastFailureMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@service-email/client', () => ({
+ emailClient: {
+ addDraftAttachment: addDraftAttachmentMock,
+ removeDraftAttachment: removeDraftAttachmentMock,
+ },
+}));
+
+vi.mock('@service-storage/util/uploadToPresignedUrl', () => ({
+ uploadToPresignedUrl: uploadToPresignedUrlMock,
+}));
+
+vi.mock('@core/util/hash', () => ({
+ contentHash: vi.fn(async () => 'a'.repeat(64)),
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: toastFailureMock },
+}));
+
+let testQueryClient: QueryClient;
+let dispose: (() => void) | undefined;
+
+function renderHook<T>(factory: () => T): T {
+ let hook!: T;
+ dispose = render(
+ () => (
+ <QueryClientProvider client={testQueryClient}>
+ {(() => {
+ hook = factory();
+ return null as unknown as JSX.Element;
+ })()}
+ </QueryClientProvider>
+ ),
+ document.body
+ );
+ return hook;
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+// jsdom's File lacks arrayBuffer()
+const file = () => {
+ const f = new File([new Uint8Array([1, 2, 3])], 'demo.pdf', {
+ type: 'application/pdf',
+ });
+ Object.defineProperty(f, 'arrayBuffer', {
+ value: async () => new Uint8Array([1, 2, 3]).buffer,
+ });
+ return f;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ testQueryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ addDraftAttachmentMock.mockResolvedValue(
+ ok({
+ attachment_id: 'att-1',
+ upload_url: 'https://bucket/att-1',
+ content_type: 'application/pdf',
+ })
+ );
+ removeDraftAttachmentMock.mockResolvedValue(ok(undefined));
+});
+
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+});
+
+describe('useUploadDraftAttachmentsMutation', () => {
+ it('assigns the attachment id before the content upload completes', async () => {
+ const upload = deferred<Result<void, never>>();
+ uploadToPresignedUrlMock.mockReturnValue(upload.promise);
+ const onAttachmentAdded = vi.fn();
+ const attachment = file();
+
+ const mutation = renderHook(() => useUploadDraftAttachmentsMutation());
+ const pending = mutation.mutateAsync({
+ draftID: 'draft-1',
+ attachments: [attachment],
+ onAttachmentAdded,
+ });
+
+ await vi.waitFor(() => expect(onAttachmentAdded).toHaveBeenCalled());
+ expect(onAttachmentAdded).toHaveBeenCalledWith(attachment, 'att-1');
+
+ upload.resolve(ok(undefined));
+ await pending;
+ expect(toastFailureMock).not.toHaveBeenCalled();
+ });
+
+ it('keeps the id when the record removal fails after a failed upload', async () => {
+ uploadToPresignedUrlMock.mockResolvedValue(
+ err([{ code: 'SERVER_ERROR', message: 'upload failed' }])
+ );
+ removeDraftAttachmentMock.mockResolvedValue(
+ err([{ code: 'SERVER_ERROR', message: 'removal failed' }])
+ );
+ const onAttachmentUploadFailed = vi.fn();
+ const attachment = file();
+
+ const mutation = renderHook(() => useUploadDraftAttachmentsMutation());
+ await expect(
+ mutation.mutateAsync({
+ draftID: 'draft-1',
+ attachments: [attachment],
+ onAttachmentUploadFailed,
+ })
+ ).rejects.toThrow('upload failed');
+
+ expect(removeDraftAttachmentMock).toHaveBeenCalled();
+ expect(onAttachmentUploadFailed).not.toHaveBeenCalled();
+ expect(toastFailureMock).toHaveBeenCalledWith('Failed to save attachments');
+ });
+
+ it('removes the record and clears the id when the content upload throws', async () => {
+ uploadToPresignedUrlMock.mockRejectedValue(new Error('network dropped'));
+ const onAttachmentUploadFailed = vi.fn();
+ const attachment = file();
+
+ const mutation = renderHook(() => useUploadDraftAttachmentsMutation());
+ await expect(
+ mutation.mutateAsync({
+ draftID: 'draft-1',
+ attachments: [attachment],
+ onAttachmentUploadFailed,
+ })
+ ).rejects.toThrow('Upload failed');
+
+ expect(removeDraftAttachmentMock).toHaveBeenCalledWith(
+ { draftID: 'draft-1', attachmentID: 'att-1' },
+ undefined
+ );
+ expect(onAttachmentUploadFailed).toHaveBeenCalledWith(attachment);
+ expect(toastFailureMock).toHaveBeenCalledWith('Failed to save attachments');
+ });
+
+ it('removes the record and clears the id when the content upload fails', async () => {
+ uploadToPresignedUrlMock.mockResolvedValue(
+ err([{ code: 'SERVER_ERROR', message: 'upload failed' }])
+ );
+ const onAttachmentAdded = vi.fn();
+ const onAttachmentUploadFailed = vi.fn();
+ const attachment = file();
+
+ const mutation = renderHook(() => useUploadDraftAttachmentsMutation());
+ await expect(
+ mutation.mutateAsync({
+ draftID: 'draft-1',
+ attachments: [attachment],
+ onAttachmentAdded,
+ onAttachmentUploadFailed,
+ })
+ ).rejects.toThrow('upload failed');
+
+ expect(onAttachmentAdded).toHaveBeenCalledWith(attachment, 'att-1');
+ expect(removeDraftAttachmentMock).toHaveBeenCalledWith(
+ { draftID: 'draft-1', attachmentID: 'att-1' },
+ undefined
+ );
+ expect(onAttachmentUploadFailed).toHaveBeenCalledWith(attachment);
+ expect(toastFailureMock).toHaveBeenCalledWith('Failed to save attachments');
+ });
+});
diff --git a/apps/web/src/lib/queries/email/attachment.ts b/apps/web/src/lib/queries/email/attachment.ts
index dfa6ca110e..8978dfbbbf 100644
--- a/apps/web/src/lib/queries/email/attachment.ts
+++ b/apps/web/src/lib/queries/email/attachment.ts
@@ -11,10 +11,20 @@ type UploadDraftAttachmentsParams = {
attachments: File[];
/** Target inbox for a non-primary inbox; sent as the X-Email-Link-Id header. */
linkId?: string;
-};
-
-type UploadDraftAttachmentsReturn = {
- attachments: { file: File; attachmentID: string }[];
+ /**
+ * Called as soon as the attachment record exists, before the content upload.
+ * Callers must record the id here rather than after the mutation settles --
+ * the content upload can take a long time, and a debounced draft save that
+ * still sees the file without an id would add it to the draft a second time.
+ */
+ onAttachmentAdded?: (file: File, attachmentID: string) => void;
+ /**
+ * Called when the content upload fails, once its attachment record has been
+ * confirmed removed from the draft, so the file becomes eligible for a
+ * retry. Not called when the removal itself fails -- retrying a file whose
+ * record survived would duplicate it on the draft.
+ */
+ onAttachmentUploadFailed?: (file: File) => void;
};
class UploadDraftAttachmentError extends Error {
@@ -28,16 +38,10 @@ class UploadDraftAttachmentError extends Error {
}
export const useUploadDraftAttachmentsMutation = (
- callbacks?: MutationCallbacks<
- UploadDraftAttachmentsReturn,
- Error,
- UploadDraftAttachmentsParams
- >
+ callbacks?: MutationCallbacks<void, Error, UploadDraftAttachmentsParams>
) => {
return useMutation(() => ({
mutationFn: async (params: UploadDraftAttachmentsParams) => {
- const uploadedAttachments = [];
-
for (const attachment of params.attachments) {
const arrayBuffer = await attachment.arrayBuffer();
const sha = await contentHash(arrayBuffer);
@@ -57,17 +61,30 @@ export const useUploadDraftAttachmentsMutation = (
)
);
- uploadedAttachments.push({
- file: attachment,
- attachmentID: result.attachment_id,
- });
-
- const uploadedResponse = await uploadToPresignedUrl({
- presignedUrl: result.upload_url,
- sha,
- buffer: arrayBuffer,
- type: result.content_type,
- });
+ params.onAttachmentAdded?.(attachment, result.attachment_id);
+
+ // Any content-upload failure must become an UploadDraftAttachmentError
+ // so onError removes the record and clears the id -- a plain throw from
+ // the fetch (network drop, abort) would otherwise leave the id in
+ // place and the broken record would never be retried.
+ let uploadedResponse: Awaited<ReturnType<typeof uploadToPresignedUrl>>;
+ try {
+ uploadedResponse = await uploadToPresignedUrl({
+ presignedUrl: result.upload_url,
+ sha,
+ buffer: arrayBuffer,
+ type: result.content_type,
+ });
+ } catch (cause) {
+ throw new UploadDraftAttachmentError(
+ 'Upload failed',
+ { cause },
+ {
+ attachmentID: result.attachment_id,
+ file: attachment,
+ }
+ );
+ }
if (uploadedResponse.isErr()) {
const uploadError = uploadedResponse.error[0] ?? {
@@ -84,25 +101,23 @@ export const useUploadDraftAttachmentsMutation = (
);
}
}
-
- return { attachments: uploadedAttachments };
},
- ...withCallbacks<
- UploadDraftAttachmentsReturn,
- Error,
- UploadDraftAttachmentsParams
- >(
+ ...withCallbacks<void, Error, UploadDraftAttachmentsParams>(
{
async onError(error, variables) {
if (error instanceof UploadDraftAttachmentError) {
try {
- await emailClient.removeDraftAttachment(
- {
- draftID: variables.draftID,
- attachmentID: error.context.attachmentID,
- },
- variables.linkId
+ await throwOnErr(
+ async () =>
+ await emailClient.removeDraftAttachment(
+ {
+ draftID: variables.draftID,
+ attachmentID: error.context.attachmentID,
+ },
+ variables.linkId
+ )
);
+ variables.onAttachmentUploadFailed?.(error.context.file);
} catch {
console.error('Unable to remove draft attachment after failure');
}