Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

44.1 KB
Raw Blame

Email feature architecture

Email applies the stronger composition and capability boundaries in Frontend feature architecture. Its reusable packages live under apps/web/src/features/. The application still opens /app/email/:threadId, and existing drafts and mailto composition use the same application routes.

Ownership

Package Owns Does not own
packages/email-renderer Deterministic preparation of HTML/plaintext bodies; framework-independent browser containment, colors, layout, and resource lifecycle Solid, message DTOs, threads, app services, sender classification, block state
email-message A received or sent message, its sender/header, body renderer lifecycle and policy, Macro Markdown, quote expansion controls, and attachment presentation Thread ordering, pagination, selection policy, drafts, reply placement, navigation, block state
email-thread A conversation, chronological ordering, hidden middle messages, pagination, draft association, reading stops, selection, scroll coordination, and where a reply appears Rendering the internals of an email, editing or sending a draft, block lifecycle
email-compose Form state, recipient rules, editor content, attachments, draft persistence, sending, scheduling, signatures, and undo recovery Thread pagination/rendering, block identity, app routes or split navigation
block-email The legacy document-block adapter plus host-neutral thread body shared with the Email view: load gate, read marker, modals, side panel, and host actions Reusable thread, message, composer state, or a host's top bar

An email thread and an individual email are independent features. A message can be rendered without a thread provider. A composer can run without a thread: the standalone new-email route and the AI compose surface are examples. A reply takes a narrow EmailReplySession describing only the conversation information it needs.

Dependency arrows mean “imports or consumes”:

flowchart TD
  Block[block-email adapter] --> HostView[email thread host view]
  EmailView[email view detail] --> HostView
  HostView --> ThreadRoot[email-thread production entry]
  ThreadRoot --> Thread[email-thread surface and state]
  ThreadRoot --> Adapters[production adapters and shared queries]
  Thread --> Message[email-message view]
  Thread --> Compose[email-compose view]
  Compose --> Model[email-message core types]
  Message --> Model
  Message --> RendererBrowser[email-renderer/browser]
  RendererBrowser --> RendererCore[email-renderer core]
  Adapters --> Contracts[feature-owned contracts]
  Thread --> Contracts
  Compose --> Contracts

email-message must never import email-thread or email-compose. email-compose must never import email-thread. Thread composition may import both features' reusable views and contracts. No module in these three packages may import a block package, @core/block, or block-related signal modules.

Production entry points and reusable surfaces

  • email-message/views/email-message.tsx receives one EmailMessage plus resolved presentation values and event callbacks. Its caller provides the rendering context, selection, expansion, reply actions, and footer.
  • email-thread/email-thread.tsx constructs the existing shared thread query, source adapter, viewer/contact capabilities, thread commands, composer capabilities, notification subscription, rendering adapters, and host-independent cache cleanup. views/email-thread-surface.tsx builds thread state and providers from supplied contexts. It imports no production entry point for a nested message or composer.
  • email-compose/email-compose.tsx supplies the production compose context and split-host callbacks to views/email-compose.tsx. Desktop mounts it in the Email view's mail-compose route (email-view/components/EmailComposeRouteView.tsx); touch keeps the email-compose component split. Inline replies use views/reply-input.tsx with explicit capabilities and a reply session. email-thread/views/thread-reply-input.tsx owns the keyed reply lifetime; email-compose/primitives/reply-composer.ts owns the compose workflow.
  • block-email/EmailBlockAdapter.tsx translates block focus, keyboard scope, location parameters, and block methods into EmailThreadHost callbacks. block-email/EmailThreadHostView.tsx composes the shared thread body without reading block state, so the Email view can mount it directly and compose its own top bar. The thread does not read a block ID or register a block method itself. The adapter captures block signal accessors during setup; event callbacks use those captured functions instead of resolving a provider after setup.
  • email-view owns an EntityDetailNavigationStack. Ordinary list activation mounts the thread inside /app/component/mail; Shift-open navigation continues through the standalone /app/email/:threadId block. The filtered data source outlives the list UI so Previous, Next, Mark done, and restored list focus keep their source order while detail is mounted.

Capability contracts and provider/consumer modules live in context/. Prepared view-state types live in primitives/; views mount the providers. These scoped UI providers have no production fallback. A missing required provider throws a specific error instead of silently initializing the app.

