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): flashing on draft save (#7003)

Peter Chinman37885b73361b
diff --git a/apps/web/src/features/email-message/primitives/email-message-body.test.ts b/apps/web/src/features/email-message/primitives/email-message-body.test.ts
index db71a89d3f..a5b909614c 100644
--- a/apps/web/src/features/email-message/primitives/email-message-body.test.ts
+++ b/apps/web/src/features/email-message/primitives/email-message-body.test.ts
@@ -25,6 +25,77 @@ const bodyOptions: Omit<EmailMessageBodyProps, 'message'> = {
};
describe('independent email body', () => {
afterEach(() => vi.unstubAllGlobals());
+ it('preserves the body and image resources across unchanged thread snapshots', async () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ }
+ );
+ const releaseImages = vi.fn();
+ const resolveImages = vi.fn(
+ async (_root, _attachments, lifetime: ResourceLifetime) => {
+ lifetime.onDispose(releaseImages);
+ }
+ );
+ const original = message('one', {
+ body_html_sanitized: '<p>Hello</p><img src="cid:photo">',
+ attachments: [{ db_id: 'photo', content_id: 'photo', sfs_id: 'file' }],
+ });
+ const root = createRoot((dispose) => {
+ const [value, setValue] = createSignal(original);
+ const body = createEmailMessageBody(
+ {
+ get message() {
+ return value();
+ },
+ ...bodyOptions,
+ // Production passes derived getters which also read the message.
+ get isPersonal() {
+ return value().from?.email === '[email protected]';
+ },
+ get showFullContent() {
+ return value().db_id === 'one';
+ },
+ },
+ { theme: () => theme, resolveImages }
+ );
+ return { dispose, body, setValue };
+ });
+ try {
+ await Promise.resolve();
+ const host = root.body.host();
+ const image = host?.shadowRoot?.querySelector('img');
+ for (let i = 0; i < 3; i++) {
+ root.setValue({
+ ...structuredClone(original),
+ updated_at: `2026-09-0${i + 1}T00:00:00Z`,
+ labels: [{ provider_label_id: 'UNREAD' }],
+ });
+ expect(root.body.host()).toBe(host);
+ expect(root.body.host()?.shadowRoot?.querySelector('img')).toBe(image);
+ }
+ expect(resolveImages).toHaveBeenCalledTimes(1);
+ expect(releaseImages).not.toHaveBeenCalled();
+
+ root.setValue({
+ ...original,
+ attachments: [{ ...original.attachments[0], sfs_id: 'new-file' }],
+ });
+ await Promise.resolve();
+ expect(root.body.host()).not.toBe(host);
+ expect(releaseImages).toHaveBeenCalledTimes(1);
+ expect(resolveImages).toHaveBeenCalledTimes(2);
+
+ const updatedHost = root.body.host();
+ root.setValue({ ...original, body_html_sanitized: '<p>Edited</p>' });
+ expect(root.body.host()).not.toBe(updatedHost);
+ expect(root.body.host()?.shadowRoot?.textContent).toContain('Edited');
+ } finally {
+ root.dispose();
+ }
+ });
it('renders one message, rewires its DOM on source changes, and cleans image/resize resources on disposal', async () => {
const disconnect = vi.fn();
vi.stubGlobal(
diff --git a/apps/web/src/features/email-message/primitives/email-message-body.ts b/apps/web/src/features/email-message/primitives/email-message-body.ts
index 98b0501526..c2d6be9eab 100644
--- a/apps/web/src/features/email-message/primitives/email-message-body.ts
+++ b/apps/web/src/features/email-message/primitives/email-message-body.ts
@@ -1,3 +1,4 @@
+import { deepEqual } from '@core/util/compareUtils';
import { prepareEmailBody } from '@macro-inc/email-renderer';
import { mountEmailBody } from '@macro-inc/email-renderer/browser';
import {
@@ -27,40 +28,46 @@ export function createEmailMessageBody(
renderingContext: EmailRenderingContextValue
) {
const [showFullHTML, setShowFullHTML] = createSignal(false);
+ // Thread refreshes replace message objects after every draft save. Only
+ // changes to rendering inputs should dispose the body and its image resources.
+ const content = createMemo(
+ () => ({
+ id: props.message.db_id,
+ html: props.message.body_html_sanitized,
+ replylessHtml: props.message.body_replyless,
+ text: props.message.body_text,
+ macro: props.message.body_macro,
+ attachments: props.message.attachments,
+ isPersonal: props.isPersonal,
+ showFullContent: props.showFullContent,
+ normalizeFonts:
+ props.isPersonal &&
+ !props.message.from?.email?.toLowerCase().endsWith('@macro.com'),
+ }),
+ undefined,
+ { equals: deepEqual }
+ );
const prepared = createMemo(() =>
- prepareEmailBody(
- {
- html: props.message.body_html_sanitized,
- replylessHtml: props.message.body_replyless,
- text: props.message.body_text,
- },
- {
- showQuotedContent: showFullHTML(),
- showFullContent: props.showFullContent,
- images: renderingContext.images,
- }
- )
+ prepareEmailBody(content(), {
+ showQuotedContent: showFullHTML(),
+ showFullContent: content().showFullContent,
+ images: renderingContext.images,
+ })
);
const rendered = createMemo(() => {
// Preserve the app's existing Markdown paths without starting hidden HTML
// resources behind them. Their Lexical semantics stay at the app boundary.
- if (
- (!showFullHTML() && props.message.body_macro) ||
- !props.message.body_html_sanitized
- )
- return;
+ if ((!showFullHTML() && content().macro) || !content().html) return;
const body = prepared();
- const attachments = props.message.attachments;
+ const attachments = content().attachments;
const host = document.createElement('div');
// Keep the renderer at pane width so wide designed email scrolls within it.
host.style.minWidth = '0';
host.style.width = '100%';
const renderer = mountEmailBody(host, body, {
theme: renderingContext.theme(),
- adaptColors: props.isPersonal || !body.hasTable,
- normalizeFonts:
- props.isPersonal &&
- !props.message.from?.email?.toLowerCase().endsWith('@macro.com'),
+ adaptColors: content().isPersonal || !body.hasTable,
+ normalizeFonts: content().normalizeFonts,
expanded: untrack(props.isBodyExpanded),
prepareLinks: renderingContext.prepareLinks,
resolveImages: (root, lifetime) =>
diff --git a/apps/web/src/features/email-thread/views/email-participants.test.tsx b/apps/web/src/features/email-thread/views/email-participants.test.tsx
new file mode 100644
index 0000000000..29fec2a75d
--- /dev/null
+++ b/apps/web/src/features/email-thread/views/email-participants.test.tsx
@@ -0,0 +1,66 @@
+import { render } from '@solidjs/testing-library';
+import { createSignal, type ParentProps } from 'solid-js';
+import { expect, it, vi } from 'vitest';
+import { createComposeContext } from '../../email-compose/tests/capabilities';
+import { EmailThreadStateProvider } from '../context/email-thread-state-context';
+import { EmailThreadViewProvider } from '../context/email-thread-view-context';
+import { createEmailThreadState } from '../primitives/email-thread-state';
+import { createThreadContext, message, thread } from '../tests/fixtures';
+import { EmailParticipants } from './email-participants';
+
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => <span /> }));
+vi.mock('@app/features/email-message/components/email-user-tooltip', () => ({
+ EmailUserTooltip: (props: ParentProps) => <>{props.children}</>,
+}));
+
+it('keeps participant order and nodes through draft creation, deletion and refetches', () => {
+ const sent = message('sent', {
+ from: { email: '[email protected]', name: 'Sender' },
+ to: [{ email: '[email protected]' }],
+ });
+ const draft = message('draft', {
+ is_draft: true,
+ replying_to_id: sent.db_id,
+ from: { email: '[email protected]' },
+ to: [{ email: '[email protected]', name: 'Unsent' }],
+ });
+ const [messages, setMessages] = createSignal([sent]);
+ const view = render(() => {
+ const context = createThreadContext({ thread: () => thread(messages()) });
+ const state = createEmailThreadState(context);
+ return (
+ <EmailThreadViewProvider
+ value={{
+ thread: context,
+ compose: createComposeContext(),
+ rendering: {},
+ }}
+ >
+ <EmailThreadStateProvider value={state}>
+ <EmailParticipants />
+ </EmailThreadStateProvider>
+ </EmailThreadViewProvider>
+ );
+ });
+ try {
+ const original = view.getAllByRole('listitem');
+ expect(original.map((node) => node.textContent)).toEqual(['Sender', 'Me']);
+ for (const snapshot of [
+ [draft, sent],
+ [sent],
+ [draft, sent],
+ [sent, draft],
+ ]) {
+ setMessages(structuredClone(snapshot));
+ const current = view.getAllByRole('listitem');
+ expect(current.map((node) => node.textContent)).toEqual(['Sender', 'Me']);
+ current.forEach((node, index) => expect(node).toBe(original[index]));
+ }
+ // Stable keys must still propagate changed contact details.
+ setMessages([{ ...sent, from: { ...sent.from!, name: 'Updated' } }]);
+ expect(view.getAllByRole('listitem')[0]).toBe(original[0]);
+ expect(original[0].textContent).toBe('Updated');
+ } finally {
+ view.unmount();
+ }
+});
diff --git a/apps/web/src/features/email-thread/views/email-participants.tsx b/apps/web/src/features/email-thread/views/email-participants.tsx
index 09d6cad3f1..9873684559 100644
--- a/apps/web/src/features/email-thread/views/email-participants.tsx
+++ b/apps/web/src/features/email-thread/views/email-participants.tsx
@@ -1,7 +1,8 @@
import { EmailUserTooltip } from '@app/features/email-message/components/email-user-tooltip';
import { UserIcon, type UserIconProps } from '@core/component/UserIcon';
import { emailToMacroId } from '@core/user/macroId';
-import { createMemo, createSignal, For, Show } from 'solid-js';
+import { Key } from '@solid-primitives/keyed';
+import { createMemo, createSignal, Show } from 'solid-js';
import { useEmailThreadState } from '../context/email-thread-state-context';
import { useEmailThreadViewContext } from '../context/email-thread-view-context';
@@ -19,7 +20,9 @@ export function EmailParticipants() {
const [expanded, setExpanded] = createSignal(false);
const participants = createMemo(() => {
- const messages = context.messages.unfiltered();
+ // Unsent drafts can be prepended optimistically and removed when emptied.
+ // Participants describe the conversation, not the current draft envelope.
+ const messages = context.messages.list();
const seen = new Map<string, Participant>();
for (const m of messages) {
@@ -73,30 +76,30 @@ export function EmailParticipants() {
return (
<div class="flex flex-wrap gap-1.5" role="list">
- <For each={visibleParticipants()}>
+ <Key each={visibleParticipants()} by="email">
{(participant) => (
<EmailUserTooltip
- recipient={{ email: participant.email, name: participant.name }}
- photoUrl={participant.photoUrl}
+ recipient={{ email: participant().email, name: participant().name }}
+ photoUrl={participant().photoUrl}
>
<div
role="listitem"
class="inline-flex items-center gap-1.5 rounded-full border border-ink-muted/8 bg-ink-muted/[0.025] py-1 pr-2.5 pl-1.5 text-sm text-ink hover:bg-ink-muted/[0.06] cursor-default"
>
<UserIcon
- {...getIconProps(participant)}
+ {...getIconProps(participant())}
isDeleted={false}
size="sm"
suppressClick
showTooltip={false}
/>
<span class="truncate max-w-32">
- {getDisplayName(participant)}
+ {getDisplayName(participant())}
</span>
</div>
</EmailUserTooltip>
)}
- </For>
+ </Key>
<Show when={hiddenCount() > 0}>
<button
type="button"