apps/mail is the standalone Tuturuuu mailbox app. It runs on
https://mail.tuturuuu.com in production and port 7820 locally, delegates
auth to apps/web, and preserves Tuturuuu workspace and mailbox-role checks.
Platform operators may configure additional managed domains; a mailbox address
must match its linked private.mail_domains row.
Managed send outcomes
Managed mailbox sends reserve the draft atomically before provider dispatch. An exception or an unknown delivery outcome retains thesending claim; the
message is not marked failed and replaying its ID cannot dispatch it again.
Only a confirmed rejection is marked failed. Provider acceptance is recorded
as sent; persistence errors never release the claim for another delivery.
Public send exceptions return MAIL_SEND_UNCONFIRMED without provider details.
Operators must reconcile uncertain messages with provider records before any
manual recovery. This applies to managed Mail API consumers; connected accounts
retain their separate uncertain claim contract.
Regression coverage: apps/mail/src/lib/mail/repository/send-claim.test.ts.
Flutter Mail
The mobile Apps hub exposes Mail to exact@tuturuuu.com accounts, genuine
managed subdomain accounts, and tagged
reviewer accounts on the routed @tutur3u.com domain. Discovery from mobile
session metadata is only a hint: the Mail API checks the live administrator
reviewer tag, active account, workspace membership, and personal workspace on
every request. Subdomain admission additionally requires current confirmed Auth
and an existing active owned personal mailbox; discovery alone grants no access.
Reviewers cannot access shared or staff mailboxes. The review
domain has an active Mail domain row for personal mailbox bootstrap; the exact
reviewer address is forwarded to the verified QA inbox for login codes. The
Mail UI defaults to the reviewer’s own personal workspace.
Its API client
routes workspace Mail requests directly to mail.tuturuuu.com (port 7820 in
development), with an optional MAIL_API_BASE_URL build override. Bearer API
requests skip browser-cookie refresh in the Mail proxy but still pass the API
guard and route-level workspace and mailbox authorization.
The native client supports mailbox switching, paginated conversations, search,
standard folders, labels and custom folders, read/star/archive/trash actions,
bounded bulk actions, and folder-wide mark-read. Drafts retain their server ID,
recipients, reply headers and attachments. Closing saves pending edits; a failed
save keeps the editor open. Composer attachments use bounded authenticated
uploads, and forwarding copies attachments through the authorized draft API.
Rich-text composition uses Quill and exports email HTML through the same draft
and send contracts as the web client. Untouched saved HTML is preserved. AI
results require review before replacing the editor content and never send mail
automatically. Owners and admins can manage mailbox settings, forwarding,
smart-label configuration, custom folders/labels and group membership.
Account or workspace changes dispose the entire Mail navigation stack. Attachment
downloads reject redirects and oversized responses. Original HTML renders in an
isolated, script-disabled web view. Remote images follow the saved Mail image
preference, which is on until the user turns it off; notification-opened
readers suppress them until revealed (see
Mail inbound notifications).
Downloaded attachments use the device’s native share sheet.
Run ttr resources run -- bun check:mobile after native changes, and the Mail
proxy auth tests plus the actual Mail build after auth-routing changes. Unit and
widget checks do not prove real-provider sending, receiving, or store delivery;
verify those separately with the intended authenticated account.
Tablet reading pane and instant open
Scope: the Flutter Mail inbox on every platform. When the Mail body is at least 720dp wide (landscape tablets, portrait tablets 800dp and wider beside the 80dp rail, desktops), the inbox list and the open conversation sit side by side. Without a selection, the pane shows a localized empty state. Narrower bodies keep the pushed reader. The open conversation survives rotation and window resizing, moving between the pane and the pushed reader. Notification deep links open in the pane on wide layouts. On wide layouts, the first Back (dock, rail or system) and Escape close the pane; the next Back leaves Mail. The pane’s action bar holds Reply, Reply all and Forward, then the default action, More and Close; the shell navbar and dock keep the inbox title, filters and actions. As on web Mail, the list takes 38% of the split by default; a drag handle between the panes keeps the list between 28% and 48% and the reader at 45% or more. The chosen split is stored on the device with the other Mail settings. On desktop the handle also takes focus: arrow keys step it (Shift for larger steps), Home and End jump to the limits, and a double click restores the default. Assistive technologies see it as an adjustable slider. Coverage:mail_pane_split_test.dart.
The mobile reader follows web Mail’s thread layout. The subject is the
content’s first, large semibold heading and wraps instead of truncating. Below
it a pill shows the conversation’s message count, followed by the labels as
small badges and a failed-lookup retry. A rounded muted group of icon buttons
holds Labels, the read state, Star, Archive (Restore in Archive and Trash) and
Delete, each with a tooltip; it sits beside the subject when there is room and
below it otherwise, and it leaves out whichever command is the default action
so no command appears twice on screen. Conversations with attachments show
Conversation and Attachments (N) tabs; the Attachments tab lays the files out
in one, two or three columns as the reader widens. Each message is a rounded
card with a token ring, and the open card is slightly raised. Only the newest
message is open by default; a folded card shows a two-line snippet and opens
on tap. The card header shows the avatar, name, “to me” or “to Name +N” (the
first To recipient, or the first Cc or Bcc recipient when there is no To,
counting the rest as “+N”), the message’s labels and the date. A wide card
shows the full date in mono at the end; a narrow one keeps the relative time
(“4h ago”, then the date, with the full date as its tooltip) beside the name.
Tapping the recipients toggle expands the From, To, Cc and date inline. The
card’s menu offers Reply, Reply all and Forward for that message. On phones the
navbar names the folder until the subject heading scrolls away, then shows the
subject. On tablets and desktops the bottom bar leads with Reply, Reply all and
Forward, labelled pills from 600dp and icon-only below, then the default
action, More and Close. Coverage: mail_reader_parity_test.dart.
On phones the reader registers one action bar beside the shell’s Back: Reply,
Reply all and Forward. A mailbox that cannot send shows its read-state and
Snooze commands there instead. There is no separate floating circle. The user’s
default email action sits on the top navbar, one tap away: Archive by default,
Restore in Archive and Trash, and Delete or Mark unread when chosen (retired
reply preferences migrate to Archive on load). More holds
every other command in three sections. The first holds the read state, Snooze,
Mute (conversations), Labels, Archive (when it is not the default action) and
Move. The second holds the message appearance, remote images and Share (which
includes the sender’s address only when their profile affirms it is visible;
hidden, unknown and unresolved senders are named without it). Delete
comes last on its own, styled destructive. Delete and Archive close the reader at
once; in Inbox their writes wait through the Undo window so Undo cancels them
without altering older archived or trashed messages in the conversation.
Feedback that becomes ready while a reader, the composer or Mail settings covers
the list is shown when the originating list returns; opening one of those while
an Undo is showing dismisses it and submits its held write. Swiping the
conversation that a split-view pane is showing to Archive or Delete closes the
pane, so no later change there can overtake the held write, and opening a
conversation whose write is still held or on its way first submits it and waits
for it to land, unless another conversation is opened or the mailbox or folder
changes during that wait. The server applies Archive and Delete to every message a
conversation has when the write arrives, so a list reload during the Undo window
that reports a newer message than the reader or the row showed cancels the
held write, returns the row and says so, including a response that was already
on its way when the write was held; the hold therefore hides no mail that the list would have
shown. A held write that lands does not reload the list under a selection in
progress. Undo returns the row as the visible list and the reader
last showed it (a conversation read from the Unread filter, or unstarred from
Starred, stays out; a filter chosen while a split-view reader stayed open is the
list it returns to) and then reloads the list, so the server decides what it
holds. Selection actions and Mark all as read first submit any write still
inside its Undo window, wait for it, and end with a reload; their optimistic
change applies only while the list acted on is still the visible one, and the
write goes to the mailbox and folder acted on even if another list or mailbox
is chosen during the wait. Hiding the app submits held writes
at once. A held write that fails puts its row back in the list it left without
waiting on a reload, and a write still on its way for another mailbox never
holds back the visible mailbox’s reload. A held write is dropped, never sent, once mailbox access is lost or
the signed-in account differs from the one that asked; the same check guards a
selection action or Mark all as read after its wait.
Coverage: mail_deferred_writes_test.dart. Standalone and
split-pane readers show the default action beside an overflow menu that lists
the same entries. Quarantined messages offer neither Archive, Move nor Delete.
HTML mail follows the app’s dark theme unless the
user picked Original or Light. Profile lookups never block reading: a failed
lookup retries once after two seconds, and only a second failure shows an inline
retry caption. Report spam is not offered because the Mail state API has no
spam action.
The mobile inbox uses dense three-line rows: sender and time, subject with up
to two label badges and an optional delivery badge sharing a width budget, and
a one-line snippet. Unread rows are bold with a dot. A quick filter above the
list (All, Unread, Starred, Attachments) adds is:unread, is:starred or
has:attachment to the list query, resets on mailbox or folder changes, is
ignored in Drafts, and is saved with the view. By default, swiping left archives
and swiping right deletes; Inbox Archive and Delete swipes also defer their
writes through the Undo window.
Coverage: mail_reader_states_test.dart, mail_reader_dock_test.dart,
mail_reader_dock_plan_test.dart, mail_reader_sheet_test.dart,
mail_reader_header_test.dart and mail_compact_flow_test.dart.
Rendered HTML bodies are memoized per Mail view (12 entries by exact HTML and
rendering options). One render runs per document however many callers ask for
it. The row under the finger and an open conversation’s previous and next
neighbours render ahead (at most two at a time). An open that follows a
finished render shows its body in the reader’s first frame; an earlier open
joins the render in flight and shows the body when it completes. Rows that are
only visible are prefetched but not rendered. The first WebView of an app run
blocks the platform thread while its engine loads and its first view is created,
so Mail creates and disposes one off-screen view with an empty page once, after
the first inbox result has painted, instead of paying that in front of the first
reader’s opening frame (coverage: mail_webview_warmup_test.dart). Bodies with inline images are never memoized, and the memo clears
with the view and on access denial, fencing any in-flight render started before
clear() or disposal so stale private HTML cannot repopulate the cache.
Coverage: mail_rendered_documents_test.dart and mail_compact_flow_test.dart.
Mobile Mail benchmark
apps/mobile/integration_test/perf/mail_benchmark_test.dart runs the real Mail
view against a synthetic in-memory repository and prints one MAIL_BENCH JSON
line per round: inbox and thread scroll frame percentiles and jank counts, time
to the subject and to the HTML body for the first open and for the next
conversation, and resident memory. Run it in profile mode on a fleet Mac, never
in debug mode:
--host-vmservice-port <port> and
restore the ADB forward that the verbose log prints.
Opening never waits for the network. The reader renders the inbox row’s
subject, participants and snippet over placeholder lines in the opening frame
(a deep link without a row shows a conversation-shaped skeleton), then hydrates from the
in-memory preview store, the encrypted Mail cache, or one detail request (one
retry on transient failures). A conversation shown from memory or from the
encrypted snapshot is revalidated with one refresh request when it opens. A
failed load stays in the reader with an inline Retry, keeping
notification-entry image suppression. Drafts bypass the preview store: each
open loads the saved draft through the repository before the composer opens.
Switching mailbox closes the open conversation, and a resize never reopens a
conversation from another mailbox.
Prefetching is bounded. For verified mailboxes it fetches the rows currently
built in the list, after scrolling pauses for 250ms: conversations in thread
folders and message details in Sent; never drafts. At most two
requests run, eight are queued, and each makes one attempt. A failure is not
retried in the background. The queue is replaced when the visible rows change,
and the neighbours of an opened conversation are queued next. A press that
holds still for 40ms on an inbox row starts loading that row’s body, and the
open shares the request; a press that turns into a scroll fetches nothing. A
cold inbox shows placeholder rows until the list arrives. Prefetching
fetches message JSON only; images load only when a body is shown, under the
saved remote-image preference (or the notification-entry suppression). The
preview store lives in memory for one signed-in workspace view, holds 40
details, and is cleared on access denial.
Regression coverage: mail_master_detail_test.dart,
mail_preview_latency_test.dart, mail_tap_warmup_test.dart,
mail_preview_revalidation_test.dart,
mail_rendered_documents_test.dart and mail_workspace_test.dart in
apps/mobile/test/features/mail, and core/layout/master_detail_test.dart.
Read state and archive actions
Opening a loaded conversation optimistically clears its unread indicators and updates cached Inbox counts. Failed writes restore that conversation’s prior state. Marking a conversation unread from the reader’s default action closes it, preventing automatic viewing from immediately clearing it; Mark unread under More keeps the conversation open. Archive actions persist botharchived_at and read_at for the current user;
users can explicitly mark an archived conversation unread afterward.
Inbox and Archive each offer a folder-wide Mark all as read action. This
covers the selected mailbox’s entire folder, including unloaded messages, and
ignores the current search and selection. The app-local POST endpoint
/api/v1/workspaces/:wsId/mail/mailboxes/:mailboxId/read-all scans 250 inbound
messages per request. Clients continue with the returned nextCursor and
before until the cursor is null. The timestamp excludes later arrivals;
mailbox access and group-message visibility are checked for every batch.
Batches persist independently. If a request fails, already completed batches
remain read and the client refreshes the mailbox; retrying completes remaining
unread messages. Thread and selected-thread actions also paginate message IDs
and write bounded batches instead of silently truncating long conversations.
Similar deliveries and failed recipients
The copy addressed to the active mailbox stays separate. Alternate-recipient copies with the same sender and normalized subject within ten minutes share a compact expandable summary. All original copies remain inside that group with their own selection, content, read state, and actions; personalized previews do not split otherwise matching deliveries. Recognized delivery failures offer a blacklist shortcut in the list and reader. The reason defaults to Inactive/Abandoned and supports additional Infrastructure quick reasons. The action writes to the existing globalemail_blacklist, blocking platform outbound email to the chosen recipient.
It requires Mail mailbox access, a root-workspace linked user, and
view_infrastructure. The server derives allowed recipients from the authorized
failure message, validates the submitted address, and records the current actor.
Existing blacklist entries retain their reason and actor. Ordinary messages and
delay notifications do not produce automatic blacklist suggestions.
SES bounce and complaint notifications
Platform outbound email learns about bounces and complaints from SES through SNS atPOST /api/v1/webhooks/email/ses in the web app.
- Trust: the topic ARN must be listed in
SES_NOTIFICATIONS_TOPIC_ARNS(comma-separated). Otherwise the request gets 403, or 503 while the variable is empty. The SNS signature must be SignatureVersion 2 (RSA-SHA256) and at most a day old. The signing certificate must come from the topic’s ownhttps://sns.<region>.amazonaws.com/SimpleNotificationService-*.pem, be in date, be issued by Amazon and be valid for the SNS host; otherwise 401. If the certificate cannot be fetched right now (network error, timeout, 5xx or 429), the answer is 503 so SNS retries. Up to 32 certificates are cached. A subscription confirmation is confirmed only through that same regional host’sConfirmSubscriptionURL for the same topic. - Effect: each SNS
MessageIdis processed once (private.ses_notification_receipts). Permanent bounces and complaints add anemail_blacklistrow (ses_hard_bounceorses_complaint), whichEmailServicechecks before every send; an existing entry is kept. Every bounce and complaint is recorded inprivate.email_bounce_complaintsby address hash, with no message body or headers. Transient and undetermined bounces are recorded but suppress nothing. A policy-notice ledger row sent with the same SES message id becomesbouncedorcomplained, which the notice’s automatic stop counts. - Limits: 300 requests per minute per client IP; the limiter fails open, and logs it, when Redis is unavailable. The body is capped at 256 KiB while it is read, so a larger body is cut off with 413 and never buffered whole.
SignatureVersion=2, publish SES Bounce and Complaint notifications for the
sending identity (or a configuration set event destination) to it, subscribe the
HTTPS endpoint above, and set SES_NOTIFICATIONS_TOPIC_ARNS on the web app. The
subscription confirms itself once the variable is set.
Architecture
Native Start runtime
The Mail candidate uses@tuturuuu/start-bridge for request context, middleware,
route dispatch, function authentication, navigation and locale adapters. Mail
keeps its own function-body bounds, API middleware matcher, action ports and
response policy, including signed webhook exemptions and attachment framing.
The Email Routing Worker remains a separate service.
apps/mail/start-bridge.routes.json generates the API registry and page manifest.
Run bun run --cwd apps/mail bridge:generate after adding or moving routes, then
bun run --cwd apps/mail bridge:check. The owning Mail build runs the check
before vp build; stale or unregistered routes fail closed. The page policy
covers every generated PagePattern, so a new page also requires an explicit
view policy. API regressions retain all 41 original routes and assert the
authenticated request and decoded params reaching each handler.
The bridge resolves the app base per request: the subdomain serves the root,
while the apex serves /mail. Its head script hands the resolved base to the
browser before hydration; asset, navigation and function URLs follow that base.
Both hosts use one compiled artifact. Mount support is source readiness, not
canonical-route admission. Keep production publication held until the release owner records
the exact artifact, independent review, provider/webhook/attachment acceptance,
mount/session acceptance and rollback evidence.
TTR_ONE_ORIGIN_MAIL is the only admission switch. Unset or off refuses the
apex mount and serves the subdomain unchanged; shadow serves both hosts, the
apex noindex, with no redirect; only on redirects subdomain navigations to
tuturuuu.com/mail. Server functions, the RUM beacon, /api, /assets, public
assets and the /verify-token handoff return (mailMachinePathPrefixes) are
served on the subdomain in every mode, in Mail’s decision and in the bridge’s own
one-origin step.
Under the mount the shared session is read, never written. mailMounts.isolation
gives Mail code an access-token-only Supabase session (no refresh or provider
token), the logout fence and Mail’s own cookies (NEXT_LOCALE, the sidebar
preferences and mail_oauth_state); only those are written, host-only at
Path=/mail. A malformed or sessionless shared cookie is withheld, an expired
access token cannot be refreshed by Mail, and no sb-* or app-session
Set-Cookie leaves the mount. Web alone refreshes and ends the shared session.
The subdomain keeps its session and cookie behavior.
A signed-out mounted page redirects to Web’s /login with
https://tuturuuu.com/mail/verify-token?nextUrl=<Mail path and query> as its
returnUrl. The mounted verifier checks Web’s shared session and resumes the
Mail destination for GET or HEAD. Page requests on the alternate Mail mount
redirect to the canonical apex mount. This follows the
one-origin login return decision.
Mail ships its locale bundles in the build, so no runtime locale fetch needs a
base.
Connected-account OAuth state is host-bound by design: the state cookie is set
and read on the host that started the flow, so the apex and the subdomain each
need their own registered callback and the legacy subdomain callback is never
reused for an apex start. The subdomain flow is unchanged. Each provider
(Google and Microsoft) registers both callbacks with its OAuth client:
https://mail.tuturuuu.com/api/v1/mail/connected/callback through
MAIL_*_REDIRECT_URI, and
https://tuturuuu.com/mail/api/v1/mail/connected/callback through
MAIL_GOOGLE_APEX_REDIRECT_URI / MAIL_MICROSOFT_APEX_REDIRECT_URI. A host
without a registered callback answers 400 Mail authorization host is not registered. Mail registers its internal-api base resolver for app mail, so its
own helpers resolve under the mount and connected-account requests on the apex
stay same-origin; the connected route rejects any other Origin exactly
(mail-api-client.test.ts).
Regression coverage: mounted-routing.test.ts, mounted-isolation.test.ts,
one-origin.test.ts, login-model.test.ts, mounted-session-endpoints.test.ts,
page-model.test.ts, proxy-auth.test.ts, oauth-callback-url.test.ts.
Under /mail, Web owns shared-session writes: Mail rejects logout, token
verification and session refresh before middleware or endpoint dispatch. The
fence uses the bridge’s route matcher, so trailing and repeated slash variants
receive the same rejection without calling handlers or providers or emitting
session cookies. Subdomain endpoints retain their existing methods and cookie
behavior. mounted-session-endpoints.test.ts exercises this boundary through the
real bridge dispatcher, including canonical paths and subdomain controls.
apps/mailowns the mailbox UI and protected app-local APIs under/api/v1/workspaces/:wsId/mail/*.- The mailbox mirror is stored in service-only
private.mail_*tables. Browser code never reads those tables directly; routes verify workspace membership and mailbox roles before using an admin client. - SES and Cloudflare Email Service are permanent outbound transports. The
domain default comes from
mail_domains.outbound_provider; an optional mailbox override wins. Shared abuse, rate-limit, and audit controls in@tuturuuu/email-servicestill run for both providers. - Inbound transport is domain-wide. SES receipt/S3/SNS ingestion remains
supported, while Cloudflare Email Routing invokes the Worker at
apps/mail/src/email-worker/index.ts. - Supabase is authoritative for domains, authorization, audit, threads, search, AI state, and MCP credentials. The private R2 bucket contains raw MIME, body objects, and attachment bytes; callers receive authorized short-lived access, never raw keys or R2 credentials.
- Thread resolution checks
Message-ID,In-Reply-To, andReferencesfirst. Normalized subject is only a recent-reply fallback and is not unique.
/verify-token in the proxy before centralized auth handling so
local Portless handoffs set cookies on mail.tuturuuu.localhost. The app keeps
token refresh same-origin through /api/auth/refresh-app-session; a valid
refresh cookie should rotate the Mail-local and Web-issued app-session cookies
without sending the browser back through apps/web login.
Authenticated root and personal workspace entry requests redirect directly to
/personal/inbox in the proxy, preserving query state and locale. Mailbox discovery
uses bootstrap ?view=mailboxes; unread badges load separately through
?view=counts and stay unknown until available. Both paths retain session and
membership checks. The default bootstrap response still includes counts for other
clients. Thread scans fetch previews rather than full bodies; missing legacy
snippets are loaded only for the visible page. State scans exclude read-only rows
unless the requested search needs read state.
Mailbox access and slow reads
In managed web Mail, the URL selects the mailbox. A saved local hint can start loading the default mailbox while discovery is pending. If the selected mailbox’s thread list or organization request returns 403, Mail stops retrying it, clears any matching hint, and switches to the first remaining active mailbox from discovery. Mail also clears mailbox-specific thread, folder, and label selections. A notice explains the switch. Mail skips any candidate that also returns 403 during the workspace view and shows the existing no-mailbox state if none remain. Every request still checks workspace and mailbox access, including group mailbox eligibility. Managed bootstrap, unread counts, thread list, and organization reads have a 12-second request budget. Session and workspace checks and repository Supabase calls have a four-second limit per stage or call. Mail returns503 MAIL_READ_TIMEOUT with Retry-After: 5 when a deadline expires. The web
thread list and mailbox discovery show a localized retry message. Unread
counts remain optional.
Regression coverage lives in mail-client-archive.test.ts for selection,
notices, empty state and manual retry, and in read-budget.test.ts for
deadline timing, upstream cancellation and the membership boundary.
Reading and attachment previews
Settings → Reading stores the archive navigation and email appearance preferences in the current browser. Archiving an open inbox conversation selects the next visible conversation by default, falling back to the previous one at the end of the loaded list. Users can choose to return to the list instead. Bulk archive skips all selected conversations when choosing the next message. Loaded unread conversations are marked read even when opened through restored URLs or archive navigation. Read updates wait for pending archive/trash operations to settle. Archive controls wait for read-state writes to settle before another mutation. Its header remains available from the inbox summary while the message body loads. Failed operations restore only their own conversations and counters; mailbox reconciliation waits for overlapping operations to finish. Catch-all headers fall back to the observed delivery recipient, then the envelope recipient when parsed To recipients are absent. Sender and recipient summaries clamp long addresses and expose full text in tooltips. Email frames remain hidden until the saved appearance is restored and contrast adjustments finish. Dark mode matches neutral paper surfaces to the reader’s background, including black and gray panels and neutral gradients, and softens bright neutral borders while preserving colored panels and images. Compact App theme/Dark/Original icon controls live on the floating action toolbar with tooltips. New browsers follow the selected app theme; saved explicit choices remain unchanged. Original mode retains sender backgrounds and images, while unreadable text is corrected to at least 4.5:1 contrast on resolved solid backgrounds, including calendar invitations. Dark mode keeps the same contrast floor. Regression coverage lives inmail-preview-contrast-dom.test.ts and mail-preview-appearance.test.ts. Neither mode enables scripts inside email HTML.
Message headers use a single truncated sender-to-recipient row. The details
chevron expands people and delivery details inline; the separate chevron
collapses the message.
Participant profiles open only on click, Enter, Space or ArrowDown, never on
hover: a right-side sheet on desktop and a bottom drawer below 768 px. Escape
or the overlay closes it and returns focus to the name, unless an open form or
dialog inside the card holds it. Names and avatar initials come from the
permission-checked workspace people lookup, then the message header name. A
workspace-hidden email never appears, including as initials. A failed lookup
keeps the header name and offers Try again in the card.
The delivery details show Sent (stored send time, else the Date header) and add
Received only when it differs from Sent by at least a minute, or is the only date. Dates
use the viewer’s browser time zone after hydration. The
raw Date header and headers without a translated label stay in a collapsed
Technical headers disclosure. Regression coverage lives in
mail-sender-contact-card.test.ts, message-details-model.test.ts and
message-details-panel.test.ts.
The reader collapses recognized Gmail, Outlook, cite-style, and plain-text reply
history into a native disclosure. Quote-only and unrecognized messages remain
visible. Quote detection runs on the sanitized isolated document before it is
revealed; it never modifies stored message content or outgoing reply headers.
The protected attachment endpoint accepts ?preview=1 for a passive-format
allowlist: raster images, supported video/audio types, and plain text (including
.txt files stored as application/octet-stream). Preview access uses the same
mailbox and message authorization as downloads and preserves byte-range support.
HTML, SVG, and other unsupported types remain downloads. Responses are private,
uncached, MIME-sniffing-disabled, and sandboxed. The reader exposes previews from
both the conversation and Attachments tab, with a separate download action. Text
previews use the internal API client, render escaped text in the reader theme, and
fall back to download on authorization failures or files larger than 1 MiB.
The web message reader resolves cid: image references against that message’s
stored raster attachments through the same authenticated preview endpoint.
Content-ID matching accepts angle brackets, case differences, and percent-encoded
CID URLs. MIME parameters do not exclude supported images. Missing parts and
unsupported image formats never receive a public URL fallback. The email frame’s
sandbox and CSP remain in force. inline-images.test.ts covers this path with a
multipart/related RFC822 fixture, including subdomain and /mail mounts.
Outgoing inline images replace the entire draft attachment URL with a CID URL.
The reader also recognizes stored CID references prefixed by a Mail draft path,
resolving only to an attachment belonging to the displayed message.
The mobile reader applies the same Content-ID matching rules
(mail_inline_images.dart). It fetches each referenced raster image (at most
4 MB each, 8 MB per message) through the authenticated attachment API and
embeds it as a data URI, so no attachment URL or credential reaches the
WebView. A placeholder holds the image’s place until the bytes arrive, and
tapping a resolved image opens the full-screen attachment viewer. Coverage:
test/features/mail/mail_inline_images_test.dart.
Each web message’s more menu offers View source, Copy raw message, and Copy headers.
These actions read the original stored RFC822 message, including duplicate and
folded headers, only after the existing mailbox membership and message visibility
checks succeed. Source is served as private, uncached plain text and displayed in
a read-only text field. Copies retain the original header block; they do not use
the reader’s filtered header summary. Messages without a retained raw object show
an unavailable state rather than a reconstructed message. The browser limits
source reads to 25 MiB and reports larger messages as unavailable for copying.
Regression coverage lives in repository/raw-source.test.ts, the source route’s
route.test.ts, and packages/internal-api/src/mail-source.test.ts.
Composing and draft recovery
Close saves the latest draft before dismissing the composer; offline or failed saves keep the editor open. Untouched empty composers close without creating a draft. Drafts exposes Continue editing and deletion, and reopening keeps the original draft identity, recipients, reply headers and attachments. Switching composers waits for the previous draft to save before starting a new editor session. The reader header omits its back button; narrow layouts retain a message-list action on the floating toolbar. The composer keeps recognized trailing Gmail/Outlook history outside the rich-text editor, collapsed by default, preserving its HTML when saving or sending. Bounded reply blocks are recognized; ambiguous Outlook tails and authored quotations stay editable. Inline quoted images retain their attachment metadata. Selecting text exposes Enhance selection. AI previews replace only that passage after review; a document change invalidates the captured selection. Plain-text reading caps runs of blank lines without changing stored text or meaningful indentation. Draft attachment images are stored with raw/api/v1/... paths. The editor mounts
them only for display, so a draft saved at tuturuuu.com/mail can reopen at
mail.tuturuuu.com and vice versa. Previously saved /mail/api/... draft image
references are normalized when the editor loads them. External image URLs retain
their original value. The composer regression in
apps/mail/src/app/[locale]/(dashboard)/[wsId]/mail-composer-editor.test.ts
covers both directions and the legacy reference.
Selecting an image in the web composer shows 25%, 50%, 75% and 100% width
presets in the toolbar and four corner drag handles on the image (web only).
Dragging a corner resizes with the aspect ratio locked, previewing in the DOM
and saving once when the pointer is released. It works with mouse, touch and pen
(pointer capture); Escape or a cancelled pointer discards the drag. The
south-east handle is also a keyboard slider: arrow keys change the width by 10px
(50px with Shift), Home sets the 48px minimum and End the editor content width.
Widths are clamped between 48px and the editor content width.
A preset stores a percentage width attribute (for example 50%) and a drag
or key press stores a pixel width (for example 240). Both add an inline
width, max-width: 100% and height: auto style, so the image never
overflows a phone-width viewport in the composer, saved drafts, sent HTML or the
Mail reader, and the saved size persists. The outbound sanitizer allows the
literal auto for height (any other non-length value is still dropped) so
that declaration survives sending; the isolated reader already caps images at
max-width: 100%. Pixel widths from existing mail stay as pixels, and any other
width value is dropped on load. The nodeview updates in place, wraps the image
to host the handles, and keeps the raw attachment src in serialized HTML.
Regression coverage lives in the composer test file and
apps/mail/src/lib/mail/html.test.ts.
Uploads, placeholders and removal
Scope: the web Mail composer (apps/mail) only. Attachment, inline-image and
removal requests go through the existing uploadMailDraftAttachment and
deleteMailDraftAttachment helpers; nothing in packages/internal-api changed,
and no other app has a composer that uses them.
- Immediate placeholders. Choosing, pasting or dropping files creates one item
per file at once. Inline images insert an image node at the caret with the local
preview and a stable client id; attachments appear as chips. Items upload one at
a time and move
queued→uploading→uploadedorfailed. The box of an image is reserved from its decoded local size, and the server image replaces the preview in the same node, by id, only after it has decoded. - Honest progress.
fetchreports no upload bytes, so progress is an indeterminate hairline plus a status label, never a percentage. - Failure and retry. A failed item stays in place (inline image or chip) with
Retry and Remove. The footer shows
Uploading nandn failed; the failed count jumps to the first failed item. Retry re-queues the same item at the back. - No duplicates. An uploaded inline image appears in the editor only. It falls back to a chip only when the body no longer references it (for example the user deleted the image with the keyboard), so it stays removable.
- Send and close wait. Send is disabled while any item is queued, uploading, failed or removing. Save-and-close waits for queued, uploading and removing items; failed items are discarded with the composer.
- Image instances. Every image node has its own client-only instance id (assigned on parse, so reopened drafts, pasted and dropped images each get one; a repeated id from a modifier-key drag copy is reassigned, and a copied placeholder is dropped). The id is never the server attachment id. Copies of an image therefore share one attachment but are removed one at a time; the toolbar Remove acts on the selected node only.
- Optimistic removal. Removing an image node deletes that node at once. The attachment is deleted from the server only when no other node still shows it; that last node is hidden in place until the delete settles, so a failure restores the same node at the same position and a toast offers Try again. Removing a chip works the same way for its item, and also removes any node an undo brought back. A missing server object (404) counts as removed. Toolbar and chip removals are not undoable; deleting an image with the keyboard is, and while the body has lost an image its chip is the intentional recovery path.
- Nothing resurrects. Removing or closing cancels the in-flight request. If the server still created the attachment, only that known id is deleted. An upload whose outcome is unknown (failed, never answered) is never deleted blindly. Closing the composer aborts requests and revokes every preview object URL.
- Work stays with its owner. Each attachment records the workspace, mailbox and draft that own it when it is created or seeded. A late cleanup, a removal or a retry after the composer was closed and reopened (another draft, mailbox or workspace) always addresses that owner, never the composer’s current state.
- Drafts never carry local state. Placeholder images (queued, uploading,
failed or being removed) serialize with a
data-mail-uploadmarker and are stripped, together with anyblob:/data:source, before the body reaches the composer state, the draft save or the send payload. Settled images keep the raw attachmentsrc. - Editor isolation. Upload state lives in a store outside React and updates placeholder DOM through node attributes. The editor component is memoized, keeps one TipTap instance (also while the composer is minimized) and is not re-rendered by status changes: the uploaded-attachment list handed to it keeps its reference until the set of uploaded attachments actually changes. Placeholder insertion and swaps skip undo history so undo never restores a placeholder.
mail-composer-upload-store.test.ts (ordering, replace-by-id, failure, retry,
races, rollback, cancellation, cleanup), mail-composer-upload-store-ownership.test.ts
(late results and removals keep their owner, shared-attachment ownership, stable
attachment reference), mail-composer-image-instances.test.ts (real TipTap copy,
paste, drag-copy and reopened duplicates through the real store),
mail-composer-image-nodes.test.ts (serialization stripping, ids),
mail-composer-editor-media.test.ts (one editor, in-place swap, reserved size)
and floating-composer-media.test.ts (send gate, draft and send payloads, dedup,
cleanup on close and unmount, reopen elsewhere, stable editor attachments).
Measuring input latency and editor renders
floating-composer-media.harness.test.ts replays one deterministic workload
against the real composer, editor, footer and chips with the upload transport
replaced by a manually released mock: 20 control keystrokes, selecting 3 images and
2 files, 40 keystrokes while every upload is held, then 30 keystrokes while uploads
complete one by one. It records per-keystroke time for a synchronous editor
dispatch plus the React commit, editor component render counts (via useEditor
calls), composer commits and Profiler time, TipTap transactions, editor identity
count, what is on screen immediately after selecting files, and how many distinct
attachments arrays the composer hands the editor while files are only queued or
uploading (editorAttachmentRefsAtSelect; each new array defeats the editor’s
memoization, so it should stay at 0). It is skipped unless MAIL_MEDIA_HARNESS=1.
It uses only public props and the DOM, so the same file runs on any commit. Run it
on the baseline commit and on the changed commit on the same machine, interleaved,
then compare:
Mail frontend observability
Wave 1 Mail usesobservability.enabled: true and head_sampling_rate: 1 in
staging and production. After cf deploy --prebuilt activates the version,
CI polls settings with GET every five seconds for up to 60 seconds, retrying
failed reads inside that bound. Both values must match before CI accepts the
release. If the emitted Build Output does not declare these values, CI refuses
before deploying.
For a manual production release, publish the qualified artifact with the
strict Void publisher.
Version uploads leave script settings as they are. Assign the uploaded version
with the captured serving version and the expected settings.
PATCH /accounts/{account_id}/workers/scripts/tuturuuu-mail/script-settings
with observability.enabled: true and observability.head_sampling_rate: 1,
preserving other observability fields. Confirm both values with GET before acceptance.
SES Receiving Setup
Do not change DNS from code or migrations. The current public MX fortuturuuu.com is Google-routed, so real @tuturuuu.com receiving requires an explicit staged MX cutover or a pilot subdomain first.
- Verify the domain or pilot subdomain in the SES receiving region.
- Create an S3 bucket for raw MIME objects.
- Create an SNS topic for receipt notifications.
- Configure
MAIL_SES_INBOUND_TOPIC_ARN,MAIL_SES_INBOUND_BUCKET,MAIL_SES_INBOUND_KEY_PREFIX, andMAIL_SES_REGIONon the Mail Worker. - Subscribe the Mail webhook
POST /api/v1/webhooks/mail/sesto the topic. The subscription confirmation must reach a Worker that already has the topic ARN. - Create an SES receipt rule that stores raw MIME in S3 and publishes the SNS notification.
- Only after validation, stage the MX/DNS change outside the app repository.
MAIL_SES_SNS_SIGNATURE_VERIFICATION=disabled. Do not use that setting in production.
SES inbound is optional. Without MAIL_SES_INBOUND_TOPIC_ARN, POST /api/v1/webhooks/mail/ses answers 410 Gone (SES inbound is not configured)
before reading or verifying the body. SNS treats a 410 as a permanent failure
and does not retry it. Production inbound runs through Cloudflare Email Routing.
Configure the topic and the other MAIL_SES_* values on the Mail Worker before
subscribing SNS to the endpoint. Coverage: apps/mail/src/app/api/v1/webhooks/mail/ses/route.test.ts.
Email Routing Worker logs
tuturuuu-mail-email-routing has Workers Observability enabled in
apps/mail/wrangler.email-routing.jsonc at the default head_sampling_rate
of 1. Per-message failures are queryable there alongside the zone’s Email
Routing activity log.
Cost envelope. Logging is billed per invocation, and invocations equal
Email Routing delivery attempts:
- The Worker writes no
consoleoutput. Each attempt produces one invocation log. An uncaught exception is recorded on that invocation. - Within one invocation, the ingest call is tried up to three times on
429or5xx. These are subrequests of the same invocation, not separate invocations. - When the Worker calls
setReject(an invalid recipient, a message over 25 MiB, or a domain that Mail refuses), the sender receives a permanent failure and does not retry. - When the Worker throws (an ingest outage or a transient ingest error), the sender receives a temporary failure and retries on its own schedule. Each retry is a new invocation. An ingest outage therefore multiplies events by the senders’ retry counts, and a spam burst multiplies them by message count.
- Cloudflare truncates a log at 256 KB, so one attempt ingests at most 256 KB.
- Until December 1, 2026: 20 million log events per month are included, then $0.60 per million.
- From December 1, 2026: Workers Logs draw on the account’s shared Cloudflare Observability allowance, then cost $0.25 per GB ingested and $0.10 per GB-month stored, with 7-day retention. At the 256 KB ceiling, that is at most $0.064 of ingestion per 1,000 attempts beyond the allowance. Enterprise accounts switch at contract renewal, and legacy Log Explorer usage is billed separately.
main, so a committed value is the durable state. Each production write
below (a deploy or a settings PATCH) needs the release authority’s ACK on an
exact-hash write packet first.
- Immediate stop, no build. Send
PATCH /accounts/{account_id}/workers/scripts/tuturuuu-mail-email-routing/script-settingswith{"observability":{"enabled":false}}, using a token with Workers Scripts Write. Read backGET …/script-settings; it must show observability disabled. New invocations stop producing logs. Logs already stored expire after the 7-day retention. - Durable stop. Only when the release authority decides that logging
stays off, commit
"enabled": falseinapps/mail/wrangler.email-routing.jsoncbefore the next deploy of this Worker. Until then the checked-in value istrue, so a deploy resumes logging; after an immediate stop, hold deploys of this Worker or repeat thePATCHafter each one.
head_sampling_rate reduces ingestion but does not stop it.
Delivery does not depend on logging.
Stop verification. The production stop check exercises the immediate
stop, under one ACKed packet for all three writes:
- Deploy from
mainwith logging on, then confirm that a delivery is ingested and logged. - Turn logging off with the settings
PATCH, then confirm that the next delivery is still ingested and produces no new log event. - Turn logging back on with the same
PATCH, then confirm that logging resumes.
main carries
"enabled": true. For
that reason the check does not deploy a committed false. That path is an
ordinary config change plus a manual deploy, and its effect is visible in the
same settings readback.
Cloudflare onboarding
Cloudflare must already manage DNS for an onboarded domain. Arbitrary-recipient sending also requires Email Sending to be enabled for the account. Configure a staging domain before changing a production domain.- Create a private R2 bucket (the checked-in Worker configuration uses
tuturuuu-mail) and bind it asMAIL_R2_BUCKETinapps/mail/wrangler.email-routing.jsonc. - Configure the Mail app server with
MAIL_R2_ACCOUNT_ID,MAIL_R2_ACCESS_KEY_ID,MAIL_R2_SECRET_ACCESS_KEY, andMAIL_R2_BUCKET_NAME. The bucket name must match the Worker binding.MAIL_R2_ENDPOINTis only needed for an R2-compatible development or test endpoint. Object keys are private implementation details and must not be returned to clients. Seeapps/mail/env.examplefor the complete contract. - Set the Worker secret with
bunx wrangler secret put MAIL_INGEST_SECRET --config apps/mail/wrangler.email-routing.jsonc. - Configure the same value as
MAIL_CLOUDFLARE_INGEST_SECRETon the Mail Worker. Signed events include the request body and a timestamp, and the API rejects invalid or older-than-five-minute signatures. - Set
MAIL_INGEST_URLto the deployed Mail endpoint/api/v1/webhooks/mail/cloudflare. The Email Routing Worker uses theMAIL_INGESTservice binding to pass a signed request directly totuturuuu-mail. Verify the domain check and an isolated test delivery through the bound version before changing the public webhook route. - In Cloudflare Email Routing, onboard the domain and route its intended
address patterns to
tuturuuu-mail-email-routing. - Configure the domain row through
GET/PUT /api/v1/mail/domains. Only root workspace operators may use this endpoint. Move the domain fromverifyingtoactiveonly after DNS and routing checks pass. - For outbound Cloudflare sends, set
MAIL_CLOUDFLARE_API_TOKENwith Email Sending permission and either store the managed account ID on the domain or setMAIL_CLOUDFLARE_ACCOUNT_IDas the fallback.
postal-mime, stores deterministic R2 objects, and submits a signed
idempotent delivery event. Malformed or spam/virus-signaled deliveries are
recorded as quarantined. Transient API failures are thrown so Email Routing can
retry without creating duplicate messages.
Cloudflare controls the outbound Message-ID header and rejects clients that
set it. Mail therefore sends only In-Reply-To and References through the
Cloudflare API. SES raw MIME sends retain a deterministic Message-ID. Store
Cloudflare’s returned provider identifier separately; do not substitute it for
an RFC message identifier unless the provider explicitly returns one in that
format.
Mailbox API foundation
Mailbox routes require workspace membership and a mailbox role on every request. The API provides chronological thread retrieval and thread-level state changes, label and custom-folder CRUD, bulk message mutations, and private attachment upload/download/delete routes. Attachment downloads stream through an authorized route with byte-range support; clients never receive an R2 object key. Message listing accepts the structured search operatorsfrom:, to:,
cc:, bcc:, subject:, is:, has:attachment, before:, after:, and
label:. Quote values containing spaces. Structured filters are combined with
remaining free text and mailbox/folder state filters. Client applications
should call these routes through packages/internal-api/src/mail.ts.
Cloudflare currently permits 50 combined to/cc/bcc recipients and a
normal outbound size of 5 MiB including attachments. Email Routing accepts up
to 25 MiB inbound. The provider enforces outbound limits before making the API
request; the Worker rejects inbound events above the routing limit. Reconfirm
current quotas in the
Cloudflare Email Service limits
before changing these constants.
The managed staging baseline uses tutur3u.com for Email Routing and Email
Sending and the private tuturuuu-mail R2 bucket. Do not attach a routing rule
to the inbound Worker until the Mail deployment has the matching ingestion
secret and Supabase has an enabled ingest.tutur3u.com domain row linked to
the canonical tuturuuu.com row. Email Sending and R2 can be verified
independently before that inbound cutover.
Google Workspace shadow-ingestion migration
Do not onboardtuturuuu.com into Cloudflare Email Routing while Google
Workspace still owns its apex MX records. Email Routing is enabled at the zone
level before Cloudflare allows routing subdomains, so onboarding the production
zone would replace and lock the Google MX records too early. Use the already
onboarded staging zone as the shadow bridge instead:
- Cloudflare Email Routing is enabled for
ingest.tutur3u.com; its routing DNS records are managed and locked by Cloudflare. - A temporary exact-address routing rule may forward a pilot shadow address to a verified test inbox. Replace this action with the deployed ingestion Worker before starting a parity run.
- Google Workspace has a recipient-address-map setting named
Cloudflare shadow ingestion pilot. Keep it disabled between tests. It must map each selected@tuturuuu.comaddress to the same local part at@ingest.tutur3u.com, retain the original Gmail destination, and addX-Gm-Original-To. - The public
tuturuuu.comMX records remain Google-only throughout the shadow phase. Never publish Google and Cloudflare MX records together as a substitute for dual delivery.
Activation gates
Complete all of these before changing the temporary Cloudflare forwarding rule to the ingestion Worker or enabling the Google pilot:- Canonicalize a trusted shadow recipient such as
user@ingest.tutur3u.comtouser@tuturuuu.com. Preserve both addresses in the ingestion event and acceptX-Gm-Original-Toonly on the configured shadow domain. - Configure the same HMAC secret as
MAIL_INGEST_SECRETon the Worker andMAIL_CLOUDFLARE_INGEST_SECRETon the Mail deployment. - Deploy the Worker with the private
tuturuuu-mailR2 binding and confirm a signed domain check and ingestion event reach the Mail webhook. - Ensure Supabase has enabled domain metadata for the shadow and canonical domains, including their explicit relationship. Do not infer an arbitrary production domain from an inbound subdomain.
- Prove direct shadow delivery, raw MIME storage, body and attachment storage, quarantine behavior, and duplicate retry before enabling Google delivery.
add_mail_domain_canonical_relationship migration installs this
exact staging relationship. Apply it through the normal database release path;
do not push it ad hoc from a workstation. The Worker derives the canonical
recipient only after a signed domain check, and the webhook independently
validates the ingress domain, canonical domain, observed recipient, and local
part. Duplicate transport deliveries with the same mailbox and RFC
Message-ID reuse the existing message instead of incrementing thread counts.
Rollout plan
- Single-address pilot: point one exact Cloudflare shadow rule at the Worker, enable only the matching Google address-map entry, and send external and internal test messages. The original Gmail delivery must remain enabled.
- Shadow parity: expand the explicit map to the active user, group, and
alias inventory. Run for at least three days and preferably seven. Compare
Google Email Log Search with Supabase ingestion records by authoritative
Message-ID, recipient, timestamp, raw MIME hash, attachment count, and quarantine result. - Cutover readiness: require no unexplained missing messages, idempotent duplicate handling, correct canonical recipients, attachment parity, and an alertable ingestion-latency baseline. Snapshot the Google MX records and lower or verify their DNS TTL at least 24 hours before the change.
- Apex cutover: during a low-traffic window, onboard
tuturuuu.comin Cloudflare and route its intended addresses to the same Worker. Keep Google Workspace and the shadow address map available for at least seven days so senders using cached Google MX records still feed the Cloudflare ingestion path. - Stabilization: remove the temporary test forwarding destination only after the Worker route is verified. Retire the Google shadow map after the cached-MX window and parity checks are complete; migrate outbound transport separately.
Rollback
Restore the saved Google MX records first and wait for DNS confirmation. Keep the Google shadow map and Cloudflare staging subdomain available during rollback so messages delivered through either cached MX path still reach the same idempotent ingestion boundary. Change the Supabase inbound-provider flag only after DNS is serving the intended provider. A rollback must not delete R2 objects, mail metadata, Google accounts, or the disabled pilot configuration. The initial transport smoke test used distinct subjects for Google outbound and Google-to-Cloudflare shadow delivery. Google delivered the original inbound message to the Workspace inbox, and Cloudflare recorded the mapped shadow copy as forwarded. After the test, the Google pilot setting was returned to its disabled state.Catch-all delivery
Catch-all routing is platform-operated because it affects an entire inbound domain. The destination is relational metadata onprivate.mail_domains, not a
workspace secret: catch_all_mailbox_id must reference an active mailbox on the
canonical domain, and catch_all_enabled defaults to false. Automatic drafts
for catch-all deliveries have a separate opt-in and remain disabled unless a
platform operator explicitly enables them.
Activate the bridge in this order:
- Apply the additive
mail_catch_all_deliverymigration through the normal database release process and deploy the matching Mail app and Email Routing Worker. - Open Mail settings as a root workspace operator, select
ingest.tutur3u.com, choose the destination mailbox, and enable the logical catch-all route. The initial pilot destination is<owner-mailbox>when that mailbox exists. - In Cloudflare Email Routing, select the already-onboarded
ingest.tutur3u.comsubdomain and set its catch-all action to thetuturuuu-mail-email-routingWorker. Keep explicit rules enabled; they take precedence over catch-all. - Send a unique random local part directly to the ingress subdomain. Confirm the original recipient is visible in Mail, raw MIME and attachments are in R2, and a retry does not create another message.
- In Google Admin, add a rule named
Tuturuuu Mail catch-all bridgefor inbound Unrecognized/Catch-all recipients only. Replace only the recipient domain withingest.tutur3u.com, addX-Gm-Original-To, and leave Users and Groups unchecked. This keeps recognized Google Workspace delivery unchanged while preserving the unknown local part for Mail.
tuturuuu.com apex while Google
owns its MX records. To roll back, disable the Google unrecognized-recipient
rule first, disable the Cloudflare subdomain catch-all second, and disable the
logical Mail route last. Do not delete ingested metadata or R2 objects.
Provider rollout and rollback
Provider selection is independent in each direction. Change only one direction at a time on the staging domain, complete inbound delivery, outbound delivery, attachment, threading, duplicate retry, and bounce/throttle smoke tests, then enable the production domain. A mailbox override may be used for a narrow outbound canary. To roll back outbound delivery, clear the mailbox override and set the domain outbound provider toses. To roll back inbound delivery, restore the domain’s
SES MX/receipt-rule configuration first, then set inbound_provider to ses.
Do not change the database flag before DNS is serving the intended provider.
Existing SES jobs, raw S3 metadata, and credentials remain supported throughout
the rollback.
Operations
Mail settings and account settings
Mailbox settings use themailSettings=open query parameter. The shared
satellite account settings use settingsDialog=open and settingsTab; keep
these separate so the guidance dialog cannot cover the mailbox delivery,
membership, and sender controls. Closing either dialog must preserve the
other dialog’s query state.
Mail sanitizes message HTML and signatures with sanitize-html in both the
server ingestion/draft path and browser previews. Its allowlist retains email
tables, typography, and cid: image references while excluding active content
and CSS resource URLs. Avoid reintroducing an externalized jsdom-based sanitizer:
an incompatible CommonJS/ESM dependency can fail module initialization and make
even the mailbox bootstrap route return HTTP 500. Validate sanitizer security
fixtures and a real Mail build when changing this dependency boundary.
Full Google mail migration
Inventory active and suspended accounts, aliases, group membership, delegated mailbox access, and existing routing before importing data. Preserve suspended account access restrictions. Google groups can also authorize access to Google Cloud resources; migrating their email does not authorize deleting those groups or changing their IAM membership. For the Tuturuuu migration, suspended accounts stay suspended while incoming mail for their addresses follows the domain catch-all to<owner-mailbox>.
An existing inactive mailbox must not be recreated by automatic provisioning.
This delivery policy does not grant the suspended user mailbox access.
Google Admin’s available organization export may include all services rather
than Gmail alone. Review the actual scope before starting it, obtain approval
for non-mail data, and use only the mail portion for this migration. A scheduled
or in-progress export is not an imported archive. Keep the source service until
the completed export has been downloaded, reconciled, and imported with original
dates, folders/labels, read state, attachments, and mailbox ownership intact.
The live Cloudflare webhook imports new inbound deliveries; it is not a
historical Gmail importer and must not be used to silently flatten sent mail,
drafts, or labels into the inbox.
Use the resumable Google Takeout importer after extracting only each account’s
Takeout/Mail directory into one directory per email address. Run it without
--apply first and reconcile its report with an independent MBOX inventory:
--apply. The
importer writes raw MIME and attachments to the configured Mail R2 bucket,
uses deterministic IDs, and skips existing provider or Internet Message-ID
records so an interrupted run can resume safely. It processes Deleted MBOX
files first so duplicates retain their trash state. It preserves Gmail thread
IDs, original timestamps, sent/draft/spam/trash/read/star/archive state, system
labels, and custom labels. State rows may be recorded for a suspended user’s
existing profile, but the importer does not activate a mailbox or create a
mailbox membership.
After the apply run, compare its report with counts from
private.mail_messages, private.mail_raw_messages,
private.mail_attachments, and private.mail_stored_objects. Re-run the
importer with the same arguments to verify that every message is reported as
already present. Keep the source export until database counts, R2 objects, and
an authenticated Mail reader sample all agree.
Onboard Cloudflare Email Sending separately from Email Routing. Sending
uses its bounce subdomain and DKIM records and can be prepared while the apex
MX remains on Google. Verify the existing DMARC policy and reporting addresses
after onboarding. Check the account’s actual daily quota and the outbound
message-size limit before switching the application provider; domain activation
alone does not prove application sends or recipient delivery.
For tuturuuu.com, the requested catch-all destination is
<owner-mailbox>. Configure the logical Mail destination first, route the
Cloudflare catch-all to the ingestion Worker, and retain explicit recipient
routes. Prove delivery to a new random local part, the preserved original
recipient, attachment storage, and duplicate handling before enabling the Google
catch-all bridge or changing the apex MX. Never use SMTP forwarding back to the
same domain as a substitute for internal mailbox ingestion.
Smart labels and AI-assisted drafting
Apply themail_smart_labels migration before deploying the matching settings
UI. It adds a description, mailbox-scoped AI instructions, an enable flag, and
an auto-apply flag to each private custom label. The migration is additive and
defaults every AI option to disabled. Label CRUD remains limited to mailbox
owners and admins; senders may apply configured labels but cannot redefine the
taxonomy.
Mail exposes AI drafting and smart-label classification only through
mailbox-authorized app routes and packages/internal-api. Drafting supports new
messages, rewrites, and follow-ups with bounded thread context. Message content
is treated as untrusted reference material so instructions embedded in an
email cannot override the system prompt. Generated text is returned to the
composer as an editable draft; the AI route has no send, schedule, or transport
tool.
Smart-label suggestions help owners/admins create a taxonomy from recent
mailbox patterns. Classification accepts explicit thread IDs, validates every
thread and label against the active mailbox, and applies labels only after an
authorized user invokes the workflow. ai_auto_apply records whether a label
may be applied by an authorized automatic workflow; it does not grant AI any
additional mailbox role or send capability.
The repair_mail_thread_subjects migration backfills blank legacy thread
subjects from the newest meaningful message. Runtime thread hydration also
falls back to the newest message so sent mail remains accurate when application
deployment precedes the migration.
- Run
bun sb:uplocally after mail schema changes, thenbun sb:typegen. - Keep new mail route access checks in
apps/mail; do not add direct client Supabase reads. - Use
packages/internal-api/src/mail.tsfor client helpers and TanStack Query in the app UI. - Unknown inbound recipients are retained as
quarantinedjobs for administrator review instead of being delivered to a user inbox. - Keep generated public assets such as
/manifest.webmanifest,/sw.js, and offline worker files out of the auth proxy matcher. Redirecting those files to central Web login breaks standalone Mail startup and PWA registration. - Keep
apps/mail/src/proxy.tsconfig.matcherentries as inline string literals. Next.js statically parses proxy matcher config during Vercel builds and rejects imported constants even when they resolve to strings.
CI and deployment
Mail qualification and Cloudflare publication usemail-cloudflare.yaml and
the native Start migration runbook.
Fresh disposable hosted runners explicitly provision resource launchers with
bun packages/sdk/src/cli/resources-entry.ts setup --root "$GITHUB_WORKSPACE" --shell none
before the first queued setup workload. Both subsequent commands reuse that same
installation and canonical queue. run never provisions missing launchers; a cold
caller must complete explicit setup first. This hosted bootstrap does not authorize
updating an installed developer or Studio scheduler. Workflow ordering is covered
by scripts/ci/mail-profile-runtime.test.mjs; the cold reject → explicit setup →
admitted run boundary is covered by packages/sdk/src/cli/resources-provisioning.test.ts.
The exact-head mail-profile-runtime-contract.yaml follows resource CLI changes and uses
frozen normal setup through the shared queue for Lettin profile upload/save/reload and
independent Chromium session transport tests. Its exclusive disposable VM owns complete-schema
Supabase Auth/REST/Storage on safe local API port 8001, local D1 fixtures and Next apps. The profile browser and session cookies use registered http://localhost:7833; Web/API, storage and readiness retain their independent IPv4 bindings. This fixture origin matches the existing signed-upload CORS registry without widening capability or authentication policy.
Storage uses an owned HTTPS proxy and one-day CA with normal verification. Chromium sandboxing
stays enabled: hosted-only setup authenticates Google’s signed Release/Packages SHA256 chain,
extracts only a fresh packaged helper without maintainer scripts, and records package/helper hashes.
Root installs it exclusively at /usr/local/libexec/tuturuuu-mail/chrome-sandbox with protected
parents and 4755 mode; CHROME_DEVEL_SANDBOX selects it using Chromium’s helper option.
No existing /opt bytes, shared Linux permissions or security policy change; require actual runtime success. Initial profile navigation failures retain at most 20 navigation-response source/target route classes, fixed locale presence, same-path booleans and HTTP status codes, without URLs, query values, workspace IDs, headers or bodies. Navigation failure records also retain document-body completion and observed DOMContentLoaded/load booleans. HTTP 200 alone does not prove a completed HTML stream or a loaded page; these observations never extend navigation deadlines or replace profile assertions. Terminal receipts retain actual statuses for the two named tests even on failure; stopped app records remain available to startup diagnostics. The disposable hosted fixture also enables default-off profile proxy provenance: fixed response-producer and request/Next pathname locale categories with a same-path boolean, without URL, tenant, query, cookie or token values. An absent marker is unclassified, not proof of a post-proxy cause; a marker identifies the proxy producer, not the redirect root cause. Lettin uses Next.js skipProxyUrlNormalize so locale canonicalization sees the original client URL instead of a synthesized locale prefix; explicit /en and /vi redirects, locale cookies, queries, shared-session and MFA checks remain enforced. Config changes require the real Lettin build and hosted profile runtime. Source checks and these observations do not turn a failed runtime gate into a pass.
Missing/skipped/retried tests and failed cleanup fail the gate; fixtures delete only their
synthetic IDs/media and stop recorded project/app/proxy processes. No provider credentials,
raw traces or private CA keys are published. Broad E2E stays disabled; terminal evidence proves
local profile/session behavior, not Worker/provider/production/customer delivery; pgTAP/schema types remain separate.
Mail client navigation and recovery
Mail owns one settings entry in its sidebar. Its shell disables the shared settings utility withshowSettingsButton={false}; other satellite apps keep
the default. Mail settings continue using the mailSettings URL state, and keep
their tab in mailSettingsTab; the shared settingsTab parameter belongs to the
account settings dialog, which would otherwise open on top of Mail settings.
The sidebar account picker under Compose switches between managed mailboxes
(personal first, then shared groups) and connected Gmail or Outlook accounts; the
inbox has no source tab bar. It offers search once five or more entries exist and
closes the mobile drawer after a choice. Managed choices write mailbox=<id>;
connected choices write connected=1&account=<id>. The connected=1 URL
parameter still selects connected accounts, and non-@tuturuuu.com accounts
still default to them. An unknown or disconnected account falls back to the
first connected account.
In connected mode the sidebar lists only the provider folders (Inbox, Sent,
Drafts, Archive, Spam, Trash) and hides Labels, custom folders, Snoozed, Muted
and Starred; the folder comes from the route, and a managed-only route shows the
inbox. Managed mode keeps its existing folders and labels. The sidebar Compose
button opens the connected composer through ?compose=1 while connected.
Settings → Accounts (tab key source, so mailSettingsTab=source links keep
working) lists managed mailboxes with a Mailbox settings shortcut, and connected
accounts with Disconnect and its confirmation. Verified staff in their personal
workspace also see Connect Gmail and Connect Outlook. The picker’s Manage
accounts entry opens this tab. The connected pane keeps search, refresh, compose,
list and reader only. Roles, group policy, disconnect semantics and the default
source stay the same, and preferences for the default source are not persisted. mail-source-selection.test.ts,
mailbox-groups.test.ts and mail-account-messages.test.ts cover the URL,
folder and grouping rules and the English and Vietnamese copy.
The inbox sync icon is tied to the refresh request, not a timer. Refresh
refetches the list, mailboxes and unread counts together; the icon spins until
all of them settle, including background revalidation (but not loading an older
page), then eases back to rest. With reduced motion it stays still and dims.
use-mail-refresh.test.ts and use-settling-spin.test.ts cover this.
Unread and attachment quick filters compose with the search query. The selection
checkbox selects loaded conversations, and selection resets when the mailbox,
folder, label, or search changes. Message loading failures show an explicit retry
state instead of appearing as an empty mailbox. Sending, draft autosave, protected
attachments, and delivery settings remain behind the existing Mail APIs.
Thread rows mark unread conversations with weight and a dot rather than a filled
card. Their dates show the time for today, the day for this year and the full
date otherwise, with the exact timestamp on hover (mail-thread-date.test.ts).
The conversation pane constrains message width and keeps message details and
attachments available without expanding them by default. Small screens show one
pane at a time, with a back action returning to the message list.
Web inbox load path
The thread list does not wait for bootstrap when the mailbox is already known: themailbox URL parameter, or the default mailbox remembered from the
previous bootstrap in this browser, starts the list request in parallel. After
bootstrap, only returned mailboxes are used, and the server authorizes every
mailbox ID. Per-mailbox unread counts wait while a first thread page is loading;
on a first visit with no remembered mailbox they can start alongside it.
Bootstrap is read-only in the common case. It reads the personal mailbox,
memberships and display name in one parallel stage, and writes only to repair a
stale identity, a missing owner membership, or missing or renamed system labels.
bootstrap-personal.test.ts and use-mail-bootstrap.test.ts cover these rules.
Distribution groups
A shared address can be provisioned as a distribution group by settingprivate.mail_mailboxes.metadata.mail_group to:
Internal forwarding and smart labels
Mailbox owners and administrators can use Settings → Automation to forward new incoming messages to another accessible, active mailbox in the same domain, or to that domain’s current enabled catch-all mailbox. Delivery retains the source copy and preserves original content and attachments. Forwarding is one internal hop; forwarded copies never trigger another forwarding rule. Self, inactive, cross-domain and distribution-group targets are rejected. Distribution groups continue to use member delivery. Disabling catch-all suspends a catch-all-based forward until an eligible target is configured again. Smart inbox usesgemini-3.5-flash-lite, Google’s latest stable Flash-Lite model
verified on September 7, 2026. Enable it separately per mailbox. New incoming mail
is classified against custom labels; only labels with both AI and automatic
application enabled are applied. Gemini may suggest up to three new categories;
owners and administrators can review recent suggestions under Settings → Labels.
Suggested labels are never created automatically. Subjects, sender addresses and
up to 6,000 text characters are processed by the configured Google AI service.
Attachments are not sent to the classifier. The existing AI memory/usage wrapper
continues to apply its configured policies.
Classification is bounded to twelve seconds without provider retries. Failures
are logged and never reject accepted mail. The existing manual classification
and suggestion controls remain available for recovery and older messages.
Completed classification events prevent repeat work on normal delivery retries.
Concurrent duplicate deliveries can still produce duplicate AI requests; label
assignment itself is idempotent. Forwarding errors remain retryable through the
inbound delivery job. Configuration is stored in mailbox metadata; this feature
requires no schema migration.
The reader defaults to dark appearance, with original newsletter colors available
from the floating toolbar or Reading settings. Stylesheets are retained only inside a sandboxed iframe with
scripts, forms, remote stylesheets/fonts and network APIs blocked by CSP. The
iframe grants same-origin access to the parent solely for height measurement and
protected inline images; it never grants script execution. External links open
separately with no referrer. Raster CID images resolve through authorized
attachment endpoints. Signature sanitization still removes stylesheets. Wide
messages scroll within the reader rather than expanding the app. Rendering aims
for common Gmail-style newsletters; it is not a claim of pixel-identical Gmail
compatibility for every email template.
Thread lists always display both the message date and delivery time. The mobile
reader uses constrained native scrolling to prevent wide tables, subjects or
attachment names from widening the application viewport.
The reader preserves hidden newsletter preheaders and isolated inline CSS. Dark
appearance adapts neutral surfaces and borders while preserving branded colors. Message content uses the full pane
width; reply actions float over the bottom edge with reserved scroll space so the
last line remains reachable. The collapsed sidebar contains folder actions only.
Expanded navigation groups shared mailboxes by repeated address prefixes (for
example GCP), while personal mailboxes remain directly accessible.
Keyboard navigation
Use the keyboard button beside the mailbox filters, or? while single-key shortcuts are enabled, to open the shortcut
reference. Reading settings and the reference both let users disable single-key
shortcuts; Tab, Shift+Tab and arrow navigation remain available.
Arrow keys move focus between loaded conversations, Home/End reach the list
boundaries, and Enter opens the focused row. j/k also switch an already-open
reader. x selects a conversation, Shift+X toggles all loaded conversations, and
e, #, and Shift+I apply archive, trash, and mark-read to the checked selection.
u or Escape clears a checked selection; when no selection remains, it returns
to the list. / focuses search,
c composes, and r/a/f reply, reply all, or forward the loaded message.
g followed by a folder key navigates while preserving the active mailbox.
Composer shortcuts use Ctrl on Windows/Linux or Command on macOS: Enter sends
through the normal review flow, S saves, and J opens AI assistance. Escape saves
and closes. Focus moves to recipients for a new draft or the body for a reply,
and returns to the opener after closing. Mailbox shortcuts pause during typing,
IME composition, composing, and dialogs. Same-origin email-frame key listeners
retain the script-disabled sandbox.
Address decoding and similar deliveries
Mail recovers damaged display names from the matching original RFC 2047 address header when available, including Latin-1 encoded words incorrectly labeled UTF-8. Already-lost replacement characters cannot be reconstructed; the reader displays the address instead. New inbound records use the same decoder. This requires no production backfill and does not alter stored raw headers. The loaded list groups single-message catch-all deliveries with distinct original recipients when sender, subject, preview, attachment presence, mailbox and a 10-minute time window match. These are labeled similar deliveries, since previews do not prove identical bodies. Groups are presentation-only: records, message counts, search, permissions and per-delivery actions remain independent. Expanding a group exposes recipient rows; keyboard navigation opens a collapsed group as focus reaches those rows. Filtering and loading additional pages may change group membership. No grouping occurs across mailbox access boundaries.Mobile inbox restoration
Mail is a core mobile app for accounts whose email domain istuturuuu.com or
one of its managed subdomains, and for marked review accounts on tutur3u.com
(see Flutter Mail); other accounts do not see its launcher or
direct-route content. Discovery is only a hint: API authorization still controls
mailbox access.
The mobile inbox restores its last mailbox, folder, search, labels, and message
list from encrypted, account- and workspace-scoped storage. Snapshots expire
after seven days. Opening Mail rechecks access and refreshes messages; cached
send permissions are never trusted. Preparation shares the reader’s genuine 401/403 purge
and MFA exceptions. Pre-request key/scope revisions fence durable publication and readiness;
late responses cannot restore purged data (see mail_offline_preparation_test.dart). Draft editing and attachment downloads still require authenticated network requests.
Opening a mobile message shows the reader immediately from the inbox row and
keeps its detail request active while the inbox revalidates. Cached thread
detail renders at once; transient detail failures get one bounded retry. If
loading still fails, the reader shows the error with an inline Retry. A failed
draft open still shows a Retry action above the floating dock. The reader leaves
enough bottom scroll space to reveal the end of long messages above that dock.
HTML messages in Flutter default to the sender’s original colors on light paper,
including when the surrounding app uses a dark theme. An explicitly saved
Original, Light or Dark appearance remains authoritative. The isolated WebView
retains safe sender CSS, the viewport meta tag, disabled JavaScript and the remote
image consent policy. Authenticated CID images remain embedded data URIs.
Wide newsletter tables use automatic column allocation so un-sized spacer cells
do not divide the text into equal narrow columns. The reader captures inherited
shell dock clearance before Scaffold adjusts its body insets. Height updates come
from load and content-size callbacks rather than pointer-up events.
Regression coverage includes mail_html_document_test.dart,
mail_appearance_test.dart, mail_inline_images_test.dart,
mail_reader_clearance_test.dart and the native
integration_test/mail_html_layout_test.dart. The native corpus contains synthetic
layout structures, including an old fixed-layout negative control; it does not
represent captured vendor messages. Native WebView results, Studio unit results
and CI-pinned Linux golden results are separate evidence.
Notification navigation
Inside Mail, a mail notification row selects its mailbox and thread in the same app tab. The redundant “Open in Mail” action is hidden there; other apps retain that action. Notification reads do not mark email read. The shared bell panel has a 400 px width clamped to the viewport and a fixed height bounded by 560 px, the viewport height minus 24 px, and the available space at its anchor. Its list scrolls inside that frame. Loading, errors, empty states, filter switches and read mutations retain the same frame across apps. Regression coverage lives inpackages/ui/src/components/ui/custom/__tests__/notification-popover.test.tsx;
the shared notification fixture supports state=loading, empty and error.
Mobile incoming-mail notifications
See Incoming Mail notifications for event admission, configured domain authority, recipient preferences, physical-event deduplication, push-entry image privacy, recovery and held runtime verification gates.Snooze and mute
Snooze and mute are personal thread preferences. They do not change another member’s shared mailbox. Snooze hides a thread from your Inbox until its stored UTC deadline, including newly arriving replies. Inbox and Snoozed views refresh while open and on returning to the app; expired threads reappear without a cron write. Snoozing from Archive restores that user’s message state so the thread can return to Inbox. Muted threads remain in the Muted view until unmuted. Both states suppress incoming Mail notification creation and delivery for that recipient. Other mailbox members are unaffected. Unmuting does not replay old muted notifications. Apply20260923110000_mail_thread_snooze_mute.sql after
20260923100000_mail_received_push.sql before enabling these actions in production.
The native swipe settings include Snooze and Mute. Swipe and web actions offer
Undo; reader and web menus support rescheduling, unmuting, and returning snoozed
mail to Inbox.
Calendar invitations and message details
Mail reads scheduling requests from authorized calendar attachments, including Googlemultipart/alternative calendar parts and legacy SES raw MIME. Ordinary
ICS exports (PUBLISH), cancellation notices and calendar replies are files, not
RSVP requests. The responding address must exactly match an invited mailbox;
viewers and group delivery identities cannot send replies. Unsupported delegated
identities and multiple competing event attachments do not expose controls.
Google’s duplicate alternative-body and ICS attachment copies are treated as one
request only when their decoded contents match after newline normalization. Every
copy must independently pass mailbox authorization; differing sequence, attendee,
UID or other content remains ambiguous and hides RSVP controls. Reads are bounded
to eight copies, 256 KiB per copy and 512 KiB combined. This applies to modern
stored attachments and legacy SES raw MIME; regression coverage is in
calendar.test.ts and calendar-sources.test.ts.
The invitation card preserves the organizer, UID, sequence and occurrence when
sending an iTIP REPLY. It displays the original location and time-zone label;
Teams and Google Meet links have a separate join action. It creates no calendar
event copy. A self-organized personal hold is not the organizer’s invitation.
Replies use a persisted invitation claim and an atomic draft-to-sending claim.
Retries keep the same request identity. A pending or uncertain provider result
is checked rather than automatically sent again. Interrupted preparation can
resume with its original request identity, exposed only to its original actor.
For historical threads without indexed iCalendar identity, only the latest
inbound message in the thread can be answered; newer mail conservatively hides
older RSVP controls, including after updates or cancellation notices.
Mobile message details expand to show each authorized From, To and Cc name and
address with native text selection/copy. Bcc appears only when it exists in the
already authorized message data. A resolved empty inbox remains visible during
background refresh; exiting the reader waits for pending archive settlement
before reconciliation.
Focused synthetic verification
Run the calendar parser, attachment worker, reply claim, permission and invitation card tests inapps/mail with one Vitest worker. Run the Mail empty-inbox,
invitation-card and message-details Flutter tests with --no-pub after
flutter gen-l10n. Include existing optimistic/cache/filter/reader tests. Never
send RSVP, archive user messages or create/delete live events for verification.
A timezone-specific recurrence reply includes the original referenced VTIMEZONE
component. Mail does not infer UTC from custom or Windows timezone names. Missing,
competing, malformed or oversized definitions suppress RSVP; supported definitions
use bounded STANDARD/DAYLIGHT observances and common yearly timezone rules.
Scheduling enum parameters are case-insensitive; only individual attendee identities
are eligible, including when CUTYPE is explicitly supplied.
A completed historical request acknowledges its receipt without replacing a newer
reply claim or the current response displayed by either client. Fresh changed
intentions use fresh request identities. Preparation recovery uses the original
stored reply identity, including when reopened in another authorized workspace;
mailbox permissions and the original actor are still required. List refresh remains
available during reader mutations and overlays only the owning mailbox’s pending
reader actions, so unrelated incoming messages remain visible.
Web inbox list responses also replay state changes that were pending when the
request began or started while it was in flight. This applies to pagination and
background refresh in the owning workspace/mailbox. An archived final row stays
hidden while the action is pending; a failed action restores it without removing
new arrivals. The archive folder retains archived rows. The mounted React test
uses the actual inbox, reader, Archive control and action hooks with synthetic
API responses; it covers empty state, failure/retry and refresh after reader exit.
Pending archive refreshes compare the captured conversation revision before
hiding stale results. A newer inbound message in the same conversation remains
visible because it falls outside the earlier archive action. Failure restores
optimistic flags or missing old rows without replacing newer conversation data.
Explicit invitation links to Calendar
On web and mobile, an actionable invitation can be associated with an existing Calendar event by pasting its Calendar event link, viewing both records, and confirming. The preview separates the original invitation’s organizer, invited identity, time, physical location and conference action from the selected event’s account, organizer, attendees and location. A self-organized private hold remains a separate event even when the title and time match. No event is copied, merged, deleted or reparented, and linking never sends an RSVP. Replies continue to use the original invitation’s validated scheduling protocol and identity. The association belongs to the actor and original Mail message. The server rechecks current invitation access, Calendar workspace/account/source access, provider UID and occurrence identity, and preview authority at confirmation. Unknown identity, superseded invitations, updates/cancellations and revoked permissions fail closed. A changed preview requires a new preview; an uncertain network retry reuses its receipt. Metadata compare-and-swap preserves reply claims and other actors’ associations. Remove link deletes only the actor’s association; it never deletes the Calendar event. Opening a linked event requires a fresh Calendar-authorized target. Ordinary ICS attachments do not expose these controls. On mobile, replacing the Mail repository clears the link preview and saved target even when workspace, mailbox and message stay the same. Delayed results from the previous repository are discarded;mail_calendar_link_test.dart covers this
boundary.
Mail-owned association endpoints use the existing message path followed by
/calendar-link: GET reads the actor’s association and authorized target; POST
/preview previews { calendarWorkspaceId, eventId }; PUT confirms that selection
with receipt; DELETE removes the saved association with receipt. All responses
are private and uncached. Calendar owns the read-only event authority endpoint;
Mail accesses it using the configured Calendar origin and existing forwarded
cookie/Bearer authentication, with no Calendar table access.
Native inbox refresh and settings
Opening a Mail notification prepares the inbox alongside the reader. An existing snapshot for the same inbox remains visible, and the inbox revalidates while its reader is open. Background refresh pauses during outstanding optimistic Mail mutations. Network, timeout, and server list failures retry once. Rate limits are not automatically retried and preserve the authorized snapshot; revoked authentication/access is not retried and clears cached content. A failed refresh preserves a previously resolved empty inbox and shows a retry action rather than replacing it with a full-screen error. Cold failures remain visible. These rules apply only within the same account/workspace/mailbox and retain the existing cache permission checks.mail_background_refresh_test.dart and existing inbox mutation tests
cover this behavior; authenticated provider/device proof remains a release gate.
A completed Mail mutation can invalidate a concurrent inbox or detail fetch.
Within an unchanged actor/workspace cache scope, the native repository restarts
that interrupted read once and coalesces concurrent consumers onto the new
request. Repeated invalidations remain bounded and surface a failure for retry;
authentication, access denial, logout and scope clears never trigger this restart.
The reader awaits the API client’s transport timeout rather than starting a
shorter timeout that rejoins the same unfinished request. Real API failures still
use the existing transient-error policy. mail_invalidation_race_test.dart covers
delayed mark-read success/failure, coalescing, bounded restarts, scoped mutations
and denial/logout ABA fences with the actual encrypted cache and repository.
mail_error_scope_test.dart covers awaited fallback and cache-unavailable
publication boundaries, including late errors after a new same-ID session.
Mail quick settings and central App settings use the same mailbox settings
editor. Central settings resolves real mailbox membership before opening the
editor; members keep personal device options and only owners/admins edit mailbox
configuration. Mail settings uses the existing shell title and bottom Back/Save
actions, without a second app bar. Unsaved mailbox changes require confirmation
to discard; saves block exit until settled. Account or workspace transitions
cancel the editor, including a switch away and back.
mail_settings_navigation_test.dart covers the title/actions and edit guards.
Retained sender image and gradient backgrounds in Original view keep their
foreground colors, because a background-color alone does not establish the
painted contrast. An opaque solid child resumes contrast correction.
The immediate request reader checks monotonic elapsed time before and after each
stream read, including end-of-stream. Immediately resolved chunks cannot bypass
the ten-second deadline while timer callbacks await service; wall-clock changes
do not extend it. The existing byte/chunk/selection limits and authenticated
request ownership remain unchanged. Deadline regressions count actual stream reads
at the exact boundary; this bounds request intake, not automatic draining or spend.
Personal Gmail and Outlook accounts
Mail offers Connected accounts in a personal workspace. New Gmail and Outlook connections and reconnects are in internal early access for verified Tuturuuu staff. Existing connected accounts keep their workspace and account ownership checks. Managed Tuturuuu mailboxes keep their staff, reviewer, and mailbox-role checks. Connections belong to the authorizing user, not to workspace members or shared mailbox delegates. Account discovery and every provider operation bind both user and workspace before decrypting credentials. The connected view reads provider mail directly. Inbox, Sent, Drafts, Archive, Trash and Spam, provider search, pagination, read state, stars, archive, trash and restore therefore operate on Gmail/Outlook rather than a separate local mirror. Mailbox operations use immutable Outlook IDs. Refresh retrieves current provider state; this view does not implement push notifications, offline mail storage, custom-folder/label management, or Google Tasks/Microsoft To Do synchronization. Calendar account consent remains separate from Mail consent. Compose, Reply, Reply All and Forward send through the connected provider. Reply-To can contain multiple addresses; Reply All retains To/Cc roles, removes the user’s address and deduplicates case-insensitively. Replies to sent messages target the original recipients. Bcc is never copied into a reply. Forwarding copies selected original attachments from authorized source bytes and starts without recipients. MIME carries Unicode subjects, threading headers and calendar scheduling types. Gmail replies and reply drafts additionally retain the authorized provider thread ID when the subject is unchanged apart from reply prefixes; forwards and changed subjects start a new conversation. Attachments are limited to 10 MiB in the browser and outbound MIME to 20 MiB. Message preview and JSON request reads have bounded server-side limits. Aggregate attachment bytes are checked before MIME encoding, including forwarded copies. Drafts are saved in the provider mailbox and can be opened, edited, and sent from Drafts. Gmail edits update the existing draft. Graph does not support updating a draft with raw MIME, so an edit first creates a confirmed replacement and deletes the unchanged original with an ETag fence. A deletion conflict retains both drafts and reports that partial outcome. Untouched draft HTML, inline image content IDs, threading headers and attachment bytes are preserved. Original HTML is recovered from the authorized provider source for saving; previews still use sanitized content. Save edited drafts before using the native Drafts send action. HTML previews use a script-disabled sandbox and a restrictive CSP; remote images are blocked. Original attachments download as files withnosniff. Personal
calendar invitations use the same bounded iTIP parser as managed Mail. Accept,
Decline and Tentative send a single-attendee METHOD:REPLY to the stored organizer,
retaining UID, sequence and recurrence identity. No calendar event is copied into
Tuturuuu, and ambiguous/delegated/cancelled requests do not expose RSVP controls.
OAuth setup and delivery verification
Configure these server-only variables for the Mail deployment:MAIL_CONNECTED_ACCOUNTS_KEY: a dedicated 32-byte encryption key encoded as 64 hexadecimal characters. Credentials and PKCE verifiers use AES-256-GCM with the authenticated user ID as associated data. Keep the key stable; changing it requires reconnecting accounts.MAIL_GOOGLE_CLIENT_ID,MAIL_GOOGLE_CLIENT_SECRET,MAIL_GOOGLE_REDIRECT_URI.MAIL_MICROSOFT_CLIENT_ID,MAIL_MICROSOFT_CLIENT_SECRET,MAIL_MICROSOFT_REDIRECT_URI.
https://mail.tuturuuu.com/api/v1/mail/connected/callback. Before admitting the
apex mount, register https://tuturuuu.com/mail/api/v1/mail/connected/callback
alongside the old callback in both providers. Configure the additional
server-only MAIL_GOOGLE_APEX_REDIRECT_URI and
MAIL_MICROSOFT_APEX_REDIRECT_URI only after registration. Each request selects
an exact configured callback by its serving origin and /mail mount; it never
trusts a forwarded host or redirects authorization across hosts. The callback
exchanges the code using that same registered URI, clears state at its matching
cookie path, and returns to the inbox under the serving mount. An unconfigured
host fails closed. Existing subdomain configuration remains the default.
Webhooks, OAuth callbacks and WebSockets also continue to be served on the old
subdomain until it only redirects. Provider registration and production routes
remain separate owner operations.
Callback selection and both providers’ mounted start/completion behavior are
covered by oauth-callback-url.test.ts, oauth.test.ts and
oauth-callback.test.ts under apps/mail/src/lib/mail/connected/.
Enable the Gmail API and grant
https://www.googleapis.com/auth/gmail.modify. This is a restricted Google scope;
complete the provider’s required consent verification before public rollout.
Register the Microsoft app for organizational and personal Microsoft accounts
when both are intended. Scopes: User.Read, Mail.ReadWrite, Mail.Send,
and offline_access; Mail requests no Calendar scopes.
OAuth uses PKCE, random hashed state, an HttpOnly SameSite browser cookie, a
10-minute expiry, atomic state consumption, and renewed personal-workspace access
checks during the callback. Private connection, OAuth and send-claim tables have
RLS and no anon/authenticated grants. Expired tokens refresh on the server;
refresh writes compare revisions; only a newer scoped, valid winner can resolve a conflict.
An unauthorized read can refresh and retry once; mutations are not automatically
replayed. Disconnect removes local access and encrypted credentials without
changing provider messages. Before deleting a Gmail connection, the server posts
the stored refresh token (or the access token when no refresh token exists) to
Google’s OAuth revoke endpoint with a 5-second timeout and no retry. Microsoft has
no app-scoped revocation endpoint, and Graph revokeSignInSessions would sign the
user out of every app, so deleting the stored tokens is the Outlook revocation;
users can remove consent at https://account.live.com/consent/Manage or
https://myapps.microsoft.com. A failed, rejected or timed-out revocation never
blocks the disconnect: the row is still deleted, a token-free console.warn is
logged, and the response reports { disconnected: true, revoked: false }.
Coverage lives in revoke.test.ts and route.test.ts under
apps/mail/src/lib/mail/connected/. The Privacy Policy’s “Google user data in
Tuturuuu Mail” section (packages/legal/src/mail-google-revision-2026-11-21.ts)
describes this disconnect behavior and the Limited Use commitments.
When a token refresh shows that the user revoked access or the grant expired, the
server deletes that account’s stored credentials automatically. This is how
Mail stops accessing the account and deletes the stored tokens, as the Privacy
Policy states. The trigger is an HTTP 400 invalid_grant from the token
endpoint. For Google, that response is enough unless its error_subtype is
invalid_rapt (a Workspace re-authentication request). For Microsoft, every
reported code must be one of AADSTS 70000, 70008, 50173, 700081 or 700082 (grant
revoked or expired), with no suberror other than bad_token or
token_expired, and a 70000 that mentions scopes does not count. Credentials
are kept for network errors, timeouts, 5xx, rate limits, invalid_client and
other configuration errors, and for sign-in code exchanges. They are also kept
for Microsoft consent or interaction errors (65001, MFA, Conditional Access,
password expiry) and disabled accounts, because a scope or policy change on our
side can cause those for every account at once. The delete matches exactly one
mail_connected_accounts row: the disconnect predicate (id, user_id,
ws_id) plus the revision the failed refresh read. Send claims and receipts
cascade with the row, as they do on disconnect, so a send whose refresh finds
the grant revoked returns the same 409 rather than a claim-release failure, and
a reconnected account starts with no duplicate-send history. A concurrent
successful refresh or reconnect writes a newer revision, so it is adopted
instead of deleted. A row that is
already gone makes the delete a no-op. The server logs one console.warn with
only the account id and provider, never a token, code or response body. The
request fails with 409 Mail account access was revoked; reconnect it, which
the connected pane shows like the existing reconnect error. Coverage lives in
grant-revocation.test.ts and send.test.ts under
apps/mail/src/lib/mail/connected/.
Sends reserve an account/request claim; acceptance records a receipt. Proven pre-send
failures or explicit provider rejections release only their matching sending claim for user retry.
Completed requests acknowledge without resending; in-flight, unknown or post-acceptance failures require provider Sent checks.
Provider acceptance is not a delivery receipt. Test only with disposable mail and
meeting fixtures unless real-account actions have been explicitly authorized.
Regression coverage: apps/mail/src/lib/mail/connected/*.test.ts, connected
composer/reply tests, managed mail-reply-actions.test.ts, and the private-table
checks in apps/database/supabase/tests/connected-mail-accounts.sql. The DB gate compares
the three generated private Mail table contracts against committed types, ignoring
only presentation; it does not certify unrelated schema drift. Require the
Mail and affected workspace CI type-check, lint, tests and real app builds for the
exact authored commit. Synthetic tests do not prove provider consent, delivery or RSVP;
verify those with configured test accounts after deployment.
Complete-schema database gate
TheConnected Mail database contract workflow runs on normal pull-request updates that change migrations, its fixture or verifier. It checks out the exact PR head, applies every tracked Supabase migration in an isolated hosted database, and requires all 10 assertions in connected-mail-accounts.sql to pass without skips. Its enabled-gate check fails if the workflow is disabled.
After TAP succeeds, it generates actual public, private and storage schema types and uploads connected-mail-accounts-types-<head> for three days. Inspect the exact run’s reset, fixture-labelled TAP, type-generation and owned-project stop results, then compare the downloaded types with the authored private Mail tables before merging. A generated artifact or staging wrapper success alone does not prove the entire contract. This disposable gate does not apply production migrations or establish provider consent, mailbox delivery or RSVP outcomes.
Native Mail type boundary (candidate)
Scope: Mail’s native frontend defaults to strict noncomposite noemit app checking, then genuine Mail-only declarations, then the actual noDOM Worker check. Both app programs retain all current roots and imported-source checking; shared package export/build/check owners remain authoritative.bun run type-check sequences app, boundary and Worker. The boundary emits into .typecheck/app with rootDir ., noEmitOnError and incremental false. The Worker resolves only emitted #mail-handler declarations; Vite resolves that exact alias to the real source. Inherited Turbo prerequisites and .typecheck/** outputs are preserved. Direct Mail production/test imports use package exports: the narrow Supabase realtime-log-actions entry follows its existing dist-types/source-Bun/dist-JS convention and build roots; Satellite workspace/invitation entries already exist. The app-local resolver exempts server suppliers when porting client calls, avoiding recursive transport aliases. No supplier or shared producer is changed. Static edge regressions remain authored UNRUN; real compiler external-source classification still requires exact-source CI.
Limits: generated binding-only declarations must come from the qualified emitted deployment config. Pinned compiler workspace-external classification/rootDir behavior, declaration closure and clean/restored-cache acceptance remain unproven. Missing bridge/ambient isolation regressions are authored UNRUN in apps/mail/src/runtime/type-programs.test.ts; source assertions do not establish compiler or workerd acceptance. Unexpected foreign emission or incompatible contracts stop qualification without source exclusions. Logger timer/buffer lifetime and all provider/runtime delivery gates remain parent-owned; this decision adds no scheduler or resource.
Mounted Mail API helpers receive raw /api/... paths; the shared resolver adds /mail
for Mail routes and leaves Web routes at root. Browser and server adapters register
once and read request context at call time. Rendered attachment href/src values use
the base helper; text/DOCX helpers receive raw protected URLs. CID images get the
mount when serialized into preview HTML. See mail-api-options.test.ts,
mail-attachment-card.test.ts and mail-message-preview-utils.test.ts.
Mounted page, API and function middleware relies on the shared apex Supabase
session. It skips cross-app token consumption, satellite session refresh and
Supabase cookie clearing; OAuth state cookies remain scoped to their flow.
Root-mode Mail keeps its existing satellite session behavior. The required
NEXT_PUBLIC_SUPABASE_URL Worker secret is declared in the native artifact
profile and remains separate from browser build-time configuration. See
proxy-auth.test.ts for the no-session-cookie-write regression.
Google restricted-scope verification
Mail requestshttps://www.googleapis.com/auth/gmail.modify, a Google
restricted scope. Until Google approves the OAuth client, only accounts listed
as Test users on the consent screen (or Internal users) can complete consent;
everyone else sees an “app not verified / access blocked” screen. Approval needs
OAuth verification plus a CASA security assessment, renewed yearly.
Prerequisites before submitting:
- The public Privacy Policy discloses Gmail access and the Limited Use
commitments (the “Google user data in Tuturuuu Mail” section), and the claims
match the code: encrypted credentials, revoke on disconnect, and automatic
credential deletion on
invalid_grant(see above). - The consent screen carries the production home, privacy and terms URLs, the
authorized domain and the logo, and lists only
gmail.modifyfor this client.
gmail.modify is the narrowest scope covering reading
threads, changing labels (read/unread, archive, star, move), moving to Trash and
sending. gmail.readonly cannot modify or send, gmail.send cannot read, and
gmail.labels and gmail.metadata cannot read bodies. Full mail.google.com
access is not requested. Data serves only the connecting user’s features. It is
never used for advertising, sold, or used to train generalized AI or ML models.
Demo video (unlisted, 2-3 minutes, demo data only):
- Sign in to
tuturuuu.com/mailwith the URL bar visible. - Connect Gmail from settings, showing the consent screen with the app name,
client_idand permission text. - Show the inbox loading, then each scope use (read, mark unread, archive, label, star, Trash, reply), with the effect visible in Gmail’s own UI.
- Disconnect, then show the revoked access at
https://myaccount.google.com/permissions. - End on the Privacy Policy URL.
tuturuuu.com/mail with a test account, and
fix high or critical findings first; the security default holds releases on them.
Then submit the report and SAQ through a Google-authorized assessor portal. Paid
assessments need owner approval. Microsoft Graph delegated mail permissions have
no equivalent review; optional publisher verification only removes the
“unverified” label.
Pending Meet drafts
The two Mail clients share the explicit Meet draft preview. A fragment is parsed as untrusted draft data and matched to the current authenticated actor and the server-verified workspace UUID, including personal alias routes. It cannot select an account, mailbox, From/Cc/Bcc, reply source, HTML or attachments. Mail retains normal source selection and account/mailbox permissions. Arrival and parsing perform no draft or send mutation. Only Open draft may initialize a composer. A managed nonempty draft then follows normal autosave; connected account drafts use normal explicit Save draft or Send. Import itself never sends an email or a provider invitation. Subject/body tags are literal text, not imported markup. No notes, transcript or private recording URL is accepted. An open or retained composer blocks import without saving or replacing its contents. The user can keep it and explicitly open the handoff in a new Mail tab. Duplicate hashes and rerenders do not import again. Actor/workspace mismatch, expiry, unavailable browser replay protection and source changes during an import claim fail closed. A valid payload hash is removed immediately with history.replaceState; the pending draft stays only in actor/workspace-scoped memory across Mail source changes. New-tab transfer uses a short-lived same-origin BroadcastChannel and a random channel ID in the URL, never another email-bearing URL. Closing the tab, an expired channel, unsupported BroadcastChannel or lost memory requires a fresh handoff. Plaintext is not stored in replay receipts or application logs. A corrupt receipt store is cleared, but that claim is refused. Matching actor/workspace UUIDs does not authenticate who issued the link. Every preview warns, “Opened from a link — check the recipients and subject before sending”. Recipients remain visibly marked “Outside workspace or unverified” unless the existing permitted people search positively returns a matching workspace member. Contact-only results, hidden emails, failed/pending lookups and addresses too long for the bounded search remain unverified; they are not silently classified as members. At most 20 bounded lookups run per preview, without retry or focus polling. Subjects containing URL-like strings are rejected. See Meet’s protocol and browser limits. Signed-out resume is not guaranteed; a fresh handoff may be necessary after login. Client native loaders must project pathname/query before any server-function serialization, and the native workspace adapter must supply its verified UUID. These boundaries require explicit native acceptance in addition to component tests.People, profiles and sender blocks
Scope: the web Mail client (list rows, message header, message details and compose recipients). Flutter Mail is not covered.Resolving addresses to people
Mail resolves sender and recipient addresses throughPOST /api/v1/workspaces/{wsId}/people/resolve in Web. The caller must be a
member of the workspace and hold view_users_public_info or
view_users_private_info. A request carries 1 to 50 addresses and matches each
one exactly, ignoring case. Only members and contacts of that one workspace are
returned; other workspaces are never searched. HIDE_MEMBER_EMAIL and the other
HIDE_MEMBER_* settings apply. If they cannot be read, the request fails
instead of revealing data. An address with no match comes back as unknown.
A resolved address shows its display name and avatar, with a profile card on
hover or focus. An unknown address shows the email and an Add to Contacts
action. That action follows
explicit Mail sender creation.
Compose suggestions
To, Cc and Bcc suggest workspace members, contacts and the mailbox’s recent correspondents in one ranked list. Each address appears once, labelled as the strongest match (member, then contact, then recent). Rows are ordered by match quality, then recency score, then kind. The recency score covers 180 days: each message countsexp(-age / 30 days), and mail the mailbox sent counts double.
Matching ignores diacritics, so Vietnamese names match unaccented queries. A
member whose email the workspace hides is shown as a disabled row. The
correspondents route has the same access gate as drafts.
Sender blocks
Mailbox owners and admins can block a sender address or a domain. A domain block also covers its subdomains. Shared providers such asgmail.com cannot be
blocked as a whole domain. Ingest checks every new message against the blocks.
A blocked message gets the system blocked label instead of inbox. It sends
no push notification and is not forwarded or auto-labelled. Nothing is deleted.
It is listed only in the Blocked folder. Adding a block can move existing
mail into Blocked, and removing it can move that mail back.
workspace_users.mail_blocked mirrors whether any mailbox linked to the
contact’s workspace blocks that contact. Only Mail can write this field; a
trigger rejects any other write. A new personal mailbox is linked to its owner’s
personal workspace. It is linked only when it has exactly one owner, that owner
created it and has exactly one personal workspace, and it is neither an employee
mailbox nor an adopted one. Any other mailbox is left unlinked for an admin to
link.
Regression coverage: workspace-people-resolve.test.ts,
people/resolve/route.test.ts, correspondents-ranking.test.ts,
recipient-ranking.test.ts, sender-blocks/match.test.ts,
sender-blocks/store.test.ts, message-details-model.test.ts, and the pgTAP
suite mail-contacts-sender-blocks.sql.
Composer clipboard media
The Mail composer queues pasted image files inline and other pasted files as attachments. Embedded PNG, JPEG, GIF and WebP images in rich HTML use the same upload queue; surrounding formatted text is retained. Remote HTML image URLs remain image references. Upload failures retain retry controls and show their reason in a toast. This applies to both classic and Sorbet themes. Clipboard regression coverage lives inmail-composer-paste.test.ts.
The body editor fills the remaining composer height in the dialog, full-screen
and mobile layouts. Empty body-space clicks focus the end of the message;
text selections and toolbar or attachment actions retain their own behavior.
Long messages scroll within the body. Coverage is in
mail-composer-editor-media.test.ts.
Composer upload limits and inline image preparation
Mail draft attachments use a 10 MiB per-file and combined attachment limit. Only the exact draft-attachment POST route admits that file budget plus 64 KiB of multipart metadata. Other API routes retain the shared 512 KiB request limit. The hosting platform can impose a smaller request limit: Vercel Functions accept at most 4.5 MB including the multipart envelope. The Cloudflare Worker path retains the Mail application limit even when its zone allows larger request bodies. Pasted inline images larger than 448 KiB are prepared in the browser before upload. Static images are resized to at most 1800 pixels on their longest edge and encoded with bounded quality and scale attempts. Small images retain their original bytes. Large animated or unsupported images are rejected with a localized message rather than silently flattened. The original local preview remains while preparation and upload run; failure keeps Retry and Remove available. New inline images initially display at no more than 320 pixels wide, retain their aspect ratio and remain resizable. Saved and sent HTML retains the chosen display width. Regression coverage:mail-inline-image-preparation.test.ts,
mail-composer-editor-media.test.ts, attachment-upload-policy.test.ts and
proxy-auth.test.ts. A real browser decode check covers an input PNG over 5 MiB
and validates that the prepared multipart body fits below the shared request cap.
Mobile message reader
The Flutter reader uses the shell title and floating-dock Back control. Its Conversation tab retains message ordering and authenticated inline-image handling; the Attachments tab lists authorized files with image thumbnails and type icons. Image previews open above the shell with zoom controls. Scroll content consumes the shell bottom inset so the dock leaves the final controls accessible. Sender and recipient presentation uses the workspace-scoped people resolver when available, with visible header names and initials as fallbacks. Hidden profile emails do not supply labels, initials or detail addresses. Resolution failures retain the message and offer an explicit profile retry; they do not broaden the lookup to a member list. The collapsed Message details panel exposes only supplied recipient metadata, localized Sent/Received times and allowlisted delivery fields. Raw Date remains under a separate Technical headers disclosure. Reader actions expose snooze, labels, read state, star, archive and trash using the existing mailbox mutation contracts. Concurrent read requests are deduplicated. The grouped action sheet uses the message subject and shows one applicable snooze, mute and read action for the supplied message state. Restore uses the folder from which the reader opened (Archive or Trash), because delivery status does not carry the current user’s archive/trash state. Messages and threads that are entirely quarantined do not offer Restore, Archive or Trash: those mutations do not remove quarantine. Mixed threads keep organization actions for their legitimate messages. Removing a quarantined message from Spam requires a separate supported not-spam action. Reply and forwarding controls remain in the message footer when sending is permitted, without duplicating a primary Reply action owned by the shell. Equivalent same-scope message updates retain authenticated inline-image bytes and their viewer metadata. The isolated HTML body compares inline mappings by content, and a workspace-owned bounded memo retains measured heights by content, rendering options and pane width. Width changes remeasure the native view without recreating it. Image placeholders preserve supplied HTML dimensions or attachment and MIME dimensions; unknown thumbnails use a bounded fallback frame. These lifecycle rules do not enable scripts, remote image loads or new API access. Image thumbnail reads are limited to four automatic tiles with known sizes up to 4 MiB; other attachments retain their type, name, available size and download. PDF preview: deferred. PDFs retain a type icon, name, size and download/open-with through the platform share flow. First-page thumbnails and PDF page viewing need a separate renderer dependency review covering binary size, iOS/Android build impact and licence; this reader change adds no native PDF dependency. Regression coverage:mail_reader_actions_test.dart,
mail_reader_design_test.dart, mail_message_details_test.dart,
mail_message_delivery_test.dart, mail_people_resolver_test.dart and
mail_attachment_tile_test.dart, mail_reader_sheet_test.dart,
mail_html_lifecycle_test.dart and mail_reader_clearance_test.dart. Golden
generation requires the CI-pinned Linux Flutter toolchain.