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): link inline images when forwarding or quoting (#8035)

gbirmancd717775b38f
diff --git a/apps/web/src/features/email-compose/core/forwarded-attachments.test.ts b/apps/web/src/features/email-compose/core/forwarded-attachments.test.ts
new file mode 100644
index 0000000000..f3d428f009
--- /dev/null
+++ b/apps/web/src/features/email-compose/core/forwarded-attachments.test.ts
@@ -0,0 +1,53 @@
+import type { EmailAttachment } from '@app/features/email-message/core/email-message';
+import { describe, expect, it } from 'vitest';
+import { forwardedAttachments } from './forwarded-attachments';
+
+function attachment(
+ db_id: string,
+ overrides: Partial<EmailAttachment> = {}
+): EmailAttachment {
+ return { db_id, mime_type: 'image/png', ...overrides };
+}
+
+describe('forwardedAttachments', () => {
+ it('leaves out inline images the quoted body links to their static-file copy', () => {
+ const forwarded = forwardedAttachments({
+ body_html_sanitized: '<img src="cid:logo"><img src="cid:chart">',
+ attachments: [
+ attachment('logo', { content_id: '<logo>', sfs_id: 'logo-file' }),
+ attachment('chart', { content_id: 'chart', sfs_id: 'chart-file' }),
+ attachment('report', { mime_type: 'application/pdf' }),
+ ],
+ });
+ expect(forwarded.map((a) => a.db_id)).toEqual(['report']);
+ });
+
+ it('attaches an inline image without a static-file copy so it is not lost', () => {
+ const forwarded = forwardedAttachments({
+ body_html_sanitized: '<img src="cid:logo">',
+ attachments: [attachment('logo', { content_id: '<logo>' })],
+ });
+ expect(forwarded.map((a) => a.db_id)).toEqual(['logo']);
+ });
+
+ it('ignores cid: values outside an image source', () => {
+ const forwarded = forwardedAttachments({
+ body_html_sanitized:
+ '<img data-src="cid:logo" src="https://example.com/logo.png"><div xsrc="cid:logo"></div>',
+ attachments: [
+ attachment('logo', { content_id: '<logo>', sfs_id: 'logo-file' }),
+ ],
+ });
+ expect(forwarded.map((a) => a.db_id)).toEqual(['logo']);
+ });
+
+ it('attaches a file whose Content-ID the body never shows inline', () => {
+ const forwarded = forwardedAttachments({
+ body_html_sanitized: '<p>See attached</p>',
+ attachments: [
+ attachment('photo', { content_id: '<photo>', sfs_id: 'photo-file' }),
+ ],
+ });
+ expect(forwarded.map((a) => a.db_id)).toEqual(['photo']);
+ });
+});
diff --git a/apps/web/src/features/email-compose/core/forwarded-attachments.ts b/apps/web/src/features/email-compose/core/forwarded-attachments.ts
new file mode 100644
index 0000000000..f52c3c74e1
--- /dev/null
+++ b/apps/web/src/features/email-compose/core/forwarded-attachments.ts
@@ -0,0 +1,27 @@
+import type {
+ EmailAttachment,
+ EmailMessage,
+} from '@app/features/email-message/core/email-message';
+import {
+ inlineContentIds,
+ normalizeContentId,
+ staticFileIdsByContentId,
+} from '@app/features/email-message/core/inline-images';
+
+/**
+ * Attachments a forward of the message carries. Inline images with a
+ * static-file copy reach the recipient as links in the quoted body instead;
+ * every other attachment, including an inline image without a copy, is
+ * attached so the recipient still gets it.
+ */
+export function forwardedAttachments(
+ message: Pick<EmailMessage, 'attachments' | 'body_html_sanitized'>
+): EmailAttachment[] {
+ const shownInline = inlineContentIds(message.body_html_sanitized ?? '');
+ const linked = staticFileIdsByContentId(message.attachments);
+ return (message.attachments ?? []).filter((attachment) => {
+ if (!attachment.content_id) return true;
+ const contentId = normalizeContentId(attachment.content_id);
+ return !shownInline.has(contentId) || !linked.has(contentId);
+ });
+}
diff --git a/apps/web/src/features/email-compose/primitives/email-form-state.ts b/apps/web/src/features/email-compose/primitives/email-form-state.ts
index 3db204a68b..a813513265 100644
--- a/apps/web/src/features/email-compose/primitives/email-form-state.ts
+++ b/apps/web/src/features/email-compose/primitives/email-form-state.ts
@@ -9,6 +9,7 @@ import { createStore, reconcile, unwrap } from 'solid-js/store';
import { match } from 'ts-pattern';
import type { EmailFormContextInputs } from '../context/email-form-inputs';
import { decodeBase64Utf8 } from '../core/decode-base64';
+import { forwardedAttachments } from '../core/forwarded-attachments';
import {
convertContactInfoToEmailRecipient,
getReplyAllRecipients,
@@ -235,16 +236,16 @@ export function createEmailFormState(
if (next === 'forward') {
setState('withQuotedText', 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,
- }));
+ // Populate forwarded attachments from original message (skip inline images linked in the quote)
+ const fwdAttachments: DraftFormAttachment[] = forwardedAttachments(
+ msg
+ ).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]);
}
}
diff --git a/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts b/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts
index 556d19b55b..21ed0f5918 100644
--- a/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts
+++ b/apps/web/src/features/email-compose/primitives/prepare-email-body.test.ts
@@ -1,12 +1,19 @@
// @vitest-environment jsdom
+import { staticFileReferenceEndpoint } from '@core/constant/servers';
import { $generateNodesFromDOM } from '@lexical/html';
import { DocumentMentionNode } from '@macro-inc/lexical-core';
import { $getRoot, $nodesOfType, createEditor } from 'lexical';
import { describe, expect, it } from 'vitest';
import { message } from '../../email-message/tests/messages';
import { decodeBase64Utf8 } from '../core/decode-base64';
-import { prepareEmailBodyFromHtml } from './prepare-email-body';
+import { createEmailEditor } from '../tests/editor';
+import {
+ prepareEmailBody,
+ prepareEmailBodyFromHtml,
+ registerToggleAppendedThread,
+ TOGGLE_APPEND_EMAIL_THREAD_COMMAND,
+} from './prepare-email-body';
const replyingTo = message('original', {
from: { name: 'Ada Lovelace', email: '[email protected]' },
@@ -20,6 +27,27 @@ const replyingTo = message('original', {
attachments: [],
});
+const inlineImageMessage = {
+ ...replyingTo,
+ body_html_sanitized:
+ '<p>Chart</p><img src="cid:chart" alt="chart"><img src="cid:missing">',
+ attachments: [
+ {
+ db_id: 'chart-attachment',
+ content_id: '<chart>',
+ sfs_id: 'chart-file',
+ mime_type: 'image/png',
+ },
+ ],
+};
+
+function quotedImageSources(html: string) {
+ const body = new DOMParser().parseFromString(html, 'text/html').body;
+ return Array.from(body.querySelectorAll('.macro_quote img')).map((img) =>
+ img.getAttribute('src')
+ );
+}
+
describe('prepareEmailBodyFromHtml', () => {
it.each(['reply', 'forward'] as const)(
'keeps quoted Macro document links re-importable as rich mentions in a %s',
@@ -76,6 +104,38 @@ describe('prepareEmailBodyFromHtml', () => {
expect(decoded).toContain('href="https://example.com/accept"');
}
);
+ it.each(['reply', 'forward'] as const)(
+ 'links inline cid images to their static-file copies in an outgoing %s',
+ (replyType) => {
+ const prepared = prepareEmailBodyFromHtml('<p>My reply</p>', {
+ replyType,
+ replyingTo: inlineImageMessage,
+ });
+ const images = quotedImageSources(decodeBase64Utf8(prepared.bodyHtml));
+ expect(images).toEqual([
+ staticFileReferenceEndpoint('chart-file'),
+ 'cid:missing',
+ ]);
+ }
+ );
+ it('links inline cid images in a forward quoted in the editor', () => {
+ const editor = createEmailEditor('FYI');
+ registerToggleAppendedThread(editor);
+ editor.dispatchCommand(TOGGLE_APPEND_EMAIL_THREAD_COMMAND, {
+ replyingTo: inlineImageMessage,
+ replyType: 'forward',
+ visible: true,
+ });
+ const prepared = prepareEmailBody(editor, {
+ replyType: 'forward',
+ replyingTo: inlineImageMessage,
+ });
+ const images = quotedImageSources(decodeBase64Utf8(prepared!.bodyHtml));
+ expect(images).toEqual([
+ staticFileReferenceEndpoint('chart-file'),
+ 'cid:missing',
+ ]);
+ });
it('does not add a quote block without appendReply (undo-send restore)', () => {
const prepared = prepareEmailBodyFromHtml('<p>hi there</p>');
const decoded = decodeBase64Utf8(prepared.bodyHtml);
diff --git a/apps/web/src/features/email-compose/primitives/prepare-email-body.ts b/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
index 104a90f04d..0822b03f95 100644
--- a/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
+++ b/apps/web/src/features/email-compose/primitives/prepare-email-body.ts
@@ -1,5 +1,10 @@
import type { EmailMessage } from '@app/features/email-message/core/email-message';
+import {
+ normalizeContentId,
+ staticFileIdsByContentId,
+} from '@app/features/email-message/core/inline-images';
import { convertDocumentMentionsToLinks } from '@core/component/LexicalMarkdown/utils/convertDocumentMentionsToLinks';
+import { staticFileReferenceEndpoint } from '@core/constant/servers';
import { formatEmailDate } from '@core/util/date';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import { $createQuoteNode } from '@lexical/rich-text';
@@ -143,6 +148,19 @@ function $generateHeaderNodes(
const REPLYING_TO_ID_ATTRIBUTE = 'data-replying-to-id';
+/**
+ * The quoted message's inline parts are not sent along, so a cid: image would
+ * reach the recipient broken. Point it at the image's public static-file copy.
+ */
+function linkInlineImages(root: ParentNode, replyingTo: EmailMessage) {
+ const fileIds = staticFileIdsByContentId(replyingTo.attachments);
+ for (const img of root.querySelectorAll('img[src^="cid:"]')) {
+ const src = img.getAttribute('src') ?? '';
+ const fileId = fileIds.get(normalizeContentId(src.slice(4)));
+ if (fileId) img.setAttribute('src', staticFileReferenceEndpoint(fileId));
+ }
+}
+
const $appendPreviousEmail = (
editor: LexicalEditor,
replyingTo: EmailMessage | undefined,
@@ -176,6 +194,7 @@ const $appendPreviousEmail = (
sanitizeEmailHtml(replyingToBodyHTML),
'text/html'
);
+ linkInlineImages(dom, replyingTo);
// Forwards always embed the original as a non-editable HTML Render Node so
// the recipient gets the exact original markup. For replies, a table is a
// good indicator of content we can't convert into editable nodes correctly.
@@ -359,6 +378,7 @@ function getAppendedReplyElement(
sanitizeEmailHtml(replyingToBodyHTML),
'text/html'
);
+ linkInlineImages(innerDom, replyingTo);
// Extract style tags from head to preserve email styling for weirdo emails with initial style tags.
const styleTags = innerDom.head?.querySelectorAll('style');
styleTags?.forEach((style) => {
diff --git a/apps/web/src/features/email-message/core/inline-images.ts b/apps/web/src/features/email-message/core/inline-images.ts
new file mode 100644
index 0000000000..c4f8b80b8e
--- /dev/null
+++ b/apps/web/src/features/email-message/core/inline-images.ts
@@ -0,0 +1,30 @@
+import type { EmailAttachment } from './email-message';
+
+/** Content-IDs compare without the angle brackets their MIME headers carry. */
+export function normalizeContentId(contentId: string): string {
+ return contentId.replace(/[<>]/g, '').trim();
+}
+
+/** Content-IDs of the attachments an HTML body shows inline through `cid:`. */
+export function inlineContentIds(html: string): Set<string> {
+ const ids = new Set<string>();
+ for (const match of html.matchAll(
+ /<img\b[^>]*?\ssrc=["']cid:([^"']+)["']/gi
+ )) {
+ const id = normalizeContentId(match[1]);
+ if (id) ids.add(id);
+ }
+ return ids;
+}
+
+/** Static-file ids of the attachments that have a copy there, by Content-ID. */
+export function staticFileIdsByContentId(
+ attachments: readonly EmailAttachment[] | null | undefined
+): Map<string, string> {
+ const fileIds = new Map<string, string>();
+ for (const { content_id, sfs_id } of attachments ?? []) {
+ if (content_id && sfs_id)
+ fileIds.set(normalizeContentId(content_id), sfs_id);
+ }
+ return fileIds;
+}
diff --git a/apps/web/src/features/email-message/image-adapter.ts b/apps/web/src/features/email-message/image-adapter.ts
index 82fc6aa5c2..628282abd7 100644
--- a/apps/web/src/features/email-message/image-adapter.ts
+++ b/apps/web/src/features/email-message/image-adapter.ts
@@ -1,4 +1,8 @@
import type { EmailMessage } from '@app/features/email-message/core/email-message';
+import {
+ normalizeContentId,
+ staticFileIdsByContentId,
+} from '@app/features/email-message/core/inline-images';
import { SERVER_HOSTS } from '@core/constant/servers';
import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
@@ -8,14 +12,7 @@ export function resolveCidImages(
root: ShadowRoot,
attachments: EmailMessage['attachments']
): void {
- const contentIdToSfsId = new Map<string, string>();
- for (const att of attachments ?? []) {
- const contentId = att.content_id;
- const sfsId = att.sfs_id;
- if (!contentId || !sfsId) continue;
- const normalized = contentId.replace(/[<>]/g, '');
- contentIdToSfsId.set(normalized, sfsId);
- }
+ const contentIdToSfsId = staticFileIdsByContentId(attachments);
const cidImages = root.querySelectorAll('img[src^="cid:"]');
for (const img of cidImages) {
@@ -23,9 +20,7 @@ export function resolveCidImages(
if (img.dataset.cidResolved === 'true') continue;
const src = img.getAttribute('src');
if (!src?.startsWith('cid:')) continue;
- const rawCid = src.slice(4);
- const normalizedCid = rawCid.replace(/[<>]/g, '');
- const sfsId = contentIdToSfsId.get(normalizedCid);
+ const sfsId = contentIdToSfsId.get(normalizeContentId(src.slice(4)));
if (!sfsId) continue;
img.src = `${SERVER_HOSTS['static-file']}/file/${sfsId}`;
img.dataset.cidResolved = 'true';
diff --git a/apps/web/src/features/email-message/views/email-message.tsx b/apps/web/src/features/email-message/views/email-message.tsx
index 707967cc09..17d5e1ea9d 100644
--- a/apps/web/src/features/email-message/views/email-message.tsx
+++ b/apps/web/src/features/email-message/views/email-message.tsx
@@ -17,6 +17,7 @@ import {
groupCalendarInvitations,
} from '../core/calendar-invitation';
import type { EmailAttachment } from '../core/email-message';
+import { inlineContentIds, normalizeContentId } from '../core/inline-images';
export interface EmailMessageViewProps {
message: EmailMessage;
renderInvitation?: (
@@ -74,23 +75,16 @@ export function EmailMessageView(props: EmailMessageViewProps) {
);
// Hide attachments that are referenced in inline images
- const inlineContentIds = createMemo(() => {
- const set = new Set<string>();
- const html = props.message.body_html_sanitized ?? '';
- for (const match of html.matchAll(/src=["']cid:([^"']+)["']/gi)) {
- const normalized = match[1].replace(/[<>]/g, '').trim();
- if (normalized) set.add(normalized);
- }
- return set;
- });
+ const shownInline = createMemo(() =>
+ inlineContentIds(props.message.body_html_sanitized ?? '')
+ );
const visibleAttachments = createMemo(() => {
return props.message.attachments.filter((a) => {
if (!a.db_id) return false;
const contentId = a.content_id?.toString();
if (!contentId) return true;
- const normalized = contentId.replace(/[<>]/g, '').trim();
- return !inlineContentIds().has(normalized);
+ return !shownInline().has(normalizeContentId(contentId));
});
});