A host frame receives a content factory, () => JSX.Element. It must call that factory beneath its providers. Constructing the content first and then passing an already-created element to the frame can make nested side-panel sections execute before their layout provider exists. The surface regression test exercises this ordering.

Contracts and layer responsibilities

Contract Consumer needs
EmailThreadSource Requested identity, available domain thread, request status, pagination availability, and refresh/page completion
EmailThreadCommands Thread actions and their availability; no soup collection or mutation objects
EmailThreadContext Thread source, viewer and device state, recipients, and the command factory used by thread state and navigation
EmailThreadViewContext Thread and compose contexts, plus view callbacks and optional compose host behavior
EmailThreadHost Optional location target, focus, activation status, and keyboard registration
EmailRenderingContextValue Theme values, explicit image policy, Macro read-receipt pixel prefixes (hidden unless the thread lets a copy count an open), link preparation, and image resolution with an abortable resource lifetime
EmailFormContextInputs Viewer address and available inbox identities for recipient selection
EmailReplySession Thread identity, recipient options, personal-reply classification, a targeted reply request, and host intents for leaving the composer or removing its draft
EmailDraftStorage Save/delete and restore an undone draft, and drop a moved draft's working copy; inputs use domain inbox IDs and completion intent
EmailAttachmentStorage Upload, forward, and remove draft attachments
EmailDelivery Send, undo, schedule, unschedule, and archive operations, and each queued send's progress
EmailComposeFeedback User notices and error reporting
EmailComposeAccounts Inbox identities, availability, and the primary inbox
EmailComposePresentation View-only device state, signature visibility, upgrade action, and link preparation
EmailEditorFiles View-owned editor file upload and sharing integration
EmailComposeContext Compose capabilities supplied to views, which pass the narrow inputs each controller needs
PersistedEmailIdentity Successful save/send result: draft, thread, and inbox identity without a transport envelope
EmailComposeHost Optional navigation, a moved draft's destination, the route's draft, back handling, and focus movement supplied by the host

Core types are owned by the features. Generated email service schemas and concrete query results stop at adapters. email-thread/queries/thread-source.ts uses toEmailThread to explicitly project typed transport values and guards Solid resource reads. This projection does not validate unknown input: reserve names such as decode or parse for transformations that actually do that work. The projection selects the fields the features consume and copies nested contacts, labels, and attachment records. It preserves absent versus empty body content, provider IDs needed for replies, attachment/CID identities, and project navigation metadata. Sync headers and unused transport display settings stay out of the models. email-compose/queries/inbox-source.ts projects linked-account metadata. Actual service-client operations remain in src/lib/queries/email, alongside the existing mutations and cache conventions.

Compose controllers receive named drafts, attachmentStorage, delivery, notices, and accounts capabilities plus the values their workflow needs. They do not receive EmailComposeContext, presentation, or editorFiles. The view wires file-paste/drop plugins, document sharing, upgrade actions, device layout, and signature-link preparation. The reply controller receives a focus policy accessor and reports content edits; it does not choose a device layout.

Primitives accept these domain capabilities; they do not construct shared queries, import production adapters, or return JSX. The compose controllers use the real Lexical editor API. That is an intentional editor dependency, not an application service dependency. The narrow shared utils/setEditorStateFromHtml.ts helper avoids the broad editor utility barrel and its plugin/application side effects.

Components receive values, slots, and handlers. For example, inbox names and watermark upgrade actions are supplied from production wiring; the inbox selector and signature button do not resolve the current user themselves. Clipboard feedback, uploads, signature link interception, and editor focus traversal are also supplied capabilities or host actions.

Responsibilities within a feature

A feature boundary is not sufficient if a controller still owns every concern inside it. Keep a primitive around one invariant or lifetime, and share it when two controllers implement that same behavior. Avoid splitting a workflow into helpers that need the entire controller passed back to them.

The compose controllers now assemble these smaller responsibilities:

