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): preserve custom HTML signatures when editing (#8872)
gbirmanc92ce9a92fa7
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 4503213faf..53c3ca489a 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -156,6 +156,13 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.raised composer cards (`SettingsSurface`), row spacing, and control shapes stayconsistent; never hand-build a flat `bg-ink/*` card. Keep Integrations on theshared page width and side padding.+- Preserve email signature HTML through import, preview, and source editing;+ mount Quill only for explicit Rich text editing and confirm custom-layout+ conversion. Keep the settings and composer preview on the same sanitized HTML+ renderer. Phone settings show the preview with desktop-only editing. See the+ [signature walkthrough](../../docs/agent-guide/settings.md#email-signatures)+ for browser coverage. Keep signature commit callbacks on the mutation hook+ so account-list remounts cannot leave an already-cleared draft behind.- Keep personal accounts and agent tool connections together in Settings → Integrations;preserve `agent-connections` as an alias for existing links.- Keep bot setup focused on the token-and-SDK workflow; Agent and Ownershipdiff --git a/apps/web/src/features/email-compose/components/signature-preview.tsx b/apps/web/src/features/email-compose/components/signature-preview.tsxindex d2dd6e886c..fcdaedfd77 100644--- a/apps/web/src/features/email-compose/components/signature-preview.tsx+++ b/apps/web/src/features/email-compose/components/signature-preview.tsx@@ -1,8 +1,9 @@import CaretDownIcon from '@icon/system/regular/caret-down.svg?component-solid';import InfoIcon from '@icon/system/regular/info.svg';import XIcon from '@icon/system/regular/x.svg?component-solid';+import { sanitizeEmailHtml } from '@macro-inc/email-renderer';import { Tooltip } from '@ui';-import { createEffect, createSignal, Show } from 'solid-js';+import { createEffect, createSignal, on, Show } from 'solid-js';// Rendered inside a shadow root so the signature's structural markup (lists,// headings, bold) keeps its default styling instead of being flattened by the@@ -19,42 +20,54 @@ const SHADOW_STYLE = `img { max-width: 100%; height: auto; }`;+/** Shared by settings and compose; raw drafts are sanitized before mounting. */+export function SignatureContent(props: {+ html: string;+ label?: string;+ prepareLinks?: (root: ShadowRoot) => void;+}) {+ let mountEl!: HTMLDivElement;+ createEffect(+ on(+ () => props.html,+ (html) => {+ const root =+ mountEl.shadowRoot ?? mountEl.attachShadow({ mode: 'open' });+ root.innerHTML = `<style>${SHADOW_STYLE}</style>${sanitizeEmailHtml(html)}`;+ for (const anchor of root.querySelectorAll('a[href]')) {+ anchor.setAttribute('target', '_blank');+ anchor.setAttribute('rel', 'noopener noreferrer');+ }+ props.prepareLinks?.(root);+ }+ )+ );+ return (+ <div+ ref={mountEl}+ role="region"+ aria-label={props.label ?? 'Signature preview'}+ class="ph-no-capture min-w-0 overflow-auto rounded-lg bg-[white] px-4 py-3 text-base [contain:content]"+ />+ );+}+/*** Read-only preview of the signature that will be appended to the email on send.- * The signature is already sanitized server-side; it's rendered as-is so the- * preview matches what the recipient receives. The dismiss button drops it from+ * Shares the isolated HTML renderer with settings. The dismiss button drops it from* this one message (the parent owns the include/exclude state).*/export function SignaturePreview(props: {- /**- * Server-sanitized signature HTML. Inserted via innerHTML (the shadow root- * scopes CSS/DOM but does NOT block scripts), so callers MUST pass sanitized- * HTML — never raw user input. Today the only source is the saved inbox- * setting, sanitized server-side.- */+ /** Saved inbox signature HTML. */html: string;mobile: boolean;prepareLinks?: (root: ShadowRoot) => void;onDismiss: () => void;dismissable?: boolean;}) {- let mountEl!: HTMLDivElement;// Always starts collapsed to just the bar; the user expands to preview it.const [expanded, setExpanded] = createSignal(false);- createEffect(() => {- const html = props.html;- // Lazily attach (idempotent): a shadow root can only be attached once.- const root = mountEl.shadowRoot ?? mountEl.attachShadow({ mode: 'open' });- root.innerHTML = `<style>${SHADOW_STYLE}</style>${html}`;- for (const a of root.querySelectorAll('a[href]')) {- a.setAttribute('target', '_blank');- a.setAttribute('rel', 'noopener noreferrer');- }- // Raw mailto: anchors open the in-app composer instead of the OS mail client- props.prepareLinks?.(root);- });-return (<div class="mt-2 rounded-lg border border-edge-muted"><div@@ -77,10 +90,7 @@ export function SignaturePreview(props: {{/* Hover-only guidance; hidden on mobile where tooltips never show(Settings still points mobile users to desktop). */}<Show when={!props.mobile}>- <Tooltip- label="Edit your signature in Settings -> Connections."- as="span"- >+ <Tooltip label="Edit your signature in Settings → Email." as="span"><InfoIcon class="size-3.5 text-ink-muted" /></Tooltip></Show>@@ -98,11 +108,9 @@ export function SignaturePreview(props: {</Tooltip></Show></div>- <div- ref={mountEl}- class="rounded-b-lg bg-[white] px-3 py-2 text-base"- classList={{ hidden: !expanded() }}- />+ <Show when={expanded()}>+ <SignatureContent html={props.html} prepareLinks={props.prepareLinks} />+ </Show></div>);}diff --git a/apps/web/src/features/settings/SignatureEditor.tsx b/apps/web/src/features/settings/SignatureEditor.tsxindex 675ccf77a4..0edb9d030e 100644--- a/apps/web/src/features/settings/SignatureEditor.tsx+++ b/apps/web/src/features/settings/SignatureEditor.tsx@@ -85,6 +85,8 @@ export default function SignatureEditor(props: {/** Exposes an imperative handle once mounted so commit actions (Save/Remove)* can set the editor content deterministically, not via the reactive value. */onReady?: (handle: { setContent: (html: string) => void }) => void;+ /** Return true to preserve custom pasted HTML outside Quill's document model. */+ onPasteHtml?: (html: string) => boolean;}) {let toolbarEl!: HTMLDivElement;let editorEl!: HTMLDivElement;@@ -151,19 +153,21 @@ export default function SignatureEditor(props: {length: number,files: File[]) => {- if (!quill) return;- if (length > 0) quill.deleteText(index, length, 'user');+ const editor = quill;+ if (!editor) return;+ if (length > 0) editor.deleteText(index, length, 'user');let at = index;for (const file of files) {try {const id = await createStaticUploadFile(createUploadFile(file));- quill.insertEmbed(at, 'image', staticFileIdEndpoint(id), 'user');+ if (quill !== editor) return;+ editor.insertEmbed(at, 'image', staticFileIdEndpoint(id), 'user');at += 1;} catch {toast.failure('Failed to upload image');}}- quill.setSelection(at, 0, 'silent');+ if (quill === editor) editor.setSelection(at, 0, 'silent');};// Toolbar image button: pick a file, then upload + insert at the cursor.@@ -221,6 +225,12 @@ export default function SignatureEditor(props: {// becomes a hyperlink on those words.const onPaste = (event: ClipboardEvent) => {if (!quill) return;+ const html = event.clipboardData?.getData('text/html');+ if (html && props.onPasteHtml?.(html)) {+ event.preventDefault();+ event.stopImmediatePropagation();+ return;+ }const range = quill.getSelection();const href = pastedHyperlinkHref({clipboardPlainText: event.clipboardData?.getData('text/plain') ?? '',diff --git a/apps/web/src/features/settings/SignatureSection.tsx b/apps/web/src/features/settings/SignatureSection.tsxindex 12e9c20299..29d5bad0bf 100644--- a/apps/web/src/features/settings/SignatureSection.tsx+++ b/apps/web/src/features/settings/SignatureSection.tsx@@ -1,8 +1,10 @@import { toast } from '@core/component/Toast/Toast';import { isMobile } from '@core/mobile/isMobile';+import { fireAndForget } from '@core/util/fireAndForget';import { ThrownResultError } from '@core/util/result';import { useEmailSignature } from '@queries/email/link';import {+ traceSignatureMutation,useImportGmailSignatureMutation,useUpdateEmailSettingsMutation,} from '@queries/email/settings';@@ -13,7 +15,7 @@ import { SignatureForm } from './components/signature-form';// Keep drafts when navigating away from Email settings. Quill loads on demand.const [signatureDrafts, setSignatureDrafts] = createSignal<- Record<string, string>+ Record<string, { html: string }>>({});export function clearSignatureState(linkId: string): void {setSignatureDrafts((prev) => {@@ -35,12 +37,12 @@ function saveSignatureErrorMessage(error: Error): string {: undefined;if (!unresolved) return 'Failed to save signature. Please try again.';- return 'Unable to save images. Use the image button to add images.';+ return 'Unable to save images. Add accessible image URLs in HTML, or use the image button in Rich text.';}/*** Per-inbox signature editor. Reads the persisted signature from the links- * query (no extra fetch) into the Quill editor, tracks an unsaved draft, and+ * query (no extra fetch) into an HTML preview, tracks an unsaved draft, and* patches `email_settings` on save. The "replies & forwards" toggle patches* immediately (the backend patch is partial, so it leaves the signature alone).*/@@ -48,16 +50,10 @@ export function SignatureSection(props: { link: EmailLink }) {const signature = useEmailSignature(() => props.link.id);// Draft lives in the module-level store (keyed by link id) so it survives the// settings tab unmounting; `null` means "no unsaved edit".- const draft = () => signatureDrafts()[props.link.id] ?? null;- const setDraft = (html: string | null) =>- setSignatureDrafts((prev) => {- if (html === null) {- const next = { ...prev };- delete next[props.link.id];- return next;- }- return { ...prev, [props.link.id]: html };- });+ const draft = () => signatureDrafts()[props.link.id]?.html ?? null;+ // A fresh snapshot distinguishes a new edit even when its HTML is identical.+ const setDraft = (html: string) =>+ setSignatureDrafts((prev) => ({ ...prev, [props.link.id]: { html } }));const persisted = () => signature() ?? '';const isDirty = () => draft() !== null && draft() !== persisted();@@ -65,8 +61,6 @@ export function SignatureSection(props: { link: EmailLink }) {// "Remove" stays available even after the user manually empties the editor.const hasContent = () => persisted().length > 0 || (draft()?.length ?? 0) > 0;- const updateSettings = useUpdateEmailSettingsMutation();- const importGmailSignature = useImportGmailSignatureMutation();// Imperative handle to the editor, so Save/Remove sync its content directly// (the reactive `value` path alone didn't reliably clear the box on Remove).let editorApi: { setContent: (html: string) => void } | undefined;@@ -76,25 +70,68 @@ export function SignatureSection(props: { link: EmailLink }) {// Cleared when the user edits, starts a new save, or removes the signature.const [saveError, setSaveError] = createSignal<string | null>(null);+ // Updating the links cache can remount this row. Hook callbacks still run+ // after that; callbacks passed to mutate would leave the old draft behind.+ const updateSettings = useUpdateEmailSettingsMutation({+ onMutate: () => signatureDrafts()[props.link.id],+ onSuccess: (data, { linkId, settings }, submittedDraft) => {+ if (settings.signature === undefined) return;+ // A user may reopen settings and start another draft while this finishes.+ if (signatureDrafts()[linkId] === submittedDraft) {+ clearSignatureState(linkId);+ editorApi?.setContent(data.settings.signature ?? '');+ }+ toast.success(+ settings.signature ? 'Signature saved' : 'Signature removed'+ );+ },+ onError: (error, { settings }) => {+ if (settings.signature === undefined) {+ toast.failure('Failed to update setting.');+ } else if (settings.signature === '') {+ toast.failure('Failed to remove signature. Please try again.');+ } else {+ setSaveError(saveSignatureErrorMessage(error));+ }+ },+ });++ const importGmailSignature = useImportGmailSignatureMutation({+ onMutate: () => signatureDrafts()[props.link.id],+ onSuccess: (result, { linkId }, submittedDraft) => {+ if (result.success) {+ if (signatureDrafts()[linkId] === submittedDraft) {+ clearSignatureState(linkId);+ editorApi?.setContent(result.settings.signature ?? '');+ }+ toast.success('Signature imported from Gmail');+ } else if (result.reason === 'no_signature') {+ toast.failure('No signature found in Gmail');+ } else if (result.reason === 'unresolved_images') {+ setSaveError(+ "Couldn't import images from your Gmail signature. Add accessible image URLs in HTML, or use the image button in Rich text."+ );+ } else {+ toast.failure('Failed to import signature. Please try again.');+ }+ },+ onError: () =>+ toast.failure('Failed to import signature. Please try again.'),+ });+const saveSignature = () => {const next = draft();if (next === null) return;setSaveError(null);- updateSettings.mutate(- { linkId: props.link.id, settings: { signature: next } },- {- onSuccess: (data) => {- setDraft(null);- editorApi?.setContent(data.settings.signature ?? '');- toast.success('Signature saved');- },- // The backend rejects the whole patch (HTTP 422, nothing persisted) when- // a signature has images that won't render for recipients — e.g. pasted- // from another webmail account, so reachable only by that session. Show- // the (long) message inline below the buttons and keep the draft so the- // user can re-add those images and retry.- onError: (error) => setSaveError(saveSignatureErrorMessage(error)),- }+ fireAndForget(+ traceSignatureMutation('save', props.link.id, (span) =>+ updateSettings.mutateAsync({+ span,+ linkId: props.link.id,+ settings: { signature: next },+ })+ ),+ 'email-signature');};@@ -102,17 +139,15 @@ export function SignatureSection(props: { link: EmailLink }) {// "clear" contract; the editor reseeds to empty once the cache updates.const removeSignature = () => {setSaveError(null);- updateSettings.mutate(- { linkId: props.link.id, settings: { signature: '' } },- {- onSuccess: () => {- setDraft(null);- editorApi?.setContent('');- toast.success('Signature removed');- },- onError: () =>- toast.failure('Failed to remove signature. Please try again.'),- }+ fireAndForget(+ traceSignatureMutation('clear', props.link.id, (span) =>+ updateSettings.mutateAsync({+ span,+ linkId: props.link.id,+ settings: { signature: '' },+ })+ ),+ 'email-signature');};@@ -120,44 +155,25 @@ export function SignatureSection(props: { link: EmailLink }) {// editor shows the persisted value and any unsaved draft is discarded.const importFromGmail = () => {setSaveError(null);- importGmailSignature.mutate(- { linkId: props.link.id },- {- onSuccess: (result) => {- if (result.success) {- setDraft(null);- editorApi?.setContent(result.settings.signature ?? '');- toast.success('Signature imported from Gmail');- } else if (result.reason === 'no_signature') {- toast.failure('No signature found in Gmail');- } else if (result.reason === 'unresolved_images') {- setSaveError(- "Couldn't import images from your Gmail signature. Add the text here and use the image button to add images."- );- } else {- toast.failure('Failed to import signature. Please try again.');- }- },- onError: () =>- toast.failure('Failed to import signature. Please try again.'),- }+ fireAndForget(+ traceSignatureMutation('import', props.link.id, (span) =>+ importGmailSignature.mutateAsync({ linkId: props.link.id, span })+ ),+ 'email-signature');};const setOnRepliesForwards = (checked: boolean) => {- updateSettings.mutate(- {- linkId: props.link.id,- settings: { signature_on_replies_forwards: checked },- },- { onError: () => toast.failure('Failed to update setting.') }- );+ updateSettings.mutate({+ linkId: props.link.id,+ settings: { signature_on_replies_forwards: checked },+ });};return (<SignatureFormemail={props.link.email_address}- value={draft() ?? persisted()}+ value={isMobile() ? persisted() : (draft() ?? persisted())}onInput={(html) => {setDraft(html);setSaveError(null);diff --git a/apps/web/src/features/settings/browser-test/signatures/fixture.tsx b/apps/web/src/features/settings/browser-test/signatures/fixture.tsxnew file mode 100644index 0000000000..cb33020436--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/fixture.tsx@@ -0,0 +1,88 @@+import '@fontsource-variable/inter';+import '../../../../index.css';+import { SignaturePreview } from '@app/features/email-compose/components/signature-preview';+import { isMobile } from '@core/mobile/isMobile';+import { QueryClientProvider } from '@tanstack/solid-query';+import { createSignal, For, onMount, Show } from 'solid-js';+import { render } from 'solid-js/web';+import { macroDarkTheme } from '../../../theme/themes/macro-dark';+import { macroLightTheme } from '../../../theme/themes/macro-light';+import { themeCssVars } from '../../../theme/utils/themeColorTokens';+import {+ SettingsButton as Button,+ SettingsPage,+ SettingsSection,+ SettingsSurface,+} from '../../primitives';+import { SignatureSection } from '../../SignatureSection';+import {+ link,+ queryClient,+ status,+ useEmailLinksQuery,+ useEmailSignature,+} from './services';++function Fixture() {+ const [mounted, setMounted] = createSignal(true);+ const signature = useEmailSignature(() => link.id);+ const links = useEmailLinksQuery();+ onMount(() => {+ const dark = new URLSearchParams(location.search).has('dark');+ for (const [key, value] of Object.entries(+ themeCssVars(dark ? macroDarkTheme : macroLightTheme)+ ))+ document.documentElement.style.setProperty(key, value);+ document.documentElement.style.colorScheme = dark ? 'dark' : 'light';+ document.documentElement.dataset.themeLight = String(!dark);+ });+ return (+ <main class="h-dvh bg-panel text-ink">+ <SettingsPage+ title="Email"+ description="Manage your inboxes and the signature you send with each account."+ >+ <SettingsSection+ title="Signatures"+ description="Create a signature for each email account, import from Gmail, or paste your HTML. Preview it before sending."+ >+ <Show when={mounted()}>+ <For each={links.isSuccess ? links.data.links : []}>+ {(inbox) => <SignatureSection link={inbox} />}+ </For>+ </Show>+ <p role="status" class="text-sm text-ink-muted">+ {status()}+ </p>+ </SettingsSection>+ <SettingsSection title="New email preview">+ <SettingsSurface class="p-4">+ <p class="text-sm">Hello,</p>+ <Show when={signature()}>+ {(html) => (+ <SignaturePreview+ html={html()}+ mobile={isMobile()}+ onDismiss={() => {}}+ />+ )}+ </Show>+ </SettingsSurface>+ </SettingsSection>+ <Button variant="ghost" onClick={() => setMounted((value) => !value)}>+ {mounted() ? 'Leave settings' : 'Reopen settings'}+ </Button>+ </SettingsPage>+ </main>+ );+}+const root = document.getElementById('root');+if (root)+ render(+ () => (+ <QueryClientProvider client={queryClient}>+ <Fixture />+ </QueryClientProvider>+ ),+ root+ );diff --git a/apps/web/src/features/settings/browser-test/signatures/index.html b/apps/web/src/features/settings/browser-test/signatures/index.htmlnew file mode 100644index 0000000000..4e202ad8af--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/index.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><title>Email signature preview</title></head><body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body></html>diff --git a/apps/web/src/features/settings/browser-test/signatures/playwright.config.ts b/apps/web/src/features/settings/browser-test/signatures/playwright.config.tsnew file mode 100644index 0000000000..43b7de8c95--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/playwright.config.ts@@ -0,0 +1,35 @@+import { fileURLToPath } from 'node:url';+import { defineConfig, devices } from '@playwright/test';++const directory = fileURLToPath(new URL('.', import.meta.url));+const web = fileURLToPath(new URL('../../../../../', import.meta.url));+const port = Number(process.env.SIGNATURE_BROWSER_PORT ?? 3098);+export default defineConfig({+ testDir: directory,+ testMatch: '*.browser.e2e.ts',+ outputDir: `${directory}/test-results`,+ timeout: 45_000,+ use: {+ baseURL: `http://127.0.0.1:${port}`,+ trace: 'retain-on-failure',+ screenshot: 'only-on-failure',+ contextOptions: { reducedMotion: 'reduce' },+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ },+ webServer: {+ command: `bunx vite --config src/features/settings/browser-test/signatures/vite.config.ts --port ${port}`,+ cwd: web,+ url: `http://127.0.0.1:${port}`,+ reuseExistingServer: false,+ timeout: 120_000,+ },+ projects: [+ { name: 'desktop', use: { ...devices['Desktop Chrome'] } },+ {+ name: 'phone',+ use: { ...devices['iPhone 13'], defaultBrowserType: 'chromium' },+ },+ ],+});diff --git a/apps/web/src/features/settings/browser-test/signatures/public/social.svg b/apps/web/src/features/settings/browser-test/signatures/public/social.svgnew file mode 100644index 0000000000..d68a2909f3--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/public/social.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22"><rect width="22" height="22" rx="3"/><path fill="white" d="M5 9h3v8H5zm0-4h3v3H5zm5 4h3v1c2-2 5-1 5 2v5h-3v-4c0-2-2-2-2 0v4h-3z"/></svg>diff --git a/apps/web/src/features/settings/browser-test/signatures/sample.ts b/apps/web/src/features/settings/browser-test/signatures/sample.tsnew file mode 100644index 0000000000..6ac482bcf6--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/sample.ts@@ -0,0 +1,2 @@+// Synthetic nested-table layout reproducing signatures generated by webmail tools.+export const signatureHtml = `<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;font-family:Courier New;font-size:12px"><tbody><tr><td><table cellpadding="0" cellspacing="0"><tbody><tr><td style="padding:0 16px 8px 0">Alex Morgan</td></tr><tr><td>Brand and Marketing Strategist</td></tr><tr><td><a href="https://example.com">Example Studio</a></td></tr><tr><td><a href="mailto:[email protected]">[email protected]</a></td></tr></tbody></table></td></tr><tr><td><table cellpadding="0" cellspacing="0"><tbody><tr><td style="padding-right:8px"><a href="https://example.com/social"><img src="/social.svg" width="22" height="22" alt="Social profile"></a></td><td><a href="https://example.com/contact">Contact</a></td></tr></tbody></table></td></tr></tbody></table>`;diff --git a/apps/web/src/features/settings/browser-test/signatures/services.ts b/apps/web/src/features/settings/browser-test/signatures/services.tsnew file mode 100644index 0000000000..29eceff59a--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/services.ts@@ -0,0 +1,118 @@+import { sanitizeEmailHtml } from '@macro-inc/email-renderer';+import { emailKeys } from '@queries/email/keys';+import type {+ Link,+ ListLinksResponse,+ Settings,+} from '@service-email/generated/schemas';+import { QueryClient, useQuery } from '@tanstack/solid-query';+import { ok } from 'neverthrow';+import { createMemo, createSignal } from 'solid-js';+import { signatureHtml } from './sample';++export const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+});+export const link: Link = {+ id: 'signature-fixture-inbox',+ email_address: '[email protected]',+ macro_id: 'macro|[email protected]',+ fusionauth_user_id: 'fixture-user',+ calendar_disabled: false,+ has_calendar_data: false,+ is_primary: true,+ is_sync_active: false,+ needs_calendar_permission: false,+ needs_reauth: false,+ provider: 'GMAIL',+ sync_status: 'UP_TO_DATE',+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ settings: { signature: signatureHtml, signature_on_replies_forwards: true },+};+let settings = { ...link.settings };+const patches: Settings[] = [];+queryClient.setQueryData(emailKeys.links.queryKey, { links: [link] });+export const useNonPrimaryEmailLinkIdHeader = () => (id: string) => id;+export function useEmailLinksQuery() {+ return useQuery(() => ({+ queryKey: emailKeys.links.queryKey,+ queryFn: async (): Promise<ListLinksResponse> => ({+ links: [{ ...link, settings }],+ }),+ enabled: false,+ }));+}+export function useEmailSignature(linkId: () => string | undefined) {+ const query = useEmailLinksQuery();+ return createMemo(() =>+ query.isSuccess+ ? query.data.links.find((item) => item.id === linkId())?.settings+ .signature+ : undefined+ );+}+let refresh: Promise<void> | undefined;+let finishRefresh: (() => void) | undefined;+export async function refreshMailAccounts() {+ await refresh;+}+function holdAccountRefresh() {+ const pending = Promise.withResolvers<void>();+ refresh = pending.promise;+ finishRefresh = pending.resolve;+}+function releaseAccountRefresh() {+ finishRefresh?.();+ refresh = undefined;+ finishRefresh = undefined;+}+export const emailClient = {+ async patchSettings(input: { settings: Settings }) {+ patches.push(structuredClone(input.settings));+ const next = { ...input.settings };+ if (typeof next.signature === 'string' && next.signature) {+ const document = new DOMParser().parseFromString(+ sanitizeEmailHtml(next.signature),+ 'text/html'+ );+ next.signature = document.head.innerHTML + document.body.innerHTML;+ }+ settings = { ...settings, ...next };+ return ok({ settings: { ...settings } });+ },+ async importGmailSignature() {+ settings = { ...settings, signature: signatureHtml };+ return ok({ settings: { ...settings } });+ },+};+export const SIGNATURE_IMAGES_UNRESOLVED_CODE = 'SIGNATURE_IMAGES_UNRESOLVED';+export const [status, setStatus] = createSignal('');+export const toast = { success: setStatus, failure: setStatus };+export function createUploadFile() {+ throw new Error('Uploads are not part of this fixture');+}+export async function createStaticUploadFile() {+ throw new Error('Uploads are not part of this fixture');+}+export function readState() {+ return {+ savedSignature: settings.signature,+ patches: structuredClone(patches),+ };+}++declare global {+ interface Window {+ signatureFixture: {+ readState: typeof readState;+ holdAccountRefresh: typeof holdAccountRefresh;+ releaseAccountRefresh: typeof releaseAccountRefresh;+ };+ }+}+window.signatureFixture = {+ readState,+ holdAccountRefresh,+ releaseAccountRefresh,+};diff --git a/apps/web/src/features/settings/browser-test/signatures/signature.browser.e2e.ts b/apps/web/src/features/settings/browser-test/signatures/signature.browser.e2e.tsnew file mode 100644index 0000000000..68a84178bb--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/signature.browser.e2e.ts@@ -0,0 +1,384 @@+import { expect, test } from '@playwright/test';+import { signatureHtml } from './sample';+import type {} from './services';++test.beforeEach(async ({ page }) => {+ await page.goto('/');+ await expect(+ page.getByRole('region', { name: 'Signature preview for [email protected]' })+ ).toBeVisible();+});++test('saved HTML keeps its nested layout in settings and new-message previews', async ({+ page,+}) => {+ const preview = page.getByRole('region', {+ name: 'Signature preview for [email protected]',+ });+ await expect(preview.locator('table')).toHaveCount(3);+ await expect(preview.locator('table table')).toHaveCount(2);+ await expect(preview.locator('td').first()).toHaveCSS(+ 'border-top-width',+ '0px'+ );+ const name = preview.getByText('Alex Morgan');+ const title = preview.getByText('Brand and Marketing Strategist');+ const nameBox = await name.boundingBox();+ const titleBox = await title.boundingBox();+ expect(nameBox && titleBox && nameBox.y < titleBox.y).toBeTruthy();+ await page.getByRole('button', { name: 'Signature', exact: true }).click();+ const outgoing = page.getByRole('region', {+ name: 'Signature preview',+ exact: true,+ });+ await expect(outgoing.locator('table')).toHaveCount(3);+ expect(+ await outgoing.evaluate((element) => element.shadowRoot?.innerHTML)+ ).toBe(await preview.evaluate((element) => element.shadowRoot?.innerHTML));+ await page.getByRole('button', { name: 'Leave settings' }).click();+ await page.getByRole('button', { name: 'Reopen settings' }).click();+ await expect(preview.locator('table')).toHaveCount(3);+ expect(+ await page.evaluate(() => window.signatureFixture.readState().patches)+ ).toEqual([]);+ expect(+ await page.evaluate(+ () => document.documentElement.scrollWidth <= innerWidth+ )+ ).toBe(true);+});++test('import, HTML edits, save, and reopening preserve the future signature', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('button', { name: 'Import from Gmail' }).click();+ await expect(page.getByRole('status')).toHaveText(+ 'Signature imported from Gmail'+ );+ expect(+ await page.evaluate(+ () => window.signatureFixture.readState().savedSignature+ )+ ).toBe(signatureHtml);+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await page.getByRole('button', { name: 'Continue to rich text' }).click();+ await page.getByRole('button', { name: 'Import from Gmail' }).click();+ await expect(+ page.getByRole('region', { name: 'Signature preview for [email protected]' })+ ).toBeVisible();+ await page.getByRole('tab', { name: 'HTML', exact: true }).click();+ const html = page.getByRole('textbox', {+ name: 'Signature HTML for [email protected]',+ });+ await expect(html).toHaveValue(signatureHtml);+ const edited = signatureHtml.replace('Alex Morgan', 'Alex Morgan · Updated');+ await html.fill(edited);+ await page.getByRole('tab', { name: 'Preview', exact: true }).click();+ await expect(+ page.getByText('Alex Morgan · Updated', { exact: true })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature saved');+ expect(+ await page.evaluate(() => window.signatureFixture.readState().patches)+ ).toEqual([{ signature: edited }]);+ await page.getByRole('button', { name: 'Signature', exact: true }).click();+ const outgoing = page.getByRole('region', {+ name: 'Signature preview',+ exact: true,+ });+ await expect(outgoing.getByText('Alex Morgan · Updated')).toBeVisible();+ await expect(outgoing.locator('table table')).toHaveCount(2);+ await page.getByRole('button', { name: 'Leave settings' }).click();+ await page.getByRole('button', { name: 'Reopen settings' }).click();+ await page.getByRole('tab', { name: 'HTML', exact: true }).click();+ await expect(html).toHaveValue(+ await page.evaluate(+ () => window.signatureFixture.readState().savedSignature ?? ''+ )+ );+ await expect(+ page.getByRole('button', { name: 'Save signature' })+ ).toBeDisabled();+});++test('rich text conversion requires consent and cancel leaves HTML untouched', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await expect(page.getByRole('dialog')).toBeVisible();+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();+ await expect(+ page+ .getByRole('region', { name: 'Signature preview for [email protected]' })+ .locator('table table')+ ).toHaveCount(2);+ expect(+ await page.evaluate(() => window.signatureFixture.readState().patches)+ ).toEqual([]);+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await page.getByRole('button', { name: 'Continue to rich text' }).click();+ await expect(+ page.getByRole('textbox', { name: 'Signature for [email protected]' })+ ).toBeVisible();+ await page.getByRole('tab', { name: 'Preview', exact: true }).click();+ await expect(+ page+ .getByRole('region', { name: 'Signature preview for [email protected]' })+ .locator('table table')+ ).toHaveCount(2);+ await expect(+ page.getByRole('button', { name: 'Save signature' })+ ).toBeDisabled();+});++test('saved rich text can be reopened and edited without HTML conversion', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('button', { name: 'Clear signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature removed');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ const editor = page.getByRole('textbox', {+ name: 'Signature for [email protected]',+ });+ await editor.fill('Alex Morgan');+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature saved');+ const preview = page.getByRole('region', {+ name: 'Signature preview for [email protected]',+ });+ await expect(preview.locator('p')).toHaveCSS('margin', '0px');+ await page.getByRole('button', { name: 'Leave settings' }).click();+ await page.getByRole('button', { name: 'Reopen settings' }).click();+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await expect(editor).toBeVisible();+ await editor.fill('Alex Morgan updated');+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(preview.getByText('Alex Morgan updated')).toBeVisible();+ expect(+ await page.evaluate(+ () => window.signatureFixture.readState().savedSignature+ )+ ).toContain('updated');+});++test('partial and logical margins still require HTML conversion', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ for (const style of [+ 'margin-top:0',+ 'margin:0;margin-inline-start:24px',+ 'margin:0!important',+ 'margin:0;margin-left:0!important',+ ]) {+ await page.getByRole('tab', { name: 'HTML', exact: true }).click();+ const html = page.getByRole('textbox', {+ name: 'Signature HTML for [email protected]',+ });+ const source = `<p style="${style}">Custom spacing</p>`;+ await html.fill(source);+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await expect(page.getByRole('dialog')).toBeVisible();+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();+ await expect(html).toHaveValue(source);+ }+ expect(+ await page.evaluate(() => window.signatureFixture.readState().patches)+ ).toEqual([]);+});++for (const saved of [true, false]) {+ test(`clearing a rich text draft with saved signature ${saved} removes the draft`, async ({+ page,+ isMobile,+ }) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ const clear = page.getByRole('button', { name: 'Clear signature' });+ if (!saved) {+ await clear.click();+ await expect(clear).toBeDisabled();+ }+ await page.getByRole('tab', { name: 'Rich text' }).click();+ if (saved)+ await page.getByRole('button', { name: 'Continue to rich text' }).click();+ const editor = page.getByRole('textbox', {+ name: 'Signature for [email protected]',+ });+ await editor.fill('Unsaved signature draft');+ await clear.click();+ await expect(clear).toBeDisabled();+ await expect(+ page.getByRole('button', { name: 'Save signature' })+ ).toBeDisabled();+ expect(+ await page.evaluate(+ () => window.signatureFixture.readState().savedSignature+ )+ ).toBe('');+ await expect(+ page.getByRole('button', { name: 'Signature', exact: true })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Leave settings' }).click();+ await page.getByRole('button', { name: 'Reopen settings' }).click();+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await expect(editor).toBeEmpty();+ await expect(clear).toBeDisabled();+ });+}++test('a finishing clear keeps a newer draft even when its text matches', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('button', { name: 'Clear signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature removed');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ const editor = page.getByRole('textbox', {+ name: 'Signature for [email protected]',+ });+ await editor.fill('First draft');+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature saved');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await editor.fill('Pending draft');+ await page.evaluate(() => window.signatureFixture.holdAccountRefresh());+ await page.getByRole('button', { name: 'Clear signature' }).click();+ // The cache update remounts settings before the mutation's refresh completes.+ await expect(+ page.getByRole('tab', { name: 'Preview', exact: true })+ ).toHaveAttribute('aria-selected', 'true');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await editor.fill('Newer draft');+ await editor.fill('Pending draft');+ await page.evaluate(() => window.signatureFixture.releaseAccountRefresh());+ await expect(page.getByRole('status')).toHaveText('Signature removed');+ await expect(editor).toHaveText('Pending draft');+ await expect(+ page.getByRole('button', { name: 'Save signature' })+ ).toBeEnabled();+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature saved');+ await expect(+ page+ .getByRole('region', { name: 'Signature preview for [email protected]' })+ .getByText('Pending draft')+ ).toBeVisible();+});++test('pasting a custom signature bypasses Quill conversion', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('button', { name: 'Clear signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature removed');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ const editor = page.getByRole('textbox', {+ name: 'Signature for [email protected]',+ });+ await editor.click();+ await editor.evaluate((element, html) => {+ const data = new DataTransfer();+ data.setData('text/html', html);+ data.setData('text/plain', 'Alex Morgan');+ element.dispatchEvent(+ new ClipboardEvent('paste', {+ clipboardData: data,+ bubbles: true,+ cancelable: true,+ })+ );+ }, signatureHtml);+ const preview = page.getByRole('region', {+ name: 'Signature preview for [email protected]',+ });+ await expect(preview.locator('table table')).toHaveCount(2);+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature saved');+ expect(+ await page.evaluate(() =>+ window.signatureFixture.readState().patches.at(-1)+ )+ ).toEqual({ signature: signatureHtml });+});++test('text styling that Quill drops is kept as HTML when pasted', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('button', { name: 'Clear signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature removed');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ const editor = page.getByRole('textbox', {+ name: 'Signature for [email protected]',+ });+ await editor.click();+ const html =+ '<p style="text-align:center;font-weight:500">Centered signature</p>';+ await editor.evaluate((element, html) => {+ const data = new DataTransfer();+ data.setData('text/html', html);+ element.dispatchEvent(+ new ClipboardEvent('paste', {+ clipboardData: data,+ bubbles: true,+ cancelable: true,+ })+ );+ }, html);+ const signature = page+ .getByRole('region', { name: 'Signature preview for [email protected]' })+ .getByText('Centered signature');+ await expect(signature).toHaveCSS('text-align', 'center');+ await expect(signature).toHaveCSS('font-weight', '500');+ await page.getByRole('tab', { name: 'Rich text' }).click();+ await expect(page.getByRole('dialog')).toBeVisible();+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();+ await page.getByRole('button', { name: 'Save signature' }).click();+ await expect(page.getByRole('status')).toHaveText('Signature saved');+ expect(+ await page.evaluate(() =>+ window.signatureFixture.readState().patches.at(-1)+ )+ ).toEqual({ signature: html });+});++test('draft previews strip active markup and isolate signature styles', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Signature editing is desktop-only');+ await page.getByRole('tab', { name: 'HTML', exact: true }).click();+ await page+ .getByRole('textbox', { name: 'Signature HTML for [email protected]' })+ .fill(+ '<style>body {display:none} :host {display:none}</style><p onclick="window.alert(1)">Safe signature</p><img src="x" onerror="window.alert(1)"><script>window.alert(1)</script><a href="javascript:alert(1)">Link</a><iframe srcdoc="bad"></iframe>'+ );+ const dialogs: string[] = [];+ page.on('dialog', async (dialog) => {+ dialogs.push(dialog.message());+ await dialog.dismiss();+ });+ await page.getByRole('tab', { name: 'Preview', exact: true }).click();+ const preview = page.getByRole('region', {+ name: 'Signature preview for [email protected]',+ });+ await expect(preview.getByText('Safe signature')).toBeVisible();+ await expect(+ preview.locator('script,iframe,[onclick],[onerror],a[href^="javascript:"]')+ ).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: 'Save signature' })+ ).toBeVisible();+ expect(dialogs).toEqual([]);+});diff --git a/apps/web/src/features/settings/browser-test/signatures/vite.config.ts b/apps/web/src/features/settings/browser-test/signatures/vite.config.tsnew file mode 100644index 0000000000..027b17024f--- /dev/null+++ b/apps/web/src/features/settings/browser-test/signatures/vite.config.ts@@ -0,0 +1,52 @@+import { fileURLToPath } from 'node:url';+import tailwind from '@tailwindcss/vite';+import { defineConfig } from 'vite';+import solid from 'vite-plugin-solid';+import solidSvg from 'vite-plugin-solid-svg';+import tsconfigPaths from 'vite-tsconfig-paths';++const directory = fileURLToPath(new URL('.', import.meta.url));+const web = fileURLToPath(new URL('../../../../../', import.meta.url));+const workspace = fileURLToPath(+ new URL('../../../../../../../', import.meta.url)+);+const boundary = `${directory}/services.ts`;++export default defineConfig({+ root: directory,+ cacheDir: `${directory}/.vite`,+ plugins: [+ {+ name: 'signature-fixture-services',+ enforce: 'pre',+ resolveId(source, importer) {+ if (+ [+ '@core/component/Toast/Toast',+ '@queries/email/link',+ '@queries/client',+ '@service-email/client',+ '@core/util/uploadFile',+ ].includes(source)+ )+ return boundary;+ if (+ importer?.endsWith('/queries/email/settings.ts') &&+ ['./link', './mail-accounts'].includes(source)+ )+ return boundary;+ },+ },+ solid(),+ solidSvg({ defaultAsComponent: true }),+ tsconfigPaths({ projects: [`${web}/tsconfig.json`] }),+ tailwind(),+ ],+ resolve: { dedupe: ['solid-js'] },+ server: {+ host: '127.0.0.1',+ port: 3098,+ strictPort: true,+ fs: { allow: [workspace] },+ },+});diff --git a/apps/web/src/features/settings/components/signature-form.test.tsx b/apps/web/src/features/settings/components/signature-form.test.tsxindex 94c3f47bb9..78965e28c7 100644--- a/apps/web/src/features/settings/components/signature-form.test.tsx+++ b/apps/web/src/features/settings/components/signature-form.test.tsx@@ -1,8 +1,21 @@import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { afterEach, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { SignatureForm } from './signature-form';-afterEach(cleanup);+beforeEach(() =>+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ )+);+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});const baseProps = {email: '[email protected]',diff --git a/apps/web/src/features/settings/components/signature-form.tsx b/apps/web/src/features/settings/components/signature-form.tsxindex 7e110a70ce..b0f453be6e 100644--- a/apps/web/src/features/settings/components/signature-form.tsx+++ b/apps/web/src/features/settings/components/signature-form.tsx@@ -1,12 +1,9 @@-import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';import DownloadIcon from '@icon/system/regular/download-simple.svg?component-solid';-import SignatureIcon from '@icon/system/regular/signature.svg?component-solid';import { ToggleSwitch } from '@ui';-import { lazy, Show, Suspense } from 'solid-js';+import { Show } from 'solid-js';import { SettingsButton as Button } from '../primitives';--const SignatureEditor = lazy(() => import('../SignatureEditor'));+import { SignatureWorkspace } from './signature-workspace';export function SignatureForm(props: {email: string;@@ -53,31 +50,14 @@ export function SignatureForm(props: {)}</Show></div>- {/* Editing (Quill) is desktop-only; on mobile the section still offers- the replies/forwards toggle and Remove, with a pointer to desktop. */}- <Show- when={!props.mobile}- fallback={- <div class="flex flex-col items-center gap-1.5 rounded-lg border border-dashed border-edge-muted px-3 py-6 text-center">- <SignatureIcon class="size-5 text-ink-muted" />- <p class="text-sm text-ink-muted">- Update your signature on desktop.- </p>- </div>- }- >- <Suspense- fallback={<ListSkeleton.Bar class="h-44 w-full rounded-xl" />}- >- <SignatureEditor- label={`Signature for ${props.email}`}- value={props.value}- disabled={props.pending || props.importing}- onInput={props.onInput}- onReady={props.onReady}- />- </Suspense>- </Show>+ <SignatureWorkspace+ email={props.email}+ value={props.value}+ disabled={props.pending || !!props.importing}+ onInput={props.onInput}+ onReady={props.onReady}+ mobile={props.mobile}+ />{/* Stacks on narrow screens so the toggle label and buttons nevercrowd each other onto wrapped lines. */}<div class="flex flex-col gap-3 @[520px]/signature:flex-row @[520px]/signature:items-center @[520px]/signature:justify-between">diff --git a/apps/web/src/features/settings/components/signature-workspace.tsx b/apps/web/src/features/settings/components/signature-workspace.tsxnew file mode 100644index 0000000000..0cd459eada--- /dev/null+++ b/apps/web/src/features/settings/components/signature-workspace.tsx@@ -0,0 +1,161 @@+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';+import { SignatureContent } from '@app/features/email-compose/components/signature-preview';+import { ConfirmDialog, TabSelector } from '@ui';+import { createSignal, lazy, onMount, Show, Suspense } from 'solid-js';+import { requiresHtmlEditing } from '../core/signature-html';++const SignatureEditor = lazy(() => import('../SignatureEditor'));++export function SignatureWorkspace(props: {+ email: string;+ value: string;+ onInput: (html: string) => void;+ onReady: (api: { setContent: (html: string) => void }) => void;+ disabled: boolean;+ mobile: boolean;+}) {+ const [view, setView] = createSignal('preview');+ const [confirmConversion, setConfirmConversion] = createSignal(false);+ const [pastedHtml, setPastedHtml] = createSignal<string>();+ let editorApi: { setContent: (html: string) => void } | undefined;++ onMount(() =>+ props.onReady({+ setContent: (html) => {+ editorApi?.setContent(html);+ setView('preview');+ },+ })+ );++ const changeView = (next: string) => {+ if (props.disabled) return;+ if (next === 'rich-text' && requiresHtmlEditing(props.value)) {+ setConfirmConversion(true);+ return;+ }+ setView(next);+ };++ const usePastedHtml = (html: string) => {+ props.onInput(html);+ setPastedHtml(undefined);+ setView('preview');+ };++ const preview = () => (+ <Show+ when={props.value.trim()}+ fallback={+ <p class="px-4 py-8 text-center text-sm text-ink-muted">+ {props.mobile+ ? 'No signature saved.'+ : 'Import from Gmail, write in Rich text, or paste your HTML.'}+ </p>+ }+ >+ <SignatureContent+ html={props.value}+ label={`Signature preview for ${props.email}`}+ />+ </Show>+ );++ return (+ <div class="min-w-0">+ <Show+ when={!props.mobile}+ fallback={+ <div class="flex min-w-0 flex-col gap-2">+ {preview()}+ <p class="text-sm text-ink-muted">+ Update your signature on desktop.+ </p>+ </div>+ }+ >+ <TabSelector.Root+ value={view()}+ onChange={changeView}+ class="flex min-w-0 flex-col gap-3"+ >+ <TabSelector>+ <TabSelector.List aria-label={`Signature views for ${props.email}`}>+ <TabSelector.Tab value="preview" disabled={props.disabled}>+ Preview+ </TabSelector.Tab>+ <TabSelector.Tab value="rich-text" disabled={props.disabled}>+ Rich text+ </TabSelector.Tab>+ <TabSelector.Tab value="html" disabled={props.disabled}>+ HTML+ </TabSelector.Tab>+ </TabSelector.List>+ </TabSelector>+ <TabSelector.Panel value="preview" class="min-w-0">+ {preview()}+ </TabSelector.Panel>+ <TabSelector.Panel value="rich-text">+ <Suspense+ fallback={<ListSkeleton.Bar class="h-44 w-full rounded-xl" />}+ >+ <SignatureEditor+ value={props.value}+ label={`Signature for ${props.email}`}+ disabled={props.disabled}+ onInput={props.onInput}+ onReady={(api) => {+ editorApi = api;+ }}+ onPasteHtml={(html) => {+ if (!requiresHtmlEditing(html)) return false;+ if (props.value.trim()) setPastedHtml(html);+ else usePastedHtml(html);+ return true;+ }}+ />+ </Suspense>+ </TabSelector.Panel>+ <TabSelector.Panel value="html" class="flex flex-col gap-2">+ <p class="text-sm text-ink-muted">+ Paste or edit your signature’s HTML to keep its layout. Check+ Preview before saving.+ </p>+ <textarea+ class="settings-input ph-no-capture min-h-52 w-full resize-y py-3 font-mono text-xs"+ aria-label={`Signature HTML for ${props.email}`}+ spellcheck={false}+ value={props.value}+ disabled={props.disabled}+ onInput={(event) => props.onInput(event.currentTarget.value)}+ />+ </TabSelector.Panel>+ </TabSelector.Root>+ <ConfirmDialog+ open={confirmConversion()}+ onOpenChange={setConfirmConversion}+ title="Convert to rich text?"+ body="This signature uses custom HTML. Rich text editing can change its layout, tables, and spacing. Use HTML to keep the original formatting. Your saved signature stays unchanged until you save."+ confirmLabel="Continue to rich text"+ onConfirm={() => {+ setConfirmConversion(false);+ setView('rich-text');+ }}+ />+ <ConfirmDialog+ open={pastedHtml() !== undefined}+ onOpenChange={(open) => {+ if (!open) setPastedHtml(undefined);+ }}+ title="Replace with pasted signature?"+ body="This signature has a custom layout. Keep its HTML formatting and preview it before saving."+ confirmLabel="Use pasted signature"+ onConfirm={() => {+ const html = pastedHtml();+ if (html !== undefined) usePastedHtml(html);+ }}+ />+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/settings/core/signature-html.ts b/apps/web/src/features/settings/core/signature-html.tsnew file mode 100644index 0000000000..a8b87077fa--- /dev/null+++ b/apps/web/src/features/settings/core/signature-html.ts@@ -0,0 +1,69 @@+/** Quill can edit text formatting, but cannot round-trip custom HTML layouts. */+export function requiresHtmlEditing(html: string): boolean {+ const document = new DOMParser().parseFromString(html, 'text/html');+ if (document.head.querySelector('style')) return true;+ const tags = new Set([+ 'P',+ 'BR',+ 'SPAN',+ 'STRONG',+ 'B',+ 'EM',+ 'I',+ 'U',+ 'S',+ 'A',+ 'IMG',+ 'UL',+ 'OL',+ 'LI',+ 'BLOCKQUOTE',+ 'SUB',+ 'SUP',+ 'H1',+ 'H2',+ 'H3',+ 'H4',+ 'H5',+ 'H6',+ ]);+ const attributes = new Set([+ 'style',+ 'href',+ 'target',+ 'rel',+ 'src',+ 'alt',+ 'width',+ 'height',+ ]);+ const styles = new Set([+ 'color',+ 'background-color',+ 'font-family',+ 'font-size',+ ]);+ for (const element of document.body.querySelectorAll<HTMLElement>('*')) {+ if (!tags.has(element.tagName)) return true;+ if (+ [...element.attributes].some(+ (attribute) => !attributes.has(attribute.name)+ )+ )+ return true;+ const hasZeroMargins = element.style.margin === '0px';+ for (const property of element.style) {+ if (element.style.getPropertyPriority(property)) return true;+ // CSSOM expands the editor's margin:0 into these four physical sides.+ if (+ hasZeroMargins &&+ ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'].includes(+ property+ )+ )+ continue;+ if (!styles.has(property)) return true;+ }+ }+ return false;+}diff --git a/apps/web/src/features/settings/email-settings.tsx b/apps/web/src/features/settings/email-settings.tsxindex 0503dcf1fa..e967ad0c7a 100644--- a/apps/web/src/features/settings/email-settings.tsx+++ b/apps/web/src/features/settings/email-settings.tsx@@ -42,7 +42,7 @@ export function EmailSettings() {<Show when={signatures().enabled}><SettingsSectiontitle="Signatures"- description="Create a signature for each of your email accounts. Format text, add links, or insert an image below."+ description="Create a signature for each email account, import from Gmail, or paste your HTML. Preview it before sending."><Suspensefallback={diff --git a/apps/web/src/lib/core/util/safeFetch.ts b/apps/web/src/lib/core/util/safeFetch.tsindex 8979f531cf..7a78605745 100644--- a/apps/web/src/lib/core/util/safeFetch.ts+++ b/apps/web/src/lib/core/util/safeFetch.ts@@ -1,5 +1,5 @@import { SERVER_HOSTS, SYNC_SERVICE_HOSTS } from '@core/constant/servers';-import { Telemetry } from '@macro-inc/observability';+import { type Span, Telemetry } from '@macro-inc/observability';import { err, ok, type Result } from 'neverthrow';import { match } from 'ts-pattern';import { platformFetch } from './platformFetch';@@ -46,7 +46,11 @@ function tracedFetch(if (!url) return platformFetch(input, init);const method = (init.method ?? 'GET').toUpperCase();const path = redactLinkTokens(url.pathname);- const span = Telemetry.clientSpan(`http ${method} ${path}`);+ const span = traceOptions?.parentSpan+ ? traceOptions.parentSpan.run(() =>+ Telemetry.clientSpan(`http ${method} ${path}`)+ )+ : Telemetry.clientSpan(`http ${method} ${path}`);const started = performance.now();span.setAttr('http.method', method);// Path only: query strings can carry tokens.@@ -170,8 +174,10 @@ export interface RetryConfig {delay?: 'exponential' | number;}-/** Trace-only classification for responses that are expected by the caller. */+/** Trace context and response classification, never forwarded to fetch. */export interface SafeFetchTraceOptions {+ /** Restore the action's parent after async auth or mutation scheduling. */+ parentSpan?: Span;/** Non-OK responses that should not mark the HTTP span as failed. */expectedStatusCodes?: readonly number[];}diff --git a/apps/web/src/lib/queries/email/mail-accounts.ts b/apps/web/src/lib/queries/email/mail-accounts.tsindex a94c291d8c..da8529b41f 100644--- a/apps/web/src/lib/queries/email/mail-accounts.ts+++ b/apps/web/src/lib/queries/email/mail-accounts.ts@@ -1,18 +1,50 @@import { normalizedCacheResultMetadata } from '@graphql-cache/exchange/normalized-cache-exchange';+import { type Span, Telemetry } from '@macro-inc/observability';import { MailAccountsDocument } from '@service-storage/graphql/generated/graphql';import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import { createRequest } from '@urql/core';import { createLiveQuery } from '../../graphql-cache/solid/create-live-query';/** Reconcile account edits with mounted composers and the durable catalog. */-export async function refreshMailAccounts(): Promise<void> {- const result = await getGraphqlSoupClient()- .query(MailAccountsDocument, {}, { requestPolicy: 'network-only' })- .toPromise();- // A nullable sendAs error must not discard healthy inboxes or their aliases.- if (!result.data)- throw result.error ?? new Error('Mail accounts refresh returned no data');- const metadata = normalizedCacheResultMetadata(result);- if (metadata?.source === 'live-network') await metadata.persistence;+export function refreshMailAccounts(parentSpan?: Span): Promise<void> {+ const refresh = async (span: Span) => {+ try {+ const client = getGraphqlSoupClient();+ const operation = client.createRequestOperation(+ 'query',+ createRequest(MailAccountsDocument, {}),+ { requestPolicy: 'network-only' }+ );+ const fetch = operation.context.fetch;+ // urql schedules the transport later. Re-enter the refresh context at+ // dispatch, retaining the client's configured authentication/cache host.+ const result = await client+ .executeRequestOperation({+ ...operation,+ context: {+ ...operation.context,+ ...(fetch && {+ fetch: (input: RequestInfo | URL, init?: RequestInit) =>+ span.run(() => fetch(input, init)),+ }),+ },+ })+ .toPromise();+ // A nullable sendAs error must not discard healthy inboxes or their aliases.+ if (!result.data)+ throw (+ result.error ?? new Error('Mail accounts refresh returned no data')+ );+ const metadata = normalizedCacheResultMetadata(result);+ if (metadata?.source === 'live-network') await metadata.persistence;+ } catch (error) {+ span.error('Mail account refresh failed');+ throw error;+ }+ };+ return parentSpan+ ? parentSpan.span('email.settings.refresh', refresh)+ : Telemetry.span('email.settings.refresh', refresh);}/** One identity-scoped GraphQL catalog for inboxes and their verified senders.diff --git a/apps/web/src/lib/queries/email/settings.test.ts b/apps/web/src/lib/queries/email/settings.test.tsindex b228e323a1..ded7d4c422 100644--- a/apps/web/src/lib/queries/email/settings.test.ts+++ b/apps/web/src/lib/queries/email/settings.test.ts@@ -2,6 +2,7 @@ import { createEmailInboxSource } from '@app/features/email-compose/queries/inboimport { normalizedCacheExchange } from '@graphql-cache/exchange/normalized-cache-exchange';import type { CacheHost } from '@graphql-cache/host/types';import { INITIAL_CACHE_REVISION } from '@graphql-cache/protocol';+import { Telemetry } from '@macro-inc/observability';import type { MailAccountsQuery } from '@service-storage/graphql/generated/graphql';import { QueryClient } from '@tanstack/solid-query';import { type Client, createClient, fetchExchange } from '@urql/core';@@ -27,9 +28,6 @@ vi.mock('@service-storage/graphql-soup', () => ({vi.mock('@service-email/client', () => ({emailClient: { patchSettings: fixture.patchSettings },}));-vi.mock('@macro-inc/observability', () => ({- Telemetry: { error: fixture.reportError },-}));vi.mock('../client', () => ({get queryClient() {return queryClient;@@ -156,6 +154,7 @@ function mountComposerAccounts() {beforeEach(() => {vi.clearAllMocks();+ vi.spyOn(Telemetry, 'error').mockImplementation(fixture.reportError);fixture.cacheEnabled = true;queryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },@@ -225,7 +224,8 @@ describe('email settings account reconciliation', () => {signature_on_replies_forwards: false,},},- 'inbox-1'+ 'inbox-1',+ undefined);catalog.goOffline();diff --git a/apps/web/src/lib/queries/email/settings.ts b/apps/web/src/lib/queries/email/settings.tsindex b426fc7eb6..7c98b4be3e 100644--- a/apps/web/src/lib/queries/email/settings.ts+++ b/apps/web/src/lib/queries/email/settings.ts@@ -1,5 +1,5 @@import { throwOnErr } from '@core/util/result';-import { Telemetry } from '@macro-inc/observability';+import { type Span, Telemetry } from '@macro-inc/observability';import { queryClient } from '@queries/client';import {emailClient,@@ -16,7 +16,33 @@ import { emailKeys } from './keys';import { useNonPrimaryEmailLinkIdHeader } from './link';import { refreshMailAccounts } from './mail-accounts';-type UpdateSettingsVars = { linkId: string; settings: Settings };+type UpdateSettingsVars = { linkId: string; settings: Settings; span?: Span };++/** Keep the user action active through mutateAsync's write and success hooks. */+export function traceSignatureMutation(+ operation: 'save' | 'clear' | 'import',+ linkId: string,+ mutate: (+ span: Span+ ) => Promise<PatchSettingsResponse | ImportGmailSignatureResult>+): Promise<void> {+ return Telemetry.span(`email.signature.${operation}`, async (span) => {+ span.setAttr('email.link.id', linkId);+ try {+ const result = await mutate(span);+ const outcome =+ 'success' in result && !result.success ? result.reason : 'success';+ span.setAttr('email.signature.outcome', outcome);+ if (outcome === 'error' || outcome === 'unresolved_images')+ span.error(`Signature import failed: ${outcome}`);+ } catch {+ // The mutation hook owns user feedback. Never trace signature content or+ // provider errors, which may contain private addresses or image URLs.+ span.setAttr('email.signature.outcome', 'error');+ span.error('Signature mutation failed');+ }+ });+}type UpdateSettingsCallbacks = MutationCallbacks<PatchSettingsResponse,@@ -36,14 +62,14 @@ export function useUpdateEmailSettingsMutation() {const toHeaderLinkId = useNonPrimaryEmailLinkIdHeader();return useMutation(() => ({- mutationFn: async ({ linkId, settings }: UpdateSettingsVars) =>+ mutationFn: async ({ linkId, settings, span }: UpdateSettingsVars) =>throwOnErr(() =>- emailClient.patchSettings({ settings }, toHeaderLinkId(linkId))+ emailClient.patchSettings({ settings }, toHeaderLinkId(linkId), span)),...withCallbacks<PatchSettingsResponse, Error, UpdateSettingsVars>({- onSuccess: async (result, { linkId, settings }) => {+ onSuccess: async (result, { linkId, settings, span }) => {queryClient.setQueryData<ListLinksResponse>(emailKeys.links.queryKey,(old) =>@@ -73,7 +99,7 @@ export function useUpdateEmailSettingsMutation(// The REST write has committed. A failed catalog refresh must not// turn it into a failed settings mutation or prompt another save.try {- await refreshMailAccounts();+ await refreshMailAccounts(span);} catch (error) {Telemetry.error(error instanceof Error ? error : new Error(String(error))@@ -86,7 +112,7 @@ export function useUpdateEmailSettingsMutation(}));}-type ImportGmailSignatureVars = { linkId: string };+type ImportGmailSignatureVars = { linkId: string; span?: Span };export type ImportGmailSignatureResult =| { success: true; settings: Settings }@@ -113,9 +139,11 @@ export function useImportGmailSignatureMutation(return useMutation(() => ({mutationFn: async ({linkId,+ span,}: ImportGmailSignatureVars): Promise<ImportGmailSignatureResult> => {const result = await emailClient.importGmailSignature(- toHeaderLinkId(linkId)+ toHeaderLinkId(linkId),+ span);return result.match((response) => ({ success: true, settings: response.settings }),@@ -136,7 +164,7 @@ export function useImportGmailSignatureMutation(ImportGmailSignatureVars>({- onSuccess: async (result, { linkId }) => {+ onSuccess: async (result, { linkId, span }) => {if (!result.success) return;queryClient.setQueryData<ListLinksResponse>(emailKeys.links.queryKey,@@ -155,7 +183,7 @@ export function useImportGmailSignatureMutation(: old);try {- await refreshMailAccounts();+ await refreshMailAccounts(span);} catch (error) {Telemetry.error(error instanceof Error ? error : new Error(String(error))diff --git a/apps/web/src/lib/service-clients/service-email/client.test.ts b/apps/web/src/lib/service-clients/service-email/client.test.tsnew file mode 100644index 0000000000..d2af33512b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-email/client.test.ts@@ -0,0 +1,22 @@+import { ok } from 'neverthrow';+import { expect, it, vi } from 'vitest';++const fetchWithToken = vi.hoisted(() => vi.fn());+vi.mock('@core/constant/servers', () => ({+ SERVER_HOSTS: {+ 'email-service': 'https://gateway.example/email',+ 'calendar-service': 'https://gateway.example/calendar',+ },+}));+vi.mock('@core/util/fetchWithToken', () => ({ fetchWithToken }));++import { emailClient } from './client';++it('scopes settings polling to the inbox and adds the email host once', async () => {+ fetchWithToken.mockResolvedValue(ok([]));+ await emailClient.settingsOperations('inbox-1');+ expect(fetchWithToken).toHaveBeenCalledWith(+ 'https://gateway.example/email/email/settings/operations',+ { headers: { 'X-Email-Link-Id': 'inbox-1' } }+ );+});diff --git a/apps/web/src/lib/service-clients/service-email/client.ts b/apps/web/src/lib/service-clients/service-email/client.tsindex ac194a95ed..39d0413cea 100644--- a/apps/web/src/lib/service-clients/service-email/client.ts+++ b/apps/web/src/lib/service-clients/service-email/client.ts@@ -5,6 +5,7 @@ import {} from '@core/util/fetchWithToken';import type { ObjectLike, ResultError } from '@core/util/result';import type { SafeFetchInit } from '@core/util/safeFetch';+import type { Span } from '@macro-inc/observability';import type {CalendarEvent,CalendarEventProviderUrl,@@ -161,10 +162,9 @@ export const SIGNATURE_IMAGES_UNRESOLVED_CODE =export const emailClient = {settingsOperations: (linkId: string) =>- emailFetch<MailboxSettingsOperation[]>(- `${emailHost}/email/settings/operations`,- { headers: emailLinkHeaders(linkId) }- ),+ emailFetch<MailboxSettingsOperation[]>('/email/settings/operations', {+ headers: emailLinkHeaders(linkId),+ }),async threadOperations(threadId: string) {return emailFetch<import('./generated/schemas').MailboxOperation[]>(@@ -463,7 +463,11 @@ export const emailClient = {// Patches the settings for one inbox. Scoped to `linkId` via the// X-Email-Link-Id header (the backend resolves the link from it); omit for// the primary inbox. Partial: fields omitted from `settings` are left as-is.- async patchSettings(args: PatchSettingsRequest, linkId?: string) {+ async patchSettings(+ args: PatchSettingsRequest,+ linkId?: string,+ parentSpan?: Span+ ) {return fetchWithToken<PatchSettingsResponse,typeof SIGNATURE_IMAGES_UNRESOLVED_CODE@@ -471,6 +475,7 @@ export const emailClient = {method: 'PATCH',body: JSON.stringify(args),headers: emailLinkHeaders(linkId),+ trace: { parentSpan },// The 422 body carries how many signature images couldn't be loaded;// surface it as the error message so the caller can prompt a re-add.// Other statuses fall back to the default HTTP_ERROR shape.@@ -922,13 +927,14 @@ export const emailClient = {);},- async importGmailSignature(linkId?: string) {+ async importGmailSignature(linkId?: string, parentSpan?: Span) {return fetchWithToken<PatchSettingsResponse,'NO_SIGNATURE_FOUND' | typeof SIGNATURE_IMAGES_UNRESOLVED_CODE>(`${emailHost}/email/settings/import-signature`, {method: 'POST',headers: emailLinkHeaders(linkId),+ trace: { parentSpan },errorResponseHandler: async (response) => {if (response.status === 404) {return { code: 'NO_SIGNATURE_FOUND' as const, message: '' };diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex c54eef1c69..da9dd748d0 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -60,22 +60,48 @@ live-backend release gates and documents staging retention and recovery.### Email signatures-Open **Settings → Email → Signatures**. Each owned inbox has a visible editor;-there is no expand/collapse control. Format the text, add links or images, and-choose **Save signature**. **Clear signature** removes only the signature, while+Open **Settings → Email → Signatures**. Each owned inbox opens in **Preview**,+using the same isolated HTML renderer as the email composer. **HTML** lets you+paste or edit a custom signature without flattening its tables or spacing.+**Rich text** offers text formatting, links, and image uploads; opening a custom+HTML layout there asks before converting it. Switching views alone never changes+the saved signature. Pasting a custom layout into Rich text preserves its HTML+and opens Preview (ask to replace first when the editor already has content).+Choose **Save signature** to save edits and return to the canonical preview.+**Clear signature** removes the saved signature and the current unsaved draft;+after clearing, reopening Rich text starts empty. It leaves the inbox connected, while**Remove inbox** in Accounts uses the existing inbox removal confirmation.**Add to replies & forwards** saves that preference immediately. On desktop,**Import from Gmail** in each inbox's header fetches that account's Gmailsignature and saves it right away, replacing any unsaved draft; a toast reportswhen Gmail has no signature. Unsaved drafts-survive switching settings pages. On phones, signature editing remains desktop-only;-the replies/forwards toggle and clear action are available.+survive switching settings pages. On phones, the signature preview, replies/forwards+toggle, and clear action are available; editing and import remain desktop-only.Email accounts can also be managed from **Integrations**. Its **Email settings**gear opens the dedicated page, and Email links to Notifications and Calendar.With a composer open, save a changed signature or reply-signature preference andverify its preview updates. Once the account refresh completes, reopen a composeroffline and confirm it uses the saved settings.+Regression check: import a nested-table signature, edit its source in HTML,+preview, save, leave settings, and reopen. Confirm the tables, spacing, and image+sizes survive in both settings and the new-message preview. Cancel a Rich text+conversion and verify the saved HTML is unchanged. Check the preview on a phone+and ensure a wide signature scrolls inside its own preview instead of the page.+Save a signature created in Rich text, reopen settings, and confirm Rich text+editing resumes without a conversion prompt.+Type an unsaved Rich text draft and clear it, both with and without an existing+saved signature. Reopen settings and confirm the editor stays empty and the+composer no longer includes a signature. A delayed clear must preserve a newer+draft, even if its text matches the old draft. HTML with `!important` styles must+still ask before conversion to Rich text. The backend-free browser suite uses+the real form, Quill, settings mutations, account-list remounts, query cache,+and composer preview with fixture services:+`bunx playwright test --config src/features/settings/browser-test/signatures/playwright.config.ts`.+Trace signature actions under `email.signature.save`, `email.signature.clear`,+or `email.signature.import`; the REST write and `email.settings.refresh` run+under that action, including the account catalog's durable refresh.+### Notification permission promptAfter onboarding, an eligible desktop app user sees **Enable Desktop