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
fix(email): keep HTML mail readable without shrinking it to dust (#5890)
Cameron Pak2d1bbaab29c9
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4152c6f537..4b34deacd0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -87,6 +87,8 @@ cargo test -p {crate}`just test` does not exist. Leave `SQLX_OFFLINE` unset when you run `cargo test`. Run `just prepare_db` only if you changed SQL queries.+Email rendering snapshots (Playwright HTML fixtures, not inbox e2e) live in `apps/web/src/lib/core/email/tests`. Run `just test-email-rendering`. Add a fixture under `fixtures/` then `just test-email-rendering-update`.+### Pre Commit```bashcargo fmt # formatdiff --git a/Cargo.lock b/Cargo.lockindex 6a6e14d173..50e30de2d5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14160,6 +14160,7 @@ dependencies = ["clap","comms_db_client","email_db_client",+ "email_utils","entity_access","entity_access_db_utils","fusionauth",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 3c1f932ccd..5178a5aad1 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -1,9 +1,11 @@## Development Commands+- Use `bun` as the package manager and script runner (`bun run build`, `bunx tsc`).- `bun run test`: run tests- `bun run check`: check typescript changes- `bun run lint`: lint with biome- `bun run format`: format changes with biome- `bun run knip`: to check for dead code+- Email rendering snapshots (Playwright HTML fixtures, not inbox e2e) live in `src/lib/core/email/tests`. Run `just test-email-rendering`. Add a fixture under `fixtures/` then `just test-email-rendering-update`.## Development Patternsdiff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.mdindex 96140f7a0d..43c994c2d3 100644--- a/apps/web/CLAUDE.md+++ b/apps/web/CLAUDE.md@@ -1,5 +1 @@-AGENTS.md--## Development--- Use `bun` as the package manager and script runner (e.g. `bun run build`, `bunx tsc`).\ No newline at end of filediff --git a/apps/web/justfile b/apps/web/justfileindex c9c511c741..c40ea995f6 100644--- a/apps/web/justfile+++ b/apps/web/justfile@@ -104,7 +104,7 @@ test-watch:bunx --bun vitesttest-email-rendering:- cd src/lib/core/email/tests && bunx playwright test && bunx playwright show-report+ cd src/lib/core/email/tests && bunx playwright testtest-email-rendering-update:cd src/lib/core/email/tests && bunx playwright test --update-snapshotsdiff --git a/apps/web/src/features/block-email/component/EmailMessageBody.tsx b/apps/web/src/features/block-email/component/EmailMessageBody.tsxindex 623f1dab71..50b1da5324 100644--- a/apps/web/src/features/block-email/component/EmailMessageBody.tsx+++ b/apps/web/src/features/block-email/component/EmailMessageBody.tsx@@ -24,6 +24,8 @@ import {} from 'solid-js';import { themeReactive } from '../../theme/signals/themeReactive';import { themeUpdate } from '../../theme/signals/themeSignals';+import { EMAIL_BODY_CONTAINMENT_CSS } from '../util/emailBodyContainmentCss';+import { fitToWidthZoom } from '../util/fitToWidthZoom';import { isPersonalMessage } from '../util/isPersonalMessage';import {fetchImagesViaPlatform,@@ -144,16 +146,9 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {isPersonal() && !isMacroSender()? `*:not(code):not(pre):not(code *):not(pre *):not([data-macro-btn]){font-family: system-ui, sans-serif !important; font-size: inherit !important; line-height: 1.5 !important;}`: '';- // Let long -joined signature lines wrap (overflow-wrap is inherited)- // and fixed-width tables scroll, so a wide signature doesn't trip the- // fit-to-width zoom below and shrink the whole message.- const signatureContain = `.macro-email-signature{max-width:100%;overflow-x:auto;overflow-wrap:anywhere;}`;- // Browser default blockquote margins apply on both sides. In long email- // reply chains that compounds into a narrow column, so keep quote nesting- // as a left indent only.- const quoteContain =- 'blockquote{margin-block:0.75em!important;margin-inline-start:1.5em!important;margin-inline-end:0!important;max-width:100%!important;box-sizing:border-box;}';- styleEl.textContent = `img{display: var(--macro-email-img-display, initial); max-width: 100% !important; height: auto !important;}${signatureContain}${quoteContain}${fontOverride}`;+ // Containment (images, signatures, quotes, pre/code) lives in+ // EMAIL_BODY_CONTAINMENT_CSS so the snapshot harness stays in lockstep.+ styleEl.textContent = `${EMAIL_BODY_CONTAINMENT_CSS}${fontOverride}`;shadow.appendChild(styleEl);const messageDiv = document.createElement('div');messageDiv.innerHTML = source()?.mainContent ?? '';@@ -253,7 +248,8 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {);});- // Scale down wide HTML emails to fit the container width (like Gmail on mobile)+ // After containment, shrink leftover wide canvases (newsletter tables)+ // to the pane. Pathological width is floored so type stays readable.createEffect(() => {const container = host();// Re-run when source changes@@ -266,6 +262,7 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {if (messageDiv instanceof HTMLElement) {messageDiv.style.zoom = '';messageDiv.style.overflow = '';+ messageDiv.style.overflowX = '';}};@@ -280,22 +277,28 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {const messageDiv = root.querySelector('div');if (!messageDiv || !(messageDiv instanceof HTMLElement)) return;- // Reset any previous scaling before measuring+ // Reset any previous scaling before measuring. overflowX is a longhand+ // and survives clearing the overflow shorthand.messageDiv.style.zoom = '';messageDiv.style.overflow = '';+ messageDiv.style.overflowX = '';- const containerWidth = container.clientWidth;- const contentWidth = messageDiv.scrollWidth;-- if (containerWidth > 0 && contentWidth > containerWidth) {- const scale = containerWidth / contentWidth;- // Use zoom instead of transform: scale() so that backgrounds,- // borders, and layout all shrink together without clipping.- messageDiv.style.zoom = `${scale}`;+ const fit = fitToWidthZoom({+ containerWidth: container.clientWidth,+ contentWidth: messageDiv.scrollWidth,+ });+ if (!fit) {+ // When content fits, leave overflow alone. overflow:auto on a fitting+ // body turns hidden tracking-pixel divs into a message-height scrollbar.+ return;+ }+ // Use zoom instead of transform: scale() so backgrounds, borders, and+ // layout shrink together without clipping. The floor keeps leftover+ // canvas overflow (a 600px newsletter on a skinny pane) readable.+ messageDiv.style.zoom = `${fit.zoom}`;+ if (fit.overflowsAfterZoom) {+ messageDiv.style.overflowX = 'auto';}- // When content fits, leave overflow alone — an overflow:auto wrapper- // turns hidden tracking-pixel divs (e.g. max-height:1px) into a- // message-height scrollbar.};// Re-run on container resize (e.g. orientation change, split resize)diff --git a/apps/web/src/features/block-email/util/emailBodyContainmentCss.ts b/apps/web/src/features/block-email/util/emailBodyContainmentCss.tsnew file mode 100644index 0000000000..c62c5c0072--- /dev/null+++ b/apps/web/src/features/block-email/util/emailBodyContainmentCss.ts@@ -0,0 +1,13 @@+/** Shadow-root containment shared with the email rendering snapshot harness.+ *+ * Images already cap at the pane. Long signature lines wrap instead of+ * tripping whole-message zoom. Quote nesting indents left only. GitHub+ * review mail uses one unwrapped `<pre>` line; wrap like Gmail. Leave+ * designed tables alone so newsletters can still use the fit-to-width floor.+ */+export const EMAIL_BODY_CONTAINMENT_CSS = [+ 'img{display: var(--macro-email-img-display, initial); max-width: 100% !important; height: auto !important;}',+ '.macro-email-signature{max-width:100%;overflow-x:auto;overflow-wrap:anywhere;}',+ 'blockquote{margin-block:0.75em!important;margin-inline-start:1.5em!important;margin-inline-end:0!important;max-width:100%!important;box-sizing:border-box;}',+ 'pre,code{white-space:pre-wrap!important;overflow-wrap:anywhere;word-break:break-word;max-width:100%!important;box-sizing:border-box;}',+].join('');diff --git a/apps/web/src/features/block-email/util/fitToWidthZoom.test.ts b/apps/web/src/features/block-email/util/fitToWidthZoom.test.tsnew file mode 100644index 0000000000..edd1b4b0b1--- /dev/null+++ b/apps/web/src/features/block-email/util/fitToWidthZoom.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { FIT_TO_WIDTH_ZOOM_FLOOR, fitToWidthZoom } from './fitToWidthZoom';++describe('fitToWidthZoom', () => {+ it('does not zoom when content fits', () => {+ expect(+ fitToWidthZoom({ containerWidth: 800, contentWidth: 600 })+ ).toBeUndefined();+ });++ it('does not zoom when sizes are equal', () => {+ expect(+ fitToWidthZoom({ containerWidth: 800, contentWidth: 800 })+ ).toBeUndefined();+ });++ it('ignores a zero-width container', () => {+ expect(+ fitToWidthZoom({ containerWidth: 0, contentWidth: 1200 })+ ).toBeUndefined();+ });++ it('uses the raw ratio for a mild newsletter overflow', () => {+ expect(fitToWidthZoom({ containerWidth: 800, contentWidth: 836 })).toEqual({+ zoom: 800 / 836,+ overflowsAfterZoom: false,+ });+ });++ it('floors pathological width instead of shrinking to dust', () => {+ const result = fitToWidthZoom({+ containerWidth: 800,+ contentWidth: 4000,+ });+ expect(result?.zoom).toBe(FIT_TO_WIDTH_ZOOM_FLOOR);+ expect(result?.overflowsAfterZoom).toBe(true);+ });+});diff --git a/apps/web/src/features/block-email/util/fitToWidthZoom.ts b/apps/web/src/features/block-email/util/fitToWidthZoom.tsnew file mode 100644index 0000000000..c72b717107--- /dev/null+++ b/apps/web/src/features/block-email/util/fitToWidthZoom.ts@@ -0,0 +1,18 @@+/** Floor so a leftover wide canvas (newsletter table) can shrink a little+ * without collapsing type the way unbounded `pane / content` zoom does. */+export const FIT_TO_WIDTH_ZOOM_FLOOR = 0.7;++export function fitToWidthZoom(args: {+ containerWidth: number;+ contentWidth: number;+}): { zoom: number; overflowsAfterZoom: boolean } | undefined {+ const { containerWidth, contentWidth } = args;+ if (containerWidth <= 0 || contentWidth <= containerWidth) {+ return undefined;+ }+ const zoom = Math.max(FIT_TO_WIDTH_ZOOM_FLOOR, containerWidth / contentWidth);+ return {+ zoom,+ overflowsAfterZoom: contentWidth * zoom > containerWidth + 1,+ };+}diff --git a/apps/web/src/lib/core/email/tests/email-rendering.pw.ts b/apps/web/src/lib/core/email/tests/email-rendering.pw.tsindex cfbdd5cbfe..55efdcd8a6 100644--- a/apps/web/src/lib/core/email/tests/email-rendering.pw.ts+++ b/apps/web/src/lib/core/email/tests/email-rendering.pw.ts@@ -1,13 +1,9 @@import fs from 'node:fs';import path from 'node:path';-import { expect, test } from '@playwright/test';+import { expect, type Page, test } from '@playwright/test';import { DEFAULT_THEMES } from '@theme/constants';-import { getOklch } from '@theme/utils/colorUtil';-import type { ThemeColorParams } from '../transform-email-colors';--// =============================================================================-// Types-// =============================================================================+import { EMAIL_BODY_CONTAINMENT_CSS } from '../../../../features/block-email/util/emailBodyContainmentCss';+import { fitToWidthZoom } from '../../../../features/block-email/util/fitToWidthZoom';/*** Email fixture format - matches the structure from email service.@@ -15,9 +11,12 @@ import type { ThemeColorParams } from '../transform-email-colors';* ## Adding a new fixture:* 1. Create a JSON file in the fixtures/ directory (e.g., `my-email.json`)* 2. Copy `body_html_sanitized` from an email API response into the file- * 3. Run `just test-email-rendering-update` to generate baseline screenshots+ * 3. From the repo root, run `just test-email-rendering-update`* 4. Commit the fixture and snapshots*+ * Optional `container_widths` (default `[600]`) snapshots extra pane sizes.+ * Use that only when a fixture needs a width the default pane cannot prove.+ ** ## Example fixture file:* ```json* {@@ -34,36 +33,17 @@ interface EmailFixture {description: string;/** The sanitized HTML body - copy directly from email service `body_html_sanitized` field */body_html_sanitized: string;+ /** Pane widths in CSS pixels. Omit to use the default 600px reader pane. */+ container_widths?: number[];}-// =============================================================================-// Configuration-// =============================================================================-/** Themes to test - uses actual Macro theme definitions */const THEMES = ['Macro Dark', 'Macro Light'] as const;-// =============================================================================-// Theme Helpers-// =============================================================================+const DEFAULT_CONTAINER_WIDTH = 600;-function getThemeConfig(themeName: string): ThemeColorParams {- const theme = DEFAULT_THEMES.find((t) => t.name === themeName);- if (!theme) {- throw new Error(`Theme "${themeName}" not found in DEFAULT_THEMES`);- }- const ink = getOklch(theme.colorTokens['content-0']);- const panel = getOklch(theme.colorTokens['surface-1']);- const accent = getOklch(theme.colorTokens.accent);- return {- inkL: ink.l,- inkC: ink.c,- inkH: ink.h,- panelL: panel.l,- accentL: accent.l,- accentC: accent.c,- accentH: accent.h,- };+function containerWidths(fixture: EmailFixture): number[] {+ return fixture.container_widths ?? [DEFAULT_CONTAINER_WIDTH];}function generateThemeCSS(themeName: string): string {@@ -77,15 +57,11 @@ function generateThemeCSS(themeName: string): string {return `:root {\n ${vars}\n }`;}-// =============================================================================-// HTML Generation-// =============================================================================--function createTestHTML(fixture: EmailFixture, themeName: string): string {- const themeCSS = generateThemeCSS(themeName);- const theme = getThemeConfig(themeName);- const bgColor = `oklch(${theme.panelL} 0 0)`;- const textColor = `oklch(${theme.inkL} ${theme.inkC} ${theme.inkH})`;+function createTestHTML(args: {+ themeName: string;+ containerWidth: number;+}): string {+ const themeCSS = generateThemeCSS(args.themeName);return `<!DOCTYPE html><html>@@ -101,36 +77,23 @@ function createTestHTML(fixture: EmailFixture, themeName: string): string {font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;font-size: 14px;line-height: 1.5;- background-color: ${bgColor};- color: ${textColor};- padding: 16px;- }-- .email-container {- max-width: 600px;- width: 100%;+ background-color: var(--color-surface-1);+ color: var(--color-content-0);padding: 16px;- background-color: ${bgColor};}- /* Default link styling using accent color */- a {- color: oklch(${theme.accentL} ${theme.accentC} ${theme.accentH});+ .email-host {+ width: ${args.containerWidth}px;+ background-color: var(--color-surface-1);}</style></head><body>- <div class="email-container">- ${fixture.body_html_sanitized}- </div>+ <div class="email-host"></div></body></html>`;}-// =============================================================================-// Fixture Loading-// =============================================================================-function loadFixtures(): EmailFixture[] {const fixturesDir = path.join(import.meta.dirname, 'fixtures');@@ -146,41 +109,95 @@ function loadFixtures(): EmailFixture[] {});}-// =============================================================================-// Snapshot Naming-// =============================================================================+function snapshotName(args: {+ fixtureName: string;+ themeName: string;+ containerWidth: number;+}): string {+ const themeSuffix = args.themeName.toLowerCase().replace(/\s+/g, '-');+ if (args.containerWidth === DEFAULT_CONTAINER_WIDTH) {+ return `${args.fixtureName}-${themeSuffix}.png`;+ }+ return `${args.fixtureName}-${args.containerWidth}-${themeSuffix}.png`;+}-function snapshotName(fixtureName: string, themeName: string): string {- const themeSuffix = themeName.toLowerCase().replace(/\s+/g, '-');- return `${fixtureName}-${themeSuffix}.png`;+async function mountEmailBody(args: {+ page: Page;+ html: string;+}): Promise<void> {+ await args.page.locator('.email-host').evaluate(+ (host, next) => {+ const root = host.shadowRoot ?? host.attachShadow({ mode: 'open' });+ root.replaceChildren();+ const styleEl = document.createElement('style');+ styleEl.textContent = next.css;+ const messageDiv = document.createElement('div');+ messageDiv.innerHTML = next.html;+ root.append(styleEl, messageDiv);+ },+ { css: EMAIL_BODY_CONTAINMENT_CSS, html: args.html }+ );}-// =============================================================================-// Tests-// =============================================================================+async function applyFitToWidth(page: Page): Promise<void> {+ const host = page.locator('.email-host');+ const measured = await host.evaluate((el) => {+ const message = el.shadowRoot?.querySelector('div');+ if (!(message instanceof HTMLElement)) {+ return undefined;+ }+ return {+ containerWidth: el.clientWidth,+ contentWidth: message.scrollWidth,+ };+ });+ if (!measured) return;+ const fit = fitToWidthZoom(measured);+ if (!fit) return;+ await host.evaluate((el, next) => {+ const message = el.shadowRoot?.querySelector('div');+ if (!(message instanceof HTMLElement)) return;+ message.style.zoom = String(next.zoom);+ if (next.overflowsAfterZoom) {+ message.style.overflowX = 'auto';+ }+ }, fit);+}const fixtures = loadFixtures();test.describe('Email Rendering', () => {for (const fixture of fixtures) {test(fixture.name, async ({ page }, testInfo) => {- await page.setViewportSize({ width: 700, height: 800 });-- for (const themeName of THEMES) {- const html = createTestHTML(fixture, themeName);- await page.setContent(html);- await page.waitForLoadState('networkidle');-- // Attach screenshot to report (visible even for passing tests)- const screenshot = await page.screenshot();- await testInfo.attach(`${themeName}`, {- body: screenshot,- contentType: 'image/png',+ for (const containerWidth of containerWidths(fixture)) {+ await page.setViewportSize({+ width: containerWidth + 64,+ height: 800,});- await expect(page).toHaveScreenshot(- snapshotName(fixture.name, themeName)- );+ for (const themeName of THEMES) {+ await page.setContent(createTestHTML({ themeName, containerWidth }));+ await mountEmailBody({+ page,+ html: fixture.body_html_sanitized,+ });+ await page.waitForLoadState('networkidle');+ await applyFitToWidth(page);++ const screenshot = await page.screenshot();+ await testInfo.attach(`${themeName}-${containerWidth}`, {+ body: screenshot,+ contentType: 'image/png',+ });++ await expect(page).toHaveScreenshot(+ snapshotName({+ fixtureName: fixture.name,+ themeName,+ containerWidth,+ })+ );+ }}});}diff --git a/apps/web/src/lib/core/email/tests/fixtures/github-pr-review.json b/apps/web/src/lib/core/email/tests/fixtures/github-pr-review.jsonnew file mode 100644index 0000000000..d962588830--- /dev/null+++ b/apps/web/src/lib/core/email/tests/fixtures/github-pr-review.json@@ -0,0 +1,5 @@+{+ "name": "github-pr-review",+ "description": "Unwrapped <pre> review diff. Without pre-wrap this inflates scrollWidth and used to zoom the whole letter.",+ "body_html_sanitized": "<div><p>cam requested changes on this pull request.</p><p>apps/web/src/features/block-email/component/EmailMessageBody.tsx</p><pre>@@ -291,8 +291,20 @@ export function EmailMessageBody() {\n const contentWidth = messageDiv.scrollWidth;\n- messageDiv.style.zoom = `${container.clientWidth / contentWidth}`;\n+ const fit = fitToWidthZoom({ containerWidth: container.clientWidth, contentWidth });\n+ // One unwrapped pre line like this must not shrink the letter to dust: const leftoverWideCanvas = 'newsletter-table-width-836px-and-a-pathological-diff-hunk-that-would-be-two-thousand-pixels-if-white-space-were-pre';\n</pre></div>"+}diff --git a/apps/web/src/lib/core/email/tests/fixtures/wide-table.json b/apps/web/src/lib/core/email/tests/fixtures/wide-table.jsonnew file mode 100644index 0000000000..d015b31acc--- /dev/null+++ b/apps/web/src/lib/core/email/tests/fixtures/wide-table.json@@ -0,0 +1,6 @@+{+ "name": "wide-table",+ "description": "Fixed-width 836px table. At 360px the viewer should floor zoom at 0.7 and scroll. At 800px it should shrink slightly without hitting the floor.",+ "container_widths": [360, 800],+ "body_html_sanitized": "<table width=\"836\" cellpadding=\"0\" cellspacing=\"0\"><tr><td style=\"padding:16px;font-size:16px;\">Panelist invitation for a designed newsletter table.</td></tr></table>"+}diff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/github-pr-review-macro-dark.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/github-pr-review-macro-dark.pngnew file mode 100644index 0000000000..4cdae37c50Binary files /dev/null and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/github-pr-review-macro-dark.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/github-pr-review-macro-light.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/github-pr-review-macro-light.pngnew file mode 100644index 0000000000..f320e3f66eBinary files /dev/null and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/github-pr-review-macro-light.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-dark.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-dark.pngindex 1915e9c022..1edab39462 100644Binary files a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-dark.png and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-dark.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-light.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-light.pngindex ce24cdb5e7..2b2a021114 100644Binary files a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-light.png and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/google-calendar-invite-macro-light.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.pngindex b2476b54d6..ee87f8eff6 100644Binary files a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.png and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-dark.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.pngindex 3203d78bed..67fbc1014d 100644Binary files a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.png and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/nested-quotes-macro-light.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.pngindex 6f50f4dc57..72ed6f38b8 100644Binary files a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.png and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-dark.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.pngindex 099aa11e43..a52921ace8 100644Binary files a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.png and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/styled-email-macro-light.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-360-macro-dark.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-360-macro-dark.pngnew file mode 100644index 0000000000..67fa0456afBinary files /dev/null and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-360-macro-dark.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-360-macro-light.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-360-macro-light.pngnew file mode 100644index 0000000000..63878f5f89Binary files /dev/null and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-360-macro-light.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-800-macro-dark.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-800-macro-dark.pngnew file mode 100644index 0000000000..5aa93770f1Binary files /dev/null and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-800-macro-dark.png differdiff --git a/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-800-macro-light.png b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-800-macro-light.pngnew file mode 100644index 0000000000..dd058a80a3Binary files /dev/null and b/apps/web/src/lib/core/email/tests/snapshots/email-rendering.pw.ts/wide-table-800-macro-light.png differdiff --git a/justfile b/justfileindex 1148557ab9..5734d43df0 100644--- a/justfile+++ b/justfile@@ -51,6 +51,15 @@ local-e2e-seed:just initialize_dbsjust tooling/seed_cli/local-e2e-smoke+# Email rendering snapshots (Playwright HTML fixtures, not inbox e2e).+# Add a fixture under apps/web/src/lib/core/email/tests/fixtures, then+# `just test-email-rendering-update`.+test-email-rendering:+ just apps/web/test-email-rendering++test-email-rendering-update:+ just apps/web/test-email-rendering-update+# Apply a seed scenario (teams/perms/entities) to the local stack, e.g.# `just seed-scenario apply --file seed/scenarios/team-perms.json`.# Add --force to drop and re-migrate the local database first (pristine world).diff --git a/tooling/seed_cli/Cargo.toml b/tooling/seed_cli/Cargo.tomlindex 8713d45d3b..899ee80177 100644--- a/tooling/seed_cli/Cargo.toml+++ b/tooling/seed_cli/Cargo.toml@@ -13,6 +13,7 @@ chrono = { workspace = true }clap = { workspace = true }comms_db_client = { path = "../../crates/comms_db_client" }email_db_client = { path = "../../crates/email_db_client" }+email_utils = { path = "../../crates/email_utils" }entity_access = { path = "../../crates/entity_access", default-features = false, features = ["outbound"] }entity_access_db_utils = { path = "../../crates/entity_access_db_utils" }fusionauth = { path = "../../crates/fusionauth" }diff --git a/tooling/seed_cli/src/entity/scenario/apply.rs b/tooling/seed_cli/src/entity/scenario/apply.rsindex 2bf6568472..4aae016d27 100644--- a/tooling/seed_cli/src/entity/scenario/apply.rs+++ b/tooling/seed_cli/src/entity/scenario/apply.rs@@ -37,6 +37,16 @@ use super::spec::{use super::{sql_string, values_sql};use crate::config::SeedCliContext;+#[cfg(test)]+mod test;++fn scenario_body_html_sanitized(body_html: Option<&str>, body_text: &str) -> String {+ let raw = body_html+ .map(str::to_string)+ .unwrap_or_else(|| format!("<p>{body_text}</p>"));+ email_utils::sanitize_email_html(&raw)+}+/// Canonical blank-markdown loro snapshot, matching the one production uses/// to initialize empty documents.const MARKDOWN_GOLDEN_SNAPSHOT: &[u8] =@@ -1079,7 +1089,10 @@ fn build_thread(bcc: vec![],labels,body_text: Some(body_text.clone()),- body_html_sanitized: Some(format!("<p>{body_text}</p>")),+ body_html_sanitized: Some(scenario_body_html_sanitized(+ thread_spec.body_html.as_deref(),+ &body_text,+ )),body_macro: None,attachments: vec![],attachments_draft: vec![],diff --git a/tooling/seed_cli/src/entity/scenario/apply/test.rs b/tooling/seed_cli/src/entity/scenario/apply/test.rsnew file mode 100644index 0000000000..441dbcbecb--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/apply/test.rs@@ -0,0 +1,15 @@+use super::*;++#[test]+fn supplied_html_is_sanitized_like_inbound_mail() {+ let cleaned = scenario_body_html_sanitized(Some("<p>hi</p><script>alert(1)</script>"), "plain");+ assert!(cleaned.contains("<p>hi</p>"));+ assert!(!cleaned.to_ascii_lowercase().contains("<script"));+}++#[test]+fn plaintext_fallback_is_also_sanitized() {+ let cleaned = scenario_body_html_sanitized(None, "hello<script>x</script>");+ assert!(cleaned.contains("hello"));+ assert!(!cleaned.to_ascii_lowercase().contains("<script"));+}diff --git a/tooling/seed_cli/src/entity/scenario/spec.rs b/tooling/seed_cli/src/entity/scenario/spec.rsindex 770eaf625a..e157a7f662 100644--- a/tooling/seed_cli/src/entity/scenario/spec.rs+++ b/tooling/seed_cli/src/entity/scenario/spec.rs@@ -362,6 +362,11 @@ pub struct EmailThreadSpec {/// Plain-text body. Defaults to a short generated body.#[serde(default)]pub body: Option<String>,+ /// Raw HTML body. Apply runs it through [`email_utils::sanitize_email_html`]+ /// before writing `body_html_sanitized`. When omitted, the plaintext body+ /// is wrapped in a paragraph and sanitized.+ #[serde(default)]+ pub body_html: Option<String>,/// Whether the thread is unread.#[serde(default)]pub unread: bool,diff --git a/tooling/seed_cli/src/entity/scenario/spec/test.rs b/tooling/seed_cli/src/entity/scenario/spec/test.rsindex 49832be273..ad6bfd712a 100644--- a/tooling/seed_cli/src/entity/scenario/spec/test.rs+++ b/tooling/seed_cli/src/entity/scenario/spec/test.rs@@ -267,6 +267,34 @@ fn entity_ref_parsing() {assert!(EntityRef::parse("widget:x").is_err());}+#[test]+fn email_thread_keeps_supplied_html() {+ let spec = minimal(serde_json::json!({+ "scenario": "html-mail",+ "users": { "alice": { "email": "[email protected]" } },+ "emails": {+ "alice-inbox": {+ "owner": "alice",+ "threads": {+ "wide": {+ "subject": "Wide HTML",+ "from": "[email protected]",+ "body": "plain",+ "body_html": "<pre style='color:#555'>diff</pre>"+ }+ }+ }+ }+ }))+ .unwrap();+ let thread = &spec.emails["alice-inbox"].threads["wide"];+ assert_eq!(+ thread.body_html.as_deref(),+ Some("<pre style='color:#555'>diff</pre>")+ );+ assert_eq!(thread.body.as_deref(), Some("plain"));+}+#[test]fn project_chain_walks_parents() {let spec = minimal(serde_json::json!({