Module Responsibility and boundary
attachment-persistence.ts Upload/remove operations and completion tracking. Receives attachment state and three transport capabilities. A saved attachment ID does not mean its content upload has finished; every save waits for outstanding uploads.
email-send-schedule.ts Confirmed send time, pending changes, unscheduling and archive feedback. Send Later and schedule updates save the draft first, then schedule it through the REST endpoint. Cancellation only unlocks editing after confirmation.
draft-session.ts / draft-persistence.ts Shared draft identity, queued-write status, rejection policy, and save/delete ordering. Server identity and a committed latest save are separate facts; uploads and updates to existing legacy schedules wait for a committed save.
send-readiness.ts Outbox admission allows offline delivery with complete attachment references and rejects unfinished uploads.
draft-autosave.ts One debounce and serialized write queue used by reply and standalone compose. Captures editor values before queueing, flushes pending edits when visibility changes and on disposal, retries a failed local write on visibility changes and disposal unless cancelled, and exposes cancellation and completion for send/discard.
reply-recipient-fields.ts Recipient field expansion, drag/drop and outside interaction. Receives values, a setter and a change callback; it knows nothing about saving or sending.
reply-composer-focus.ts Deferred editor/recipient focus and the forward focus guard. Receives DOM accessors and an editor focus() capability. Its timers, animation frames and event listeners end with its owner.
views/reply-envelope.tsx Sender, recipients and subject presentation. One recipient input implementation supplies the desktop/mobile layouts while the parent keeps a single editor mounted.

A reply retains the draft ID and the thread returned by persistence together. Changing the sender can move the draft to another inbox's thread; the displayed conversation still owns focus, completion and local undo recovery. Each serialized save reports its previous persisted thread to the production adapter, which marks both affected message caches for cleanup on disposal. Undo retains the selected inbox and envelope and reconciles the actual sent thread, even after navigation. Discard and scheduling also address the persisted thread.

The reply controller still owns draft collection, sending, reset and undo as one coordinated workflow: they share editor snapshots, draft identity and pending operation guards. Breaking that sequence into mutually dependent controllers would make ordering harder to inspect. Its view receives named actions and pending accessors instead of mutation objects, and derives layout details itself.

The shared autosave primitive wraps @solid-primitives/scheduled with explicit pending-edit tracking and a disposal flush. Debounce cancellation alone would lose the last edit. The queue captures body/envelope/inbox values before waiting; each write uses the draft ID allocated by the preceding write. An ID is retained before uploads finish so a failed upload can still be retried or discarded. Attachment membership is reconciled after the save, so a forwarded file removed while saving is not added back from an old snapshot.

Cached forms contain values and an edit revision. They retain no editor, controller callback, focus flag, or timer. Reset/clear restore values without emitting a user edit. The mounted reply controller observes edits and owns focus and quote commands, including cancellation of deferred work. Showing an existing quote is idempotent across editor remounts. DOM listeners use the installed @solid-primitives/event-listener cleanup.

flowchart TD
  View[Mounted compose view] --> Controller[Reply or standalone controller]
  View --> Presentation[Device and signature presentation]
  View --> FileIntegration[Editor upload and sharing capabilities]
  Controller --> Form[Form values and edit revision]
  Controller --> Editor[Mounted Lexical editor and focus lifetime]
  Controller --> Save[Shared draft autosave queue]
  Controller --> Schedule[Schedule workflow]
  Schedule --> Save
  Save --> DraftContract[Draft storage contract]
  Controller --> Attachment[Attachment persistence]
  Attachment --> AttachmentContract[Attachment storage contract]
  Schedule --> DeliveryContract[Delivery contract]
  Controller --> Host[Host intent callbacks]
  Controller --> Feedback[Feedback capability]
  Production[Production adapter] --> DraftContract
  Production --> AttachmentContract
  Production --> DeliveryContract
  Production --> Queries[Shared queries, inbox headers and cache reconciliation]

These are dependency edges, not event flow. Cached form values do not point back to the editor or controller. A reply's host owns message selection and DOM focus; the composer requests exitToThread('last' | 'selected'). The thread resolves that request inside its own container, including when two split panes contain the same message. Standalone compose receives a draft seed directly, rather than receiving an entire thread session to look it up.

Production adapters translate domain inbox IDs to transport headers. They also own preview invalidation, old-thread reconciliation when a draft changes inbox, and restoring sent-message caches during undo. A composer supplies the saved content and intended thread completion; it does not name query keys, choose between cache implementations, or sequence cache repair calls.

Thread state composes thread-drafts.ts for stale-response reconciliation and thread-recipients.ts for contact aggregation. thread-navigation.ts owns reading stops, focus and scrolling; thread-reply-area.ts owns bottom/drawer reply placement. Thread reset and cached-draft auto-open remain in one effect so reset cannot overwrite an immediately available draft. Production read/unread and completion/undo wiring live in separate adapters, with one shared link-header converter created by thread-action-adapter.tsx. EmailThreadViewContext supplies the EmailThreadContext consumed by state and navigation, alongside the compose context and view callbacks. State creates one retained thread snapshot and passes that accessor to the injected command factory, so commands and reading state cannot disagree because they retained separate snapshots.

