Modern Apps git

← Modern-Apps.git

email: add stored peekContent column (+migration 19->20); list/widget read light projection

Commit
f111dfd0138bf034610951d94b9c5f8e2620b8f0
Author
vayun-mathur <[email protected]>
When
2026-08-16 03:56 UTC (3 months ago)
Parents
ac22e8f

Diff

email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex 11d1e6ee4b..aa903e3beb 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -8,6 +8,7 @@ import androidx.activity.enableEdgeToEdge import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.email.data.DateMillisBackfill+import com.vayunmathur.email.data.PeekContentBackfill import com.vayunmathur.email.data.EmailSyncWorker import com.vayunmathur.email.data.ImapIdleService import com.vayunmathur.email.data.OutboxSendWorker@@ -32,6 +33,7 @@ class MainActivity : ComponentActivity() {         OutboxSendWorker.runNow(this)         ImapIdleService.start(this)         DateMillisBackfill.runIfNeeded(lifecycleScope, this)+        PeekContentBackfill.runIfNeeded(lifecycleScope, this)         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {             if (checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {                 requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 7331)
email/src/main/java/com/vayunmathur/email/data/EmailDao.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDao.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDao.ktindex 3b06e6a57e..21b8d344d3 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDao.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDao.kt@@ -53,8 +53,19 @@ interface EmailDao {     @Query("SELECT * FROM EmailMessage WHERE accountEmail = :accountEmail AND threadId = :threadId ORDER BY dateMillis ASC, id ASC")     fun getThreadFlow(accountEmail: String, threadId: String): Flow<List<EmailMessage>> +    /** Raw insert — do not call directly. Use [insertMessages], which populates+     *  [EmailMessage.peekContent] before delegating here. */     @Insert(onConflict = OnConflictStrategy.REPLACE)-    suspend fun insertMessages(messages: List<EmailMessage>)+    suspend fun _insertMessages(messages: List<EmailMessage>)++    /**+     * Insert messages, always (re)computing [EmailMessage.peekContent] from the+     * incoming body via [previewText] so the stored snippet stays in sync with the+     * body regardless of caller. Runs in one transaction.+     */+    @Transaction+    suspend fun insertMessages(messages: List<EmailMessage>) =+        _insertMessages(messages.map { it.copy(peekContent = it.previewText(PEEK_LEN)) })      @Query("SELECT * FROM EmailMessage WHERE accountEmail = :accountEmail AND id = :uid AND folderName = :folderName")     suspend fun getMessage(accountEmail: String, folderName: String, uid: Long): EmailMessage?@@ -126,6 +137,25 @@ interface EmailDao {     @Query("SELECT * FROM EmailMessage WHERE folderName = 'INBOX' ORDER BY dateMillis DESC, id DESC LIMIT 10")     fun getRecentUnifiedMessagesFlow(): Flow<List<EmailMessage>> +    // ---- Light preview projections (no body) for list/widget screens ----+    // These SELECT only the columns [EmailPreview] needs and read the stored+    // peekContent snippet, so list rows and the widget never load the full body.++    @Query("SELECT accountEmail, folderName, id, threadId, subject, `from`, date, dateMillis, isRead, hasAttachments, snoozedUntil, peekContent FROM EmailMessage WHERE accountEmail = :accountEmail AND folderName = :folderName AND snoozedUntil <= :now ORDER BY dateMillis DESC, id DESC")+    fun getMessagesPreviewFlow(accountEmail: String, folderName: String, now: Long): Flow<List<EmailPreview>>++    @Query("SELECT accountEmail, folderName, id, threadId, subject, `from`, date, dateMillis, isRead, hasAttachments, snoozedUntil, peekContent FROM EmailMessage WHERE accountEmail = :accountEmail AND folderName = :folderName AND snoozedUntil <= :now AND (subject LIKE '%' || :query || '%' OR `from` LIKE '%' || :query || '%' OR body LIKE '%' || :query || '%') ORDER BY dateMillis DESC, id DESC")+    fun searchMessagesPreviewFlow(accountEmail: String, folderName: String, query: String, now: Long): Flow<List<EmailPreview>>++    @Query("SELECT accountEmail, folderName, id, threadId, subject, `from`, date, dateMillis, isRead, hasAttachments, snoozedUntil, peekContent FROM EmailMessage WHERE folderName = :folderName AND snoozedUntil <= :now ORDER BY dateMillis DESC, id DESC")+    fun getUnifiedMessagesPreviewFlow(folderName: String, now: Long): Flow<List<EmailPreview>>++    @Query("SELECT accountEmail, folderName, id, threadId, subject, `from`, date, dateMillis, isRead, hasAttachments, snoozedUntil, peekContent FROM EmailMessage WHERE folderName = :folderName AND snoozedUntil <= :now AND (subject LIKE '%' || :query || '%' OR `from` LIKE '%' || :query || '%' OR body LIKE '%' || :query || '%') ORDER BY dateMillis DESC, id DESC")+    fun searchUnifiedMessagesPreviewFlow(folderName: String, query: String, now: Long): Flow<List<EmailPreview>>++    @Query("SELECT accountEmail, folderName, id, threadId, subject, `from`, date, dateMillis, isRead, hasAttachments, snoozedUntil, peekContent FROM EmailMessage WHERE folderName = 'INBOX' ORDER BY dateMillis DESC, id DESC LIMIT 100")+    suspend fun getRecentUnifiedPreview(): List<EmailPreview>+     // ---- One-time backfill for the dateMillis column ----      /** Rows persisted before `dateMillis` existed; their `date` string needs parsing. */@@ -135,6 +165,18 @@ interface EmailDao {     @Query("UPDATE EmailMessage SET dateMillis = :millis WHERE accountEmail = :accountEmail AND folderName = :folderName AND id = :uid")     suspend fun updateDateMillis(accountEmail: String, folderName: String, uid: Long, millis: Long) +    // ---- One-time backfill for the peekContent column ----++    /** Rows with a body but no computed preview yet — either persisted before the+     *  peekContent column existed (default '') or inserted with an empty body since+     *  filled in. previewText's HTML strip can't be done in SQL, so recompute in+     *  Kotlin (see [PeekContentBackfill]). */+    @Query("SELECT * FROM EmailMessage WHERE peekContent = '' AND body IS NOT NULL AND body != '' LIMIT 1000")+    suspend fun getRowsWithEmptyPeek(): List<EmailMessage>++    @Query("UPDATE EmailMessage SET peekContent = :peek WHERE accountEmail = :accountEmail AND folderName = :folderName AND id = :uid")+    suspend fun updatePeekContent(accountEmail: String, folderName: String, uid: Long, peek: String)+     // Attachments     @Insert(onConflict = OnConflictStrategy.REPLACE)     suspend fun insertAttachments(attachments: List<Attachment>)
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex e22ba35b73..0259999a0d 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -4,6 +4,7 @@ import android.content.Context import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.migration.Migration+import com.vayunmathur.library.util.DatabaseMigrations import com.vayunmathur.email.data.EmailFolder import com.vayunmathur.email.data.EmailMessage import com.vayunmathur.email.data.EmailAccount@@ -24,13 +25,13 @@ import com.vayunmathur.email.data.Attachment         BlockedSender::class,         DeletedUid::class,     ],-    version = 19,+    version = 20,     exportSchema = false, ) abstract class EmailDatabase : RoomDatabase() {     abstract fun emailDao(): EmailDao -    companion object {+    companion object : DatabaseMigrations {         @Volatile         private var instance: EmailDatabase? = null @@ -176,6 +177,41 @@ abstract class EmailDatabase : RoomDatabase() {             )         } +        /**+         * Adds the stored `peekContent` snippet column (see [EmailMessage.peekContent]).+         * Purely additive: existing rows get `''` and are backfilled from their body on+         * app start ([PeekContentBackfill]); the matching `@ColumnInfo(defaultValue = "")`+         * on the entity keeps the generated schema in sync so Room's post-migration+         * validation passes. No existing data is read or modified.+         */+        private val MIGRATION_19_20 = Migration(19, 20) {+            it.execSQL("ALTER TABLE EmailMessage ADD COLUMN peekContent TEXT NOT NULL DEFAULT ''")+        }++        /**+         * Every migration for this database, registered with the Room builder via the+         * [DatabaseMigrations] reflection hook in `openRoomDatabase`. Order is+         * irrelevant to Room; kept numeric here for readability.+         */+        override val migrations: List<Migration> = listOf(+            MIGRATION_4_5,+            MIGRATION_5_6,+            MIGRATION_6_7,+            MIGRATION_7_8,+            MIGRATION_8_9,+            MIGRATION_9_10,+            MIGRATION_10_11,+            MIGRATION_11_12,+            MIGRATION_12_13,+            MIGRATION_13_14,+            MIGRATION_14_15,+            MIGRATION_15_16,+            MIGRATION_16_17,+            MIGRATION_17_18,+            MIGRATION_18_19,+            MIGRATION_19_20,+        )+         fun getInstance(context: Context): EmailDatabase =             EmailRepository.get(context).getDatabase()     }
email/src/main/java/com/vayunmathur/email/data/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/data/EmailModels.ktindex 7833f47ebe..bcd051381a 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt@@ -1,376 +1,414 @@-package com.vayunmathur.email.data--import androidx.room.ColumnInfo-import androidx.room.Entity-import androidx.room.PrimaryKey-import androidx.core.text.HtmlCompat-import kotlinx.serialization.Serializable-import com.vayunmathur.email.network.imap.MimeParser--@Serializable-@Entity(primaryKeys = ["accountEmail", "fullName"])-data class EmailFolder(-    val accountEmail: String,-    val fullName: String,-    val name: String,-    val parentFullName: String? = null,-    val holdsMessages: Boolean = true,-    val delimiter: String = "/"-)--@Serializable-@Entity(primaryKeys = ["accountEmail", "folderName", "id"])-data class EmailMessage(-    val accountEmail: String,-    val folderName: String,-    val id: Long, // IMAP UID-    val serverId: String? = null, // Message-ID header-    val threadId: String? = null, // Gmail Thread ID or custom grouping-    val subject: String,-    val from: String,-    val to: String? = null,-    val cc: String? = null,-    val date: String,-    /** Date in epoch-millis. Used for chronological ordering, especially in the-     *  cross-account unified inbox where IMAP UIDs aren't comparable. Defaults-     *  to 0 for rows persisted before this column existed; backfilled on app-     *  start via [EmailDao.getRowsWithZeroDateMillis]. */-    val dateMillis: Long = 0,-    val body: String? = null,-    val isHtml: Boolean = false,-    val isRead: Boolean = false,-    val references: String? = null, // References/In-Reply-To for threading-    val hasAttachments: Boolean = false,-    val snoozedUntil: Long = 0, // 0 = not snoozed; else epoch millis to resurface-    val listUnsubscribe: String? = null, // raw List-Unsubscribe header, if present-    val listUnsubscribePost: String? = null, // raw List-Unsubscribe-Post header (RFC 8058), if present-)--@Entity-data class BlockedSender(-    @PrimaryKey val address: String,-)--/**- * Tombstone for a locally-deleted message. Recorded when the user deletes a- * message so that the sync worker / IMAP IDLE fetch skips its UID and never- * re-inserts it (the server expunge can lag or fail, leaving the UID briefly- * fetchable). Keyed by the same (account, folder, uid) tuple as EmailMessage.- */-@Entity(primaryKeys = ["accountEmail", "folderName", "uid"])-data class DeletedUid(-    val accountEmail: String,-    val folderName: String,-    val uid: Long,-)--@Serializable-@Entity(primaryKeys = ["accountEmail", "messageId", "partId"])-data class Attachment(-    val accountEmail: String,-    val folderName: String,-    val messageId: Long, // IMAP UID-    val partId: String,-    val fileName: String,-    val mimeType: String,-    val size: Long,-    val localUri: String? = null-)--@Serializable-@Entity-data class EmailAccount(-    @PrimaryKey val email: String,-    /**-     * Legacy OAuth-token columns. Kept in the schema so old DB rows still-     * load, but no longer written: every account now uses an app password.-     */-    val accessToken: String = "",-    val refreshToken: String? = null,-    val expiresAt: Long = 0,-    /**-     * Preset identifier — `gmail`, `outlook`, `yahoo`, `icloud`, `fastmail`, or-     * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering)-     * for non-Gmail accounts, and (b) display the provider name in-     * account-picker UIs.-     *-     * `@ColumnInfo(defaultValue = ...)` is required so the schema generated-     * from this entity matches `MIGRATION_6_7`, which `ALTER TABLE`s these-     * columns in with a SQL default. Without it Room would throw-     * `IllegalStateException: Migration didn't properly handle: EmailAccount`-     * at startup for users upgrading from v6.-     */-    @ColumnInfo(defaultValue = "gmail")-    val provider: String = "gmail",-    /** IMAP hostname this account fetches from. Hard-coded to Gmail's pre-multi-provider migration. */-    @ColumnInfo(defaultValue = "imap.gmail.com")-    val imapHost: String = "imap.gmail.com",-    @ColumnInfo(defaultValue = "993")-    val imapPort: Int = 993,-    /** true = implicit SSL/TLS on connect, false = plaintext + STARTTLS upgrade. */-    @ColumnInfo(defaultValue = "1")-    val imapUseSsl: Boolean = true,-    @ColumnInfo(defaultValue = "smtp.gmail.com")-    val smtpHost: String = "smtp.gmail.com",-    @ColumnInfo(defaultValue = "465")-    val smtpPort: Int = 465,-    @ColumnInfo(defaultValue = "1")-    val smtpUseSsl: Boolean = true,-    /**-     * Optional login username for IMAP/SMTP authentication when it differs-     * from the email address (common with custom providers). When null or-     * blank, [email] is used for authentication.-     */-    @ColumnInfo(defaultValue = "")-    val username: String = "",-    /**-     * Auth scheme. Only `password` is supported now; the column is preserved-     * with its original default for legacy DB compatibility, but every newly-     * added account stores credentials as an encrypted app password.-     */-    @ColumnInfo(defaultValue = "oauth2")-    val authType: String = "password",-    /** AES-256-GCM ciphertext of the app password. */-    val passwordEncrypted: ByteArray? = null,-    /** GCM IV used to decrypt [passwordEncrypted]. */-    val passwordIv: ByteArray? = null,-    /** Plain-text signature appended to outgoing messages from this account. */-    @ColumnInfo(defaultValue = "")-    val signature: String = "",-) {-    fun getColor(): Long = accountColor(email)-}--/** Material palette used to give each account a stable color, by email hash. */-val ACCOUNT_COLORS: List<Long> = listOf(-    0xFFF44336, // Red-    0xFFE91E63, // Pink-    0xFF9C27B0, // Purple-    0xFF673AB7, // Deep Purple-    0xFF3F51B5, // Indigo-    0xFF2196F3, // Blue-    0xFF03A9F4, // Light Blue-    0xFF00BCD4, // Cyan-    0xFF009688, // Teal-    0xFF4CAF50, // Green-    0xFF8BC34A, // Light Green-    0xFFCDDC39, // Lime-    0xFFFFEB3B, // Yellow-    0xFFFFC107, // Amber-    0xFFFF9800, // Orange-    0xFFFF5722, // Deep Orange-    0xFF795548, // Brown-    0xFF9E9E9E, // Grey-    0xFF607D8B  // Blue Grey-)--/** Stable color for [email], derived from its hash. */-fun accountColor(email: String): Long {-    val hash = email.hashCode()-    return ACCOUNT_COLORS[(hash and Int.MAX_VALUE) % ACCOUNT_COLORS.size]-}--/**- * Content of `<script>`, `<style>`, `<head>` and `<title>` elements.- *- * [HtmlCompat.fromHtml] emits the *text* inside these rather than dropping- * them, so a message whose body is a full HTML document renders its stylesheet- * as the first hundred characters of the preview.- */-private val HTML_NON_CONTENT = Regex("""<(script|style|head|title)\b[^>]*>.*?</\1\s*>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))-private val HTML_COMMENT = Regex("""<!--.*?-->""", RegexOption.DOT_MATCHES_ALL)-private val HTML_DECLARATION = Regex("""<[!?][^>]*>""")-/** Tags common enough that their presence means the body is HTML whatever the flag says. */-private val LOOKS_LIKE_HTML = Regex("""<(html|body|head|div|table|p|br|span|a|img|font)\b[^>]*>""", RegexOption.IGNORE_CASE)-/**- * Includes the non-breaking space `fromHtml` produces from `&nbsp;` and the- * Unicode line/paragraph separators, none of which `\s` matches.- */-private val WHITESPACE_RUN = Regex("""[\s\u00A0\u2028\u2029]+""")--/**- * Characters that draw as an empty box, or as nothing at all.- *- * `fromHtml` returns a `Spanned` in which every `<img>` is a U+FFFC anchored to- * an `ImageSpan`; `toString()` discards the span and leaves the placeholder- * behind with nothing to stand for. U+FFFD is the decoder's marker for bytes it- * could not make sense of. The zero-width characters are the invisible padding- * marketing mail uses to pull its preheader around, and the C0/C1 controls come- * through from mail that was never really text.- *- * Deliberately excludes tab, newline and the vertical whitespace controls -- * those separate words, so deleting them would run the words together where- * collapsing them to a space does not.- */-private val UNRENDERABLE = Regex("[\\uFFFC\\uFFFD\\u200B-\\u200F\\uFEFF\\u0000-\\u0008\\u000E-\\u001F\\u007F]")--/**- * Plain-text rendering of this message's body.- *- * Falls back to sniffing the markup when [EmailMessage.isHtml] is false, because- * plenty of senders set `text/plain` on a body that is anything but.- */-fun EmailMessage.plainTextBody(): String? {-    val raw = body ?: return null-    if (!isHtml && !LOOKS_LIKE_HTML.containsMatchIn(raw)) return raw.replace(UNRENDERABLE, "")-    val stripped = raw-        .replace(HTML_COMMENT, " ")-        .replace(HTML_NON_CONTENT, " ")-        .replace(HTML_DECLARATION, " ")-    return HtmlCompat.fromHtml(stripped, HtmlCompat.FROM_HTML_MODE_LEGACY)-        .toString()-        .replace(UNRENDERABLE, "")-}--/**- * A single-line snippet of the body for list rows, widgets and notifications.- *- * Collapses whitespace before truncating: the block structure of an HTML mail- * turns into leading blank lines, so [plainTextBody] truncated as-is is often- * entirely empty.- */-fun EmailMessage.previewText(maxChars: Int): String =-    (plainTextBody() ?: "").replace(WHITESPACE_RUN, " ").trim().take(maxChars)--/** Display name for a "Name <addr>" sender header, falling back to the address.- * Implemented via own RFC2047 decode + simple parse to remove Jakarta dependency. */-fun senderDisplayName(from: String): String {-    if (from.isBlank()) return ""-    // Try to extract "Name <addr>" pattern-    val trimmed = from.trim()-    // Decode RFC2047 first-    val decoded = MimeParser.decodeHeader(trimmed)-    // Look for <...> format-    val angleMatch = Regex("""^(.*)<([^>]+)>$""").find(decoded.trim())-    if (angleMatch != null) {-        val namePart = angleMatch.groupValues[1].trim().trim('"').trim()-        val addr = angleMatch.groupValues[2].trim()-        if (namePart.isNotBlank()) return namePart-        return addr-    }-    // No angle brackets — could be bare address or just name-    if (decoded.contains("@")) return decoded.substringBefore("<").trim()-    return decoded-}--/**- * A detected way to unsubscribe from a message. Produced by [detectUnsubscribe]- * and acted on by the message-view UI.- */-sealed interface UnsubscribeMethod {-    /** RFC 8058 one-click: HTTPS POST to [url] with body `List-Unsubscribe=One-Click`. */-    data class OneClickPost(val url: String) : UnsubscribeMethod-    /** Open an unsubscribe web page ([url]) in the browser. */-    data class OpenWeb(val url: String) : UnsubscribeMethod-    /** Compose an unsubscribe email to [address] using the in-app composer. */-    data class SendMail(val address: String) : UnsubscribeMethod-}--/** Words that signal an unsubscribe affordance; kept small to avoid false positives. */-private val UNSUBSCRIBE_KEYWORDS = listOf("unsubscribe", "opt out", "opt-out", "optout")--/**- * Work out how (if at all) the user can unsubscribe from this message.- *- * Order of preference, per the email standards:- *  1. RFC 8058 one-click POST — when `List-Unsubscribe-Post: List-Unsubscribe=One-Click`- *     is present together with an https URL in `List-Unsubscribe`.- *  2. An https/http URL from the `List-Unsubscribe` header (opened in the browser).- *  3. A `mailto:` target from the `List-Unsubscribe` header (composed in-app).- *  4. Fallback: a conservative scan of the body for an "unsubscribe" link.- */-fun EmailMessage.detectUnsubscribe(): UnsubscribeMethod? {-    listUnsubscribe?.let { header ->-        val targets = parseListUnsubscribe(header)-        val webUrl = targets.firstOrNull { it.startsWith("http", ignoreCase = true) }-        val httpsUrl = targets.firstOrNull { it.startsWith("https://", ignoreCase = true) }-        val mailto = targets.firstOrNull { it.startsWith("mailto:", ignoreCase = true) }--        val isOneClick = listUnsubscribePost?.contains("one-click", ignoreCase = true) == true-        if (isOneClick && httpsUrl != null) return UnsubscribeMethod.OneClickPost(httpsUrl)-        if (webUrl != null) return UnsubscribeMethod.OpenWeb(webUrl)-        if (mailto != null) {-            val address = mailto.removePrefix("mailto:").removePrefix("MAILTO:").substringBefore("?").trim()-            if (address.contains("@")) return UnsubscribeMethod.SendMail(address)-        }-    }-    return findUnsubscribeLinkInBody()?.let { UnsubscribeMethod.OpenWeb(it) }-}--/** Extract the angle-bracketed targets from a List-Unsubscribe header (RFC 2369). */-private fun parseListUnsubscribe(header: String): List<String> =-    Regex("<([^>]+)>").findAll(header).map { it.groupValues[1].trim() }.toList()-        .ifEmpty { header.split(",").map { it.trim() }.filter { it.isNotEmpty() } }--/**- * Conservatively look for an unsubscribe link in the body. Only returns a link- * when the word "unsubscribe" (or an "opt out" variant) appears in the link's- * href or visible text, to avoid mistaking ordinary links for unsubscribe ones.- */-private fun EmailMessage.findUnsubscribeLinkInBody(): String? {-    val content = body ?: return null-    if (isHtml) {-        val anchor = Regex(-            "<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>(.*?)</a>",-            setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),-        )-        for (match in anchor.findAll(content)) {-            val href = match.groupValues[1].trim()-            if (!href.startsWith("http", ignoreCase = true)) continue-            val haystack = (href + " " + match.groupValues[2]).lowercase()-            if (UNSUBSCRIBE_KEYWORDS.any { haystack.contains(it) }) return href-        }-        return null-    }-    // Plain text: return an http(s) URL sitting on a line that mentions unsubscribe.-    for (line in content.lineSequence()) {-        val lower = line.lowercase()-        if (UNSUBSCRIBE_KEYWORDS.none { lower.contains(it) }) continue-        Regex("https?://\\S+", RegexOption.IGNORE_CASE).find(line)?.value-            ?.trimEnd('.', ',', ')', '>', ']')-            ?.let { return it }-    }-    return null-}--/// Pending outgoing message stored locally until it is successfully sent by the-/// background sender. Attachments are copied to app-private storage at queue time-/// (the original `content://` URIs aren't reliably readable across process-/// restarts) and `attachmentLocalPaths` is a JSON-encoded `List<String>` of those-/// absolute file paths. [inlineImageJson] stores JSON array of {cid,path,mime,name}.-@Serializable-@Entity-data class OutboxEntry(-    @PrimaryKey(autoGenerate = true) val id: Long = 0,-    val accountEmail: String,-    val to: String,-    val cc: String? = null,-    val bcc: String? = null,-    val subject: String,-    val body: String,-    val attachmentLocalPaths: String = "[]",-    @ColumnInfo(defaultValue = "[]")-    val inlineImageJson: String = "[]",-    val inReplyTo: String? = null,-    val references: String? = null,-    val createdAt: Long = System.currentTimeMillis(),-    val lastError: String? = null,-    val attemptCount: Int = 0,-    val lastAttemptAt: Long = 0,-    val scheduledAt: Long = 0,-    val isHtml: Boolean = false-)--@Entity-data class DraftEntry(-    @PrimaryKey(autoGenerate = true) val id: Long = 0,-    val accountEmail: String,-    val to: String = "",-    val cc: String = "",-    val bcc: String = "",-    val subject: String = "",-    val body: String = "",-    @ColumnInfo(defaultValue = "[]")-    val inlineImageJson: String = "[]",-    val updatedAt: Long = System.currentTimeMillis(),-)+package com.vayunmathur.email.data++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.PrimaryKey+import androidx.core.text.HtmlCompat+import kotlinx.serialization.Serializable+import com.vayunmathur.email.network.imap.MimeParser++@Serializable+@Entity(primaryKeys = ["accountEmail", "fullName"])+data class EmailFolder(+    val accountEmail: String,+    val fullName: String,+    val name: String,+    val parentFullName: String? = null,+    val holdsMessages: Boolean = true,+    val delimiter: String = "/"+)++@Serializable+@Entity(primaryKeys = ["accountEmail", "folderName", "id"])+data class EmailMessage(+    val accountEmail: String,+    val folderName: String,+    val id: Long, // IMAP UID+    val serverId: String? = null, // Message-ID header+    val threadId: String? = null, // Gmail Thread ID or custom grouping+    val subject: String,+    val from: String,+    val to: String? = null,+    val cc: String? = null,+    val date: String,+    /** Date in epoch-millis. Used for chronological ordering, especially in the+     *  cross-account unified inbox where IMAP UIDs aren't comparable. Defaults+     *  to 0 for rows persisted before this column existed; backfilled on app+     *  start via [EmailDao.getRowsWithZeroDateMillis]. */+    val dateMillis: Long = 0,+    val body: String? = null,+    val isHtml: Boolean = false,+    val isRead: Boolean = false,+    val references: String? = null, // References/In-Reply-To for threading+    val hasAttachments: Boolean = false,+    val snoozedUntil: Long = 0, // 0 = not snoozed; else epoch millis to resurface+    val listUnsubscribe: String? = null, // raw List-Unsubscribe header, if present+    val listUnsubscribePost: String? = null, // raw List-Unsubscribe-Post header (RFC 8058), if present+    /**+     * Stored plain-text snippet of [body] (first [PEEK_LEN] chars), computed via+     * [previewText] on every insert (see [EmailDao.insertMessages]). Lets list and+     * widget screens render a preview without loading the full [body] column.+     *+     * `@ColumnInfo(defaultValue = "")` is required so the schema generated from this+     * entity matches `MIGRATION_19_20`, which `ALTER TABLE`s this column in with a+     * SQL `DEFAULT ''`; without it Room throws "Migration didn't properly handle:+     * EmailMessage" on open. Rows persisted before this column existed default to+     * `""` and are backfilled on app start via [EmailDao.getRowsWithEmptyPeek].+     */+    @ColumnInfo(defaultValue = "")+    val peekContent: String = "",+)++/** Max length of the stored [EmailMessage.peekContent] snippet — enough for any+ *  single-line list row, widget item or notification preview. */+const val PEEK_LEN = 200++/**+ * Lightweight projection of [EmailMessage] for list and widget screens: every+ * column those screens draw, but **not** the heavy [EmailMessage.body]. Populated+ * by the `…Preview` `@Query` variants in [EmailDao], which read the stored+ * [EmailMessage.peekContent] instead of recomputing a preview from the body.+ */+data class EmailPreview(+    val accountEmail: String,+    val folderName: String,+    val id: Long,+    val threadId: String? = null,+    val subject: String,+    val from: String,+    val date: String,+    val dateMillis: Long = 0,+    val isRead: Boolean = false,+    val hasAttachments: Boolean = false,+    val snoozedUntil: Long = 0,+    val peekContent: String = "",+)++@Entity+data class BlockedSender(+    @PrimaryKey val address: String,+)++/**+ * Tombstone for a locally-deleted message. Recorded when the user deletes a+ * message so that the sync worker / IMAP IDLE fetch skips its UID and never+ * re-inserts it (the server expunge can lag or fail, leaving the UID briefly+ * fetchable). Keyed by the same (account, folder, uid) tuple as EmailMessage.+ */+@Entity(primaryKeys = ["accountEmail", "folderName", "uid"])+data class DeletedUid(+    val accountEmail: String,+    val folderName: String,+    val uid: Long,+)++@Serializable+@Entity(primaryKeys = ["accountEmail", "messageId", "partId"])+data class Attachment(+    val accountEmail: String,+    val folderName: String,+    val messageId: Long, // IMAP UID+    val partId: String,+    val fileName: String,+    val mimeType: String,+    val size: Long,+    val localUri: String? = null+)++@Serializable+@Entity+data class EmailAccount(+    @PrimaryKey val email: String,+    /**+     * Legacy OAuth-token columns. Kept in the schema so old DB rows still+     * load, but no longer written: every account now uses an app password.+     */+    val accessToken: String = "",+    val refreshToken: String? = null,+    val expiresAt: Long = 0,+    /**+     * Preset identifier — `gmail`, `outlook`, `yahoo`, `icloud`, `fastmail`, or+     * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering)+     * for non-Gmail accounts, and (b) display the provider name in+     * account-picker UIs.+     *+     * `@ColumnInfo(defaultValue = ...)` is required so the schema generated+     * from this entity matches `MIGRATION_6_7`, which `ALTER TABLE`s these+     * columns in with a SQL default. Without it Room would throw+     * `IllegalStateException: Migration didn't properly handle: EmailAccount`+     * at startup for users upgrading from v6.+     */+    @ColumnInfo(defaultValue = "gmail")+    val provider: String = "gmail",+    /** IMAP hostname this account fetches from. Hard-coded to Gmail's pre-multi-provider migration. */+    @ColumnInfo(defaultValue = "imap.gmail.com")+    val imapHost: String = "imap.gmail.com",+    @ColumnInfo(defaultValue = "993")+    val imapPort: Int = 993,+    /** true = implicit SSL/TLS on connect, false = plaintext + STARTTLS upgrade. */+    @ColumnInfo(defaultValue = "1")+    val imapUseSsl: Boolean = true,+    @ColumnInfo(defaultValue = "smtp.gmail.com")+    val smtpHost: String = "smtp.gmail.com",+    @ColumnInfo(defaultValue = "465")+    val smtpPort: Int = 465,+    @ColumnInfo(defaultValue = "1")+    val smtpUseSsl: Boolean = true,+    /**+     * Optional login username for IMAP/SMTP authentication when it differs+     * from the email address (common with custom providers). When null or+     * blank, [email] is used for authentication.+     */+    @ColumnInfo(defaultValue = "")+    val username: String = "",+    /**+     * Auth scheme. Only `password` is supported now; the column is preserved+     * with its original default for legacy DB compatibility, but every newly+     * added account stores credentials as an encrypted app password.+     */+    @ColumnInfo(defaultValue = "oauth2")+    val authType: String = "password",+    /** AES-256-GCM ciphertext of the app password. */+    val passwordEncrypted: ByteArray? = null,+    /** GCM IV used to decrypt [passwordEncrypted]. */+    val passwordIv: ByteArray? = null,+    /** Plain-text signature appended to outgoing messages from this account. */+    @ColumnInfo(defaultValue = "")+    val signature: String = "",+) {+    fun getColor(): Long = accountColor(email)+}++/** Material palette used to give each account a stable color, by email hash. */+val ACCOUNT_COLORS: List<Long> = listOf(+    0xFFF44336, // Red+    0xFFE91E63, // Pink+    0xFF9C27B0, // Purple+    0xFF673AB7, // Deep Purple+    0xFF3F51B5, // Indigo+    0xFF2196F3, // Blue+    0xFF03A9F4, // Light Blue+    0xFF00BCD4, // Cyan+    0xFF009688, // Teal+    0xFF4CAF50, // Green+    0xFF8BC34A, // Light Green+    0xFFCDDC39, // Lime+    0xFFFFEB3B, // Yellow+    0xFFFFC107, // Amber+    0xFFFF9800, // Orange+    0xFFFF5722, // Deep Orange+    0xFF795548, // Brown+    0xFF9E9E9E, // Grey+    0xFF607D8B  // Blue Grey+)++/** Stable color for [email], derived from its hash. */+fun accountColor(email: String): Long {+    val hash = email.hashCode()+    return ACCOUNT_COLORS[(hash and Int.MAX_VALUE) % ACCOUNT_COLORS.size]+}++/**+ * Content of `<script>`, `<style>`, `<head>` and `<title>` elements.+ *+ * [HtmlCompat.fromHtml] emits the *text* inside these rather than dropping+ * them, so a message whose body is a full HTML document renders its stylesheet+ * as the first hundred characters of the preview.+ */+private val HTML_NON_CONTENT = Regex("""<(script|style|head|title)\b[^>]*>.*?</\1\s*>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))+private val HTML_COMMENT = Regex("""<!--.*?-->""", RegexOption.DOT_MATCHES_ALL)+private val HTML_DECLARATION = Regex("""<[!?][^>]*>""")+/** Tags common enough that their presence means the body is HTML whatever the flag says. */+private val LOOKS_LIKE_HTML = Regex("""<(html|body|head|div|table|p|br|span|a|img|font)\b[^>]*>""", RegexOption.IGNORE_CASE)+/**+ * Includes the non-breaking space `fromHtml` produces from `&nbsp;` and the+ * Unicode line/paragraph separators, none of which `\s` matches.+ */+private val WHITESPACE_RUN = Regex("""[\s\u00A0\u2028\u2029]+""")++/**+ * Characters that draw as an empty box, or as nothing at all.+ *+ * `fromHtml` returns a `Spanned` in which every `<img>` is a U+FFFC anchored to+ * an `ImageSpan`; `toString()` discards the span and leaves the placeholder+ * behind with nothing to stand for. U+FFFD is the decoder's marker for bytes it+ * could not make sense of. The zero-width characters are the invisible padding+ * marketing mail uses to pull its preheader around, and the C0/C1 controls come+ * through from mail that was never really text.+ *+ * Deliberately excludes tab, newline and the vertical whitespace controls -+ * those separate words, so deleting them would run the words together where+ * collapsing them to a space does not.+ */+private val UNRENDERABLE = Regex("[\\uFFFC\\uFFFD\\u200B-\\u200F\\uFEFF\\u0000-\\u0008\\u000E-\\u001F\\u007F]")++/**+ * Plain-text rendering of this message's body.+ *+ * Falls back to sniffing the markup when [EmailMessage.isHtml] is false, because+ * plenty of senders set `text/plain` on a body that is anything but.+ */+fun EmailMessage.plainTextBody(): String? {+    val raw = body ?: return null+    if (!isHtml && !LOOKS_LIKE_HTML.containsMatchIn(raw)) return raw.replace(UNRENDERABLE, "")+    val stripped = raw+        .replace(HTML_COMMENT, " ")+        .replace(HTML_NON_CONTENT, " ")+        .replace(HTML_DECLARATION, " ")+    return HtmlCompat.fromHtml(stripped, HtmlCompat.FROM_HTML_MODE_LEGACY)+        .toString()+        .replace(UNRENDERABLE, "")+}++/**+ * A single-line snippet of the body for list rows, widgets and notifications.+ *+ * Collapses whitespace before truncating: the block structure of an HTML mail+ * turns into leading blank lines, so [plainTextBody] truncated as-is is often+ * entirely empty.+ */+fun EmailMessage.previewText(maxChars: Int): String =+    (plainTextBody() ?: "").replace(WHITESPACE_RUN, " ").trim().take(maxChars)++/** Display name for a "Name <addr>" sender header, falling back to the address.+ * Implemented via own RFC2047 decode + simple parse to remove Jakarta dependency. */+fun senderDisplayName(from: String): String {+    if (from.isBlank()) return ""+    // Try to extract "Name <addr>" pattern+    val trimmed = from.trim()+    // Decode RFC2047 first+    val decoded = MimeParser.decodeHeader(trimmed)+    // Look for <...> format+    val angleMatch = Regex("""^(.*)<([^>]+)>$""").find(decoded.trim())+    if (angleMatch != null) {+        val namePart = angleMatch.groupValues[1].trim().trim('"').trim()+        val addr = angleMatch.groupValues[2].trim()+        if (namePart.isNotBlank()) return namePart+        return addr+    }+    // No angle brackets — could be bare address or just name+    if (decoded.contains("@")) return decoded.substringBefore("<").trim()+    return decoded+}++/**+ * A detected way to unsubscribe from a message. Produced by [detectUnsubscribe]+ * and acted on by the message-view UI.+ */+sealed interface UnsubscribeMethod {+    /** RFC 8058 one-click: HTTPS POST to [url] with body `List-Unsubscribe=One-Click`. */+    data class OneClickPost(val url: String) : UnsubscribeMethod+    /** Open an unsubscribe web page ([url]) in the browser. */+    data class OpenWeb(val url: String) : UnsubscribeMethod+    /** Compose an unsubscribe email to [address] using the in-app composer. */+    data class SendMail(val address: String) : UnsubscribeMethod+}++/** Words that signal an unsubscribe affordance; kept small to avoid false positives. */+private val UNSUBSCRIBE_KEYWORDS = listOf("unsubscribe", "opt out", "opt-out", "optout")++/**+ * Work out how (if at all) the user can unsubscribe from this message.+ *+ * Order of preference, per the email standards:+ *  1. RFC 8058 one-click POST — when `List-Unsubscribe-Post: List-Unsubscribe=One-Click`+ *     is present together with an https URL in `List-Unsubscribe`.+ *  2. An https/http URL from the `List-Unsubscribe` header (opened in the browser).+ *  3. A `mailto:` target from the `List-Unsubscribe` header (composed in-app).+ *  4. Fallback: a conservative scan of the body for an "unsubscribe" link.+ */+fun EmailMessage.detectUnsubscribe(): UnsubscribeMethod? {+    listUnsubscribe?.let { header ->+        val targets = parseListUnsubscribe(header)+        val webUrl = targets.firstOrNull { it.startsWith("http", ignoreCase = true) }+        val httpsUrl = targets.firstOrNull { it.startsWith("https://", ignoreCase = true) }+        val mailto = targets.firstOrNull { it.startsWith("mailto:", ignoreCase = true) }++        val isOneClick = listUnsubscribePost?.contains("one-click", ignoreCase = true) == true+        if (isOneClick && httpsUrl != null) return UnsubscribeMethod.OneClickPost(httpsUrl)+        if (webUrl != null) return UnsubscribeMethod.OpenWeb(webUrl)+        if (mailto != null) {+            val address = mailto.removePrefix("mailto:").removePrefix("MAILTO:").substringBefore("?").trim()+            if (address.contains("@")) return UnsubscribeMethod.SendMail(address)+        }+    }+    return findUnsubscribeLinkInBody()?.let { UnsubscribeMethod.OpenWeb(it) }+}++/** Extract the angle-bracketed targets from a List-Unsubscribe header (RFC 2369). */+private fun parseListUnsubscribe(header: String): List<String> =+    Regex("<([^>]+)>").findAll(header).map { it.groupValues[1].trim() }.toList()+        .ifEmpty { header.split(",").map { it.trim() }.filter { it.isNotEmpty() } }++/**+ * Conservatively look for an unsubscribe link in the body. Only returns a link+ * when the word "unsubscribe" (or an "opt out" variant) appears in the link's+ * href or visible text, to avoid mistaking ordinary links for unsubscribe ones.+ */+private fun EmailMessage.findUnsubscribeLinkInBody(): String? {+    val content = body ?: return null+    if (isHtml) {+        val anchor = Regex(+            "<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>(.*?)</a>",+            setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),+        )+        for (match in anchor.findAll(content)) {+            val href = match.groupValues[1].trim()+            if (!href.startsWith("http", ignoreCase = true)) continue+            val haystack = (href + " " + match.groupValues[2]).lowercase()+            if (UNSUBSCRIBE_KEYWORDS.any { haystack.contains(it) }) return href+        }+        return null+    }+    // Plain text: return an http(s) URL sitting on a line that mentions unsubscribe.+    for (line in content.lineSequence()) {+        val lower = line.lowercase()+        if (UNSUBSCRIBE_KEYWORDS.none { lower.contains(it) }) continue+        Regex("https?://\\S+", RegexOption.IGNORE_CASE).find(line)?.value+            ?.trimEnd('.', ',', ')', '>', ']')+            ?.let { return it }+    }+    return null+}++/// Pending outgoing message stored locally until it is successfully sent by the+/// background sender. Attachments are copied to app-private storage at queue time+/// (the original `content://` URIs aren't reliably readable across process+/// restarts) and `attachmentLocalPaths` is a JSON-encoded `List<String>` of those+/// absolute file paths. [inlineImageJson] stores JSON array of {cid,path,mime,name}.+@Serializable+@Entity+data class OutboxEntry(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val accountEmail: String,+    val to: String,+    val cc: String? = null,+    val bcc: String? = null,+    val subject: String,+    val body: String,+    val attachmentLocalPaths: String = "[]",+    @ColumnInfo(defaultValue = "[]")+    val inlineImageJson: String = "[]",+    val inReplyTo: String? = null,+    val references: String? = null,+    val createdAt: Long = System.currentTimeMillis(),+    val lastError: String? = null,+    val attemptCount: Int = 0,+    val lastAttemptAt: Long = 0,+    val scheduledAt: Long = 0,+    val isHtml: Boolean = false+)++@Entity+data class DraftEntry(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val accountEmail: String,+    val to: String = "",+    val cc: String = "",+    val bcc: String = "",+    val subject: String = "",+    val body: String = "",+    @ColumnInfo(defaultValue = "[]")+    val inlineImageJson: String = "[]",+    val updatedAt: Long = System.currentTimeMillis(),+)
email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt b/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.ktnew file mode 100644index 0000000000..a092673e2d--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/PeekContentBackfill.kt@@ -0,0 +1,42 @@+package com.vayunmathur.email.data++import android.content.Context+import android.util.Log+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch++/**+ * One-time backfill that computes [EmailMessage.peekContent] for rows that have a+ * body but no stored preview yet — rows persisted before the `peekContent` column+ * existed (default `''`, added by `MIGRATION_19_20`). The snippet is derived with+ * [previewText], whose HTML strip can't be expressed in SQL, so it runs in Kotlin.+ * Called from `MainActivity.onCreate`; a no-op once every bodied row has a preview.+ */+object PeekContentBackfill {++    fun runIfNeeded(scope: CoroutineScope, context: Context) {+        scope.launch(Dispatchers.IO) {+            val dao = EmailRepository.get(context).getDatabase().emailDao()+            var batch = dao.getRowsWithEmptyPeek()+            var fixed = 0+            while (batch.isNotEmpty()) {+                for (row in batch) {+                    val peek = row.previewText(PEEK_LEN)+                    // Guard against an all-whitespace/empty preview: writing '' would+                    // leave the row eligible again and loop forever. Fall back to a+                    // single space so the row is marked done.+                    dao.updatePeekContent(+                        row.accountEmail,+                        row.folderName,+                        row.id,+                        peek.ifEmpty { " " },+                    )+                    fixed+++                }+                batch = dao.getRowsWithEmptyPeek()+            }+            if (fixed > 0) Log.d("PeekContentBackfill", "Backfilled $fixed row(s)")+        }+    }+}
email/src/main/java/com/vayunmathur/email/platform/EmailUiContract.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailUiContract.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailUiContract.ktindex da483998a2..3df2bb1588 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailUiContract.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailUiContract.kt@@ -4,6 +4,7 @@ import android.content.Context import android.net.Uri import com.vayunmathur.email.data.Attachment import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailPreview import java.io.File  /**@@ -22,7 +23,7 @@ import java.io.File  /** Everything the message list draws. */ data class MessageListUiState(-    val messages: List<EmailMessage> = emptyList(),+    val messages: List<EmailPreview> = emptyList(),     /** null means the unified inbox, i.e. every account at once. */     val selectedAccountEmail: String? = null,     val selectedFolderName: String = "INBOX",@@ -47,7 +48,7 @@ interface MessageListActions {     fun markAsRead(accountEmail: String, folderName: String, uid: Long, isRead: Boolean) {}     fun deleteMessage(accountEmail: String, folderName: String, uid: Long) {}     fun refresh(context: Context) {}-    fun requestAiSummary(messages: List<EmailMessage>) {}+    fun requestAiSummary(messages: List<EmailPreview>) {}      companion object {         val Noop: MessageListActions = object : MessageListActions {}
email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.ktindex 2811674c4a..4fb45001a3 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailViewModel.kt@@ -10,8 +10,8 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.email.data.EmailAccount import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailPreview import com.vayunmathur.email.data.Attachment-import com.vayunmathur.email.data.previewText import com.vayunmathur.email.data.senderDisplayName import com.vayunmathur.email.data.EmailRepository import com.vayunmathur.email.data.EmailSyncState@@ -150,7 +150,7 @@ class EmailViewModel(application: Application) :     private val _selectedMessageUids = MutableStateFlow<Set<Long>>(emptySet())     val selectedMessageUids: StateFlow<Set<Long>> = _selectedMessageUids -    private val messagesRaw: Flow<List<EmailMessage>> = combine(+    private val messagesRaw: Flow<List<EmailPreview>> = combine(         _selectedAccountEmail,         _selectedFolderName,         _searchQuery@@ -160,13 +160,13 @@ class EmailViewModel(application: Application) :         val now = System.currentTimeMillis()         if (email == null) {             // Unified Inbox-            if (query.isEmpty()) dao.getUnifiedMessagesFlow("INBOX", now)-            else dao.searchUnifiedMessagesFlow("INBOX", query, now)+            if (query.isEmpty()) dao.getUnifiedMessagesPreviewFlow("INBOX", now)+            else dao.searchUnifiedMessagesPreviewFlow("INBOX", query, now)         } else {             if (query.isEmpty()) {-                dao.getMessagesFlow(email, folder, now)+                dao.getMessagesPreviewFlow(email, folder, now)             } else {-                dao.searchMessagesFlow(email, folder, query, now)+                dao.searchMessagesPreviewFlow(email, folder, query, now)             }         }     }@@ -174,7 +174,7 @@ class EmailViewModel(application: Application) :     val blockedSenders: Flow<List<com.vayunmathur.email.data.BlockedSender>> = dao.getBlockedSendersFlow()      // Hide messages from blocked senders (matched by email address substring).-    val messages: Flow<List<EmailMessage>> = combine(messagesRaw, blockedSenders) { msgs, blocked ->+    val messages: Flow<List<EmailPreview>> = combine(messagesRaw, blockedSenders) { msgs, blocked ->         val addrs = blocked.map { it.address.lowercase() }         if (addrs.isEmpty()) msgs         else msgs.filter { m -> addrs.none { m.from.lowercase().contains(it) } }@@ -214,7 +214,7 @@ class EmailViewModel(application: Application) :         }     } -    override fun requestAiSummary(messages: List<EmailMessage>) {+    override fun requestAiSummary(messages: List<EmailPreview>) {         if (_aiSummaryLoading.value) return          val pm = appContext.packageManager@@ -228,7 +228,7 @@ class EmailViewModel(application: Application) :         _aiSummary.value = null          val emailSnippets = messages.take(5).joinToString("\n---\n") { msg ->-            val plainBody = msg.previewText(150)+            val plainBody = msg.peekContent.take(150)             "Subject: ${msg.subject}\nFrom: ${senderDisplayName(msg.from)}\n$plainBody"         }         val prompt = "Summarize these emails in 1-2 sentences:\n\n$emailSnippets"
email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.ktindex 18a9fbf8a5..5aa231aec2 100644--- a/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/MessageListScreen.kt@@ -34,9 +34,8 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.email.R-import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailPreview import com.vayunmathur.email.data.accountColor-import com.vayunmathur.email.data.previewText import com.vayunmathur.email.data.senderDisplayName import com.vayunmathur.email.platform.EmailViewModel import com.vayunmathur.email.platform.MessageListActions@@ -70,7 +69,7 @@ import com.vayunmathur.library.ui.Text @Composable fun MessageListPage(     viewModel: EmailViewModel,-    onMessageClick: (EmailMessage) -> Unit,+    onMessageClick: (EmailPreview) -> Unit,     onComposeClick: () -> Unit,     onOpenDrawer: () -> Unit ) {@@ -108,7 +107,7 @@ fun MessageListPage( fun MessageListScreen(     state: MessageListUiState,     actions: MessageListActions,-    onMessageClick: (EmailMessage) -> Unit = {},+    onMessageClick: (EmailPreview) -> Unit = {},     onComposeClick: () -> Unit = {},     onOpenDrawer: () -> Unit = {},     initialSearching: Boolean = false,@@ -116,7 +115,7 @@ fun MessageListScreen(     var isSearching by remember { mutableStateOf(initialSearching) }     val context = LocalContext.current     val snackbarHostState = remember { SnackbarHostState() }-    var pendingDelete by remember { mutableStateOf<EmailMessage?>(null) }+    var pendingDelete by remember { mutableStateOf<EmailPreview?>(null) }      LaunchedEffect(pendingDelete) {         val msg = pendingDelete ?: return@LaunchedEffect@@ -270,7 +269,7 @@ fun MessageListScreen(                                             supportingContent = {                                                 Column {                                                     Text(text = senderDisplayName(message.from), style = MaterialTheme.typography.titleSmall)-                                                    val preview = remember(message.body, message.isHtml) { message.previewText(100) }+                                                    val preview = remember(message.peekContent) { message.peekContent.take(100) }                                                     Text(text = preview, style = MaterialTheme.typography.bodySmall, maxLines = 1, color = MaterialTheme.colorScheme.onSurfaceVariant)                                                 }                                             },
email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt
diff --git a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.ktindex 66b4df3994..b915d49721 100644--- a/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt+++ b/email/src/main/java/com/vayunmathur/email/widget/EmailWidget.kt@@ -23,9 +23,8 @@ import androidx.glance.layout.* import androidx.glance.text.* import androidx.glance.unit.ColorProvider import com.vayunmathur.email.MainActivity-import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailPreview import com.vayunmathur.email.data.accountColor-import com.vayunmathur.email.data.previewText import com.vayunmathur.email.data.senderDisplayName import com.vayunmathur.email.data.EmailRepository import com.vayunmathur.library.widgets.DynamicThemeGlance@@ -39,7 +38,7 @@ class EmailWidget : GlanceAppWidget() {         // No read status indicators, so widget doesn't need to refresh on read changes.         val messages = withContext(Dispatchers.IO) {             try {-                EmailRepository.get(context).getDatabase().emailDao().getRecentUnifiedMessages()+                EmailRepository.get(context).getDatabase().emailDao().getRecentUnifiedPreview()             } catch (e: Throwable) {                 Log.e("EmailWidget", "DB fail", e)                 emptyList()@@ -60,20 +59,20 @@ class EmailWidget : GlanceAppWidget() {     override suspend fun providePreview(context: Context, widgetCategory: Int) {         try {             val sample = listOf(-                EmailMessage(+                EmailPreview(                     accountEmail = "[email protected]", folderName = "INBOX", id = 1,                     subject = "Lunch tomorrow?", from = "Alex Johnson <[email protected]>",-                    date = "Jul 6", body = "Are we still on for noon at the usual place?",+                    date = "Jul 6", peekContent = "Are we still on for noon at the usual place?",                 ),-                EmailMessage(+                EmailPreview(                     accountEmail = "[email protected]", folderName = "INBOX", id = 2,                     subject = "Q3 report is ready", from = "Priya Patel <[email protected]>",-                    date = "Jul 5", body = "I've attached the final numbers for review.",+                    date = "Jul 5", peekContent = "I've attached the final numbers for review.",                 ),-                EmailMessage(+                EmailPreview(                     accountEmail = "[email protected]", folderName = "INBOX", id = 3,                     subject = "Your weekly digest", from = "Tech Weekly <[email protected]>",-                    date = "Jul 5", body = "Top stories and updates from this week.",+                    date = "Jul 5", peekContent = "Top stories and updates from this week.",                 ),             )             provideContent {@@ -95,7 +94,7 @@ class EmailWidget : GlanceAppWidget() {      @SuppressLint("RestrictedApi")     @Composable-    private fun EmailWidgetContent(messages: List<EmailMessage>) {+    private fun EmailWidgetContent(messages: List<EmailPreview>) {         val ctx = LocalContext.current         Scaffold(             titleBar = {@@ -137,7 +136,7 @@ class EmailWidget : GlanceAppWidget() {      @SuppressLint("RestrictedApi")     @Composable-    private fun EmailItem(msg: EmailMessage) {+    private fun EmailItem(msg: EmailPreview) {         val barColor = accountColor(msg.accountEmail)                  Row(@@ -193,7 +192,7 @@ class EmailWidget : GlanceAppWidget() {                     maxLines = 1                 )                 Text(-                    text = msg.previewText(50),+                    text = msg.peekContent.take(50),                     style = TextStyle(                         fontSize = 12.sp,                         color = GlanceTheme.colors.onSurfaceVariant
email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt
diff --git a/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt b/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.ktindex ecf0b4be76..3281578237 100644--- a/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt+++ b/email/src/screenshotTest/kotlin/com/vayunmathur/email/MetadataPreviews.kt@@ -1,260 +1,287 @@-package com.vayunmathur.email--import androidx.compose.runtime.Composable-import androidx.compose.ui.tooling.preview.Preview-import com.android.tools.screenshot.PreviewTest-import com.vayunmathur.email.ui.AddAccountScreen-import com.vayunmathur.email.platform.MessageListActions-import com.vayunmathur.email.platform.MessageListUiState-import com.vayunmathur.email.platform.MessageThreadActions-import com.vayunmathur.library.ui.DynamicTheme--/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */-private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"--/**- * Store listing images for `:email`, rendered from Compose previews instead of from an- * instrumented test on a device.- *- * `./gradlew :email:metadata` renders these and copies the PNGs into- * `metadata_data/photos/email/`, where `release.sh` picks them up.- *- * Two things to keep in mind when editing:- *- *  - Order matters, and it comes from the function names. The generated PNG filenames- *    embed the function name, so `Preview1Inbox`/`Preview2Conversation`/... sort into- *    listing order no matter how the plugin formats the rest of the filename. Renumber the- *    functions if you reorder the listing.- *  - Everything must be a literal. These render with no ViewModel, no database and no mail- *    server, so the messages below are the whole input — which is also what keeps the- *    output reproducible from a clean checkout, and is why no real account is involved.- *  - Each preview needs @PreviewTest as well as @Preview. @Preview alone renders in- *    Studio but is not collected as a screenshot test, and the build fails with the- *    unhelpful "did not discover any tests".- *  - The previews must be members of a class, not top-level functions. Android Studio- *    renders top-level previews happily, but the screenshot engine discovers previews as- *    JUnit tests and needs a real class to attach them to — top-level functions land in a- *    synthetic `…Kt` facade and are silently skipped.- */-class MetadataPreviews {--    @PreviewTest-    @Preview(name = "1-inbox", device = PHONE, showSystemUi = true)-    @Composable-    fun Preview1Inbox() {-        DynamicTheme(darkTheme = true) {-            MessageListScreen(-                // selectedAccountEmail stays null so this is the unified inbox, which is-                // the arrangement the coloured per-account band exists for.-                state = MessageListUiState(messages = INBOX),-                actions = MessageListActions.Noop,-            )-        }-    }--    @PreviewTest-    @Preview(name = "2-conversation", device = PHONE, showSystemUi = true)-    @Composable-    fun Preview2Conversation() {-        DynamicTheme(darkTheme = true) {-            MessageThreadScreen(-                messages = THREAD,-                actions = MessageThreadActions.Noop,-                threadId = "thread-review",-            )-        }-    }--    @PreviewTest-    @Preview(name = "3-search", device = PHONE, showSystemUi = true)-    @Composable-    fun Preview3Search() {-        DynamicTheme(darkTheme = true) {-            MessageListScreen(-                state = MessageListUiState(-                    messages = SEARCH_HITS,-                    searchQuery = "invoice",-                    aiSummary = "Three invoices arrived this month: Fastmail and the " +-                        "domain renewal are both paid, and the studio invoice for £480 " +-                        "is still due on 8 August.",-                ),-                actions = MessageListActions.Noop,-                initialSearching = true,-            )-        }-    }--    @PreviewTest-    @Preview(name = "4-add-account", device = PHONE, showSystemUi = true)-    @Composable-    fun Preview4AddAccount() {-        DynamicTheme(darkTheme = true) {-            AddAccountScreen(onBack = {}, onAccountAdded = {})-        }-    }-}--private const val ME = "[email protected]"-private const val WORK = "[email protected]"--/**- * Sample messages, hand-built rather than fetched.- *- * [EmailMessage.date] is a `java.util.Date.toString()`, because that is what the IMAP- * fetch stores; the list shows its first word and the conversation view everything up to- * the last colon, so the format matters to how the shots read.- */-private fun message(-    account: String,-    id: Long,-    subject: String,-    from: String,-    date: String,-    body: String,-    isRead: Boolean = true,-    hasAttachments: Boolean = false,-    threadId: String? = null,-) = EmailMessage(-    accountEmail = account,-    folderName = "INBOX",-    id = id,-    threadId = threadId,-    subject = subject,-    from = from,-    to = account,-    date = date,-    body = body,-    isRead = isRead,-    hasAttachments = hasAttachments,-)--private val INBOX = listOf(-    message(-        account = WORK,-        id = 5121,-        subject = "Re: Northgate rebrand — final round",-        from = "Priya Raman <[email protected]>",-        date = "Tue Jul 28 09:14:02 GMT 2026",-        body = "The board signed off on option B this morning. Can you get the " +-            "updated wordmark over to the print shop before Thursday?",-        isRead = false,-    ),-    message(-        account = ME,-        id = 4407,-        subject = "Your invoice for July is ready",-        from = "Fastmail Billing <[email protected]>",-        date = "Tue Jul 28 07:02:40 GMT 2026",-        body = "Invoice FM-2026-07 for £4.20 has been paid with the card ending 4419. " +-            "No action is needed.",-        isRead = false,-        hasAttachments = true,-    ),-    message(-        account = WORK,-        id = 5118,-        subject = "Standup notes, week 31",-        from = "Tomasz Nowak <[email protected]>",-        date = "Mon Jul 27 17:48:11 GMT 2026",-        body = "Shipping the caching change today. Blocked on the staging certificate, " +-            "which ops say lands tomorrow morning.",-    ),-    message(-        account = ME,-        id = 4399,-        subject = "Trail run on Saturday?",-        from = "Ellie Grant <[email protected]>",-        date = "Mon Jul 27 12:30:05 GMT 2026",-        body = "Thinking of doing the reservoir loop at eight before it gets hot. " +-            "Bring the good water bottle this time.",-    ),-    message(-        account = WORK,-        id = 5109,-        subject = "Contract renewal — signed copy attached",-        from = "Hannah Boyce <[email protected]>",-        date = "Mon Jul 27 10:05:52 GMT 2026",-        body = "Both parties have now signed. The countersigned PDF is attached for " +-            "your records.",-        hasAttachments = true,-    ),-    message(-        account = ME,-        id = 4382,-        subject = "Your package is out for delivery",-        from = "Parcel Tracking <[email protected]>",-        date = "Sun Jul 26 06:41:19 GMT 2026",-        body = "Your parcel is on the van and should arrive between 11:00 and 15:00.",-    ),-    message(-        account = WORK,-        id = 5094,-        subject = "Q3 hiring plan",-        from = "Dev Chaudhary <[email protected]>",-        date = "Fri Jul 24 15:22:37 GMT 2026",-        body = "Two more engineers approved for Q3. I've put the draft role descriptions " +-            "in the shared drive if you want to redline them.",-    ),-)--/** A short reply chain, including quoted history so the collapse control is visible. */-private val THREAD = listOf(-    message(-        account = WORK,-        id = 5107,-        subject = "Northgate rebrand — final round",-        from = "Priya Raman <[email protected]>",-        date = "Mon Jul 27 14:02:18 GMT 2026",-        body = "Sam — three options attached from the studio. My preference is B: it " +-            "holds up at favicon size and the counters don't fill in when it's " +-            "embroidered.\n\nWhat do you think?",-        threadId = "thread-review",-    ),-    message(-        account = WORK,-        id = 5119,-        subject = "Re: Northgate rebrand — final round",-        from = "Sam Whitfield <[email protected]>",-        date = "Tue Jul 28 09:14:02 GMT 2026",-        body = "Agreed on B. One change: the descender on the g is a hair too long at " +-            "small sizes, so I'd shorten it by about five percent before we send " +-            "anything to print.\n\n" +-            "On Mon Jul 27 Priya Raman wrote:\n" +-            "> Sam — three options attached from the studio. My preference is B: it\n" +-            "> holds up at favicon size and the counters don't fill in when it's\n" +-            "> embroidered.",-        threadId = "thread-review",-    ),-)--private val SEARCH_HITS = listOf(-    message(-        account = ME,-        id = 4407,-        subject = "Your invoice for July is ready",-        from = "Fastmail Billing <[email protected]>",-        date = "Tue Jul 28 07:02:40 GMT 2026",-        body = "Invoice FM-2026-07 for £4.20 has been paid with the card ending 4419.",-        hasAttachments = true,-    ),-    message(-        account = WORK,-        id = 5088,-        subject = "Invoice 2026-114 — studio, July retainer",-        from = "Marek Adamski <[email protected]>",-        date = "Thu Jul 23 11:19:56 GMT 2026",-        body = "Attaching invoice 2026-114 for £480, due 8 August. Bank details are " +-            "unchanged from last month.",-        isRead = false,-        hasAttachments = true,-    ),-    message(-        account = ME,-        id = 4361,-        subject = "Invoice paid: northgate.co.uk domain renewal",-        from = "Registrar Billing <[email protected]>",-        date = "Wed Jul 15 08:44:03 GMT 2026",-        body = "Your renewal invoice for northgate.co.uk has been paid. The domain is " +-            "now registered until July 2028.",-    ),-)+package com.vayunmathur.email++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.data.EmailPreview+import com.vayunmathur.email.ui.AddAccountScreen+import com.vayunmathur.email.platform.MessageListActions+import com.vayunmathur.email.platform.MessageListUiState+import com.vayunmathur.email.platform.MessageThreadActions+import com.vayunmathur.library.ui.DynamicTheme++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * Store listing images for `:email`, rendered from Compose previews instead of from an+ * instrumented test on a device.+ *+ * `./gradlew :email:metadata` renders these and copies the PNGs into+ * `metadata_data/photos/email/`, where `release.sh` picks them up.+ *+ * Two things to keep in mind when editing:+ *+ *  - Order matters, and it comes from the function names. The generated PNG filenames+ *    embed the function name, so `Preview1Inbox`/`Preview2Conversation`/... sort into+ *    listing order no matter how the plugin formats the rest of the filename. Renumber the+ *    functions if you reorder the listing.+ *  - Everything must be a literal. These render with no ViewModel, no database and no mail+ *    server, so the messages below are the whole input — which is also what keeps the+ *    output reproducible from a clean checkout, and is why no real account is involved.+ *  - Each preview needs @PreviewTest as well as @Preview. @Preview alone renders in+ *    Studio but is not collected as a screenshot test, and the build fails with the+ *    unhelpful "did not discover any tests".+ *  - The previews must be members of a class, not top-level functions. Android Studio+ *    renders top-level previews happily, but the screenshot engine discovers previews as+ *    JUnit tests and needs a real class to attach them to — top-level functions land in a+ *    synthetic `…Kt` facade and are silently skipped.+ */+class MetadataPreviews {++    @PreviewTest+    @Preview(name = "1-inbox", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview1Inbox() {+        DynamicTheme(darkTheme = true) {+            MessageListScreen(+                // selectedAccountEmail stays null so this is the unified inbox, which is+                // the arrangement the coloured per-account band exists for.+                state = MessageListUiState(messages = INBOX),+                actions = MessageListActions.Noop,+            )+        }+    }++    @PreviewTest+    @Preview(name = "2-conversation", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview2Conversation() {+        DynamicTheme(darkTheme = true) {+            MessageThreadScreen(+                messages = THREAD,+                actions = MessageThreadActions.Noop,+                threadId = "thread-review",+            )+        }+    }++    @PreviewTest+    @Preview(name = "3-search", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview3Search() {+        DynamicTheme(darkTheme = true) {+            MessageListScreen(+                state = MessageListUiState(+                    messages = SEARCH_HITS,+                    searchQuery = "invoice",+                    aiSummary = "Three invoices arrived this month: Fastmail and the " ++                        "domain renewal are both paid, and the studio invoice for £480 " ++                        "is still due on 8 August.",+                ),+                actions = MessageListActions.Noop,+                initialSearching = true,+            )+        }+    }++    @PreviewTest+    @Preview(name = "4-add-account", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview4AddAccount() {+        DynamicTheme(darkTheme = true) {+            AddAccountScreen(onBack = {}, onAccountAdded = {})+        }+    }+}++private const val ME = "[email protected]"+private const val WORK = "[email protected]"++/**+ * Sample messages, hand-built rather than fetched.+ *+ * [EmailMessage.date] is a `java.util.Date.toString()`, because that is what the IMAP+ * fetch stores; the list shows its first word and the conversation view everything up to+ * the last colon, so the format matters to how the shots read.+ */+private fun message(+    account: String,+    id: Long,+    subject: String,+    from: String,+    date: String,+    body: String,+    isRead: Boolean = true,+    hasAttachments: Boolean = false,+    threadId: String? = null,+) = EmailMessage(+    accountEmail = account,+    folderName = "INBOX",+    id = id,+    threadId = threadId,+    subject = subject,+    from = from,+    to = account,+    date = date,+    body = body,+    isRead = isRead,+    hasAttachments = hasAttachments,+)++/** Same as [message] but as the light [EmailPreview] projection the list screen now+ *  consumes; [body] becomes the stored [EmailPreview.peekContent] snippet directly. */+private fun preview(+    account: String,+    id: Long,+    subject: String,+    from: String,+    date: String,+    body: String,+    isRead: Boolean = true,+    hasAttachments: Boolean = false,+    threadId: String? = null,+) = EmailPreview(+    accountEmail = account,+    folderName = "INBOX",+    id = id,+    threadId = threadId,+    subject = subject,+    from = from,+    date = date,+    isRead = isRead,+    hasAttachments = hasAttachments,+    peekContent = body,+)++private val INBOX = listOf(+    preview(+        account = WORK,+        id = 5121,+        subject = "Re: Northgate rebrand — final round",+        from = "Priya Raman <[email protected]>",+        date = "Tue Jul 28 09:14:02 GMT 2026",+        body = "The board signed off on option B this morning. Can you get the " ++            "updated wordmark over to the print shop before Thursday?",+        isRead = false,+    ),+    preview(+        account = ME,+        id = 4407,+        subject = "Your invoice for July is ready",+        from = "Fastmail Billing <[email protected]>",+        date = "Tue Jul 28 07:02:40 GMT 2026",+        body = "Invoice FM-2026-07 for £4.20 has been paid with the card ending 4419. " ++            "No action is needed.",+        isRead = false,+        hasAttachments = true,+    ),+    preview(+        account = WORK,+        id = 5118,+        subject = "Standup notes, week 31",+        from = "Tomasz Nowak <[email protected]>",+        date = "Mon Jul 27 17:48:11 GMT 2026",+        body = "Shipping the caching change today. Blocked on the staging certificate, " ++            "which ops say lands tomorrow morning.",+    ),+    preview(+        account = ME,+        id = 4399,+        subject = "Trail run on Saturday?",+        from = "Ellie Grant <[email protected]>",+        date = "Mon Jul 27 12:30:05 GMT 2026",+        body = "Thinking of doing the reservoir loop at eight before it gets hot. " ++            "Bring the good water bottle this time.",+    ),+    preview(+        account = WORK,+        id = 5109,+        subject = "Contract renewal — signed copy attached",+        from = "Hannah Boyce <[email protected]>",+        date = "Mon Jul 27 10:05:52 GMT 2026",+        body = "Both parties have now signed. The countersigned PDF is attached for " ++            "your records.",+        hasAttachments = true,+    ),+    preview(+        account = ME,+        id = 4382,+        subject = "Your package is out for delivery",+        from = "Parcel Tracking <[email protected]>",+        date = "Sun Jul 26 06:41:19 GMT 2026",+        body = "Your parcel is on the van and should arrive between 11:00 and 15:00.",+    ),+    preview(+        account = WORK,+        id = 5094,+        subject = "Q3 hiring plan",+        from = "Dev Chaudhary <[email protected]>",+        date = "Fri Jul 24 15:22:37 GMT 2026",+        body = "Two more engineers approved for Q3. I've put the draft role descriptions " ++            "in the shared drive if you want to redline them.",+    ),+)++/** A short reply chain, including quoted history so the collapse control is visible. */+private val THREAD = listOf(+    message(+        account = WORK,+        id = 5107,+        subject = "Northgate rebrand — final round",+        from = "Priya Raman <[email protected]>",+        date = "Mon Jul 27 14:02:18 GMT 2026",+        body = "Sam — three options attached from the studio. My preference is B: it " ++            "holds up at favicon size and the counters don't fill in when it's " ++            "embroidered.\n\nWhat do you think?",+        threadId = "thread-review",+    ),+    message(+        account = WORK,+        id = 5119,+        subject = "Re: Northgate rebrand — final round",+        from = "Sam Whitfield <[email protected]>",+        date = "Tue Jul 28 09:14:02 GMT 2026",+        body = "Agreed on B. One change: the descender on the g is a hair too long at " ++            "small sizes, so I'd shorten it by about five percent before we send " ++            "anything to print.\n\n" ++            "On Mon Jul 27 Priya Raman wrote:\n" ++            "> Sam — three options attached from the studio. My preference is B: it\n" ++            "> holds up at favicon size and the counters don't fill in when it's\n" ++            "> embroidered.",+        threadId = "thread-review",+    ),+)++private val SEARCH_HITS = listOf(+    preview(+        account = ME,+        id = 4407,+        subject = "Your invoice for July is ready",+        from = "Fastmail Billing <[email protected]>",+        date = "Tue Jul 28 07:02:40 GMT 2026",+        body = "Invoice FM-2026-07 for £4.20 has been paid with the card ending 4419.",+        hasAttachments = true,+    ),+    preview(+        account = WORK,+        id = 5088,+        subject = "Invoice 2026-114 — studio, July retainer",+        from = "Marek Adamski <[email protected]>",+        date = "Thu Jul 23 11:19:56 GMT 2026",+        body = "Attaching invoice 2026-114 for £480, due 8 August. Bank details are " ++            "unchanged from last month.",+        isRead = false,+        hasAttachments = true,+    ),+    preview(+        account = ME,+        id = 4361,+        subject = "Invoice paid: northgate.co.uk domain renewal",+        from = "Registrar Billing <[email protected]>",+        date = "Wed Jul 15 08:44:03 GMT 2026",+        body = "Your renewal invoice for northgate.co.uk has been paid. The domain is " ++            "now registered until July 2028.",+    ),+)