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-compose): preview the reply signature above the quoted text (#8805)
teob8a367b111e6
diff --git a/apps/web/src/features/email-compose/context/compose-capabilities.ts b/apps/web/src/features/email-compose/context/compose-capabilities.tsindex d20c15d9fb..f7d4b72192 100644--- a/apps/web/src/features/email-compose/context/compose-capabilities.ts+++ b/apps/web/src/features/email-compose/context/compose-capabilities.ts@@ -238,7 +238,8 @@ export interface OutgoingEmail {/*** One queued send as this device's outbox last recorded it. `accepted` is* cancellable until the server's `undoUntil`; `pending` covers waiting,- * delivering, and cancellation in progress.+ * delivering, and cancellation in progress. `untracked` means the send left+ * the outbox and the server could not say whether it was delivered.*/export type EmailSendProgress =| { state: 'pending' }@@ -246,7 +247,8 @@ export type EmailSendProgress =| { state: 'sent' }| { state: 'failed' }| { state: 'cancelled' }- | { state: 'unconfirmed' };+ | { state: 'unconfirmed' }+ | { state: 'untracked' };export interface EmailDelivery {/** Whether sends can be persisted and replayed without connectivity. */diff --git a/apps/web/src/features/email-compose/primitives/queued-send-notice.ts b/apps/web/src/features/email-compose/primitives/queued-send-notice.tsindex 8a006a5b16..009cf354e8 100644--- a/apps/web/src/features/email-compose/primitives/queued-send-notice.ts+++ b/apps/web/src/features/email-compose/primitives/queued-send-notice.ts@@ -83,6 +83,7 @@ export function announceQueuedSend(options: {subtext: 'Check your sent mail. We will not resend automatically.',});})+ .with({ state: 'untracked' }, withdrawUndo).exhaustive());}diff --git a/apps/web/src/features/email-compose/queries/send-progress.test.ts b/apps/web/src/features/email-compose/queries/send-progress.test.tsindex 55eba680b3..54f9bab8b4 100644--- a/apps/web/src/features/email-compose/queries/send-progress.test.ts+++ b/apps/web/src/features/email-compose/queries/send-progress.test.ts@@ -8,12 +8,17 @@ import {cancelEmailSendQueued,type EmailSendIntent,} from '@queries/email/send-queue';+import { readEmailSendStatus } from '@service-storage/email-send';import type { EmailSendAttemptFieldsFragment } from '@service-storage/graphql/generated/graphql';import { CombinedError } from '@urql/core';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import type { EmailSendProgress } from '../context/compose-capabilities';import { watchEmailSendProgress } from './send-progress';+vi.mock('@service-storage/email-send', () => ({+ readEmailSendStatus: vi.fn(),+}));+vi.mock('@queries/email/local-drafts', async () => {const { createLocalDraftStore } = await import('@queries/email/local-draft-store'@@ -141,6 +146,29 @@ function dispatch(return runner;}+/** Another tab delivers the send and retires it before this tab reads the outbox again. */+async function deliverInAnotherTab(+ session: Awaited<ReturnType<typeof emailStorageSession>>,+ queued: EmailSendIntent+) {+ const claimed = await localDraftStore.claimSend(+ session,+ queued.uuid,+ 'other-tab',+ Date.now()+ );+ if (!claimed?.dispatch) throw new Error('The other tab did not claim it');+ const settled = localDraftStore.settleSend(+ session,+ queued.uuid,+ 'other-tab',+ claimed.dispatch.generation,+ { attempt: attempt(queued, 'SENT'), nextAttemptAt: Date.now() }+ );+ await localDraftStore.removeSend(session, queued.uuid);+ await settled;+}+it.each(inboxes)('reports a $provider send as undoable until the server deadline, then failed',async (inbox) => {@@ -246,3 +274,38 @@ it.each(inboxes)(]);});++it.each(inboxes)(+ 'reports a $provider send another tab delivered and retired as sent',+ async (inbox) => {+ const { session, queued, progress } = await queue(inbox);+ await progress.reached('pending');+ vi.mocked(readEmailSendStatus).mockImplementation(async (input) =>+ input.attemptId === queued.uuid && input.linkId === inbox.linkId+ ? attempt(queued, 'SENT')+ : null+ );+ await deliverInAnotherTab(session, queued);+ await progress.reached('sent');++ expect(progress.updates).toEqual([{ state: 'pending' }, { state: 'sent' }]);+ }+);++it.each(inboxes)(+ 'stops following a $provider send that left the outbox when the server cannot say how',+ async (inbox) => {+ const { session, queued, progress } = await queue(inbox);+ await progress.reached('pending');+ vi.mocked(readEmailSendStatus).mockRejectedValue(+ new TypeError('Failed to fetch')+ );+ await deliverInAnotherTab(session, queued);+ await progress.reached('untracked');++ expect(progress.updates).toEqual([+ { state: 'pending' },+ { state: 'untracked' },+ ]);+ }+);diff --git a/apps/web/src/features/email-compose/queries/send-progress.ts b/apps/web/src/features/email-compose/queries/send-progress.tsindex c9571ffcda..4b250838b5 100644--- a/apps/web/src/features/email-compose/queries/send-progress.ts+++ b/apps/web/src/features/email-compose/queries/send-progress.ts@@ -3,11 +3,12 @@ import { fireAndForget } from '@core/util/fireAndForget';import {type EmailSendIntent,emailSendLocked,+ fetchEmailSendStatus,readEmailSendIntents,settledSendAttempt,watchEmailSends,} from '@queries/email/send-queue';-import { recordEmailSend } from '@queries/email/send-telemetry';+import { recordEmailSend, traceEmailSend } from '@queries/email/send-telemetry';import type { EmailSendProgress } from '../context/compose-capabilities';function emailSendProgress(intent: EmailSendIntent): EmailSendProgress {@@ -29,13 +30,41 @@ function emailSendProgress(intent: EmailSendIntent): EmailSendProgress {return { state: 'pending' };}+/** The outbox drops a send only once it is sent, or when it restores a cancelled one. */+async function departedSendProgress(+ seen: EmailSendIntent | undefined,+ started: number+): Promise<EmailSendProgress> {+ if (!seen) return { state: 'untracked' };+ const attempt = await traceEmailSend(+ 'status',+ seen.metadata.payload.input.attempt,+ () => fetchEmailSendStatus(seen)+ );+ recordEmailSend(+ {+ operation: 'status',+ outcome: 'observed',+ status: attempt?.status,+ durationMs: performance.now() - started,+ },+ seen+ );+ if (attempt?.status === 'SENT') return { state: 'sent' };+ // A restored send was cancelled, or never reached the server.+ if (!attempt || attempt.status === 'CANCELLED') return { state: 'cancelled' };+ return { state: 'untracked' };+}+export function watchEmailSendProgress(sendAttemptId: string,changed: (progress: EmailSendProgress) => void): () => void {const started = performance.now();let last: EmailSendProgress | undefined;+ let seen: EmailSendIntent | undefined;let stopped = false;+ let disposed = false;let reading = false;let rerun = false;const stop = () => {@@ -47,8 +76,18 @@ export function watchEmailSendProgress((row) => row.uuid === sendAttemptId);if (stopped) return;- // Retired after delivery or restored after cancellation, possibly by another tab.- if (!intent) return stop();+ // Another tab can retire or restore the send before this one reads it.+ if (!intent) {+ stop();+ let progress: EmailSendProgress = { state: 'untracked' };+ try {+ progress = await departedSendProgress(seen, started);+ } finally {+ if (!disposed) changed(progress);+ }+ return;+ }+ seen = intent;const progress = emailSendProgress(intent);if (last && deepEqual(last, progress)) return;last = progress;@@ -91,5 +130,8 @@ export function watchEmailSendProgress(};const unsubscribe = watchEmailSends(refresh);refresh();- return stop;+ return () => {+ disposed = true;+ stop();+ };}diff --git a/apps/web/src/features/email-compose/views/reply-input.tsx b/apps/web/src/features/email-compose/views/reply-input.tsxindex 9e194d9eec..bb40f272e2 100644--- a/apps/web/src/features/email-compose/views/reply-input.tsx+++ b/apps/web/src/features/email-compose/views/reply-input.tsx@@ -255,10 +255,6 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {const isMobileCompose = () => props.mobileCompose !== undefined;const composePortalScope = () =>isMobileCompose() ? ('local' as const) : undefined;- const scrollAreaSignatureHtml = () =>- isMobileCompose() ? signatureHtml() : undefined;- const footerSignatureHtml = () =>- isMobileCompose() ? undefined : signatureHtml();// File sharing and editor plugin wiring belong to this view. The controller only// needs to know when editor content has changed and requires another save.const editorConfig = buildConfig('markdown')@@ -462,6 +458,25 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {</Show>);+ const SignatureRow = () => (+ <Show when={signatureHtml()}>+ {(html) => (+ <SignaturePreview+ mobile={composeContext.presentation.isMobile()}+ prepareLinks={composeContext.presentation.prepareSignatureLinks}+ html={html()}+ dismissable={!editingDisabled()}+ onDismiss={() => {+ // Dismissal is composer-local state worth keeping — latch+ // the seed so a draft upgrade can't remount it away.+ props.onEngaged?.();+ setIncludeSignature(false);+ }}+ />+ )}+ </Show>+ );+const AttachButton = () => (<Buttonvariant="ghost"@@ -708,26 +723,14 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {</Show><Show when={isMobileCompose()}><AttachmentsRow />- </Show>- <Show when={scrollAreaSignatureHtml()}>- {(html) => (- <SignaturePreview- mobile={composeContext.presentation.isMobile()}- prepareLinks={- composeContext.presentation.prepareSignatureLinks- }- html={html()}- dismissable={!editingDisabled()}- onDismiss={() => {- // Dismissal is composer-local state worth keeping — latch- // the seed so a draft upgrade can't remount it away.- props.onEngaged?.();- setIncludeSignature(false);- }}- />- )}+ <SignatureRow /></Show></div>+ {/* Sending inserts the signature above the quoted thread, so the+ preview stays above the quoted-text controls. */}+ <Show when={!isMobileCompose()}>+ <SignatureRow />+ </Show>{/* Quoted-text controls live below the scroll area so they stayanchored to the composer bottom instead of scrolling with (andfloating over) tall content. */}@@ -779,25 +782,7 @@ function LoadedReplyInputView(props: ReplyInputViewProps) {<Show when={!isMobileCompose()}>{/* Below the scroll area so quoted email content can never overlap it */}<AttachmentsRow class="px-4" />- <Show when={footerSignatureHtml()}>- {(html) => (- <SignaturePreview- mobile={composeContext.presentation.isMobile()}- prepareLinks={- composeContext.presentation.prepareSignatureLinks- }- html={html()}- dismissable={!editingDisabled()}- onDismiss={() => {- // Dismissal is composer-local state worth keeping — latch- // the seed so a draft upgrade can't remount it away.- props.onEngaged?.();- setIncludeSignature(false);- }}- />- )}- </Show>- {/* Keep the footer intrinsic-height so it cannot overlap the signature. */}+ {/* Keep the footer intrinsic-height so it cannot overlap the rows above it. */}<divref={bottomBarRef}class="shrink-0 flex min-w-0 justify-end pt-1.5"diff --git a/apps/web/src/features/email-compose/views/reply-signature-order.test.tsx b/apps/web/src/features/email-compose/views/reply-signature-order.test.tsxnew file mode 100644index 0000000000..a304bdeaff--- /dev/null+++ b/apps/web/src/features/email-compose/views/reply-signature-order.test.tsx@@ -0,0 +1,211 @@+import { cleanup, render, screen } from '@solidjs/testing-library';+import { createSignal, type JSX, onMount } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { message } from '../../email-message/tests/messages';+import type { EmailInbox } from '../context/compose-capabilities';+import { EmailFormContextProvider } from '../context/email-form-context';+import type { ReplyType } from '../core/reply-type';+import { createComposeContext } from '../tests/capabilities';+import { createEmailEditor } from '../tests/editor';+import { ReplyInputView } from './reply-input';++// Keep the real view, reply composer and signature preview. Stub only+// app-owned editor plugins and presentation unrelated to the layout order.+vi.mock('@core/hotkey/hotkeys', () => ({+ registerHotkey: vi.fn(),+ useHotkeyDOMScope: () => [() => {}, 'reply'],+}));+vi.mock(+ '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder',+ () => ({+ buildConfig: () => {+ const config = {+ withAppLinkResolver: () => config,+ namespace: () => config,+ withMentions: () => config,+ withEmojis: () => config,+ withLinks: () => config,+ withHistory: () => config,+ withMedia: () => config,+ withCode: () => config,+ withCheckboxToTask: () => config,+ withRestoreFocus: () => config,+ withSelectionData: () => config,+ withFloatingFormatMenu: () => config,+ use: () => config,+ onChange: () => config,+ withFilePaste: () => config,+ buildHandle: () => ({ lexical: createEmailEditor('Sounds good') }),+ };+ return config;+ },+ })+);+vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({+ MarkdownShell: (props: { onConnect?: () => void }) => {+ onMount(() => props.onConnect?.());+ return <div role="textbox" aria-label="Message" />;+ },+}));+vi.mock('@components/app/split-layout/split-router/mention-links', () => ({+ useMacroMentionLinkResolver: () => undefined,+}));+vi.mock('@ui', () => ({+ cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),+ Surface: (props: JSX.HTMLAttributes<HTMLDivElement>) => (+ <div ref={props.ref}>{props.children}</div>+ ),+ Tooltip: (props: { children: JSX.Element }) => props.children,+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),+ SendButton: () => <button>Send</button>,+}));+vi.mock('../components/mobile-reply-toolbar', () => ({+ MobileReplyToolbar: () => null,+}));+vi.mock('../components/draft-back-menu', () => ({ DraftBackMenu: () => null }));+vi.mock('../components/attachment-viewer', () => ({+ createAttachmentViewer: () => ({}),+}));+vi.mock('../components/draft-sync-status', () => ({+ DraftSyncStatus: () => null,+}));+vi.mock('../components/email-schedule-summary', () => ({+ EmailScheduleBar: () => null,+ EmailScheduleSummary: () => null,+}));+vi.mock('./reply-envelope', () => ({ ReplyEnvelope: () => null }));+vi.mock('@core/component/FileDropOverlay', () => ({+ FileDropOverlay: () => null,+}));+vi.mock('@core/directive/fileFolderDrop', () => ({ fileFolderDrop: () => {} }));+vi.mock('@core/mobile/useTouchOutsideToDismissKeyboard', () => ({+ useTouchOutsideToDismissKeyboard: () => {},+}));++afterEach(cleanup);++const parent = message('parent', {+ from: { name: 'Ada Lovelace', email: '[email protected]' },+ to: [{ email: '[email protected]' }],+ subject: 'Numbers',+ body_html_sanitized: '<p>Original message text</p>',+});++function mount(+ provider: EmailInbox['provider'],+ layout: 'desktop' | 'mobile',+ replyType: ReplyType+) {+ const context = createComposeContext();+ context.accounts.inboxes = () => [+ {+ id: 'inbox',+ email_address: '[email protected]',+ provider,+ settings: {+ signature: '<p>Regards, Me</p>',+ signature_on_replies_forwards: true,+ },+ },+ ];+ context.presentation.signaturesEnabled = () => true;+ context.presentation.scheduleEnabled = false;+ context.presentation.isTouch = () => layout === 'mobile';+ context.presentation.isMobile = () => layout === 'mobile';+ const [requested, setRequested] = createSignal<ReplyType | undefined>(+ replyType+ );+ render(() => (+ <EmailFormContextProvider+ context={{+ viewerEmail: context.viewerEmail,+ inboxes: context.accounts.inboxes,+ }}+ formOptions={{+ getMessageById: () => parent,+ getDraftForMessageReply: () => undefined,+ }}+ >+ <ReplyInputView+ context={context}+ sourceEntityId="thread"+ replyingTo={() => parent}+ session={{+ thread: () => ({+ db_id: 'thread',+ link_id: 'inbox',+ inbox_visible: true,+ }),+ recipientOptions: () => [],+ isPersonalReply: () => false,+ onDraftRemoved() {},+ exitToThread: () => false,+ replyRequest: {+ replyType: requested,+ clear: () => setRequested(undefined),+ },+ }}+ mobileCompose={+ layout === 'mobile'+ ? {+ portalMount: () => undefined,+ onClose() {},+ registerClose() {},+ }+ : undefined+ }+ />+ </EmailFormContextProvider>+ ));+}++/** Names the composer rows in the order a reader meets them. */+function readingOrder(rows: Record<string, Element>) {+ return Object.entries(rows)+ .sort(([, a], [, b]) =>+ a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1+ )+ .map(([name]) => name);+}++const cases = (['GMAIL', 'OUTLOOK'] as const).flatMap((provider) =>+ (['desktop', 'mobile'] as const).map((layout) => ({ provider, layout }))+);++// Sending inserts the signature above the quoted thread for both providers,+// so the preview has to sit between the message and the quote controls.+it.each(cases)(+ 'previews the $provider reply signature above the quoted text on $layout',+ async ({ provider, layout }) => {+ mount(provider, layout, 'reply');++ const quote = await screen.findByRole('button', { name: 'quoted text' });+ expect(+ readingOrder({+ quote,+ signature: screen.getByRole('button', { name: 'Signature' }),+ message: screen.getByRole('textbox', { name: 'Message' }),+ })+ ).toEqual(['message', 'signature', 'quote']);+ }+);++it.each(cases)(+ 'previews the $provider forward signature above the forwarded message on $layout',+ async ({ provider, layout }) => {+ mount(provider, layout, 'forward');++ const forwarded = await screen.findByRole('button', {+ name: 'Show forwarded message',+ });+ expect(+ readingOrder({+ forwarded,+ signature: screen.getByRole('button', { name: 'Signature' }),+ message: screen.getByRole('textbox', { name: 'Message' }),+ })+ ).toEqual(['message', 'signature', 'forwarded']);+ }+);diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex cfb0ef5e91..1d9d7d5631 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -622,6 +622,9 @@ without the forwarded message. A reply quoting a message that was itselfforwarded stays a reply. Collapsed content is named: **Show forwarded message**on a forward, **Show quoted text** on a reply. The toggle beside the editor keepsthe name `forwarded message` or `quoted text` and reports whether it is pressed.+With **Add to replies & forwards** on, the **Signature** bar sits between the+written message and these controls on desktop and mobile, where sending inserts+the signature above the quoted thread on Gmail and Outlook.Check recipient suggestions from a Gmail and an Outlook inbox. Typing a fulladdress and pressing Enter commits that address, ahead of longer matches suchas `[email protected]`, whether or not it is a saved contact. A name or@@ -826,7 +829,10 @@ conversation and a reply closes its composer, and the message appears as sentthere immediately, before the server or provider confirms it. Once the serveraccepts the send, **Undo** stays on offer until the server's undo deadline (theaccepted attempt's `sendTime`), not for a fixed client duration. The notice says-**Email sent** only after delivery. A send that fails after it was queued shows+**Email sent** only after delivery. This holds when another Mail tab delivers or+cancels the send first, and a cancelled reply still returns its thread to Inbox.+When the server cannot say how such a send ended, the notice only withdraws+**Undo**. A send that fails after it was queued showsa persistent **Email failed to send**, and **Delivery unconfirmed** reports asend the provider did not confirm. An offline send shows **Email queued tosend** and returns to the email list. The status panel shows a send only while it waits on thisdiff --git a/docs/architecture/email.md b/docs/architecture/email.mdindex aebe13c95c..e4c70f74a1 100644--- a/docs/architecture/email.md+++ b/docs/architecture/email.md@@ -287,7 +287,10 @@ The send notice follows each queued send through `EmailDelivery.watchSend`,which reads the device outbox. Undo stays on offer until the deadline the serverreturned with the accepted attempt. A reply whose send fails, is cancelled, or isrestored reverses its mark-done through the same undo handle, including when-marking done finishes later.+marking done finishes later. A send can leave the outbox before the watcher reads+it again, as when another tab delivers or restores it. The watcher then asks the+server how the send ended. When the server cannot say, it reports the send as+`untracked` and the notice withdraws Undo.`EmailThreadSource.refresh()` and `fetchOlder()` require `Promise<void>`. Theiradapters await the underlying query, and callers that need fresh messages await