Async completion and naming

TanStack remains in the production/query adapters. A write capability is a plain async function: it resolves when its write succeeds and rejects when the write fails. Do not wrap it in another mutation object with its own result, callbacks, error state, or start() method. createComposeOperation was removed. The shared query layer owns requests and cache conventions; feature workflows own ordering between draft persistence, attachments, send, schedule, and undo.

Each composer keeps a local idle | preparing | sending phase because those phases span multiple writes and multiple composers can share the same production capabilities. This is workflow state, not a second server-state cache. Autosave's serialized queue, schedule's exclusion guard, and the attachment set of outstanding uploads each protect a concrete ordering invariant.

A successful server write stays successful if analytics, cache refresh, toast, or navigation work fails afterward. Query callbacks catch/report their own post-write errors, including detached refresh rejections. Moving a throwing callback into TanStack's lifecycle callbacks alone does not establish that separation: the installed mutation implementation awaits those callbacks within its failure handling. Adapter tests therefore exercise real TanStack mutations.

Failure Owner and behavior
Draft save/delete or attachment write Existing shared mutation reports the write failure; callers do not add a second schedule/save notice.
Send Composer reports the failed send once. A failed reply restores only its original still-mounted editor; a newer editor's work is preserved.
Queued send that fails later The send notice reports the failure; a reply that marked its thread done returns it to the inbox.
Schedule/unschedule Schedule workflow reports the failed request and keeps the last confirmed time.
Post-send refresh/navigation/analytics Report the presentation/cache error; do not report that delivery failed or enable a duplicate send.
Archive after scheduling Keep the confirmed schedule and identify the archive failure separately.

Replies still clear optimistically when dispatch starts. After successful send, the controller establishes the mark-done undo handle before starting a detached, error-reported refresh. A slow refresh must not delay Undo or leave an Undo-restored editor disabled. Each send owns its mentions, completion target, and undo handle; sending again must preserve the earlier notification's undo action. Standalone compose marks completion before its navigation callback, so disposal cannot autosave or resend the successful message. Discard navigates first instead. It pauses autosave and cancels the pending edit, leaves, then finishes the in-flight save, the local flush, and the deletion in the background. A queued write can wait out the mutation queue's request and delivery timeouts, and the optimistic delete empties a draft-only thread around the composer, so leaving cannot wait on either. A host that fails to leave is reported, and the deletion still runs.

The send notice follows each queued send through EmailDelivery.watchSend, which reads the device outbox. Undo stays on offer until the deadline the server returned with the accepted attempt. A reply whose send fails, is cancelled, or is restored reverses its mark-done through the same undo handle, including when marking done finishes later. A send can leave the outbox before the watcher reads it again, as when another tab delivers or restores it. The watcher then asks the server how the send ended. When the server cannot say, it reports the send as untracked and the notice withdraws Undo.

EmailThreadSource.refresh() and fetchOlder() require Promise<void>. Their adapters await the underlying query, and callers that need fresh messages await that completion. They must not launch the request and resolve early.

Feature capability parameters use draftId, threadId, attachmentId, and inboxId; scheduling uses sendTime. compose-adapter.ts translates these to transport draftID, attachmentID, linkId headers, and send_time. A domain inbox ID is not a precomputed header: primary-inbox omission belongs to the adapter. Existing message/thread model fields retain their established snake_case spelling; this cleanup does not rename generated schemas or persisted URLs. In particular, the host still reads/writes the existing draftID compose route parameter. Those parameters live only in memory, so the compose route also records the composer's draft in its email-compose.draft pane search, replacing the current history entry, and reopens that draft ahead of draftID (compose-route-draft.ts). It records the draft the composer opened right away, since this device can read it while a save is queued, and records a draft the composer creates or moves to only once the server confirms it. A From switch that moves a draft keeps the compose route in place, while a thread route follows the moved draft to its new thread (compose-host-adapter.ts).

EmailThreadStateProvider and useEmailThreadState name mounted thread state. ThreadReplyInput names the thread-owned reply entry point, while createReplyComposer names the compose controller. Import a module that owns the value directly; the old root compose-layout barrel and provider type re-exports were removed. The frontend feature skill remains deleted while these rules are refined in documentation.

