Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mail): 修复邮件阅读排版并统一深色适配
Dash3536778956cd
diff --git a/apps/desktop/scripts/fixtures/mail-reading/fixture.tsx b/apps/desktop/scripts/fixtures/mail-reading/fixture.tsxnew file mode 100644index 0000000000..1abd4c6ad0--- /dev/null+++ b/apps/desktop/scripts/fixtures/mail-reading/fixture.tsx@@ -0,0 +1,32 @@+import { mountPage } from '../../ui-page/harness';+import { MailHtmlPreview } from '../../../src/renderer/components/chat/MailHtmlPreview';++// Structural reproduction of an indented HTML ticket, without private mail data.+const ticket = `<html><head><style>+body{margin:0;background:white;font-family:Arial,sans-serif}+.card{width:100%;max-width:600px;margin:auto;background:#f99a3c}+.address{padding:20px 55px;text-align:left}+.address p{margin:0;line-height:28px;font-size:17px;color:black}+@media(max-width:400px){.address{padding:20px 25px}}+</style></head><body>+<table class="card" cellspacing="0" cellpadding="0"><tr><td>+<h1 style="text-align:center;color:black;font-size:28px;padding:24px">Your event ticket</h1>+<div style="margin:20px;padding:20px;background:white;color:#333;border-radius:10px">+<strong style="font-size:28px">47 EXAMPLE</strong><p style="margin:8px 0 0;font-size:24px">104/194</p></div>+<div class="address"><p><strong>+ SAMPLE+ </strong></p><p>+ Alex+ </p><p>+ 28 Example Road+ </p><p>+ Example City+ </p></div>+<p style="text-align:center;padding:20px;color:black">Keep this ticket for your visit.</p>+</td></tr></table></body></html>`;++void mountPage({ render: ctx => <main className="min-h-screen p-3">+ <MailHtmlPreview reading value={ctx.case === 'fixed-width'+ ? '<table style="width:800px;min-width:800px"><tr><td>Left edge</td><td style="text-align:right">Right edge</td></tr></table>'+ : ticket} />+</main> });diff --git a/apps/desktop/scripts/fixtures/mail-reading/ui-page.mjs b/apps/desktop/scripts/fixtures/mail-reading/ui-page.mjsnew file mode 100644index 0000000000..049d6e66e3--- /dev/null+++ b/apps/desktop/scripts/fixtures/mail-reading/ui-page.mjs@@ -0,0 +1,41 @@+export default {+ name: 'mail-reading',+ entry: './fixture.tsx',+ real: 'MailHtmlPreview and shared sanitized reading document',+ notCovered: 'Mailbox access, original remote image fetching and native mobile WebView',+ viewport: { width: 640, height: 700 },+ cases: {+ default: { about: 'Authored light colors, readable dark palette and collapsed source indentation' },+ narrow: { about: 'Sender responsive layout in a narrow reader', viewport: { width: 320, height: 700 } },+ 'fixed-width': { about: 'A fixed-width message remains scrollable inside its own document', viewport: { width: 320, height: 400 } },+ },+ async check(page, ui) {+ await page.locator('iframe[aria-busy="false"]').waitFor();+ const result = await page.evaluate(() => {+ const frame = document.querySelector('iframe'), doc = frame.contentDocument;+ const css = el => doc.defaultView.getComputedStyle(el);+ if (!doc.querySelector('.card')) {+ doc.scrollingElement.scrollLeft = 800;+ return { scroll: doc.scrollingElement.scrollLeft, scrolling: frame.getAttribute('scrolling'), color: css(doc.querySelector('td')).color };+ }+ const paragraphs = [...doc.querySelectorAll('.address p')];+ return {+ background: css(doc.querySelector('.card')).backgroundColor,+ color: css(paragraphs[0]).color,+ heights: paragraphs.map(el => el.getBoundingClientRect().height),+ runs: doc.querySelectorAll('[data-cindy-mail-run]').length,+ padding: css(doc.querySelector('.address')).paddingLeft,+ };+ });+ if (ui.case === 'fixed-width') {+ if (result.scroll <= 0 || result.scrolling === 'no') throw new Error('Fixed-width mail is clipped instead of scrollable');+ if (ui.theme === 'dark' && result.color === 'rgb(17, 17, 17)') throw new Error('Inherited text stayed dark');+ return;+ }+ if (result.background !== (ui.theme === 'dark' ? 'rgb(129, 71, 14)' : 'rgb(249, 154, 60)')) throw new Error('Mail background lost its intended hue/brightness');+ if (ui.theme === 'light' && result.color !== 'rgb(0, 0, 0)') throw new Error('Authored light text changed');+ if (ui.theme === 'dark' && result.color === 'rgb(0, 0, 0)') throw new Error('Text was not adapted to the dark background');+ if (result.runs || result.heights.some(height => height !== 28)) throw new Error('Source indentation changed the rendered line spacing');+ if (result.padding !== (ui.case === 'narrow' ? '25px' : '55px')) throw new Error('Sender responsive CSS was lost');+ },+};diff --git a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsxindex 356f2006a1..a76c2b250e 100644--- a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx+++ b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx@@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import * as Dialog from '@radix-ui/react-dialog';import { Maximize2, X } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { externalMailImageUrl, hasMailExternalImages, mailInlineDocument, safeMailDocument, validMailImageUrl } from '@cindy/maker-shared/mail-text-edit';+import { externalMailImageUrl, hasMailExternalImages, mailInlineDocument, mailReadingDocument, safeMailDocument, validMailImageUrl } from '@cindy/maker-shared/mail-text-edit';import { Button } from '@/components/ui/button';import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';import { useChatSessionFile } from './ChatSessionFileContext';@@ -29,9 +29,10 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, dconst current = useRef({ disabled, onChange, images, reading, sidebarTargetSessionId, t });current.current = { disabled, onChange, images, reading, sidebarTargetSessionId, t };const revision = model.current.revision;+ const previewDocument = onChange ? mailInlineDocument : mailReadingDocument;// Keep the browsing context alive in both views. Other-view autosaves update// its sanitized DOM before paint rather than navigating through a blank page.- const [html] = useState(() => mailInlineDocument(value, images, allowExternalImages));+ const [html] = useState(() => previewDocument(value, images, allowExternalImages));const ready = useRef(false);const serialize = useRef<ReturnType<typeof mailBodySerializer> | undefined>(undefined);const fit = () => {@@ -65,7 +66,7 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, dconst scroll = [doc.documentElement.scrollTop, doc.body.scrollTop];stopTheme.current?.();if (replaceContents) {- const next = new DOMParser().parseFromString(mailInlineDocument(model.current.emitted, current.current.images, allowExternalImages), 'text/html');+ const next = new DOMParser().parseFromString(previewDocument(model.current.emitted, current.current.images, allowExternalImages), 'text/html');for (const [target, source] of [[doc.documentElement, next.documentElement], [doc.head, next.head], [doc.body, next.body]]) {for (const attr of [...target.attributes]) target.removeAttribute(attr.name);for (const attr of source.attributes) target.setAttribute(attr.name, attr.value);@@ -73,8 +74,8 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, ddoc.head.replaceChildren(...[...next.head.childNodes].map(node => doc.importNode(node, true)));doc.body.replaceChildren(...[...next.body.childNodes].map(node => doc.importNode(node, true)));}- serialize.current = mailBodySerializer(doc, model.current.emitted, () => current.current.images);- stopTheme.current = followMailPreviewTheme(doc, document, current.current.reading && !current.current.onChange);+ serialize.current = current.current.onChange ? mailBodySerializer(doc, model.current.emitted, () => current.current.images) : undefined;+ stopTheme.current = followMailPreviewTheme(doc, document, !current.current.onChange);bodyResize.current?.disconnect();if (!enlarged && typeof ResizeObserver !== 'undefined') {bodyResize.current = new ResizeObserver(fit);@@ -95,7 +96,7 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, dreturn () => observer.disconnect();}, [enlarged, reading]);// Hide only the initial load. Synchronized content never hides/remounts it.- return <iframe ref={frame} title={t('chat.ghostCall.mailPreview')} sandbox="allow-same-origin" scrolling={reading ? 'no' : undefined}+ return <iframe ref={frame} title={t('chat.ghostCall.mailPreview')} sandbox="allow-same-origin"className="block w-full border-0" aria-busy="true"style={{ height: enlarged ? '100%' : 120, visibility: 'hidden', backgroundColor: 'transparent' }} srcDoc={html}onLoad={() => {@@ -104,7 +105,7 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, dif (boundDocument.current === doc) return;boundDocument.current = doc;ready.current = true;- applySource(mailInlineDocument(model.current.emitted, current.current.images, allowExternalImages) !== html);+ applySource(previewDocument(model.current.emitted, current.current.images, allowExternalImages) !== html);let composing = false;const update = () => {if (composing || current.current.disabled || !current.current.onChange) return;diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsxindex 05e6102006..757d966a95 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx@@ -6,7 +6,7 @@ import { GhostCardForm } from '../GhostCardForm';import { ChatSessionFileProvider } from '../ChatSessionFileContext';import { openUrlInSidebarBrowser } from '@/features/right-sidebar/lib/openInSidebarBrowser';import { _resetLinkOpenPreferenceForTests } from '@/hooks/useLinkOpenPreference';-import { mailInlineBindingScript, mailInlineRefreshScript } from '@cindy/maker-shared/mail-text-edit';+import { mailInlineBindingScript, mailInlineRefreshScript, mailReadingColor, mailReadingThemeScript } from '@cindy/maker-shared/mail-text-edit';import { mailBodySerializer } from '../mailBodyEditing';vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('../ImageLightbox', () => ({ ImageLightbox: ({ src }: { src: string }) => <img alt="attachment-preview" src={src} /> }));@@ -95,7 +95,7 @@ it('opens reader links with chat preferences and modifiers but never navigates t// must also leave authored styles intact when this frame becomes an editor.// Unit regression for #7062: inert mailto/credential targets must not expose// keyboard/AT links; prior tests checked only paint and swallowed clicks.-it('keeps link affordances in both themes and restores source styles for editing', async () => {+it('keeps link affordances and authored colors in both themes and restores source styles for editing', async () => {const root = document.documentElement, originalClass = root.className, originalStyle = root.getAttribute('style');const value = '<style>a{text-decoration:none!important}</style><p><a style="text-decoration:none!important;color:red" href="https://example.test/page">Web</a><a style="text-decoration:underline!important" href="mailto:[email protected]">Email</a><a role="link" href="https://user:[email protected]">Credentials</a></p>';const change = vi.fn();@@ -111,8 +111,9 @@ it('keeps link affordances in both themes and restores source styles for editingconst [web, email] = [...doc.querySelectorAll('a')];expect(web.style.textDecoration).toBe('underline');expect(web.style.getPropertyPriority('text-decoration')).toBe('important');- expect(web.style.color).toBe('inherit');- expect(web.querySelector('span')!.style.color).toBe('inherit');+ if (dark) expect(web.style.color).not.toBe('red');+ else expect(web.style.color).toBe('red');+ expect(web.querySelector('[data-cindy-mail-run]')).toBeNull();expect(web.style.cursor).toBe('pointer');expect(email.style.textDecoration).toBe('none');expect(email.style.cursor).toBe('text');@@ -221,7 +222,72 @@ it('lets the reader grow with long mail and late images while keeping chat cardsfireEvent.load(card);expect(parseInt(card.style.height)).toBeLessThan(height);});-// Dark neutral backgrounds merge into the reading surface. Light mode keeps+// EasyVote regression: dim the colored paper without crushing its hue, keeping+// text structure and original image pixels intact across host theme changes.+it('adapts the reading palette without changing text structure or accumulating dimming', async () => {+ const root = document.documentElement, oldClass = root.className, oldStyle = root.getAttribute('style');+ try {+ root.classList.add('dark');+ root.style.setProperty('--surface', '#181818');+ root.style.setProperty('--text-primary', '#eeeeee');+ const source = '<body style="background:#f99a3c;color:black"><div style="background:white;border:5px solid white"><p style="margin:0;line-height:28px">\n Alex\n </p></div><img src="cid:logo"></body>';+ const view = render(<MailHtmlPreview value={source} reading />);+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement, doc = frame.contentDocument!;+ doc.open(); doc.write(frame.srcdoc); doc.close(); fireEvent.load(frame);+ const paragraph = doc.querySelector('p');+ for (const dark of [true, false, true]) {+ await act(async () => { root.classList.toggle('dark', dark); });+ expect(doc.body.style.backgroundColor).toBe(dark ? 'rgb(129, 71, 14)' : 'rgb(249, 154, 60)');+ expect(doc.body.style.color).toBe(dark ? 'rgb(238, 238, 238)' : 'black');+ expect(doc.querySelector('div')!.style.backgroundColor).toBe(dark ? 'rgb(24, 24, 24)' : 'white');+ expect(doc.querySelector('div')!.style.borderTopColor).toBe(dark ? 'rgb(24, 24, 24)' : 'white');+ expect(doc.querySelector('img')!.getAttribute('style')).toBeNull();+ expect(doc.querySelector('[data-cindy-mail-run]')).toBeNull();+ expect(doc.querySelector('p')).toBe(paragraph);+ expect(doc.body.contentEditable).toBe('false');+ }+ view.rerender(<MailHtmlPreview value={source.replace('Alex', 'Sam')} reading />);+ expect(frame.contentDocument).toBe(doc);+ expect(doc.querySelector('p')!.textContent).toBe('\n Sam\n ');+ expect(doc.body.style.backgroundColor).toBe('rgb(129, 71, 14)');+ } finally {+ cleanup(); root.className = oldClass;+ if (oldStyle === null) root.removeAttribute('style'); else root.setAttribute('style', oldStyle);+ }+});+it('uses the same reading palette in native injection and restores the original on light mode', () => {+ const frame = document.createElement('iframe'); document.body.append(frame);+ try {+ const doc = frame.contentDocument!;+ doc.body.innerHTML = '<p style="background:rgb(249,154,60);color:black;border:5px solid white">Ticket</p><img src="data:image/png;base64,YQ==">';+ const original = doc.body.innerHTML;+ const palette = { surface: '#181818', text: '#eeeeee' };+ const apply = (dark: boolean) => new Function('document', 'getComputedStyle', mailReadingThemeScript(dark, palette))(doc, doc.defaultView!.getComputedStyle.bind(doc.defaultView));+ apply(true);+ const painted = doc.body.innerHTML;+ expect(doc.querySelector('p')!.style.backgroundColor).toBe('rgb(129, 71, 14)');+ expect(mailReadingColor('rgb(249, 154, 60)', 'background', palette)).toBe('rgba(129, 71, 14, 1)');+ expect(doc.querySelector('p')!.style.color).toBe('rgb(238, 238, 238)');+ expect(doc.querySelector('img')!.getAttribute('style')).toBeNull();+ apply(true);+ expect(doc.body.innerHTML).toBe(painted);+ apply(false);+ expect(doc.body.innerHTML).toBe(original);+ // The native literal must match the desktop function even in Hermes builds,+ // where serializing the function itself would only return a bytecode stub.+ for (const color of ['rgb(250, 250, 250)', 'rgb(24, 24, 24)', 'rgb(0, 140, 255)', 'rgb(250, 50, 150)', 'rgb(30, 180, 80)', 'rgba(100, 180, 220, 0.5)', 'rgba(0, 0, 0, 0)']) {+ doc.body.innerHTML = `<p style="background-color:${color};color:${color}">Color</p>`;+ const expected = doc.createElement('p');+ expected.style.backgroundColor = mailReadingColor(color, 'background', palette);+ expected.style.color = mailReadingColor(color, 'text', palette);+ apply(true);+ expect(doc.querySelector('p')!.style.backgroundColor).toBe(expected.style.backgroundColor);+ expect(doc.querySelector('p')!.style.color).toBe(expected.style.color);+ apply(false);+ }+ } finally { frame.remove(); }+});+// Dark neutral backgrounds merge into the composing surface. Light mode keeps// authored white paper intact so signature images/tables don't acquire seams.// Theme changes must never reload the preview or save a draft (unit regression).it('adapts authored mail colors to the app theme and restores them without changing content', async () => {diff --git a/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts b/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.tsindex aa68aa2d37..e4ff83827a 100644--- a/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts+++ b/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts@@ -1,3 +1,5 @@+import { mailReadingColor } from '@cindy/maker-shared/mail-text-edit';+const authoredStyleAttribute = 'data-cindy-mail-authored-style';function rememberMailPreviewPaint(el: Element, style = el.getAttribute('style')) {@@ -40,10 +42,7 @@ export function followMailPreviewTheme(doc: Document, host: Document, reading =const paintLinks = () => {if (!reading) return;for (const link of doc.querySelectorAll<HTMLElement>('a')) {- for (const el of [link, ...link.querySelectorAll<HTMLElement>('*')]) {- rememberMailPreviewPaint(el);- el.style.setProperty('color', 'inherit', 'important');- }+ rememberMailPreviewPaint(link);const clickable = Boolean(mailPreviewLinkUrl(link.getAttribute('href')));if (!clickable) {link.removeAttribute('href');@@ -76,7 +75,8 @@ export function followMailPreviewTheme(doc: Document, host: Document, reading =const authored = nodes.map(el => {const css = doc.defaultView!.getComputedStyle(el);return { el, style: el.getAttribute('style'), color: css.color, background: css.backgroundColor,- image: css.backgroundImage, border: css.borderTopColor };+ image: css.backgroundImage, border: css.borderTopColor,+ borders: [css.borderTopColor, css.borderRightColor, css.borderBottomColor, css.borderLeftColor] };});const colorInfo = (color: string) => {const rgb = color.match(/^rgba?\(([^)]+)\)/)?.[1].split(/[, /]+/).map(Number);@@ -92,6 +92,14 @@ export function followMailPreviewTheme(doc: Document, host: Document, reading =// style with the clone so neither saving nor cleanup relies on identity.rememberMailPreviewPaint(el, entry.style);const set = (name: string, value: string) => el.style.setProperty(name, value, 'important');+ if (reading) {+ const palette = { surface, text };+ set('background-color', mailReadingColor(entry.background, 'background', palette));+ set('color', mailReadingColor(entry.color, 'text', palette));+ ['top', 'right', 'bottom', 'left'].forEach((side, index) =>+ set(`border-${side}-color`, mailReadingColor(entry.borders[index], 'background', palette)));+ continue;+ }const background = colorInfo(entry.background), foreground = colorInfo(entry.color);if (background && background.brightness > 0.25) {// Ordinary white/gray mail should share the reading canvas. Mixingdiff --git a/apps/mobile/src/__tests__/pluginCardActions.test.tsx b/apps/mobile/src/__tests__/pluginCardActions.test.tsxindex d6c7aef22f..1941bba730 100644--- a/apps/mobile/src/__tests__/pluginCardActions.test.tsx+++ b/apps/mobile/src/__tests__/pluginCardActions.test.tsx@@ -16,7 +16,7 @@ vi.mock("../plugins/mobileMailAttachment", () => ({ pickMobileMailAttachment: (.vi.mock("@/session/useBotGroupRemoteMedia", () => ({ useBotGroupRemoteMedia: () => h.resolve }));vi.mock('@/components/FileTypeIcon', () => ({ FileTypeIcon: () => null }));-const h = vi.hoisted(() => ({ invoke: vi.fn(), pick: vi.fn(), resolve: vi.fn(), inject: vi.fn(), web: {} as any }));+const h = vi.hoisted(() => ({ invoke: vi.fn(), pick: vi.fn(), resolve: vi.fn(), inject: vi.fn(), web: {} as any, mode: 'light' }));vi.mock("react-native", () => {const View = ({ children }: { children?: ReactNode }) =>createElement("div", {}, children);@@ -75,7 +75,7 @@ vi.mock("@/components/AppText", () => ({vi.mock("@/theme", async () => ({...(await import("../theme/tokens")),useThemedStyles: () => ({}),- useTheme: () => ({ colors: { textPrimary: '#111' } }),+ useTheme: () => ({ mode: h.mode, colors: { surface: '#181818', textPrimary: '#eeeeee' } }),}));vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),@@ -93,6 +93,7 @@ let unmount: (() => void) | undefined;afterEach(() => {unmount?.();unmount = undefined;+ h.mode = 'light';vi.clearAllMocks();});describe("native plugin card deliberate actions", () => {@@ -185,9 +186,32 @@ describe("native plugin card deliberate actions", () => {const preview = container.querySelector('[data-testid="html-preview"]')!;expect(h.inject.mock.calls.some(([script]) => script.includes('data:image/png;base64,aGVsbG8='))).toBe(true);expect(preview.getAttribute('data-html')).toContain("script-src 'none'");+ expect(preview.getAttribute('data-html')).not.toMatch(/data-cindy-mail-run|pre-wrap/);expect(html).toContain('src="cid:logo"');expect(h.invoke).not.toHaveBeenCalled();});+ it('repaints native reading colors on theme changes without replacing the document or changing mail', async () => {+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const html = '<p style="background:rgb(249,154,60);color:black">Ticket</p>';+ const render = () => act(async () => root.render(createElement(MobileMailHtmlPreview, { html, deviceId: 'device' })));+ await render();+ const source = h.web.source;+ const frame = document.createElement('iframe'); document.body.append(frame);+ try {+ const doc = frame.contentDocument!;+ doc.open(); doc.write(source.html); doc.close();+ h.inject.mockImplementation(script => new Function('document', 'window', 'getComputedStyle', script)(doc, {}, doc.defaultView!.getComputedStyle.bind(doc.defaultView)));+ for (const mode of ['dark', 'light', 'dark']) {+ h.mode = mode;+ await render();+ expect(h.web.source).toBe(source);+ expect(doc.querySelector('p')!.style.backgroundColor).toBe(mode === 'dark' ? 'rgb(129, 71, 14)' : 'rgb(249, 154, 60)');+ expect(doc.querySelector('[data-cindy-mail-run]')).toBeNull();+ }+ expect(h.invoke).not.toHaveBeenCalled();+ } finally { h.inject.mockReset(); frame.remove(); }+ });it('uploads from the phone then attaches to the same card; cancellation never dispatches', async () => {const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));h.invoke.mockImplementation(async (_device: string, _channel: string, args: any[]) => {diff --git a/apps/mobile/src/plugins/MobileMailHtmlPreview.tsx b/apps/mobile/src/plugins/MobileMailHtmlPreview.tsxindex b819eeaa3c..96a1d1ff42 100644--- a/apps/mobile/src/plugins/MobileMailHtmlPreview.tsx+++ b/apps/mobile/src/plugins/MobileMailHtmlPreview.tsx@@ -2,11 +2,11 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { Modal, Pressable, StyleSheet, View } from 'react-native';import { useTranslation } from 'react-i18next';import { Text } from '@/components/AppText';-import { applyMailInlineEdits, mailInlineDocument, mailInlineBindingScript, mailInlineRefreshScript, type MailInlineImage } from '@cindy/maker-shared/mail-text-edit';+import { applyMailInlineEdits, mailInlineDocument, mailReadingDocument, mailReadingThemeScript, mailInlineBindingScript, mailInlineRefreshScript, type MailInlineImage } from '@cindy/maker-shared/mail-text-edit';import { WebView } from 'react-native-webview';import { interceptHtmlNavigation } from '@/session/htmlNavigationPolicy';import { useBotGroupRemoteMedia } from '@/session/useBotGroupRemoteMedia';-import { useThemedStyles, spacing, typeScale, lineHeight, fontWeight, type ThemeColors } from '@/theme';+import { useTheme, useThemedStyles, spacing, typeScale, lineHeight, fontWeight, type ThemeColors } from '@/theme';/** CID substitution is preview-only. Never pass fetched URLs back into the draft. */export function MobileMailHtmlPreview({ html, images = [], deviceId, disabled, onChange }: {@@ -72,16 +72,19 @@ function MobileMailFrame({ html, images, disabled, onChange }: {html: string; images: MailInlineImage[]; disabled?: boolean; onChange?: (html: string, text: string) => void;}) {const web = useRef<WebView>(null);+ const { mode, colors } = useTheme();const model = useRef({ source: html, emitted: html, received: html, edits: {} as Record<string, string>, revision: 0 });if (model.current.received !== html) {if (html !== model.current.emitted) model.current = { source: html, emitted: html, received: html, edits: {}, revision: model.current.revision + 1 };else model.current.received = html;}const revision = model.current.revision;- const source = useMemo(() => ({ baseUrl: 'about:blank', html: mailInlineDocument(model.current.source, images) }), [revision]);+ const editable = Boolean(onChange);+ const source = useMemo(() => ({ baseUrl: 'about:blank', html: (editable ? mailInlineDocument : mailReadingDocument)(model.current.source, images) }), [revision, editable]);const settled = useRef(false), lastSource = useRef(source);if (lastSource.current !== source) { lastSource.current = source; settled.current = false; }- const refresh = mailInlineRefreshScript(Boolean(onChange) && !disabled, images);+ const appearance = editable ? '' : mailReadingThemeScript(mode === 'dark', { surface: colors.surface, text: colors.textPrimary });+ const refresh = mailInlineRefreshScript(Boolean(onChange) && !disabled, images) + appearance;useEffect(() => { web.current?.injectJavaScript(refresh); }, [refresh]);return <WebView key={revision} ref={web} source={source} javaScriptEnabledoriginWhitelist={['*']} onShouldStartLoadWithRequest={request => interceptHtmlNavigation(request, settled.current)}diff --git a/packages/maker-shared/src/__tests__/mailReadingDocument.test.ts b/packages/maker-shared/src/__tests__/mailReadingDocument.test.tsnew file mode 100644index 0000000000..46c31295fe--- /dev/null+++ b/packages/maker-shared/src/__tests__/mailReadingDocument.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import { mailInlineDocument, mailReadingDocument } from '../mailTextEdit';++describe('mail reading document', () => {+ it('preserves authored text nodes, responsive CSS and colors without editor whitespace rules', () => {+ const source = '<html><head><style>@media(max-width:600px){.card{padding:10px}}</style></head><body style="background:#f99a3c"><table><tr><td style="text-align:left"><p style="margin:0;line-height:28px">\n Alex\n </p><p>First<br>Second</p></td></tr></table></body></html>';+ const reading = mailReadingDocument(source);+ expect(reading).toContain('<p style="margin:0;line-height:28px">\n Alex\n </p>');+ expect(reading).toContain('<p>First<br>Second</p>');+ expect(reading).toContain('@media(max-width:600px){.card{padding:10px}}');+ expect(reading).toContain('background:#f99a3c');+ expect(reading).not.toMatch(/data-cindy-mail-run|pre-wrap|font:16px\/1.6/);+ expect(mailInlineDocument(source)).toContain('data-cindy-mail-run');+ });++ it('retains the same sandbox and deferred image consent in the reader and editor', () => {+ const image = { cid: 'logo', url: 'data:image/png;base64,YQ==' };+ const source = '<img src="cid:logo"><img src="https://example.test/image" onerror="evil()"><style>p{background:url(https://example.test/track)}</style><script>evil()</script><iframe src="https://example.test"></iframe><img src="file:///private/photo.png">';+ for (const render of [mailReadingDocument, mailInlineDocument]) {+ const blocked = render(source, [image]);+ expect(blocked).toContain('src="data:image/png;base64,YQ=="');+ expect(blocked).not.toContain('https://example.test/image');+ const allowed = render(source, [image], true);+ expect(allowed).toContain('data-cindy-mail-external-src="https://example.test/image"');+ expect(allowed).not.toContain(' src="https://example.test/image"');+ expect(allowed).toContain('referrerpolicy="no-referrer"');+ expect(allowed).toContain("script-src 'none'");+ expect(allowed).toContain("default-src 'none'");+ expect(allowed).not.toMatch(/evil|iframe|file:|url\(/);+ }+ });+});diff --git a/packages/maker-shared/src/mailReadingColors.ts b/packages/maker-shared/src/mailReadingColors.tsnew file mode 100644index 0000000000..2cac69c027--- /dev/null+++ b/packages/maker-shared/src/mailReadingColors.ts@@ -0,0 +1,72 @@+export type MailReadingPalette = { surface: string; text: string };++/** Keep the sender's hue instead of mixing almost all of it into the app+ * surface. This pure function also runs in the native mail WebView. */+export function mailReadingColor(color: string, role: 'background' | 'text', palette: MailReadingPalette): string {+ const parts = color.match(/^rgba?\(([^)]+)\)/)?.[1].split(/[, /]+/).map(Number);+ if (!parts || parts.length < 3 || parts[3] === 0) return color;+ const [r, g, b] = parts.map(value => value / 255);+ const max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min;+ const brightness = r * 0.2126 + g * 0.7152 + b * 0.0722;+ const neutral = delta <= 16 / 255;+ if (role === 'text') {+ if (brightness >= 0.72) return color;+ return neutral ? palette.text : `color-mix(in srgb, ${palette.text} 80%, ${color})`;+ }+ if (brightness <= 0.25) return color;+ if (neutral) return palette.surface;+ const originalLightness = (max + min) / 2;+ const saturation = Math.min(0.8, delta / (1 - Math.abs(2 * originalLightness - 1)));+ let hue = max === r ? ((g - b) / delta) % 6 : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4;+ if (hue < 0) hue += 6;+ const lightness = Math.min(originalLightness, 0.28);+ const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;+ const x = chroma * (1 - Math.abs(hue % 2 - 1)), m = lightness - chroma / 2;+ const channels = hue < 1 ? [chroma, x, 0] : hue < 2 ? [x, chroma, 0] : hue < 3 ? [0, chroma, x]+ : hue < 4 ? [0, x, chroma] : hue < 5 ? [x, 0, chroma] : [chroma, 0, x];+ const rgb = channels.map(value => Math.round((value + m) * 255));+ return `rgba(${rgb.join(', ')}, ${parts[3] ?? 1})`;+}++/** Trusted native injection only: no mail-authored scripts or bridges are enabled.+ * Restore before repainting so theme switches never accumulate dimming. */+export function mailReadingThemeScript(dark: boolean, palette: MailReadingPalette): string {+ return `(function(){+ var marker='data-cindy-mail-reading-style';+ var nodes=Array.from(document.querySelectorAll('html,body,body *')).filter(function(el){return el.tagName!=='IMG'});+ nodes.forEach(function(el){+ if(!el.hasAttribute(marker))return;+ var style=JSON.parse(el.getAttribute(marker));+ if(style===null)el.removeAttribute('style');else el.setAttribute('style',style);+ el.removeAttribute(marker);+ });+ if(!${JSON.stringify(dark)})return;+ // Keep this source literal: native Hermes does not retain Function.toString source.+ var recolor=function(color,role,palette){+ var match=color.match(/^rgba?\\(([^)]+)\\)/);+ var parts=match?match[1].split(/[, /]+/).map(Number):null;+ if(!parts||parts.length<3||parts[3]===0)return color;+ var r=parts[0]/255,g=parts[1]/255,b=parts[2]/255;+ var max=Math.max(r,g,b),min=Math.min(r,g,b),delta=max-min;+ var brightness=r*0.2126+g*0.7152+b*0.0722,neutral=delta<=16/255;+ if(role==='text')return brightness>=0.72?color:neutral?palette.text:'color-mix(in srgb, '+palette.text+' 80%, '+color+')';+ if(brightness<=0.25)return color;if(neutral)return palette.surface;+ var originalLightness=(max+min)/2,saturation=Math.min(0.8,delta/(1-Math.abs(2*originalLightness-1)));+ var hue=max===r?((g-b)/delta)%6:max===g?(b-r)/delta+2:(r-g)/delta+4;if(hue<0)hue+=6;+ var lightness=Math.min(originalLightness,0.28),chroma=(1-Math.abs(2*lightness-1))*saturation;+ var x=chroma*(1-Math.abs(hue%2-1)),m=lightness-chroma/2;+ var channels=hue<1?[chroma,x,0]:hue<2?[x,chroma,0]:hue<3?[0,chroma,x]:hue<4?[0,x,chroma]:hue<5?[x,0,chroma]:[chroma,0,x];+ return 'rgba('+channels.map(function(value){return Math.round((value+m)*255)}).join(', ')+', '+(parts[3]===undefined?1:parts[3])+')';+ };+ var palette=${JSON.stringify(palette)};+ var authored=nodes.map(function(el){var css=getComputedStyle(el);return {el:el,style:el.getAttribute('style'),background:css.backgroundColor,color:css.color,borders:['Top','Right','Bottom','Left'].map(function(side){return css['border'+side+'Color']})}});+ authored.forEach(function(item){+ var el=item.el;el.setAttribute(marker,JSON.stringify(item.style));+ el.style.setProperty('background-color',recolor(item.background,'background',palette),'important');+ el.style.setProperty('color',recolor(item.color,'text',palette),'important');+ ['top','right','bottom','left'].forEach(function(side,i){el.style.setProperty('border-'+side+'-color',recolor(item.borders[i],'background',palette),'important')});+ });+ document.documentElement.style.setProperty('color-scheme','dark','important');+ document.documentElement.style.setProperty('background-color',palette.surface,'important');+ })();true;`;+}diff --git a/packages/maker-shared/src/mailTextEdit.ts b/packages/maker-shared/src/mailTextEdit.tsindex 4ea033ceec..df3d430f82 100644--- a/packages/maker-shared/src/mailTextEdit.ts+++ b/packages/maker-shared/src/mailTextEdit.ts@@ -1,4 +1,5 @@import { parse, serialize, defaultTreeAdapter as adapter, html as htmlNames, type DefaultTreeAdapterTypes } from 'parse5';+export { mailReadingColor, mailReadingThemeScript } from './mailReadingColors';type Run = { start: number; end: number; text: string };type Paragraph = { text: string; runs: Run[] };@@ -89,7 +90,7 @@ export function hasMailExternalImages(source: string): boolean {/** Sanitize before creating our markers. Mail-provided editing attributes,* scripts, nested contexts and event handlers can never become editor controls. */-export function safeMailDocument(source: string, inline = false, images: MailInlineImage[] = [], allowExternalImages = false): string {+export function safeMailDocument(source: string, inline = false, images: MailInlineImage[] = [], allowExternalImages = false, deferExternalImages = inline): string {const doc = parse(source, { sourceCodeLocationInfo: true });const runs = inline ? mailInlineRuns(source) : [];const byStart = new Map(runs.map((run, id) => [run.start, { ...run, id }]));@@ -110,9 +111,9 @@ export function safeMailDocument(source: string, inline = false, images: MailInlnode.attrs = node.attrs.filter(a => a.name === 'style' || (attrs.has(a.name) &&(a.name !== 'href' || /^(https?:|mailto:)/i.test(a.value)) &&(a.name !== 'src' || /^(cid:|data:image\/(png|jpeg|gif|webp);base64,)/i.test(a.value))));- // Inline hosts start opted-in requests after the document is ready, so+ // Preview hosts start opted-in requests after the document is ready, so// a slow image server cannot hold the entire mail body invisible.- if (externalImage) node.attrs.push({ name: inline ? 'data-cindy-mail-external-src' : 'src', value: externalImage }, { name: 'referrerpolicy', value: 'no-referrer' });+ if (externalImage) node.attrs.push({ name: deferExternalImages ? 'data-cindy-mail-external-src' : 'src', value: externalImage }, { name: 'referrerpolicy', value: 'no-referrer' });for (const attr of node.attrs) if (attr.name === 'style') attr.value = cleanCss(attr.value);if (node.tagName === 'style') {node.childNodes = node.childNodes.filter(n => 'value' in n);@@ -155,7 +156,18 @@ export const validMailImageUrl = (url: string) => /^cindy-media:\/\/blobs\/[a-f0export const MAIL_PAPER_COLOR = 'white';export const MAIL_INLINE_STYLE = `html{color-scheme:light}body{margin:4px;background:${MAIL_PAPER_COLOR};color:#111;font:16px/1.6 Arial,Helvetica,sans-serif;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{max-width:100%}[data-cindy-mail-run]{white-space:pre-wrap;outline:none}[data-cindy-mail-run]:empty{display:inline-block;min-width:1ch;min-height:1em}`;export function mailInlineDocument(source: string, images: MailInlineImage[] = [], allowExternalImages = false): string {- return '<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'none\'; img-src data: cindy-media:' + (allowExternalImages ? ' https: http:' : '') + '; style-src \'unsafe-inline\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>' + MAIL_INLINE_STYLE + '</style>' + safeMailDocument(source, true, images, allowExternalImages);+ return mailPreviewDocument(source, images, allowExternalImages, true);+}++/** Reading keeps the sender's text nodes and whitespace collapsing. Editor+ * spans with pre-wrap would expose HTML indentation as visible gaps/newlines. */+export function mailReadingDocument(source: string, images: MailInlineImage[] = [], allowExternalImages = false): string {+ return mailPreviewDocument(source, images, allowExternalImages, false);+}++const MAIL_READING_STYLE = `html{color-scheme:light}body{margin:4px;background:${MAIL_PAPER_COLOR};color:#111;font-family:Arial,Helvetica,sans-serif;overflow-wrap:break-word}img{max-width:100%;height:auto}table{max-width:100%}`;+function mailPreviewDocument(source: string, images: MailInlineImage[], allowExternalImages: boolean, editable: boolean): string {+ return '<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'none\'; img-src data: cindy-media:' + (allowExternalImages ? ' https: http:' : '') + '; style-src \'unsafe-inline\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>' + (editable ? MAIL_INLINE_STYLE : MAIL_READING_STYLE) + '</style>' + safeMailDocument(source, editable, images, allowExternalImages, true);}/** Executed only by the native WebView injection API. The document CSP allows