State and lifetime rules

Ordinary email body rendering is now owned by packages/email-renderer. Its default entry point prepares serializable HTML from a narrow content input without DOM, Solid, flags, or services. Its /browser entry point owns Shadow DOM, computed styles, containment, width fitting, and resource cleanup. email-message only translates reactive values and registers the renderer's disposal with Solid. Production adapters supply theme, image proxy policy, CID resolution, native authenticated image fetching, and mailto interception. The package never imports the app to obtain those capabilities.

Macro Markdown and the existing plaintext fallback remain app Markdown rendering paths because document mentions and editor semantics belong to the app. Neither branch mounts an invisible HTML renderer or starts its resource requests. The standalone package also offers literal plaintext preparation, but adopting that policy in the app would be a separate behavior change. Missing replyless HTML falls back to recognized quote removal or the full body instead of a blank body. The shared editor HTML decorator still owns its Lexical/Solid lifecycle; its sanitization/color helpers delegate to the package through @core/email.

  1. Query availability and display policy are separate. The adapter can expose cached data even when a completed request failed. A pending resource is never read eagerly. primitives/thread-snapshot.ts decides to retain a readable snapshot during transient reloads and rejects a snapshot for another ID. The block's load gate continues to prioritize structural errors over cached data.
  2. Refresh and pagination preserve asynchronous completion. A caller awaiting a refresh must wait for the underlying query, particularly before revealing a newly sent message. Paging stops when the target is found, no progress is made, the source identity changes, or the owning view is disposed.
  3. Selection, expansion, hover, reply placement, scrolling, and initial-load state belong to each mounted thread. There is no block signal or global scroll flag in a feature package.
  4. A newer saved draft wins over an older response. Missing drafts in a stale response do not collapse an open editor, and locally discarded drafts are not resurrected by delayed responses.
  5. An engaged reply editor latches its seed while the same message is being edited. Server echoes must not remount it and lose focus. A different reply target owns a new composer lifetime, including on mobile. That lifetime binds its target, draft seed, form, and thread identity before disposal can observe the next target. Flushing an old editor must never retarget its body.
  6. Undo recovery survives navigation but is keyed by draft and reply identity. One composer cannot overwrite another's snapshot or restoration callback, and an older owner's cleanup cannot unregister a newer owner. Recovery history is bounded; it is not a global reactive feature-state singleton.
  7. Scheduling and immediate sending are mutually exclusive while a scheduling operation is pending. A rejected schedule keeps the previous confirmed time. If scheduling succeeds and archiving fails, the confirmed time remains and the user receives accurate feedback. A failed unschedule also retains that time. Scheduling may take precedence while an immediate send is saving its draft; it cannot start during the actual send or discard. Sender changes are also blocked while those operations own the composer.
  8. Renderer resources follow their Solid owner. Source changes or disposal release image blob URLs, resize observers and image listeners, and abort pending adapter work.

Shared UI and explicit exceptions

Isolation of state and contracts does not mean every existing shared widget is application-free. Message views still compose the shared Markdown renderer, user tooltips, image galleries, and UI controls; compose views use the shared rich editor, recipient selector, and mobile chrome. Their application integration remains outside the controllers. Sender avatars are slots in both expanded and collapsed message presentation. sender-icon-adapter.tsx supplies the app's profile lookup and user card through UserIcon; the reusable message view does not import that navigation/DM integration. Some other shared widgets still import app services: thread participants use UserIcon, which creates a direct-message mutation, and EntityIcon imports the block registry. Removing the UI test mocks exposes missing app providers and WebSocket initialization. Consequently, the contexts isolate controller behavior, but the complete thread and composer UI still require additional application providers.

Controller tests supply fake capabilities through their contexts. Their vi.fn spies and vi.mocked type helpers do not substitute imported modules. The view tests still use module mocks for the thread view, reply editor, and attachment icon; they verify provider ordering, reply lifetime/focus handoff, and keyboard behavior respectively, not complete view isolation. The native image adapter test substitutes platform detection and transport to exercise Tauri behavior.

Two narrow shared pure utilities are allowed: @core/util/base64 for the existing codec semantics and @core/user/macroId for validated identity formatting. The attachment pill also reuses the static MIME/file-type map; its shared EntityIcon component has the app coupling described above. Do not generalize the pure utility exceptions to the corresponding barrels.

Enforcement and verification

The three features are registered in both TypeScript and TSX versions of all four feature-* ast-grep families. Additional error-level email-no-block-dependencies rules reject block imports. Review cross-feature imports and transitive dependencies when changing feature boundaries.

Run from apps/web:

bun run test src/features/email
bun run check

Run from the repository root:

bunx --yes @ast-grep/[email protected] scan apps/web/src/features/email-message apps/web/src/features/email-thread apps/web/src/features/email-compose
just test-email-rendering

Regression coverage includes message parsing/containment and cleanup, chronological selection and reading stops, pagination geometry, retained snapshots, draft precedence, independent thread state, provider/frame ownership, reply target lifetimes, account failures, secondary-inbox recipients, editor draft persistence, scheduling failures and concurrency, mentions, and isolated undo recovery.

Browser verification must still exercise the mounted application: hidden-message expansion, message headers and quoted content, deep-link reveal, keyboard reply, inline draft persistence, standalone compose, and mobile reply presentation. A local account without a real mail-provider connection can verify local drafts and UI behavior; actual provider delivery requires its own integration environment.

Renderer regression coverage

The renderer's fixture viewer and Chromium suite call the same public preparation and mounting API as the app. Node tests cover preparation, resource policy, CSS recovery, quote/signature selection, colors, and width fitting. A separate TypeScript build excludes DOM libraries from core; import checks reject app and framework dependencies. The package Node tests also run through the app's default Vitest projects. Browser tests cover actual layout, delayed attachment, color round trips, collapse/expansion, URL handling, CSS cascade, and resource cleanup.

The visual fixtures include personal calendar responses and announcements in both themes. Personal fixtures explicitly enable color adaptation even when they contain tables. Screenshots have a zero differing pixel tolerance within the controlled Chromium/font environment. Standalone fixture snapshots complement mounted-app interaction checks; they do not establish full application parity.

Use bun run --cwd packages/email-renderer viewer to inspect fixtures without an account or backend. Do not regenerate visual expectations simply to make a refactor pass: reproduce the baseline in the same browser and explain each remaining difference before accepting it.

Calendar invitation snapshots

Calendar MIME extraction belongs to the email domain and happens at sync time, when live sync or backfill saves a message; re-syncing a message repeats it idempotently. email_message_calendar_invites stores the immutable components; mail without calendar parts gets no rows. Sync parses the inline bytes it already fetched. When a message has no inline calendar part, sync downloads its .ics attachments best-effort; a failed or oversized download leaves the message as plain mail, with no retry. Mail synced before the feature shipped is not reinspected, and a parser change applies only to newly synced mail. Opening a message never fetches provider MIME or parses ICS. When an already-loaded thread's saved invitations change, that thread's calendar resolution is revalidated in the background; its first load or a switch between threads does not trigger it. Cards are keyed by component, so thread refreshes keep their state. Without the calendar UI flag, cards render the saved invitation with no calendar lookup.

Scheduling revisions come only from the thread's own saved components, and are reconciled separately for each original occurrence and its series master. A lower-sequence master cancellation still cancels an instance with a higher independent sequence. RSVP carries the displayed responding address; the calendar domain verifies inbox ownership before passing only that address to Google. Optimistic responses and rollback ownership are scoped to that attendee.

The parser compatibility corpus is in crates/email/fixtures/calendar. ical 0.11 handles folded properties, parameters, and embedded VTIMEZONE syntax. chrono-tz resolves unambiguous IANA times, and the Windows zone IDs that Outlook writes map to IANA through the CLDR table in calendar_invitation_parser/windows_zones.rs. Custom zones, floating times, and DST gaps or ambiguities remain explicitly unresolved. Snapshots keep only fields that reads use. Limits are 512 KiB per part and 32 components/parts per message. Date-only ends remain exclusive; recurrence IDs retain the original occurrence identity.

Fully hydrated message reads batch-load snapshots, expose them through REST and GraphQL as a plain component list, and preserve them in the cached message projection. Parsed list previews never load them. GraphQL JSON is validated at its transport adapter. email-message owns the typed card and groups recurrence components by UID. Original bodies and attachments remain accessible. When a message has invitations, the card replaces the body and the original sits behind a "View original email" disclosure that starts closed.

email-thread/calendar-invitation.tsx composes the refreshable calendar query, shared RSVP controller, and agenda. queries/calendar-invitation.ts maps transport data to small presentation values. The body renderer has no calendar dependencies. block-email injects calendar navigation with both the original identity and current occurrence time, including when an instance has moved to another day.

The email resolution endpoint first authorizes the thread, then derives identities from the thread's newest 100 stored components in one batch, without loading its messages. It calls the calendar domain's CalendarInvitationService port in-process: the email service composition root constructs CalendarInvitationResolver over PgCalendarRepository, as it already does for its other calendar services. The calendar domain limits lookup to the verified viewer's owned, connected Google-backed copies, prefers the thread's inbox, resolves a series to its current or next live occurrence (else its latest), and withholds ambiguous, read-only, stale, cancelled, mismatched-organizer, or unresolved-instance responses. Newer saved scheduling revisions in the thread suppress stale actions while calendar sync catches up. Exception revisions are preserved independently of the master. Reads never create calendar events. Resolution does not consult calendar_service's sync kill switch: when it is off, calendar_service does not mount the RSVP route, so a response fails and the card reports that it could not be saved. Resolution failures leave the saved card useful and are retried through the existing frontend resolution query.

RSVP uses the existing provider write-through mutation. Its writer revisions cover both occurrence and invitation caches, including email-only views. Failed older requests cannot roll back a newer selection or replace its feedback. Settlement revalidates both projections. The on-demand local-day agenda shares occurrence queries and handles DST boundaries and exclusive all-day ends without mounting a calendar grid.

Independent send outbox

All immediate composer sends use a device email journal for Gmail and Outlook, independent of GraphQL normalized-cache availability and read transport. Send Later schedules the saved draft through the REST schedule endpoint, so it stays a draft listed by /email/drafts/scheduled; outbox admission makes a message non-draft, which that list excludes. send-queue.ts freezes approval and reserves the draft in IndexedDB before returning local acceptance. outbox-session.ts runs dispatch and recovery from the authenticated app shell; mounted composers only observe them. The general GraphQL queue owns draft autosaves and other ordinary mutations only; it has no send catalog or Send/Cancel replacement protocol. The former cache-queue send format was used only in local development and tests, so there is no deployed format to migrate. Unsupported journal records retain their contents and recognizable draft reservations for recovery.

email-send-dispatcher.ts submits immediately online through the fetch-only GraphQL client in service-storage/email-send.ts. Per-attempt database leases coordinate tabs, with bounded concurrency across unrelated messages. A lost response triggers a status read before resubmitting the identical attempt. Cancellation requested before any submission claim stays local; after a claim it requires authoritative server cancellation. The exception is a definitive inbox-access rejection of the first exclusive submission: the journal records local cancellation and permits restoration. Timeouts, mixed/nested errors, and later status rejections never provide that proof. Retry backoff and authentication pauses do not discard approval. email-send-restoration.ts restores content, fences the prior local lifetime, and retires send authority atomically. Newer local edits and file bytes survive restoration. Sign-out retains approved sends under their original account and stops dispatch; ordinary drafts retain their existing sign-out policy. Signing into another account without signing out ends the previous account's draft session the same way: the first page that opens draft storage with an identity it confirmed with the server retires the old epoch, starts a new one, clears the previous working copies, keeps approved sends, and discards draft saves the previous account queued before the takeover. Pages that already opened storage, or whose identity is only restored, stay fenced. When a page's draft session ends outside it (another tab's sign-out, expiry, or takeover, including one missed in the back/forward cache, or a different signed-in account), the outbox session reloads that page; a page signing itself out does not. A confirmed session expiry loads /welcome as a new page, as sign-out does, because a cleared draft session never reopens in the same page.

The server accepts the frozen message, attachment set, send attempt, and delivery job in one Postgres transaction. The existing recovery scanner and Gmail/Outlook provider reconciliation continue delivery after browser closure. Attempt IDs provide idempotent admission, not a promise of exactly-once provider delivery: unknown provider outcomes remain locked and reconcile before any resend. Unrecognized GraphQL scheduled-delivery states map to unconfirmed, preserving the thread and its delivery lock when the server is newer than the client. Gmail submission checkpoints and Outlook coordinator revisions retain their provider-specific submission boundaries.

Hard deletion of a message owned by a nonterminal send is deferred in email_deferred_message_deletions before any content compaction or attachment/job cascade. The retained provider ID and draft generation scope the deletion to that message lifetime. The recovery scanner also wakes terminal deferred deletions, even without a schedule. Workers discard markers superseded by Undo or a changed provider identity; matching terminal deletions use normal thread/CRM cleanup. Failed and unconfirmed attempts remain protected until cancellation or confirmed delivery. Explicit inbox removal revokes authority: links marked deleting_at permit batched purge, and direct inbox deletion permits its normal cascade.

email_messages.draft_generation advances at acceptance and confirmed cancellation. Save, delete, schedule, transfer, and attachment edits compare the captured generation under the message lock. Stale autosaves return DRAFT_VERSION_CONFLICT and preserve local edits for recovery; they are not classified as an already-sent message. The attempt retains draft handles and source inbox namespaces after provider deletion, preventing old queued saves from recreating the submitted draft. Versioned approval fingerprints include the generation, frozen signature and Send Later deadline. An explicit new Send after Undo uses the returned generation and a fresh attempt ID. Draft reads prefer that newer working-copy generation over stale accepted cache records; an equal or newer server delivery generation still wins. REST parsed-message reads expose the same generation alongside message content; SDK draft actions carry that version, and attachment handles retain the generation captured at reservation.

The status panel combines device intents with actor/inbox-authorized, cursor-paged pendingEmailSends, with batched message hydration. Server listing grants observation and cancellation authority, never automatic resubmission. Delivery state distinguishes local queueing, server acceptance, provider processing, sent, failed, and unconfirmed outcomes, but the panel stays silent for routine delivery: it lists a send only while it waits on this device, needs attention, or is scheduled. Thread surfaces project approved immediate sends from the journal as sent messages (email-thread/primitives/optimistic-send.ts) until the thread read shows them, and read the thread once when delivery is confirmed. Every surface reads one document-scoped journal snapshot (queries/email/queued-sends.ts). The outbox session reads it at sign-in and clears it on account change, the first mounted observer starts its watcher and poll, and Send refreshes it before the thread opens, so that thread mounts with the send already projected instead of its draft.

Deploy schema/migrations and all generation-aware backend writers before releasing this frontend, including before applying ios-update: that workflow embeds the PR's frontend with production endpoints, and once Apple approves it the next prod deploy releases it. See the iOS release flow. The outbox is unconditional; there is no feature flag or legacy send fallback. Old deployed writers do not enforce the new generation precondition. Verify cache failure, offline/reload, lost HTTP response, concurrent tabs, sign-out, Undo, stale writes, Send Later, completed attachments, both providers, and server sends from other devices before release. The separate cache-bootstrap recovery hotfix remains useful for draft synchronization and does not determine send availability.

iOS 2.0.11 build 190 was released with the production rollout on 2026-10-22. Its source is 04063d2bb35d7369eae93900c2692f3ecccf882b. The subsequent main merge through 93900478fb preserves its native/web and email interfaces. Build 190 keeps its compiled format-3 native cache; the new format-4 compression in cache version 0.6.52 belongs to the cache engine, and only JSON crosses the native/web boundary. Browser OPFS storage is separate. New native diagnostics are optional, and the agent runtime/Chromium additions are desktop-only. The skip-ios-update exception records this compatibility review, not identical build provenance. Older iOS builds therefore remain compatible with the outbox; the iOS floor is 190 only so that the next production deploy prompts them to update from the App Store.

The format-4 browser cache starts a separate physical database. Old nonempty general mutation queues are retained but are not imported into it; verify their recovery separately during the cache rollout. The email journal is independent of these cache files and retains its draft working copies and send attempts.

Agent program sends

An agent's program (a code-mode run, marked by x-macro-code-execution, or a token with agent attribution; macro_authorization::is_agent_run) never sends an email the user has not seen. The REST send (POST /email/messages) answers it 403. It sends through a session review (execution.reviews.create({kind: 'email'})), whose card the user submits, or, for a prompt from a channel or document thread, on the user's quoted approval:

  • macro.email.sendConfirmed and EmailMessage.forwardConfirmed call the harness's POST /cognition/email/send-confirmed, which runs the SendConfirmedEmail tool with its Markdown rendering, inbox choice, reply threading and document attachments. A forward is a new email quoting the message under the forwarded-message header, with the message's attachments as their Macro documents (EmailMessage.forwardDraft builds it, also for a review).
  • EmailDraft.send and EmailDraft.schedule call the schedule route (PUT /email/drafts/scheduled/{id}), which admits a program only with a non-blank user_confirmation. send schedules a few seconds ahead, so the scheduled sender delivers the saved draft within about a minute.