Dough Git

commit

Rebuild the Android app natively in Kotlin and Compose

commit
84c576ee814fb27c90d58d6db2ed2b2170e0a751
author
Clove Twilight <[email protected]>
date
2026-10-27 13:11
Replaces the Trusted Web Activity with a native app on the Worker API:
thread list with swipe actions and a long-press menu (including Edit for
drafts), conversations with sandboxed HTML rendering, a composer with
attachments and drafts, settings, and live updates over /api/live.

Sign-in runs the server's SSO flow in a Custom Tab and swaps a one-time
code plus PKCE verifier for a bearer token, kept encrypted with an
Android Keystore key. Same package and signing key, so it installs over
the TWA. minSdk goes from 23 to 26.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

diff --git a/email/README.md b/email/README.md
index fbc6f45..67e7557 100644
--- a/email/README.md
+++ b/email/README.md
@@ -1,23 +1,49 @@
 # Inbox for Android
 
-An Android app for [Inbox](../email). It's a
-[Trusted Web Activity](https://developer.chrome.com/docs/android/trusted-web-activity):
-the live site at https://mail.doughmination.gay, shown full-screen in Chrome,
-with its Web Push notifications delivered as the app's own.
+A native Android app (Kotlin, Jetpack Compose) for [Inbox](../email). It talks
+to the same Worker API as the web app.
 
-Full-screen only works while the site's `/.well-known/assetlinks.json` lists
-this app's signing key. If it doesn't match, the app still works but shows a
-small address bar at the top.
+```
+app/src/main/java/gay/doughmination/mail/
+  MainActivity.kt      sign-in redirects and links to the site land here
+  InboxApp.kt          the app-wide Api, Auth, Live and token store
+  data/
+    Api.kt             /api and /auth calls, bearer-signed
+    Auth.kt            sign-in through the SSO in a browser tab (code + PKCE)
+    TokenStore.kt      session token, encrypted with an Android Keystore key
+    Live.kt            the /api/live WebSocket while the app is open
+    Models.kt          mirrors email/src/shared/types.ts
+  ui/
+    MailViewModel.kt   state and actions for every screen
+    ThreadListScreen   folders, swipe actions, long-press menu
+    ThreadScreen       a conversation
+    EmailView.kt       the only place email HTML is rendered
+    ComposeScreen      new mail, replies, forwards, drafts
+```
+
+- **Sign-in** opens `/auth/login?app=<challenge>` in a Custom Tab. The server
+  redirects to `gay.doughmination.mail://auth?code=...` and the app swaps the code
+  and its PKCE verifier for a session token, sent as `Authorization: Bearer`.
+- **Email HTML** renders in a WebView with JavaScript off. Links open in the
+  browser, and remote content is blocked until you tap "Load remote images".
+- **Admin** stays on the web; the drawer links to it.
+- Links to `mail.doughmination.gay/inbox/...` open in the app, which needs the
+  site's `/.well-known/assetlinks.json` to list this app's signing key.
 
 ## Building
 
-Needs JDK 17+ and the Android SDK (platform 35).
+Needs JDK 17–21 (Gradle 8.11 doesn't run on newer JDKs) and the Android SDK
+(platform 35).
 
 ```sh
 echo "sdk.dir=/opt/android-sdk" > local.properties
+./gradlew assembleDebug       # app/build/outputs/apk/debug/app-debug.apk
 ./gradlew assembleRelease     # app/build/outputs/apk/release/app-release.apk
 ```
 
+`-PinboxUrl=http://10.0.2.2:5173` points a build at `npm run dev` from the
+emulator. Signing in locally needs `/auth/*` to reach that server too.
+
 Signing reads `keystore.properties` (gitignored):
 
 ```properties
@@ -33,12 +59,10 @@ changing too.
 
 ## CI
 
-`.github/workflows/android.yml` (at the repo root) builds on every push and uploads `inbox.apk` as
-an artifact. Each build from `main` replaces the rolling `latest` release, so
-the newest APK is always at
-https://github.com/doughmination/email-app/releases/download/latest/inbox.apk.
-Pushing a `v*` tag also attaches it to a GitHub release of its own. It signs
-with two repository secrets:
+`.github/workflows/android.yml` (at the repo root) builds whenever `app/`
+changes and uploads `inbox.apk` as an artifact. Each build from `main` replaces
+the rolling `latest` release, and pushing a `v*` tag attaches it to a GitHub
+release of its own. It signs with two repository secrets:
 
 - `KEYSTORE_BASE64`: `base64 -w0 inbox.jks`
 - `KEYSTORE_PASSWORD`: the keystore password
diff --git a/email/app/build.gradle.kts b/email/app/build.gradle.kts
index 95d192b..9e11881 100644
--- a/email/app/build.gradle.kts
+++ b/email/app/build.gradle.kts
@@ -2,6 +2,9 @@ import java.util.Properties
 
 plugins {
     id("com.android.application")
+    id("org.jetbrains.kotlin.android")
+    id("org.jetbrains.kotlin.plugin.compose")
+    id("org.jetbrains.kotlin.plugin.serialization")
 }
 
 // Signing details live in keystore.properties (not committed). Without it the
@@ -11,17 +14,22 @@ val keystoreProps = Properties().apply {
     if (f.exists()) f.inputStream().use { load(it) }
 }
 
+// The server the app talks to; -PinboxUrl=http://10.0.2.2:5173 points a
+// build at a local `npm run dev` from the emulator.
+val inboxUrl = (findProperty("inboxUrl") as String?) ?: "https://mail.doughmination.gay"
+
 android {
     namespace = "gay.doughmination.mail"
     compileSdk = 35
 
     defaultConfig {
         applicationId = "gay.doughmination.mail"
-        minSdk = 23
+        minSdk = 26
         targetSdk = 35
         // CI passes the run number so every build installs over the last one.
         versionCode = (System.getenv("VERSION_CODE") ?: "1").toInt()
         versionName = System.getenv("VERSION_NAME") ?: "1.0"
+        buildConfigField("String", "INBOX_URL", "\"$inboxUrl\"")
     }
 
     signingConfigs {
@@ -42,12 +50,38 @@ android {
         }
     }
 
+    buildFeatures {
+        compose = true
+        buildConfig = true
+    }
+
     compileOptions {
         sourceCompatibility = JavaVersion.VERSION_17
         targetCompatibility = JavaVersion.VERSION_17
     }
+
+    kotlinOptions {
+        jvmTarget = "17"
+    }
 }
 
 dependencies {
-    implementation("com.google.androidbrowserhelper:androidbrowserhelper:2.5.0")
+    val composeBom = platform("androidx.compose:compose-bom:2024.12.01")
+    implementation(composeBom)
+    implementation("androidx.compose.material3:material3")
+    implementation("androidx.compose.material:material-icons-extended")
+    implementation("androidx.compose.ui:ui")
+    implementation("androidx.compose.ui:ui-tooling-preview")
+    debugImplementation("androidx.compose.ui:ui-tooling")
+
+    implementation("androidx.core:core-ktx:1.15.0")
+    implementation("androidx.activity:activity-compose:1.9.3")
+    implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
+    implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
+    implementation("androidx.lifecycle:lifecycle-process:2.8.7")
+    implementation("androidx.browser:browser:1.8.0")
+
+    implementation("com.squareup.okhttp3:okhttp:4.12.0")
+    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
+    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
 }
diff --git a/email/app/src/main/AndroidManifest.xml b/email/app/src/main/AndroidManifest.xml
index 4f20965..d453b7e 100644
--- a/email/app/src/main/AndroidManifest.xml
+++ b/email/app/src/main/AndroidManifest.xml
@@ -1,105 +1,54 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- A Trusted Web Activity: the app is the live site at launch_url, shown
-     full-screen in Chrome once assetlinks.json on the site matches our key. -->
 <manifest xmlns:android="http://schemas.android.com/apk/res/android">
 
-    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+    <uses-permission android:name="android.permission.INTERNET" />
 
-    <!-- So LauncherActivity can tell whether Chrome is installed. -->
+    <!-- Custom Tabs for signing in: lets us find a browser that supports them. -->
     <queries>
-        <package android:name="com.android.chrome" />
+        <intent>
+            <action android:name="android.support.customtabs.action.CustomTabsService" />
+        </intent>
     </queries>
 
     <application
-        android:allowBackup="true"
+        android:name=".InboxApp"
+        android:allowBackup="false"
         android:icon="@mipmap/ic_launcher"
         android:label="@string/app_name"
-        android:theme="@android:style/Theme.Translucent.NoTitleBar">
-
-        <meta-data
-            android:name="asset_statements"
-            android:resource="@string/asset_statements" />
+        android:theme="@style/Theme.Inbox">
 
         <activity
-            android:name=".LauncherActivity"
+            android:name=".MainActivity"
             android:exported="true"
-            android:label="@string/app_name">
-            <meta-data
-                android:name="android.support.customtabs.trusted.DEFAULT_URL"
-                android:value="@string/launch_url" />
-            <meta-data
-                android:name="android.support.customtabs.trusted.STATUS_BAR_COLOR"
-                android:resource="@color/background" />
-            <meta-data
-                android:name="android.support.customtabs.trusted.NAVIGATION_BAR_COLOR"
-                android:resource="@color/background" />
-            <meta-data
-                android:name="android.support.customtabs.trusted.FALLBACK_STRATEGY"
-                android:value="customtabs" />
-
-            <!-- Splash: the icon on the app background until the page first
-                 paints. The site's own splash starts on this exact frame
-                 (128dp, centred) and animates from there. -->
-            <meta-data
-                android:name="android.support.customtabs.trusted.SPLASH_IMAGE_DRAWABLE"
-                android:resource="@drawable/splash" />
-            <meta-data
-                android:name="android.support.customtabs.trusted.SPLASH_SCREEN_BACKGROUND_COLOR"
-                android:resource="@color/background" />
-            <meta-data
-                android:name="android.support.customtabs.trusted.SPLASH_SCREEN_FADE_OUT_DURATION"
-                android:value="200" />
-            <meta-data
-                android:name="android.support.customtabs.trusted.FILE_PROVIDER_AUTHORITY"
-                android:value="gay.doughmination.mail.fileprovider" />
+            android:launchMode="singleTask"
+            android:windowSoftInputMode="adjustResize">
 
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
 
-            <!-- Open mail.doughmination.gay links in the app. -->
-            <intent-filter android:autoVerify="true">
+            <!-- Where the server sends the browser tab after SSO sign-in. -->
+            <intent-filter>
                 <action android:name="android.intent.action.VIEW" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.BROWSABLE" />
-                <data android:scheme="https" android:host="mail.doughmination.gay" />
+                <data android:scheme="gay.doughmination.mail" android:host="auth" />
             </intent-filter>
-        </activity>
-
-        <activity android:name="com.google.androidbrowserhelper.trusted.FocusActivity" />
-
-        <!-- Hands the splash image to Chrome. -->
-        <provider
-            android:name="androidx.core.content.FileProvider"
-            android:authorities="gay.doughmination.mail.fileprovider"
-            android:exported="false"
-            android:grantUriPermissions="true">
-            <meta-data
-                android:name="android.support.FILE_PROVIDER_PATHS"
-                android:resource="@xml/filepaths" />
-        </provider>
 
-        <!-- Shows the Android 13+ notification permission prompt when the
-             site asks for it. Without it the request fails and nothing is
-             ever delivered. -->
-        <activity
-            android:name="com.google.androidbrowserhelper.trusted.NotificationPermissionRequestActivity"
-            android:exported="false" />
-
-        <!-- Lets Chrome hand the site's Web Push notifications to the app, so
-             they show up under "Inbox" rather than under Chrome. -->
-        <service
-            android:name="com.google.androidbrowserhelper.trusted.DelegationService"
-            android:enabled="true"
-            android:exported="true">
-            <meta-data
-                android:name="android.support.customtabs.trusted.SMALL_ICON"
-                android:resource="@drawable/ic_notification" />
-            <intent-filter>
-                <action android:name="android.support.customtabs.trusted.TRUSTED_WEB_ACTIVITY_SERVICE" />
+            <!-- Links to mail open in the app. Only these paths: claiming
+                 /auth would pull the sign-in redirect out of the browser tab. -->
+            <intent-filter android:autoVerify="true">
+                <action android:name="android.intent.action.VIEW" />
                 <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.BROWSABLE" />
+                <data android:scheme="https" android:host="mail.doughmination.gay" />
+                <data android:pathPrefix="/inbox" />
+                <data android:pathPrefix="/starred" />
+                <data android:pathPrefix="/sent" />
+                <data android:pathPrefix="/drafts" />
+                <data android:pathPrefix="/bin" />
             </intent-filter>
-        </service>
+        </activity>
     </application>
 </manifest>
diff --git a/email/app/src/main/java/gay/doughmination/mail/InboxApp.kt b/email/app/src/main/java/gay/doughmination/mail/InboxApp.kt
new file mode 100644
index 0000000..ebb4892
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/InboxApp.kt
@@ -0,0 +1,51 @@
+package gay.doughmination.mail
+
+import android.app.Application
+import androidx.lifecycle.DefaultLifecycleObserver
+import androidx.lifecycle.LifecycleOwner
+import androidx.lifecycle.ProcessLifecycleOwner
+import gay.doughmination.mail.data.Api
+import gay.doughmination.mail.data.Auth
+import gay.doughmination.mail.data.Live
+import gay.doughmination.mail.data.TokenStore
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+/** Holds the app-wide pieces; there's one of each per process. */
+class InboxApp : Application() {
+    lateinit var tokens: TokenStore
+        private set
+    lateinit var api: Api
+        private set
+    lateinit var auth: Auth
+        private set
+    lateinit var live: Live
+        private set
+
+    private val _signedIn = MutableStateFlow(false)
+    val signedIn: StateFlow<Boolean> = _signedIn
+
+    override fun onCreate() {
+        super.onCreate()
+        tokens = TokenStore(this)
+        api = Api(BuildConfig.INBOX_URL, tokens) { _signedIn.value = false }
+        auth = Auth(api, tokens)
+        live = Live(api, MainScope())
+        _signedIn.value = tokens.token != null
+
+        // The live socket only runs while the app is on screen and signed in.
+        ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
+            override fun onStart(owner: LifecycleOwner) {
+                if (_signedIn.value) live.start()
+            }
+
+            override fun onStop(owner: LifecycleOwner) = live.stop()
+        })
+    }
+
+    fun setSignedIn(value: Boolean) {
+        _signedIn.value = value
+        if (value) live.start() else live.stop()
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/LauncherActivity.java b/email/app/src/main/java/gay/doughmination/mail/LauncherActivity.java
deleted file mode 100644
index a6a103a..0000000
--- a/email/app/src/main/java/gay/doughmination/mail/LauncherActivity.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package gay.doughmination.mail;
-
-import android.content.pm.PackageManager;
-
-import com.google.androidbrowserhelper.trusted.TwaLauncher;
-
-/**
- * Opens the site in Chrome even when another browser is the default. The
- * library would otherwise pick the default browser, and browsers other than
- * Chrome tend to show it as a custom tab with an address bar. Without Chrome
- * installed, it falls back to the library's own choice.
- */
-public class LauncherActivity extends com.google.androidbrowserhelper.trusted.LauncherActivity {
-    private static final String CHROME = "com.android.chrome";
-
-    @Override
-    protected TwaLauncher createTwaLauncher() {
-        return new TwaLauncher(this, isInstalled(CHROME) ? CHROME : null);
-    }
-
-    private boolean isInstalled(String pkg) {
-        try {
-            PackageManager pm = getPackageManager();
-            return pm.getApplicationInfo(pkg, 0).enabled;
-        } catch (PackageManager.NameNotFoundException e) {
-            return false;
-        }
-    }
-}
diff --git a/email/app/src/main/java/gay/doughmination/mail/MainActivity.kt b/email/app/src/main/java/gay/doughmination/mail/MainActivity.kt
new file mode 100644
index 0000000..b565a84
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/MainActivity.kt
@@ -0,0 +1,39 @@
+package gay.doughmination.mail
+
+import android.content.Intent
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.activity.viewModels
+import gay.doughmination.mail.ui.AppRoot
+import gay.doughmination.mail.ui.InboxTheme
+import gay.doughmination.mail.ui.MailViewModel
+
+class MainActivity : ComponentActivity() {
+    private val vm: MailViewModel by viewModels()
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        enableEdgeToEdge()
+        super.onCreate(savedInstanceState)
+        setContent { InboxTheme { AppRoot(vm) } }
+        // A recreated activity (rotation) has already handled its launch intent.
+        if (savedInstanceState == null) handle(intent)
+    }
+
+    override fun onNewIntent(intent: Intent) {
+        super.onNewIntent(intent)
+        handle(intent)
+    }
+
+    private fun handle(intent: Intent?) {
+        val data = intent?.data ?: return
+        when {
+            // The end of sign-in: gay.doughmination.mail://auth?code=...
+            data.scheme == "gay.doughmination.mail" && data.host == "auth" ->
+                data.getQueryParameter("code")?.let(vm::finishLogin)
+            // A link to the site, like /inbox/<thread id>.
+            data.scheme == "https" && vm.signedIn -> data.path?.let(vm::openPath)
+        }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/data/Api.kt b/email/app/src/main/java/gay/doughmination/mail/data/Api.kt
new file mode 100644
index 0000000..a6d5143
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/data/Api.kt
@@ -0,0 +1,171 @@
+package gay.doughmination.mail.data
+
+import android.content.ContentResolver
+import android.net.Uri
+import android.provider.OpenableColumns
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonPrimitive
+import okhttp3.HttpUrl
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.MediaType.Companion.toMediaTypeOrNull
+import okhttp3.MultipartBody
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody
+import okhttp3.RequestBody.Companion.toRequestBody
+import okio.BufferedSink
+import okio.source
+import java.util.concurrent.TimeUnit
+
+/** The server said no; `message` is fit to show. `draftId` is set when a failed send left a draft. */
+class ApiException(message: String, val status: Int, val draftId: String? = null) : Exception(message)
+
+/** The session is gone (expired, signed out elsewhere, account removed). */
+class SignedOutException : Exception("Signed out")
+
+/** The Worker's /api and /auth endpoints, signed in with the bearer token. */
+class Api(val baseUrl: String, private val tokens: TokenStore, private val onSignedOut: () -> Unit) {
+    val http: OkHttpClient = OkHttpClient.Builder()
+        .connectTimeout(15, TimeUnit.SECONDS)
+        .readTimeout(60, TimeUnit.SECONDS)
+        .writeTimeout(120, TimeUnit.SECONDS)
+        .build()
+
+    val json = Json {
+        ignoreUnknownKeys = true
+        encodeDefaults = true
+    }
+
+    private val jsonType = "application/json".toMediaType()
+
+    fun url(path: String): HttpUrl = "$baseUrl$path".toHttpUrl()
+
+    /** Adds the session token; for requests made outside this class (the WebView, downloads, the socket). */
+    fun authorize(builder: Request.Builder): Request.Builder =
+        tokens.token?.let { builder.header("Authorization", "Bearer $it") } ?: builder
+
+    private suspend fun send(request: Request): String = withContext(Dispatchers.IO) {
+        if (tokens.token == null) throw SignedOutException()
+        http.newCall(authorize(request.newBuilder()).build()).execute().use { res ->
+            val body = res.body?.string().orEmpty()
+            if (res.code == 401) {
+                tokens.token = null
+                onSignedOut()
+                throw SignedOutException()
+            }
+            if (!res.isSuccessful) {
+                val obj = runCatching { json.decodeFromString<JsonObject>(body) }.getOrNull()
+                throw ApiException(
+                    obj?.get("error")?.jsonPrimitive?.contentOrNull ?: "Request failed (${res.code})",
+                    res.code,
+                    obj?.get("draftId")?.jsonPrimitive?.contentOrNull,
+                )
+            }
+            body
+        }
+    }
+
+    private suspend inline fun <reified T> get(path: String): T =
+        json.decodeFromString(send(Request.Builder().url(url(path)).build()))
+
+    private suspend inline fun <reified T, reified B> call(method: String, path: String, body: B): T {
+        val payload = json.encodeToString(body).toRequestBody(jsonType)
+        return json.decodeFromString(send(Request.Builder().url(url(path)).method(method, payload).build()))
+    }
+
+    private suspend inline fun <reified T> call(method: String, path: String): T {
+        val payload = if (method == "DELETE") null else "{}".toRequestBody(jsonType)
+        return json.decodeFromString(send(Request.Builder().url(url(path)).method(method, payload).build()))
+    }
+
+    @Serializable data class Unread(val unread: Map<String, Int>)
+    @Serializable data class Count(val count: Int)
+    @Serializable data class Id(val id: String)
+    @Serializable data class Sent(val id: String, val threadId: String)
+    @Serializable private data class Read(val read: Boolean)
+    @Serializable private data class Star(val starred: Boolean)
+    @Serializable private data class Name(val name: String)
+    @Serializable private data class CodeSwap(val code: String, val verifier: String)
+    @Serializable private data class Token(val token: String)
+
+    suspend fun me(): Me = get("/api/me")
+    suspend fun unread(): Map<String, Int> = get<Unread>("/api/unread").unread
+    suspend fun setName(name: String) { call<JsonObject, Name>("PATCH", "/api/me", Name(name)) }
+
+    suspend fun threads(folder: ListFolder, mailbox: String?, cursor: String?): Page<ThreadSummary> {
+        val q = url("/api/threads").newBuilder().addQueryParameter("folder", folder.path)
+        mailbox?.let { q.addQueryParameter("mailbox", it) }
+        cursor?.let { q.addQueryParameter("cursor", it) }
+        return json.decodeFromString(send(Request.Builder().url(q.build()).build()))
+    }
+
+    /** With `bin`, only the part of the thread that's in the Bin. */
+    suspend fun thread(id: String, bin: Boolean): MailThread = get("/api/threads/$id${if (bin) "?bin=1" else ""}")
+    suspend fun message(id: String): Message = get("/api/messages/$id")
+    suspend fun markThread(id: String, read: Boolean): Map<String, Int> =
+        call<Unread, Read>("POST", "/api/threads/$id/read", Read(read)).unread
+    suspend fun starThread(id: String, starred: Boolean) { call<JsonObject, Star>("POST", "/api/threads/$id/star", Star(starred)) }
+    /** Moves it to the Bin; `forever` deletes what of it is already in the Bin. */
+    suspend fun deleteThread(id: String, forever: Boolean = false): Int =
+        call<Count>("DELETE", "/api/threads/$id${if (forever) "?forever=1" else ""}").count
+    suspend fun restoreThread(id: String): Int = call<Count>("POST", "/api/threads/$id/restore").count
+    suspend fun emptyBin(): Int = call<Count>("DELETE", "/api/bin").count
+    /** Moves it to the Bin; `forever` deletes it outright, wherever it is. */
+    suspend fun deleteMessage(id: String, forever: Boolean = false): Int =
+        call<Count>("DELETE", "/api/messages/$id${if (forever) "?forever=1" else ""}").count
+    suspend fun restoreMessage(id: String): Int = call<Count>("POST", "/api/messages/$id/restore").count
+
+    suspend fun createDraft(input: SendRequest): String = call<Id, SendRequest>("POST", "/api/drafts", input).id
+    suspend fun updateDraft(id: String, input: SendRequest): String = call<Id, SendRequest>("PUT", "/api/drafts/$id", input).id
+    suspend fun send(input: SendRequest): Sent = call("POST", "/api/send", input)
+
+    fun attachmentUrl(id: String, inline: Boolean = false): String =
+        "$baseUrl/api/attachments/$id${if (inline) "?inline=1" else ""}"
+
+    /** Streams a picked file up as an unclaimed attachment. */
+    suspend fun upload(resolver: ContentResolver, uri: Uri): AttachmentInfo {
+        var name = "attachment"
+        var size = -1L
+        resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
+            if (c.moveToFirst()) {
+                c.getString(0)?.let { name = it }
+                if (!c.isNull(1)) size = c.getLong(1)
+            }
+        }
+        val type = resolver.getType(uri)?.toMediaTypeOrNull() ?: "application/octet-stream".toMediaType()
+        val file = object : RequestBody() {
+            override fun contentType(): MediaType = type
+            override fun contentLength(): Long = size
+            override fun writeTo(sink: BufferedSink) {
+                resolver.openInputStream(uri)?.source()?.use { sink.writeAll(it) }
+                    ?: throw java.io.IOException("Couldn't read $name")
+            }
+        }
+        val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", name, file).build()
+        return json.decodeFromString(send(Request.Builder().url(url("/api/uploads")).post(form).build()))
+    }
+
+    /** Ends the session on the server. The token is dropped locally whatever happens. */
+    suspend fun logout() {
+        runCatching { call<JsonObject>("POST", "/auth/logout") }
+        tokens.token = null
+    }
+
+    /** Swaps the one-time code from the sign-in redirect for a session token. */
+    suspend fun exchangeCode(code: String, verifier: String): String = withContext(Dispatchers.IO) {
+        val payload = json.encodeToString(CodeSwap(code, verifier)).toRequestBody(jsonType)
+        http.newCall(Request.Builder().url(url("/auth/app/token")).post(payload).build()).execute().use { res ->
+            val body = res.body?.string().orEmpty()
+            if (!res.isSuccessful) throw ApiException("That sign-in didn't work. Try again.", res.code)
+            json.decodeFromString<Token>(body).token
+        }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/data/Auth.kt b/email/app/src/main/java/gay/doughmination/mail/data/Auth.kt
new file mode 100644
index 0000000..cd616a2
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/data/Auth.kt
@@ -0,0 +1,40 @@
+package gay.doughmination.mail.data
+
+import android.content.Context
+import android.net.Uri
+import android.util.Base64
+import androidx.browser.customtabs.CustomTabsIntent
+import java.security.MessageDigest
+import java.security.SecureRandom
+
+/**
+ * Sign-in goes through the server's own SSO flow in a browser tab:
+ *
+ *  1. open /auth/login?app=<challenge>, keeping the PKCE verifier here;
+ *  2. the server, once the SSO is happy, redirects to
+ *     gay.doughmination.mail://auth?code=<one-time code>;
+ *  3. MainActivity gets that and [finish] swaps code + verifier for a token.
+ *
+ * Only this app holds the verifier, so another app that grabs the redirect
+ * can't use the code.
+ */
+class Auth(private val api: Api, private val tokens: TokenStore) {
+    fun start(context: Context) {
+        val verifier = b64url(ByteArray(32).also { SecureRandom().nextBytes(it) })
+        val challenge = b64url(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray()))
+        tokens.pendingVerifier = verifier
+        CustomTabsIntent.Builder()
+            .setShowTitle(true)
+            .build()
+            .launchUrl(context, Uri.parse("${api.baseUrl}/auth/login?app=$challenge"))
+    }
+
+    suspend fun finish(code: String) {
+        val verifier = tokens.pendingVerifier ?: throw ApiException("That sign-in has expired. Try again.", 400)
+        tokens.pendingVerifier = null
+        tokens.token = api.exchangeCode(code, verifier)
+    }
+
+    private fun b64url(bytes: ByteArray): String =
+        Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/data/Live.kt b/email/app/src/main/java/gay/doughmination/mail/data/Live.kt
new file mode 100644
index 0000000..a4eb6e0
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/data/Live.kt
@@ -0,0 +1,95 @@
+package gay.doughmination.mail.data
+
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.launch
+import kotlinx.serialization.Serializable
+import okhttp3.Request
+import okhttp3.Response
+import okhttp3.WebSocket
+import okhttp3.WebSocketListener
+
+/**
+ * Keeps a WebSocket to /api/live open while the app is in the foreground and
+ * emits when new mail lands. Reconnects with backoff; a reconnect emits too,
+ * so anything missed while it was down gets picked up.
+ */
+class Live(private val api: Api, private val scope: CoroutineScope) {
+    /** The thread new mail landed in, or null for "something may have changed". */
+    private val _events = MutableSharedFlow<String?>(extraBufferCapacity = 16)
+    val events: SharedFlow<String?> = _events
+
+    private var socket: WebSocket? = null
+    private var pinger: Job? = null
+    private var retry: Job? = null
+    private var running = false
+    private var backoffMs = 1_000L
+    private var dropped = false
+
+    @Serializable
+    private data class Event(val type: String, val threadId: String? = null)
+
+    fun start() {
+        if (running) return
+        running = true
+        connect()
+    }
+
+    fun stop() {
+        running = false
+        retry?.cancel()
+        pinger?.cancel()
+        socket?.close(1000, null)
+        socket = null
+        dropped = true
+    }
+
+    private fun connect() {
+        if (!running || socket != null) return
+        val url = api.baseUrl.replaceFirst("http", "ws") + "/api/live"
+        val request = api.authorize(Request.Builder().url(url)).build()
+        socket = api.http.newWebSocket(request, object : WebSocketListener() {
+            override fun onOpen(webSocket: WebSocket, response: Response) {
+                scope.launch {
+                    if (socket !== webSocket) return@launch
+                    backoffMs = 1_000L
+                    // Cloudflare drops idle sockets after ~100s; the server answers without waking.
+                    pinger = scope.launch {
+                        while (true) {
+                            delay(30_000)
+                            webSocket.send("ping")
+                        }
+                    }
+                    if (dropped) _events.tryEmit(null)
+                }
+            }
+
+            override fun onMessage(webSocket: WebSocket, text: String) {
+                if (text == "pong") return
+                val event = runCatching { api.json.decodeFromString<Event>(text) }.getOrNull() ?: return
+                if (event.type == "mail") _events.tryEmit(event.threadId)
+            }
+
+            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = lost(webSocket)
+            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = lost(webSocket)
+        })
+    }
+
+    private fun lost(webSocket: WebSocket) {
+        scope.launch {
+            if (socket !== webSocket) return@launch
+            pinger?.cancel()
+            socket = null
+            dropped = true
+            if (!running) return@launch
+            retry = scope.launch {
+                delay(backoffMs)
+                backoffMs = (backoffMs * 2).coerceAtMost(60_000L)
+                connect()
+            }
+        }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/data/Models.kt b/email/app/src/main/java/gay/doughmination/mail/data/Models.kt
new file mode 100644
index 0000000..6c671ed
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/data/Models.kt
@@ -0,0 +1,102 @@
+package gay.doughmination.mail.data
+
+import kotlinx.serialization.Serializable
+
+// Mirrors email/src/shared/types.ts. Keep the two in step.
+
+@Serializable
+data class Me(
+    val username: String,
+    /** Display name put on outgoing mail; null sends from the bare address. */
+    val name: String? = null,
+    val isAdmin: Boolean,
+    /** Every address this user can send from. */
+    val addresses: List<String>,
+    val domains: List<String>,
+)
+
+@Serializable
+data class Page<T>(val items: List<T>, val nextCursor: String? = null)
+
+@Serializable
+data class ThreadSummary(
+    val id: String,
+    val latestId: String,
+    val mailbox: String,
+    val subject: String,
+    val from: String,
+    val to: List<String>,
+    val snippet: String,
+    val lastAt: Long,
+    val count: Int,
+    val unread: Int,
+    val hasAttachments: Boolean,
+    val starred: Boolean,
+)
+
+@Serializable
+data class AttachmentInfo(
+    val id: String,
+    val filename: String,
+    val contentType: String,
+    val size: Long,
+    val contentId: String? = null,
+)
+
+@Serializable
+data class Message(
+    val id: String,
+    val threadId: String,
+    /** "inbox", "sent" or "drafts". */
+    val folder: String,
+    val mailbox: String,
+    val from: String,
+    val to: List<String>,
+    val cc: List<String>,
+    val bcc: List<String>,
+    val subject: String,
+    val snippet: String,
+    /** Email HTML. Only ever render it in EmailView. */
+    val html: String? = null,
+    val text: String? = null,
+    val sentAt: Long,
+    val read: Boolean,
+    val attachments: List<AttachmentInfo>,
+)
+
+@Serializable
+data class MailThread(
+    val id: String,
+    val subject: String,
+    val starred: Boolean,
+    val messages: List<Message>,
+)
+
+@Serializable
+data class SendRequest(
+    val from: String,
+    val to: List<String>,
+    val cc: List<String>,
+    val bcc: List<String>,
+    val subject: String,
+    /** Plain text; the server renders the HTML part from it. */
+    val text: String,
+    val attachmentIds: List<String>,
+    /** Message being replied to; threads the new one onto it. */
+    val replyTo: String? = null,
+    /** Only for /send: the draft to update and send. */
+    val draftId: String? = null,
+)
+
+/** What the thread list can show: a folder, Starred, or the Bin. */
+enum class ListFolder(val path: String, val label: String) {
+    Inbox("inbox", "Inbox"),
+    Starred("starred", "Starred"),
+    Sent("sent", "Sent"),
+    Drafts("drafts", "Drafts"),
+    Bin("bin", "Bin");
+
+    companion object {
+        fun fromPath(path: String?): ListFolder? = entries.find { it.path == path }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/data/TokenStore.kt b/email/app/src/main/java/gay/doughmination/mail/data/TokenStore.kt
new file mode 100644
index 0000000..8f31fc2
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/data/TokenStore.kt
@@ -0,0 +1,74 @@
+package gay.doughmination.mail.data
+
+import android.content.Context
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyProperties
+import android.util.Base64
+import java.security.KeyStore
+import javax.crypto.Cipher
+import javax.crypto.KeyGenerator
+import javax.crypto.SecretKey
+import javax.crypto.spec.GCMParameterSpec
+
+/**
+ * Holds the session token, encrypted with a key that never leaves the
+ * Android Keystore, so a copy of the app's files alone doesn't sign anyone in.
+ * Also keeps the PKCE verifier of a sign-in in progress, which has to survive
+ * the app being killed while the browser tab is open.
+ */
+class TokenStore(context: Context) {
+    private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE)
+
+    @Volatile
+    private var cached: String? = null
+
+    var token: String?
+        get() = cached ?: prefs.getString(KEY_TOKEN, null)?.let(::decrypt)?.also { cached = it }
+        set(value) {
+            cached = value
+            prefs.edit().apply {
+                if (value == null) remove(KEY_TOKEN) else putString(KEY_TOKEN, encrypt(value))
+            }.apply()
+        }
+
+    var pendingVerifier: String?
+        get() = prefs.getString(KEY_VERIFIER, null)
+        set(value) = prefs.edit().apply {
+            if (value == null) remove(KEY_VERIFIER) else putString(KEY_VERIFIER, value)
+        }.apply()
+
+    private fun key(): SecretKey {
+        val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+        (store.getKey(ALIAS, null) as SecretKey?)?.let { return it }
+        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
+        generator.init(
+            KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
+                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
+                .build(),
+        )
+        return generator.generateKey()
+    }
+
+    private fun encrypt(plain: String): String {
+        val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, key()) }
+        val sealed = cipher.iv + cipher.doFinal(plain.toByteArray())
+        return Base64.encodeToString(sealed, Base64.NO_WRAP)
+    }
+
+    /** Null when it can't be read (the key was wiped, say); that just means signed out. */
+    private fun decrypt(stored: String): String? = runCatching {
+        val sealed = Base64.decode(stored, Base64.NO_WRAP)
+        val cipher = Cipher.getInstance(TRANSFORM)
+        cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, sealed, 0, IV_BYTES))
+        String(cipher.doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES))
+    }.getOrNull()
+
+    private companion object {
+        const val ALIAS = "inbox-session"
+        const val TRANSFORM = "AES/GCM/NoPadding"
+        const val IV_BYTES = 12
+        const val KEY_TOKEN = "token"
+        const val KEY_VERIFIER = "verifier"
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt b/email/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
new file mode 100644
index 0000000..bada636
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
@@ -0,0 +1,109 @@
+package gay.doughmination.mail.ui
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.AnimatedContent
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.togetherWith
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.outlined.Email
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.SnackbarDuration
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.material3.SnackbarResult
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.staticCompositionLocalOf
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+
+/** One snackbar host for every screen, so messages survive moving between them. */
+val LocalSnackbar = staticCompositionLocalOf { SnackbarHostState() }
+
+@Composable
+fun AppRoot(vm: MailViewModel) {
+    val snackbar = remember { SnackbarHostState() }
+    LaunchedEffect(Unit) {
+        vm.snackbar.collect { s ->
+            val result = snackbar.showSnackbar(
+                s.text,
+                actionLabel = s.action,
+                withDismissAction = s.action == null,
+                duration = SnackbarDuration.Short,
+            )
+            if (result == SnackbarResult.ActionPerformed) s.run?.invoke()
+        }
+    }
+
+    CompositionLocalProvider(LocalSnackbar provides snackbar) {
+        Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
+            if (!vm.signedIn) {
+                LoginScreen(vm)
+                return@Surface
+            }
+            BackHandler(enabled = vm.stack.size > 1) { vm.back() }
+            AnimatedContent(
+                targetState = vm.screen,
+                transitionSpec = { fadeIn() togetherWith fadeOut() },
+                label = "screen",
+            ) { screen ->
+                when (screen) {
+                    Screen.List -> ThreadListScreen(vm)
+                    is Screen.Thread -> ThreadScreen(vm, screen)
+                    Screen.Compose -> ComposeScreen(vm)
+                    Screen.Settings -> SettingsScreen(vm)
+                }
+            }
+        }
+    }
+}
+
+@Composable
+private fun LoginScreen(vm: MailViewModel) {
+    val context = LocalContext.current
+    Column(
+        Modifier.fillMaxSize().padding(32.dp),
+        verticalArrangement = Arrangement.Center,
+        horizontalAlignment = Alignment.CenterHorizontally,
+    ) {
+        Icon(Icons.Outlined.Email, null, Modifier.size(72.dp), tint = Accent)
+        Spacer(Modifier.height(16.dp))
+        Text("Inbox", style = MaterialTheme.typography.headlineMedium)
+        Spacer(Modifier.height(8.dp))
+        Text(
+            "Sign in with your Doughmination account.",
+            style = MaterialTheme.typography.bodyMedium,
+            color = MaterialTheme.colorScheme.onSurfaceVariant,
+            textAlign = TextAlign.Center,
+        )
+        Spacer(Modifier.height(32.dp))
+        if (vm.signingIn) {
+            CircularProgressIndicator()
+        } else {
+            Button(onClick = { vm.startLogin(context) }) { Text("Sign in") }
+        }
+        vm.loginError?.let {
+            Spacer(Modifier.height(16.dp))
+            Text(it, color = MaterialTheme.colorScheme.error, textAlign = TextAlign.Center)
+        }
+    }
+    SnackbarHost(LocalSnackbar.current)
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/ComposeScreen.kt b/email/app/src/main/java/gay/doughmination/mail/ui/ComposeScreen.kt
new file mode 100644
index 0000000..c43db75
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/ComposeScreen.kt
@@ -0,0 +1,182 @@
+package gay.doughmination.mail.ui
+
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.imePadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.outlined.Send
+import androidx.compose.material.icons.outlined.AttachFile
+import androidx.compose.material.icons.outlined.Close
+import androidx.compose.material.icons.outlined.MoreVert
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExposedDropdownMenuBox
+import androidx.compose.material3.ExposedDropdownMenuDefaults
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.InputChip
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.MenuAnchorType
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TextField
+import androidx.compose.material3.TextFieldDefaults
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.unit.dp
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun ComposeScreen(vm: MailViewModel) {
+    val d = vm.draft ?: return
+    val context = LocalContext.current
+    val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris ->
+        if (uris.isNotEmpty()) vm.attach(context, uris)
+    }
+    var showCopies by remember { mutableStateOf(d.cc.isNotBlank() || d.bcc.isNotBlank()) }
+    var menu by remember { mutableStateOf(false) }
+    val busy = vm.sending || vm.uploading > 0
+
+    Scaffold(
+        topBar = {
+            TopAppBar(
+                title = { Text(d.title) },
+                navigationIcon = {
+                    IconButton(onClick = vm::closeAndSave) { Icon(Icons.Outlined.Close, "Close and save") }
+                },
+                actions = {
+                    IconButton(onClick = { pick.launch("*/*") }) { Icon(Icons.Outlined.AttachFile, "Attach") }
+                    if (busy) {
+                        CircularProgressIndicator(Modifier.padding(12.dp).size(24.dp))
+                    } else {
+                        IconButton(onClick = vm::send) { Icon(Icons.AutoMirrored.Outlined.Send, "Send", tint = Accent) }
+                    }
+                    IconButton(onClick = { menu = true }) { Icon(Icons.Outlined.MoreVert, "More") }
+                    DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
+                        DropdownMenuItem(text = { Text("Save draft") }, onClick = { menu = false; vm.closeAndSave() })
+                        DropdownMenuItem(
+                            text = { Text(if (d.draftId != null) "Delete draft" else "Discard", color = Danger) },
+                            onClick = { menu = false; vm.discard() },
+                        )
+                    }
+                },
+            )
+        },
+        snackbarHost = { SnackbarHost(LocalSnackbar.current) },
+    ) { padding ->
+        Column(
+            Modifier.padding(padding).imePadding().fillMaxSize().verticalScroll(rememberScrollState()),
+        ) {
+            FromPicker(vm.me?.addresses.orEmpty(), d.from) { vm.draft = d.copy(from = it) }
+            HorizontalDivider()
+            Row(verticalAlignment = Alignment.CenterVertically) {
+                Field("To", d.to, Modifier.weight(1f), KeyboardType.Email) { vm.draft = d.copy(to = it) }
+                if (!showCopies) TextButton(onClick = { showCopies = true }) { Text("Cc/Bcc") }
+            }
+            HorizontalDivider()
+            if (showCopies) {
+                Field("Cc", d.cc, Modifier.fillMaxWidth(), KeyboardType.Email) { vm.draft = d.copy(cc = it) }
+                HorizontalDivider()
+                Field("Bcc", d.bcc, Modifier.fillMaxWidth(), KeyboardType.Email) { vm.draft = d.copy(bcc = it) }
+                HorizontalDivider()
+            }
+            Field("Subject", d.subject, Modifier.fillMaxWidth(), KeyboardType.Text) { vm.draft = d.copy(subject = it) }
+            HorizontalDivider()
+
+            if (d.attachments.isNotEmpty() || vm.uploading > 0) {
+                Column(Modifier.padding(horizontal = 12.dp, vertical = 6.dp)) {
+                    for (a in d.attachments) {
+                        InputChip(
+                            selected = false,
+                            onClick = { vm.removeAttachment(a) },
+                            label = { Text("${a.filename} · ${fmtSize(a.size)}", maxLines = 1) },
+                            trailingIcon = { Icon(Icons.Outlined.Close, "Remove", Modifier.size(18.dp)) },
+                        )
+                    }
+                    if (vm.uploading > 0) {
+                        Text("Uploading ${vm.uploading}…", style = MaterialTheme.typography.labelMedium, color = Muted)
+                    }
+                }
+                HorizontalDivider()
+            }
+
+            TextField(
+                value = d.text,
+                onValueChange = { vm.draft = d.copy(text = it) },
+                placeholder = { Text("Write your message") },
+                modifier = Modifier.fillMaxWidth().heightIn(min = 280.dp),
+                colors = plainField(),
+                keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
+            )
+        }
+    }
+}
+
+@Composable
+private fun plainField() = TextFieldDefaults.colors(
+    focusedContainerColor = Color.Transparent,
+    unfocusedContainerColor = Color.Transparent,
+    focusedIndicatorColor = Color.Transparent,
+    unfocusedIndicatorColor = Color.Transparent,
+)
+
+@Composable
+private fun Field(label: String, value: String, modifier: Modifier, type: KeyboardType, onChange: (String) -> Unit) {
+    TextField(
+        value = value,
+        onValueChange = onChange,
+        modifier = modifier,
+        prefix = { Text("$label  ", color = Muted) },
+        singleLine = type == KeyboardType.Text,
+        colors = plainField(),
+        keyboardOptions = KeyboardOptions(keyboardType = type, imeAction = ImeAction.Next),
+    )
+}
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+private fun FromPicker(addresses: List<String>, selected: String, onPick: (String) -> Unit) {
+    var open by remember { mutableStateOf(false) }
+    ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it && addresses.size > 1 }) {
+        TextField(
+            value = selected.ifEmpty { "No address to send from" },
+            onValueChange = {},
+            readOnly = true,
+            prefix = { Text("From  ", color = Muted) },
+            trailingIcon = { if (addresses.size > 1) ExposedDropdownMenuDefaults.TrailingIcon(open) },
+            colors = plainField(),
+            modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
+        )
+        ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
+            for (addr in addresses) {
+                DropdownMenuItem(text = { Text(addr) }, onClick = { open = false; onPick(addr) })
+            }
+        }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/EmailView.kt b/email/app/src/main/java/gay/doughmination/mail/ui/EmailView.kt
new file mode 100644
index 0000000..4467e2d
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/EmailView.kt
@@ -0,0 +1,119 @@
+package gay.doughmination.mail.ui
+
+import android.annotation.SuppressLint
+import android.content.Intent
+import android.graphics.Color
+import android.view.ViewGroup
+import android.webkit.WebResourceRequest
+import android.webkit.WebResourceResponse
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.viewinterop.AndroidView
+import gay.doughmination.mail.data.Api
+import gay.doughmination.mail.data.AttachmentInfo
+import okhttp3.Request
+import java.io.ByteArrayInputStream
+
+private const val BASE_STYLE =
+    ":root{color-scheme:light}body{margin:0;padding:12px;background:#fff;color:#111;" +
+        "font:15px/1.5 sans-serif;overflow-wrap:anywhere}" +
+        "img{max-width:100%;height:auto}pre{white-space:pre-wrap}table{max-width:100%}"
+
+private val REMOTE = Regex("""(?:src|background|href)\s*=\s*["']?\s*https?:|url\(\s*["']?\s*https?:|@import""", RegexOption.IGNORE_CASE)
+
+/** Whether an email pulls anything from the internet (mostly tracking pixels). */
+fun hasRemoteContent(html: String): Boolean = REMOTE.containsMatchIn(html)
+
+/**
+ * The only place email HTML is ever rendered, like EmailFrame on the web:
+ *
+ * - no JavaScript, no file or content access;
+ * - links never load in here, they open in the browser;
+ * - remote images, fonts and stylesheets stay blocked until `showRemote`,
+ *   by both a CSP and refusing the requests outright;
+ * - cid: images load from /api/attachments with the session token.
+ */
+@SuppressLint("SetJavaScriptEnabled")
+@Composable
+fun EmailView(api: Api, html: String, attachments: List<AttachmentInfo>, showRemote: Boolean, modifier: Modifier = Modifier) {
+    val body = remember(html, attachments) {
+        val byCid = attachments.filter { it.contentId != null }.associate { it.contentId!!.lowercase() to it.id }
+        Regex("""cid:([^"'\s>)]+)""", RegexOption.IGNORE_CASE).replace(html) { m ->
+            val id = byCid[m.groupValues[1].removePrefix("<").removeSuffix(">").lowercase()]
+            if (id != null) api.attachmentUrl(id, inline = true) else m.value
+        }
+    }
+    val document = remember(body, showRemote) {
+        val remote = if (showRemote) " https:" else ""
+        val csp = "default-src 'none'; img-src ${api.baseUrl} data:$remote; style-src 'unsafe-inline'$remote; " +
+            "font-src data:$remote; media-src 'none'; form-action 'none'; base-uri 'none'"
+        "<!doctype html><html><head><meta charset=\"utf-8\">" +
+            "<meta http-equiv=\"Content-Security-Policy\" content=\"$csp\">" +
+            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" +
+            "<meta name=\"referrer\" content=\"no-referrer\"><style>$BASE_STYLE</style></head>" +
+            "<body>$body</body></html>"
+    }
+
+    AndroidView(
+        modifier = modifier,
+        factory = { context ->
+            WebView(context).apply {
+                layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+                setBackgroundColor(Color.WHITE)
+                isVerticalScrollBarEnabled = false
+                settings.apply {
+                    javaScriptEnabled = false
+                    allowFileAccess = false
+                    allowContentAccess = false
+                    domStorageEnabled = false
+                    setGeolocationEnabled(false)
+                    builtInZoomControls = true
+                    displayZoomControls = false
+                }
+            }
+        },
+        update = { view ->
+            view.webViewClient = MailClient(api, showRemote)
+            if (view.tag != document) {
+                view.tag = document
+                view.loadDataWithBaseURL(api.baseUrl + "/", document, "text/html", "utf-8", null)
+            }
+        },
+        onRelease = { it.destroy() },
+    )
+}
+
+private class MailClient(private val api: Api, private val showRemote: Boolean) : WebViewClient() {
+    private val attachmentPrefix = api.baseUrl + "/api/attachments/"
+
+    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+        val scheme = request.url.scheme?.lowercase()
+        if (scheme == "http" || scheme == "https" || scheme == "mailto") {
+            runCatching {
+                view.context.startActivity(Intent(Intent.ACTION_VIEW, request.url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+            }
+        }
+        // Nothing ever navigates inside the email itself.
+        return true
+    }
+
+    override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
+        val url = request.url.toString()
+        if (url.startsWith(attachmentPrefix)) {
+            return runCatching {
+                val res = api.http.newCall(api.authorize(Request.Builder().url(url)).build()).execute()
+                val type = res.header("Content-Type")?.substringBefore(";") ?: "application/octet-stream"
+                WebResourceResponse(type, null, res.body?.byteStream())
+            }.getOrElse { blocked() }
+        }
+        val scheme = request.url.scheme?.lowercase()
+        if (scheme == "data") return null
+        if (!showRemote || scheme != "https") return blocked()
+        return null
+    }
+
+    private fun blocked() = WebResourceResponse("text/plain", "utf-8", 403, "Blocked", emptyMap(), ByteArrayInputStream(ByteArray(0)))
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/Format.kt b/email/app/src/main/java/gay/doughmination/mail/ui/Format.kt
new file mode 100644
index 0000000..01a43e2
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/Format.kt
@@ -0,0 +1,46 @@
+package gay.doughmination.mail.ui
+
+import java.text.DateFormat
+import java.util.Calendar
+import java.util.Date
+import java.util.Locale
+
+// Ported from email/src/web/lib/format.ts.
+
+fun fmtTime(ms: Long): String {
+    val then = Calendar.getInstance().apply { timeInMillis = ms }
+    val now = Calendar.getInstance()
+    val sameYear = then.get(Calendar.YEAR) == now.get(Calendar.YEAR)
+    return when {
+        sameYear && then.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR) ->
+            DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(ms))
+        sameYear -> android.text.format.DateFormat.format(
+            android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "d MMM"),
+            ms,
+        ).toString()
+        else -> DateFormat.getDateInstance(DateFormat.SHORT).format(Date(ms))
+    }
+}
+
+fun fmtDateTime(ms: Long): String = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(ms))
+
+fun fmtSize(bytes: Long): String = when {
+    bytes < 1024 -> "$bytes B"
+    bytes < 1024 * 1024 -> "${bytes / 1024} KB"
+    else -> String.format(Locale.getDefault(), "%.1f MB", bytes / 1024.0 / 1024.0)
+}
+
+/** "Ari <[email protected]>" -> "Ari"; a bare address stays as it is. */
+fun displayName(addr: String): String {
+    val name = addr.replace(Regex("<[^>]*>"), "").replace("\"", "").trim()
+    return name.ifEmpty { addr.replace(Regex("[<>]"), "") }
+}
+
+/** "Ari <[email protected]>" -> "[email protected]". */
+fun bareAddress(addr: String): String = (Regex("<([^<>]+)>").find(addr)?.groupValues?.get(1) ?: addr).trim()
+
+fun isAddress(addr: String): Boolean = Regex("^[^\\s@<>]+@[^\\s@<>]+\\.[^\\s@<>]+$").matches(bareAddress(addr))
+
+/** Splits on , ; and newlines, except inside quotes: "Doe, Jane" <[email protected]> stays whole. */
+fun splitList(raw: String): List<String> =
+    Regex("(?:\"[^\"]*\"?|[^,;\\n\"])+").findAll(raw).map { it.value.trim() }.filter { it.isNotEmpty() }.toList()
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt b/email/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
new file mode 100644
index 0000000..f0902bc
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
@@ -0,0 +1,614 @@
+package gay.doughmination.mail.ui
+
+import android.app.Application
+import android.content.Context
+import android.net.Uri
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateListOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import gay.doughmination.mail.InboxApp
+import gay.doughmination.mail.data.ApiException
+import gay.doughmination.mail.data.AttachmentInfo
+import gay.doughmination.mail.data.ListFolder
+import gay.doughmination.mail.data.MailThread
+import gay.doughmination.mail.data.Me
+import gay.doughmination.mail.data.Message
+import gay.doughmination.mail.data.SendRequest
+import gay.doughmination.mail.data.SignedOutException
+import gay.doughmination.mail.data.ThreadSummary
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.flow.receiveAsFlow
+import kotlinx.coroutines.launch
+import java.io.IOException
+
+sealed interface Screen {
+    data object List : Screen
+    data class Thread(val id: String, val bin: Boolean) : Screen
+    data object Compose : Screen
+    data object Settings : Screen
+}
+
+/** The composer's contents. Recipients stay as typed until they're sent or saved. */
+data class Draft(
+    val title: String,
+    val draftId: String? = null,
+    val replyTo: String? = null,
+    val from: String,
+    val to: String = "",
+    val cc: String = "",
+    val bcc: String = "",
+    val subject: String = "",
+    val text: String = "",
+    val attachments: List<AttachmentInfo> = emptyList(),
+) {
+    val isBlank get() = draftId == null && to.isBlank() && cc.isBlank() && bcc.isBlank() &&
+        subject.isBlank() && text.isBlank() && attachments.isEmpty()
+}
+
+data class Snack(val text: String, val action: String? = null, val run: (() -> Unit)? = null)
+
+class MailViewModel(application: Application) : AndroidViewModel(application) {
+    private val inbox = application as InboxApp
+    private val api = inbox.api
+
+    var signedIn by mutableStateOf(inbox.signedIn.value)
+        private set
+    var signingIn by mutableStateOf(false)
+        private set
+    var loginError by mutableStateOf<String?>(null)
+        private set
+
+    var me by mutableStateOf<Me?>(null)
+        private set
+    /** Unread inbox mail per receiving address. */
+    var unread by mutableStateOf<Map<String, Int>>(emptyMap())
+        private set
+
+    var folder by mutableStateOf(ListFolder.Inbox)
+        private set
+    /** One address, "@domain" for a whole domain, or null for everything. */
+    var mailbox by mutableStateOf<String?>(null)
+        private set
+    val threads = mutableStateListOf<ThreadSummary>()
+    var nextCursor by mutableStateOf<String?>(null)
+        private set
+    var loading by mutableStateOf(false)
+        private set
+    var refreshing by mutableStateOf(false)
+        private set
+    var listError by mutableStateOf<String?>(null)
+        private set
+
+    val stack = mutableStateListOf<Screen>(Screen.List)
+    val screen: Screen get() = stack.last()
+
+    var thread by mutableStateOf<MailThread?>(null)
+        private set
+    var threadError by mutableStateOf<String?>(null)
+        private set
+    /** Bumped when the open thread should reload. */
+    var threadVersion by mutableIntStateOf(0)
+        private set
+
+    var draft by mutableStateOf<Draft?>(null)
+    var uploading by mutableIntStateOf(0)
+        private set
+    var sending by mutableStateOf(false)
+        private set
+
+    private val snacks = Channel<Snack>(Channel.BUFFERED)
+    val snackbar = snacks.receiveAsFlow()
+
+    private var listJob: Job? = null
+
+    init {
+        viewModelScope.launch {
+            inbox.signedIn.collect { value ->
+                signedIn = value
+                if (value) loadSession() else signedOutReset()
+            }
+        }
+        viewModelScope.launch {
+            inbox.live.events.collect { threadId ->
+                refreshUnread()
+                reload(quiet = true)
+                val open = screen
+                if (open is Screen.Thread && (threadId == null || threadId == open.id)) threadVersion++
+            }
+        }
+    }
+
+    // ---- errors
+
+    private fun fail(e: Throwable) {
+        val text = when (e) {
+            is SignedOutException -> return
+            is kotlinx.coroutines.CancellationException -> throw e
+            is ApiException -> e.message ?: "Something went wrong."
+            is IOException -> "Couldn't reach the server."
+            else -> e.message ?: "Something went wrong."
+        }
+        snacks.trySend(Snack(text))
+    }
+
+    private fun say(text: String, action: String? = null, run: (() -> Unit)? = null) {
+        snacks.trySend(Snack(text, action, run))
+    }
+
+    // ---- signing in and out
+
+    fun startLogin(context: Context) {
+        loginError = null
+        runCatching { inbox.auth.start(context) }.onFailure { loginError = "No browser to sign in with." }
+    }
+
+    fun finishLogin(code: String) = viewModelScope.launch {
+        signingIn = true
+        loginError = null
+        try {
+            inbox.auth.finish(code)
+            inbox.setSignedIn(true)
+        } catch (e: Exception) {
+            loginError = (e as? ApiException)?.message ?: "Couldn't reach the server."
+        } finally {
+            signingIn = false
+        }
+    }
+
+    fun signOut() = viewModelScope.launch {
+        api.logout()
+        inbox.setSignedIn(false)
+    }
+
+    private fun signedOutReset() {
+        inbox.live.stop()
+        me = null
+        unread = emptyMap()
+        threads.clear()
+        nextCursor = null
+        thread = null
+        draft = null
+        stack.clear()
+        stack.add(Screen.List)
+    }
+
+    private fun loadSession() = viewModelScope.launch {
+        try {
+            me = api.me()
+            refreshUnread()
+        } catch (e: Exception) {
+            fail(e)
+        }
+        reload()
+    }
+
+    private suspend fun refreshUnread() {
+        runCatching { api.unread() }.onSuccess { unread = it }
+    }
+
+    // ---- the list
+
+    fun show(folder: ListFolder, mailbox: String? = this.mailbox) {
+        this.folder = folder
+        this.mailbox = mailbox
+        stack.clear()
+        stack.add(Screen.List)
+        threads.clear()
+        nextCursor = null
+        reload()
+    }
+
+    /** Fetches the first page again. `quiet` keeps the spinner off (live updates). */
+    fun reload(quiet: Boolean = false, pulled: Boolean = false) {
+        listJob?.cancel()
+        listJob = viewModelScope.launch {
+            if (pulled) refreshing = true else if (!quiet) loading = true
+            try {
+                val page = api.threads(folder, mailbox, null)
+                threads.clear()
+                threads.addAll(page.items)
+                nextCursor = page.nextCursor
+                listError = null
+                if (pulled) refreshUnread()
+            } catch (e: Exception) {
+                if (e is kotlinx.coroutines.CancellationException) throw e
+                if (threads.isEmpty()) listError = "Couldn't load your mail." else fail(e)
+            } finally {
+                loading = false
+                refreshing = false
+            }
+        }
+    }
+
+    fun loadMore() {
+        val cursor = nextCursor ?: return
+        if (loading || listJob?.isActive == true) return
+        listJob = viewModelScope.launch {
+            loading = true
+            try {
+                val page = api.threads(folder, mailbox, cursor)
+                val seen = threads.map { it.id }.toSet()
+                threads.addAll(page.items.filter { it.id !in seen })
+                nextCursor = page.nextCursor
+            } catch (e: Exception) {
+                fail(e)
+            } finally {
+                loading = false
+            }
+        }
+    }
+
+    private fun replace(id: String, change: (ThreadSummary) -> ThreadSummary) {
+        val i = threads.indexOfFirst { it.id == id }
+        if (i >= 0) threads[i] = change(threads[i])
+    }
+
+    private fun takeOut(id: String) {
+        threads.removeAll { it.id == id }
+    }
+
+    fun toggleRead(t: ThreadSummary) {
+        val read = t.unread > 0
+        replace(t.id) { it.copy(unread = if (read) 0 else 1) }
+        viewModelScope.launch {
+            try {
+                unread = api.markThread(t.id, read)
+            } catch (e: Exception) {
+                fail(e)
+                reload(quiet = true)
+            }
+        }
+    }
+
+    fun toggleStar(threadId: String, starred: Boolean) {
+        if (folder == ListFolder.Starred && !starred) takeOut(threadId) else replace(threadId) { it.copy(starred = starred) }
+        thread?.takeIf { it.id == threadId }?.let { thread = it.copy(starred = starred) }
+        viewModelScope.launch {
+            try {
+                api.starThread(threadId, starred)
+            } catch (e: Exception) {
+                fail(e)
+                reload(quiet = true)
+            }
+        }
+    }
+
+    fun moveToBin(threadId: String) {
+        takeOut(threadId)
+        if ((screen as? Screen.Thread)?.id == threadId) stack.removeAt(stack.lastIndex)
+        viewModelScope.launch {
+            try {
+                api.deleteThread(threadId)
+                refreshUnread()
+                say("Moved to Bin", "Undo") { restore(threadId, undo = true) }
+            } catch (e: Exception) {
+                fail(e)
+                reload(quiet = true)
+            }
+        }
+    }
+
+    fun restore(threadId: String, undo: Boolean = false) {
+        if (!undo) takeOut(threadId)
+        if ((screen as? Screen.Thread)?.id == threadId) stack.removeAt(stack.lastIndex)
+        viewModelScope.launch {
+            try {
+                api.restoreThread(threadId)
+                refreshUnread()
+                if (undo) reload(quiet = true) else say("Restored")
+            } catch (e: Exception) {
+                fail(e)
+                reload(quiet = true)
+            }
+        }
+    }
+
+    fun deleteForever(threadId: String) {
+        takeOut(threadId)
+        if ((screen as? Screen.Thread)?.id == threadId) stack.removeAt(stack.lastIndex)
+        viewModelScope.launch {
+            try {
+                api.deleteThread(threadId, forever = true)
+            } catch (e: Exception) {
+                fail(e)
+                reload(quiet = true)
+            }
+        }
+    }
+
+    fun emptyBin() = viewModelScope.launch {
+        try {
+            val n = api.emptyBin()
+            threads.clear()
+            nextCursor = null
+            say(if (n == 1) "Deleted 1 message" else "Deleted $n messages")
+        } catch (e: Exception) {
+            fail(e)
+        }
+    }
+
+    /** Drafts open straight in the composer; everything else in the thread view. */
+    fun open(t: ThreadSummary) {
+        if (folder == ListFolder.Drafts) {
+            editDraft(t.latestId)
+            return
+        }
+        replace(t.id) { it.copy(unread = 0) }
+        openThread(t.id, folder == ListFolder.Bin)
+    }
+
+    fun openThread(id: String, bin: Boolean) {
+        thread = null
+        threadError = null
+        stack.add(Screen.Thread(id, bin))
+    }
+
+    /** For links to the site: /inbox/<thread id> and the like. */
+    fun openPath(path: String) {
+        val parts = path.split("/").filter { it.isNotEmpty() }
+        val target = ListFolder.fromPath(parts.firstOrNull()) ?: ListFolder.Inbox
+        if (target != folder || mailbox != null) show(target, null)
+        parts.getOrNull(1)?.let { openThread(it, target == ListFolder.Bin) }
+    }
+
+    // ---- the thread view
+
+    fun loadThread(id: String, bin: Boolean) = viewModelScope.launch {
+        try {
+            val loaded = api.thread(id, bin)
+            thread = loaded
+            threadError = null
+            if (!bin && loaded.messages.any { it.folder == "inbox" && !it.read }) {
+                unread = api.markThread(id, true)
+                replace(id) { it.copy(unread = 0) }
+            }
+        } catch (e: Exception) {
+            if (e is ApiException && e.status == 404) {
+                threadError = "This conversation is gone."
+            } else if (thread == null) {
+                threadError = "Couldn't load this conversation."
+            } else {
+                fail(e)
+            }
+        }
+    }
+
+    fun markUnread(threadId: String) {
+        stack.removeAt(stack.lastIndex)
+        replace(threadId) { it.copy(unread = 1) }
+        viewModelScope.launch {
+            try {
+                unread = api.markThread(threadId, false)
+            } catch (e: Exception) {
+                fail(e)
+            }
+        }
+    }
+
+    /** In the Bin a message is deleted for good; elsewhere it moves to the Bin. */
+    fun deleteMessage(m: Message, bin: Boolean) = viewModelScope.launch {
+        try {
+            api.deleteMessage(m.id, forever = bin || m.folder == "drafts")
+            afterMessageChange(m.threadId)
+            if (!bin && m.folder != "drafts") say("Moved to Bin", "Undo") { restoreMessage(m, undo = true) }
+        } catch (e: Exception) {
+            fail(e)
+        }
+    }
+
+    fun restoreMessage(m: Message, undo: Boolean = false) = viewModelScope.launch {
+        try {
+            api.restoreMessage(m.id)
+            afterMessageChange(m.threadId)
+            if (!undo) say("Restored")
+        } catch (e: Exception) {
+            fail(e)
+        }
+    }
+
+    private suspend fun afterMessageChange(threadId: String) {
+        val open = screen as? Screen.Thread
+        if (open?.id == threadId) {
+            val left = runCatching { api.thread(threadId, open.bin) }.getOrNull()
+            if (left == null) stack.removeAt(stack.lastIndex) else thread = left
+        }
+        refreshUnread()
+        reload(quiet = true)
+    }
+
+    // ---- composing
+
+    private fun defaultFrom(): String = me?.addresses?.firstOrNull() ?: ""
+
+    /** The address of ours a message was sent to, so a reply goes out from it. */
+    private fun ourAddress(m: Message): String =
+        if (me?.addresses?.contains(m.mailbox) == true) m.mailbox else defaultFrom()
+
+    private fun prefixed(prefix: String, subject: String): String =
+        if (Regex("^\\s*$prefix\\s*:", RegexOption.IGNORE_CASE).containsMatchIn(subject)) subject else "$prefix: $subject"
+
+    private fun quote(m: Message): String {
+        val body = (m.text ?: "").lines().joinToString("\n") { "> $it" }
+        return "\n\nOn ${fmtDateTime(m.sentAt)}, ${m.from} wrote:\n$body"
+    }
+
+    private fun openComposer(d: Draft) {
+        draft = d
+        stack.add(Screen.Compose)
+    }
+
+    fun composeNew() = openComposer(Draft(title = "New message", from = defaultFrom()))
+
+    fun composeReply(m: Message) = openComposer(
+        Draft(
+            title = "Reply",
+            replyTo = m.id,
+            from = ourAddress(m),
+            to = (if (m.folder != "inbox") m.to else listOf(m.from)).joinToString(", "),
+            subject = prefixed("Re", m.subject),
+            text = quote(m),
+        ),
+    )
+
+    fun composeForward(m: Message) = openComposer(
+        Draft(
+            title = "Forward",
+            from = ourAddress(m),
+            subject = prefixed("Fwd", m.subject),
+            text = "\n\n---------- Forwarded message ----------\nFrom: ${m.from}\nTo: ${m.to.joinToString(", ")}\n" +
+                "Subject: ${m.subject}\n\n${m.text ?: ""}",
+            attachments = m.attachments.filter { it.contentId == null },
+        ),
+    )
+
+    fun composeDraft(m: Message) = openComposer(
+        Draft(
+            title = "Draft",
+            draftId = m.id,
+            from = m.from,
+            to = m.to.joinToString(", "),
+            cc = m.cc.joinToString(", "),
+            bcc = m.bcc.joinToString(", "),
+            subject = m.subject,
+            text = m.text ?: "",
+            attachments = m.attachments,
+        ),
+    )
+
+    fun editDraft(messageId: String) = viewModelScope.launch {
+        try {
+            composeDraft(api.message(messageId))
+        } catch (e: Exception) {
+            fail(e)
+        }
+    }
+
+    fun attach(context: Context, uris: List<Uri>) {
+        for (uri in uris) {
+            viewModelScope.launch {
+                uploading++
+                try {
+                    val info = api.upload(context.contentResolver, uri)
+                    draft = draft?.let { it.copy(attachments = it.attachments + info) }
+                } catch (e: Exception) {
+                    fail(e)
+                } finally {
+                    uploading--
+                }
+            }
+        }
+    }
+
+    fun removeAttachment(a: AttachmentInfo) {
+        draft = draft?.let { it.copy(attachments = it.attachments - a) }
+    }
+
+    private fun request(d: Draft, keep: (String) -> Boolean): SendRequest = SendRequest(
+        from = d.from,
+        to = splitList(d.to).filter(keep),
+        cc = splitList(d.cc).filter(keep),
+        bcc = splitList(d.bcc).filter(keep),
+        subject = d.subject,
+        text = d.text,
+        attachmentIds = d.attachments.map { it.id },
+        replyTo = d.replyTo,
+    )
+
+    fun send() {
+        val d = draft ?: return
+        if (uploading > 0 || sending) return
+        val bad = (splitList(d.to) + splitList(d.cc) + splitList(d.bcc)).firstOrNull { !isAddress(it) }
+        if (bad != null) return say("$bad isn't an email address.")
+        if (splitList(d.to).isEmpty()) return say("Add at least one recipient.")
+        viewModelScope.launch {
+            sending = true
+            try {
+                api.send(request(d) { true }.copy(draftId = d.draftId))
+                closeComposer()
+                say("Sent")
+                reload(quiet = true)
+                threadVersion++
+            } catch (e: Exception) {
+                // The server keeps it as a draft when Resend refuses it.
+                (e as? ApiException)?.draftId?.let { id -> draft = draft?.copy(draftId = id) }
+                fail(e)
+            } finally {
+                sending = false
+            }
+        }
+    }
+
+    /** Back out of the composer: anything written is kept in Drafts. */
+    fun closeAndSave() {
+        val d = draft ?: return
+        if (d.isBlank) return closeComposer()
+        if (uploading > 0) return say("Wait for attachments to finish uploading.")
+        viewModelScope.launch {
+            // Half-typed addresses would be refused, so the draft keeps only the whole ones.
+            val all = splitList(d.to) + splitList(d.cc) + splitList(d.bcc)
+            val req = request(d, ::isAddress)
+            try {
+                if (d.draftId != null) api.updateDraft(d.draftId, req) else api.createDraft(req)
+                closeComposer()
+                val dropped = all.count { !isAddress(it) }
+                say(if (dropped > 0) "Saved to Drafts, without $dropped unfinished address(es)" else "Saved to Drafts")
+                reload(quiet = true)
+                threadVersion++
+            } catch (e: Exception) {
+                fail(e)
+            }
+        }
+    }
+
+    fun discard() {
+        val id = draft?.draftId
+        closeComposer()
+        if (id == null) return
+        viewModelScope.launch {
+            try {
+                api.deleteMessage(id, forever = true)
+                say("Draft discarded")
+                reload(quiet = true)
+                threadVersion++
+            } catch (e: Exception) {
+                fail(e)
+            }
+        }
+    }
+
+    private fun closeComposer() {
+        if (screen == Screen.Compose) stack.removeAt(stack.lastIndex)
+        draft = null
+    }
+
+    // ---- settings and navigation
+
+    fun openSettings() {
+        stack.add(Screen.Settings)
+    }
+
+    fun saveName(name: String) = viewModelScope.launch {
+        try {
+            api.setName(name.trim())
+            me = me?.copy(name = name.trim().ifEmpty { null })
+            say("Saved")
+        } catch (e: Exception) {
+            fail(e)
+        }
+    }
+
+    /** Returns false when there's nowhere to go back to. */
+    fun back(): Boolean {
+        when {
+            screen == Screen.Compose -> closeAndSave()
+            stack.size > 1 -> stack.removeAt(stack.lastIndex)
+            else -> return false
+        }
+        return true
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt b/email/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
new file mode 100644
index 0000000..d976eb7
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
@@ -0,0 +1,113 @@
+package gay.doughmination.mail.ui
+
+import android.net.Uri
+import androidx.browser.customtabs.CustomTabsIntent
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.outlined.ArrowBack
+import androidx.compose.material.icons.automirrored.outlined.Logout
+import androidx.compose.material.icons.outlined.Description
+import androidx.compose.material.icons.outlined.PrivacyTip
+import androidx.compose.material3.Button
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.ListItem
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.Text
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.unit.dp
+import gay.doughmination.mail.BuildConfig
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun SettingsScreen(vm: MailViewModel) {
+    val me = vm.me
+    val context = LocalContext.current
+    var name by rememberSaveable(me?.name) { mutableStateOf(me?.name.orEmpty()) }
+    val openWeb = { path: String ->
+        CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(BuildConfig.INBOX_URL + path))
+    }
+
+    Scaffold(
+        topBar = {
+            TopAppBar(
+                title = { Text("Settings") },
+                navigationIcon = {
+                    IconButton(onClick = { vm.back() }) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Back") }
+                },
+            )
+        },
+        snackbarHost = { SnackbarHost(LocalSnackbar.current) },
+    ) { padding ->
+        Column(Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState())) {
+            Column(Modifier.padding(16.dp)) {
+                Text("Your name", style = MaterialTheme.typography.titleMedium)
+                Text(
+                    "Shown on mail you send. Leave it empty to send from the bare address.",
+                    style = MaterialTheme.typography.bodySmall,
+                    color = Muted,
+                )
+                Spacer(Modifier.height(8.dp))
+                OutlinedTextField(
+                    value = name,
+                    onValueChange = { if (it.length <= 100) name = it },
+                    singleLine = true,
+                    modifier = Modifier.fillMaxWidth(),
+                )
+                Spacer(Modifier.height(8.dp))
+                Button(onClick = { vm.saveName(name) }, enabled = name.trim() != me?.name.orEmpty()) { Text("Save") }
+            }
+            HorizontalDivider()
+            Column(Modifier.padding(16.dp)) {
+                Text("Your addresses", style = MaterialTheme.typography.titleMedium)
+                Spacer(Modifier.height(4.dp))
+                for (addr in me?.addresses.orEmpty()) Text(addr, color = Muted)
+                if (me?.addresses.isNullOrEmpty()) Text("None yet. Ask an admin to switch on a domain.", color = Muted)
+            }
+            HorizontalDivider()
+            ListItem(
+                headlineContent = { Text("Privacy policy") },
+                leadingContent = { Icon(Icons.Outlined.PrivacyTip, null) },
+                modifier = Modifier.clickable { openWeb("/privacy") },
+            )
+            ListItem(
+                headlineContent = { Text("Terms of service") },
+                leadingContent = { Icon(Icons.Outlined.Description, null) },
+                modifier = Modifier.clickable { openWeb("/terms") },
+            )
+            HorizontalDivider()
+            ListItem(
+                headlineContent = { Text("Sign out", color = Danger) },
+                supportingContent = { me?.let { Text("Signed in as ${it.username}") } },
+                leadingContent = { Icon(Icons.AutoMirrored.Outlined.Logout, null, tint = Danger) },
+                modifier = Modifier.clickable { vm.signOut() },
+            )
+            Text(
+                "Inbox ${BuildConfig.VERSION_NAME}",
+                Modifier.padding(16.dp),
+                style = MaterialTheme.typography.labelSmall,
+                color = Muted,
+            )
+        }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/Theme.kt b/email/app/src/main/java/gay/doughmination/mail/ui/Theme.kt
new file mode 100644
index 0000000..fac5751
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/Theme.kt
@@ -0,0 +1,37 @@
+package gay.doughmination.mail.ui
+
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.graphics.Color
+
+// The site's palette (email/src/web/app.css).
+val Accent = Color(0xFFEB459E)
+val Danger = Color(0xFFFF5C7A)
+val Muted = Color(0xFFA49EAB)
+
+private val colors = darkColorScheme(
+    primary = Accent,
+    onPrimary = Color.White,
+    primaryContainer = Color(0xFF3A1A2C),
+    onPrimaryContainer = Color(0xFFFFD8EA),
+    secondaryContainer = Color(0xFF2A1A24),
+    onSecondaryContainer = Color(0xFFFFD8EA),
+    background = Color(0xFF0B0A0D),
+    onBackground = Color(0xFFECE9EF),
+    surface = Color(0xFF0B0A0D),
+    onSurface = Color(0xFFECE9EF),
+    surfaceVariant = Color(0xFF1C1A20),
+    onSurfaceVariant = Muted,
+    surfaceContainerLowest = Color(0xFF0B0A0D),
+    surfaceContainerLow = Color(0xFF131116),
+    surfaceContainer = Color(0xFF17151B),
+    surfaceContainerHigh = Color(0xFF1E1B22),
+    surfaceContainerHighest = Color(0xFF26222B),
+    outline = Color(0xFF3A3640),
+    outlineVariant = Color(0xFF26222B),
+    error = Danger,
+)
+
+@Composable
+fun InboxTheme(content: @Composable () -> Unit) = MaterialTheme(colorScheme = colors, content = content)
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt b/email/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
new file mode 100644
index 0000000..0a65772
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
@@ -0,0 +1,516 @@
+package gay.doughmination.mail.ui
+
+import android.os.Build
+import android.view.HapticFeedbackConstants
+import androidx.compose.foundation.ExperimentalFoundationApi
+import androidx.compose.foundation.background
+import androidx.compose.foundation.combinedClickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.outlined.Send
+import androidx.compose.material.icons.outlined.AlternateEmail
+import androidx.compose.material.icons.outlined.AllInbox
+import androidx.compose.material.icons.outlined.AttachFile
+import androidx.compose.material.icons.outlined.Delete
+import androidx.compose.material.icons.outlined.DeleteForever
+import androidx.compose.material.icons.outlined.Drafts
+import androidx.compose.material.icons.outlined.Edit
+import androidx.compose.material.icons.outlined.Inbox
+import androidx.compose.material.icons.outlined.Language
+import androidx.compose.material.icons.outlined.Mail
+import androidx.compose.material.icons.outlined.MarkEmailRead
+import androidx.compose.material.icons.outlined.MarkEmailUnread
+import androidx.compose.material.icons.outlined.Menu
+import androidx.compose.material.icons.outlined.OpenInNew
+import androidx.compose.material.icons.outlined.RestoreFromTrash
+import androidx.compose.material.icons.outlined.Settings
+import androidx.compose.material.icons.outlined.Shield
+import androidx.compose.material.icons.outlined.Star
+import androidx.compose.material.icons.outlined.StarOutline
+import androidx.compose.material.icons.filled.Star
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Badge
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExtendedFloatingActionButton
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.ListItem
+import androidx.compose.material3.ListItemDefaults
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.ModalBottomSheet
+import androidx.compose.material3.ModalDrawerSheet
+import androidx.compose.material3.ModalNavigationDrawer
+import androidx.compose.material3.NavigationDrawerItem
+import androidx.compose.material3.NavigationDrawerItemDefaults
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SwipeToDismissBox
+import androidx.compose.material3.SwipeToDismissBoxValue
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
+import androidx.compose.material3.rememberDrawerState
+import androidx.compose.material3.rememberModalBottomSheetState
+import androidx.compose.material3.rememberSwipeToDismissBoxState
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.derivedStateOf
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalView
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.browser.customtabs.CustomTabsIntent
+import android.net.Uri
+import gay.doughmination.mail.data.ListFolder
+import gay.doughmination.mail.data.ThreadSummary
+import kotlinx.coroutines.launch
+
+// CONFIRM only exists from Android 11.
+private val swipeHaptic =
+    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.VIRTUAL_KEY
+
+private val folderIcons = mapOf(
+    ListFolder.Inbox to Icons.Outlined.Inbox,
+    ListFolder.Starred to Icons.Outlined.StarOutline,
+    ListFolder.Sent to Icons.AutoMirrored.Outlined.Send,
+    ListFolder.Drafts to Icons.Outlined.Drafts,
+    ListFolder.Bin to Icons.Outlined.Delete,
+)
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun ThreadListScreen(vm: MailViewModel) {
+    val drawer = rememberDrawerState(androidx.compose.material3.DrawerValue.Closed)
+    val scope = rememberCoroutineScope()
+    var menuFor by remember { mutableStateOf<ThreadSummary?>(null) }
+    var confirmEmpty by remember { mutableStateOf(false) }
+
+    ModalNavigationDrawer(
+        drawerState = drawer,
+        drawerContent = {
+            Drawer(vm) { scope.launch { drawer.close() } }
+        },
+    ) {
+        Scaffold(
+            topBar = {
+                TopAppBar(
+                    title = {
+                        Column {
+                            Text(vm.folder.label)
+                            vm.mailbox?.let {
+                                Text(it, style = MaterialTheme.typography.labelMedium, color = Muted)
+                            }
+                        }
+                    },
+                    navigationIcon = {
+                        IconButton(onClick = { scope.launch { drawer.open() } }) {
+                            Icon(Icons.Outlined.Menu, "Folders")
+                        }
+                    },
+                    actions = {
+                        if (vm.folder == ListFolder.Bin && vm.threads.isNotEmpty()) {
+                            TextButton(onClick = { confirmEmpty = true }) { Text("Empty Bin") }
+                        }
+                    },
+                )
+            },
+            floatingActionButton = {
+                if (vm.folder != ListFolder.Bin) {
+                    ExtendedFloatingActionButton(
+                        onClick = vm::composeNew,
+                        icon = { Icon(Icons.Outlined.Edit, null) },
+                        text = { Text("Compose") },
+                    )
+                }
+            },
+            snackbarHost = { SnackbarHost(LocalSnackbar.current) },
+        ) { padding ->
+            PullToRefreshBox(
+                isRefreshing = vm.refreshing,
+                onRefresh = { vm.reload(pulled = true) },
+                modifier = Modifier.padding(padding).fillMaxSize(),
+            ) {
+                ThreadList(vm, onHold = { menuFor = it })
+            }
+        }
+    }
+
+    menuFor?.let { t ->
+        ThreadMenu(vm, t) { menuFor = null }
+    }
+
+    if (confirmEmpty) {
+        AlertDialog(
+            onDismissRequest = { confirmEmpty = false },
+            title = { Text("Empty the Bin?") },
+            text = { Text("Everything in the Bin is deleted for good.") },
+            confirmButton = {
+                TextButton(onClick = {
+                    confirmEmpty = false
+                    vm.emptyBin()
+                }) { Text("Delete forever", color = Danger) }
+            },
+            dismissButton = { TextButton(onClick = { confirmEmpty = false }) { Text("Cancel") } },
+        )
+    }
+}
+
+@Composable
+private fun ThreadList(vm: MailViewModel, onHold: (ThreadSummary) -> Unit) {
+    val state = rememberLazyListState()
+    val nearEnd by remember {
+        derivedStateOf {
+            val last = state.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
+            last >= state.layoutInfo.totalItemsCount - 5
+        }
+    }
+    LaunchedEffect(nearEnd, vm.nextCursor) {
+        if (nearEnd && vm.nextCursor != null) vm.loadMore()
+    }
+
+    when {
+        vm.threads.isEmpty() && vm.loading -> Centered { CircularProgressIndicator() }
+        vm.threads.isEmpty() && vm.listError != null -> Centered {
+            Text(vm.listError!!, color = Muted)
+            TextButton(onClick = { vm.reload() }) { Text("Try again") }
+        }
+        vm.threads.isEmpty() -> Centered {
+            Text(if (vm.folder == ListFolder.Bin) "The Bin is empty." else "Nothing here.", color = Muted)
+        }
+        else -> LazyColumn(state = state, modifier = Modifier.fillMaxSize()) {
+            items(vm.threads, key = { it.id }) { t ->
+                SwipeRow(vm, t, onHold)
+            }
+            if (vm.loading) {
+                item { Centered(Modifier.padding(16.dp)) { CircularProgressIndicator(Modifier.size(24.dp)) } }
+            }
+        }
+    }
+}
+
+@Composable
+private fun Centered(modifier: Modifier = Modifier.fillMaxSize(), content: @Composable () -> Unit) {
+    Column(
+        modifier.fillMaxWidth(),
+        verticalArrangement = Arrangement.Center,
+        horizontalAlignment = Alignment.CenterHorizontally,
+    ) { content() }
+}
+
+/**
+ * Swipe right to toggle read (or restore, in the Bin); swipe left to bin it.
+ * Same as the web app.
+ */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+private fun SwipeRow(vm: MailViewModel, t: ThreadSummary, onHold: (ThreadSummary) -> Unit) {
+    val inBin = vm.folder == ListFolder.Bin
+    val canToggleRead = vm.folder == ListFolder.Inbox || vm.folder == ListFolder.Starred
+    val view = LocalView.current
+    // Material can ask more than once for one swipe; a toggle must only run once.
+    var firedAt by remember { mutableStateOf(0L) }
+    val state = rememberSwipeToDismissBoxState(
+        confirmValueChange = { value ->
+            val now = System.currentTimeMillis()
+            if (value != SwipeToDismissBoxValue.Settled && now - firedAt < 600) return@rememberSwipeToDismissBoxState false
+            if (value != SwipeToDismissBoxValue.Settled) firedAt = now
+            when (value) {
+                SwipeToDismissBoxValue.StartToEnd -> {
+                    view.performHapticFeedback(swipeHaptic)
+                    if (inBin) {
+                        vm.restore(t.id)
+                        true
+                    } else {
+                        // Not dismissed: the row springs back, showing its new state.
+                        vm.toggleRead(t)
+                        false
+                    }
+                }
+                SwipeToDismissBoxValue.EndToStart -> {
+                    view.performHapticFeedback(swipeHaptic)
+                    vm.moveToBin(t.id)
+                    true
+                }
+                SwipeToDismissBoxValue.Settled -> true
+            }
+        },
+        positionalThreshold = { it * 0.35f },
+    )
+
+    SwipeToDismissBox(
+        state = state,
+        enableDismissFromStartToEnd = inBin || canToggleRead,
+        enableDismissFromEndToStart = !inBin,
+        backgroundContent = {
+            val direction = state.dismissDirection
+            val (icon, label, color) = when (direction) {
+                SwipeToDismissBoxValue.StartToEnd -> when {
+                    inBin -> Triple(Icons.Outlined.RestoreFromTrash, "Restore", Accent)
+                    t.unread > 0 -> Triple(Icons.Outlined.MarkEmailRead, "Read", Accent)
+                    else -> Triple(Icons.Outlined.MarkEmailUnread, "Unread", Accent)
+                }
+                SwipeToDismissBoxValue.EndToStart -> Triple(Icons.Outlined.Delete, "Bin", Danger)
+                SwipeToDismissBoxValue.Settled -> Triple(null, "", Color.Transparent)
+            }
+            Row(
+                Modifier.fillMaxSize().background(color).padding(horizontal = 24.dp),
+                horizontalArrangement = if (direction == SwipeToDismissBoxValue.EndToStart) Arrangement.End else Arrangement.Start,
+                verticalAlignment = Alignment.CenterVertically,
+            ) {
+                if (icon != null) {
+                    Icon(icon, null, tint = Color.White)
+                    Spacer(Modifier.width(8.dp))
+                    Text(label, color = Color.White, fontWeight = FontWeight.SemiBold)
+                }
+            }
+        },
+    ) {
+        ThreadRow(vm, t, onClick = { vm.open(t) }, onLongClick = {
+            view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
+            onHold(t)
+        })
+    }
+}
+
+@OptIn(ExperimentalFoundationApi::class)
+@Composable
+private fun ThreadRow(vm: MailViewModel, t: ThreadSummary, onClick: () -> Unit, onLongClick: () -> Unit) {
+    val unread = t.unread > 0
+    // The Bin and Starred mix folders; whoever it's from reads best there.
+    val who = when (vm.folder) {
+        ListFolder.Sent, ListFolder.Drafts ->
+            "To: " + (t.to.joinToString(", ") { displayName(it) }.ifEmpty { "(nobody yet)" })
+        else -> displayName(t.from)
+    }
+    Row(
+        Modifier
+            .fillMaxWidth()
+            .background(MaterialTheme.colorScheme.background)
+            .combinedClickable(onClick = onClick, onLongClick = onLongClick)
+            .padding(horizontal = 16.dp, vertical = 12.dp),
+        verticalAlignment = Alignment.Top,
+    ) {
+        Avatar(who.removePrefix("To: "))
+        Spacer(Modifier.width(12.dp))
+        Column(Modifier.weight(1f)) {
+            Row(verticalAlignment = Alignment.CenterVertically) {
+                Text(
+                    who + if (t.count > 1) "  ${t.count}" else "",
+                    Modifier.weight(1f),
+                    fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal,
+                    maxLines = 1,
+                    overflow = TextOverflow.Ellipsis,
+                )
+                Text(
+                    fmtTime(t.lastAt),
+                    style = MaterialTheme.typography.labelMedium,
+                    color = if (unread) Accent else Muted,
+                )
+            }
+            Text(
+                t.subject.ifEmpty { "(no subject)" },
+                fontWeight = if (unread) FontWeight.SemiBold else FontWeight.Normal,
+                maxLines = 1,
+                overflow = TextOverflow.Ellipsis,
+            )
+            Row(verticalAlignment = Alignment.CenterVertically) {
+                Text(
+                    t.snippet,
+                    Modifier.weight(1f),
+                    style = MaterialTheme.typography.bodyMedium,
+                    color = Muted,
+                    maxLines = 1,
+                    overflow = TextOverflow.Ellipsis,
+                )
+                if (t.hasAttachments) Icon(Icons.Outlined.AttachFile, "Has attachments", Modifier.size(16.dp), tint = Muted)
+                if (t.starred) Icon(Icons.Filled.Star, "Starred", Modifier.size(16.dp), tint = Accent)
+            }
+        }
+    }
+}
+
+private val avatarColors = listOf(
+    Color(0xFFEB459E), Color(0xFF7C5CFF), Color(0xFF2FA4FF), Color(0xFF1FB58F),
+    Color(0xFFF5A524), Color(0xFFFF6B5C), Color(0xFFB45CFF), Color(0xFF4CC3D9),
+)
+
+/** A coloured initial, as Gmail does. */
+@Composable
+private fun Avatar(name: String) {
+    val initial = name.trim().firstOrNull { it.isLetterOrDigit() }?.uppercaseChar() ?: '?'
+    val color = avatarColors[Math.floorMod(name.lowercase().hashCode(), avatarColors.size)]
+    Box(Modifier.size(40.dp).clip(CircleShape).background(color), contentAlignment = Alignment.Center) {
+        Text(initial.toString(), color = Color.White, fontWeight = FontWeight.Bold)
+    }
+}
+
+/** The long-press menu, as a bottom sheet. */
+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
+@Composable
+private fun ThreadMenu(vm: MailViewModel, t: ThreadSummary, onClose: () -> Unit) {
+    val sheet = rememberModalBottomSheetState(skipPartiallyExpanded = true)
+    var confirmDelete by remember { mutableStateOf(false) }
+
+    @Composable
+    fun item(label: String, icon: ImageVector, danger: Boolean = false, run: () -> Unit) {
+        ListItem(
+            headlineContent = { Text(label, color = if (danger) Danger else Color.Unspecified) },
+            leadingContent = { Icon(icon, null, tint = if (danger) Danger else Muted) },
+            colors = ListItemDefaults.colors(containerColor = Color.Transparent),
+            modifier = Modifier.combinedClickable(onClick = run),
+        )
+    }
+
+    ModalBottomSheet(onDismissRequest = onClose, sheetState = sheet) {
+        Column(Modifier.navigationBarsPadding().padding(bottom = 8.dp)) {
+            Text(
+                t.subject.ifEmpty { "(no subject)" },
+                Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
+                style = MaterialTheme.typography.titleMedium,
+                maxLines = 2,
+                overflow = TextOverflow.Ellipsis,
+            )
+            HorizontalDivider()
+            when (vm.folder) {
+                ListFolder.Bin -> {
+                    item("Open", Icons.Outlined.OpenInNew) { onClose(); vm.open(t) }
+                    item("Restore", Icons.Outlined.RestoreFromTrash) { onClose(); vm.restore(t.id) }
+                    item(
+                        if (confirmDelete) "Tap again to delete forever" else "Delete forever",
+                        Icons.Outlined.DeleteForever,
+                        danger = true,
+                    ) {
+                        if (!confirmDelete) confirmDelete = true else { onClose(); vm.deleteForever(t.id) }
+                    }
+                }
+                else -> {
+                    if (vm.folder == ListFolder.Drafts) {
+                        item("Edit", Icons.Outlined.Edit) { onClose(); vm.editDraft(t.latestId) }
+                        item("Open conversation", Icons.Outlined.OpenInNew) { onClose(); vm.openThread(t.id, false) }
+                    } else {
+                        item("Open", Icons.Outlined.OpenInNew) { onClose(); vm.open(t) }
+                    }
+                    if (t.starred) {
+                        item("Unstar", Icons.Outlined.StarOutline) { onClose(); vm.toggleStar(t.id, false) }
+                    } else {
+                        item("Star", Icons.Outlined.Star) { onClose(); vm.toggleStar(t.id, true) }
+                    }
+                    if (vm.folder == ListFolder.Inbox || vm.folder == ListFolder.Starred) {
+                        if (t.unread > 0) {
+                            item("Mark as read", Icons.Outlined.MarkEmailRead) { onClose(); vm.toggleRead(t) }
+                        } else {
+                            item("Mark as unread", Icons.Outlined.MarkEmailUnread) { onClose(); vm.toggleRead(t) }
+                        }
+                    }
+                    item("Move to Bin", Icons.Outlined.Delete, danger = true) { onClose(); vm.moveToBin(t.id) }
+                }
+            }
+        }
+    }
+}
+
+@Composable
+private fun Drawer(vm: MailViewModel, close: () -> Unit) {
+    val context = LocalContext.current
+    val me = vm.me
+    val inboxUnread = vm.unread.values.sum()
+
+    @Composable
+    fun entry(label: String, icon: ImageVector, selected: Boolean, badge: Int = 0, indent: Boolean = false, onClick: () -> Unit) {
+        NavigationDrawerItem(
+            label = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
+            icon = { Icon(icon, null) },
+            selected = selected,
+            badge = if (badge > 0) ({ Badge { Text("$badge") } }) else null,
+            onClick = { close(); onClick() },
+            modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding).padding(start = if (indent) 24.dp else 0.dp),
+        )
+    }
+
+    ModalDrawerSheet {
+        Column(Modifier.verticalScroll(rememberScrollState()).padding(vertical = 12.dp)) {
+            Row(Modifier.padding(horizontal = 24.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) {
+                Icon(Icons.Outlined.Mail, null, tint = Accent)
+                Spacer(Modifier.width(12.dp))
+                Column {
+                    Text(me?.name ?: me?.username ?: "Inbox", style = MaterialTheme.typography.titleMedium)
+                    me?.addresses?.firstOrNull()?.let { Text(it, style = MaterialTheme.typography.labelMedium, color = Muted) }
+                }
+            }
+            HorizontalDivider(Modifier.padding(vertical = 8.dp))
+            for (f in ListFolder.entries) {
+                entry(
+                    f.label,
+                    folderIcons.getValue(f),
+                    selected = vm.folder == f,
+                    badge = if (f == ListFolder.Inbox) inboxUnread else 0,
+                ) { vm.show(f) }
+            }
+
+            if (me != null && me.addresses.size > 1) {
+                HorizontalDivider(Modifier.padding(vertical = 8.dp))
+                entry("All addresses", Icons.Outlined.AllInbox, selected = vm.mailbox == null) { vm.show(vm.folder, null) }
+                for (domain in me.domains) {
+                    val addrs = me.addresses.filter { it.endsWith("@$domain") }
+                    entry(
+                        domain,
+                        Icons.Outlined.Language,
+                        selected = vm.mailbox == "@$domain",
+                        badge = addrs.sumOf { vm.unread[it] ?: 0 },
+                    ) { vm.show(vm.folder, "@$domain") }
+                    if (addrs.size > 1) {
+                        for (addr in addrs) {
+                            entry(
+                                addr.substringBefore("@"),
+                                Icons.Outlined.AlternateEmail,
+                                selected = vm.mailbox == addr,
+                                badge = vm.unread[addr] ?: 0,
+                                indent = true,
+                            ) { vm.show(vm.folder, addr) }
+                        }
+                    }
+                }
+            }
+
+            HorizontalDivider(Modifier.padding(vertical = 8.dp))
+            entry("Settings", Icons.Outlined.Settings, selected = false) { vm.openSettings() }
+            if (me?.isAdmin == true) {
+                // Admin stays on the web; it's rarely needed and not worth a second copy.
+                entry("Admin (web)", Icons.Outlined.Shield, selected = false) {
+                    CustomTabsIntent.Builder().build()
+                        .launchUrl(context, Uri.parse("${gay.doughmination.mail.BuildConfig.INBOX_URL}/admin"))
+                }
+            }
+        }
+    }
+}
diff --git a/email/app/src/main/java/gay/doughmination/mail/ui/ThreadScreen.kt b/email/app/src/main/java/gay/doughmination/mail/ui/ThreadScreen.kt
new file mode 100644
index 0000000..762ae85
--- /dev/null
+++ b/email/app/src/main/java/gay/doughmination/mail/ui/ThreadScreen.kt
@@ -0,0 +1,272 @@
+package gay.doughmination.mail.ui
+
+import android.app.DownloadManager
+import android.content.Context
+import android.net.Uri
+import android.os.Build
+import android.os.Environment
+import android.widget.Toast
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.outlined.ArrowBack
+import androidx.compose.material.icons.automirrored.outlined.Forward
+import androidx.compose.material.icons.automirrored.outlined.Reply
+import androidx.compose.material.icons.filled.Star
+import androidx.compose.material.icons.outlined.AttachFile
+import androidx.compose.material.icons.outlined.Delete
+import androidx.compose.material.icons.outlined.DeleteForever
+import androidx.compose.material.icons.outlined.Edit
+import androidx.compose.material.icons.outlined.Image
+import androidx.compose.material.icons.outlined.MarkEmailUnread
+import androidx.compose.material.icons.outlined.RestoreFromTrash
+import androidx.compose.material.icons.outlined.StarOutline
+import androidx.compose.material3.AssistChip
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import gay.doughmination.mail.InboxApp
+import gay.doughmination.mail.data.Api
+import gay.doughmination.mail.data.AttachmentInfo
+import gay.doughmination.mail.data.Message
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun ThreadScreen(vm: MailViewModel, screen: Screen.Thread) {
+    LaunchedEffect(screen, vm.threadVersion) { vm.loadThread(screen.id, screen.bin) }
+    val thread = vm.thread?.takeIf { it.id == screen.id }
+    var confirmDelete by remember { mutableStateOf(false) }
+
+    Scaffold(
+        topBar = {
+            TopAppBar(
+                title = {},
+                navigationIcon = {
+                    IconButton(onClick = { vm.back() }) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Back") }
+                },
+                actions = {
+                    if (thread == null) return@TopAppBar
+                    if (screen.bin) {
+                        IconButton(onClick = { vm.restore(thread.id) }) {
+                            Icon(Icons.Outlined.RestoreFromTrash, "Restore")
+                        }
+                        IconButton(onClick = { if (confirmDelete) vm.deleteForever(thread.id) else confirmDelete = true }) {
+                            Icon(Icons.Outlined.DeleteForever, if (confirmDelete) "Tap again to delete forever" else "Delete forever", tint = if (confirmDelete) Danger else Muted)
+                        }
+                    } else {
+                        IconButton(onClick = { vm.toggleStar(thread.id, !thread.starred) }) {
+                            if (thread.starred) Icon(Icons.Filled.Star, "Unstar", tint = Accent)
+                            else Icon(Icons.Outlined.StarOutline, "Star")
+                        }
+                        if (thread.messages.any { it.folder == "inbox" }) {
+                            IconButton(onClick = { vm.markUnread(thread.id) }) {
+                                Icon(Icons.Outlined.MarkEmailUnread, "Mark as unread")
+                            }
+                        }
+                        IconButton(onClick = { vm.moveToBin(thread.id) }) { Icon(Icons.Outlined.Delete, "Move to Bin") }
+                    }
+                },
+            )
+        },
+        snackbarHost = { SnackbarHost(LocalSnackbar.current) },
+    ) { padding ->
+        when {
+            thread != null -> LazyColumn(
+                Modifier.padding(padding).fillMaxSize(),
+                contentPadding = PaddingValues(12.dp),
+                verticalArrangement = Arrangement.spacedBy(10.dp),
+            ) {
+                item {
+                    Text(
+                        thread.subject.ifEmpty { "(no subject)" },
+                        Modifier.padding(horizontal = 4.dp, vertical = 4.dp),
+                        style = MaterialTheme.typography.headlineSmall,
+                    )
+                }
+                val newest = thread.messages.lastOrNull()?.id
+                items(thread.messages, key = { it.id }) { m ->
+                    MessageCard(vm, m, screen.bin, startOpen = m.id == newest || !m.read)
+                }
+            }
+            vm.threadError != null -> Column(
+                Modifier.padding(padding).fillMaxSize(),
+                verticalArrangement = Arrangement.Center,
+                horizontalAlignment = Alignment.CenterHorizontally,
+            ) {
+                Text(vm.threadError!!, color = Muted)
+                TextButton(onClick = { vm.back() }) { Text("Go back") }
+            }
+            else -> Column(
+                Modifier.padding(padding).fillMaxSize(),
+                verticalArrangement = Arrangement.Center,
+                horizontalAlignment = Alignment.CenterHorizontally,
+            ) { CircularProgressIndicator() }
+        }
+    }
+}
+
+@Composable
+private fun MessageCard(vm: MailViewModel, m: Message, bin: Boolean, startOpen: Boolean) {
+    val api = (LocalContext.current.applicationContext as InboxApp).api
+    var open by rememberSaveable(m.id) { mutableStateOf(startOpen) }
+    var showRemote by rememberSaveable(m.id) { mutableStateOf(false) }
+    var confirmDelete by remember { mutableStateOf(false) }
+    val isDraft = m.folder == "drafts"
+
+    Card(
+        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
+        modifier = Modifier.fillMaxWidth(),
+    ) {
+        Column(Modifier.clickable { open = !open }.padding(14.dp)) {
+            Row(verticalAlignment = Alignment.CenterVertically) {
+                Text(
+                    if (isDraft) "Draft" else displayName(m.from),
+                    Modifier.weight(1f),
+                    fontWeight = FontWeight.SemiBold,
+                    color = if (isDraft) Danger else MaterialTheme.colorScheme.onSurface,
+                    maxLines = 1,
+                    overflow = TextOverflow.Ellipsis,
+                )
+                Text(fmtTime(m.sentAt), style = MaterialTheme.typography.labelMedium, color = Muted)
+            }
+            if (!open) {
+                Text(m.snippet, color = Muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
+            } else {
+                Text(bareAddress(m.from), style = MaterialTheme.typography.labelMedium, color = Muted)
+                if (m.to.isNotEmpty()) Text("To: ${m.to.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = Muted)
+                if (m.cc.isNotEmpty()) Text("Cc: ${m.cc.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = Muted)
+                if (m.bcc.isNotEmpty()) Text("Bcc: ${m.bcc.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = Muted)
+            }
+        }
+        if (!open) return@Card
+
+        val html = m.html
+        if (html != null) {
+            if (hasRemoteContent(html) && !showRemote) {
+                OutlinedButton(onClick = { showRemote = true }, Modifier.padding(horizontal = 14.dp)) {
+                    Icon(Icons.Outlined.Image, null)
+                    Spacer(Modifier.width(6.dp))
+                    Text("Load remote images")
+                }
+                Spacer(Modifier.height(8.dp))
+            }
+            EmailView(api, html, m.attachments, showRemote, Modifier.fillMaxWidth())
+        } else {
+            SelectionContainer {
+                Text(m.text.orEmpty(), Modifier.padding(horizontal = 14.dp))
+            }
+        }
+
+        val files = m.attachments.filter { it.contentId == null || html == null }
+        if (files.isNotEmpty()) {
+            Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 14.dp, vertical = 8.dp)) {
+                val context = LocalContext.current
+                for (a in files) {
+                    AssistChip(
+                        onClick = { download(context, api, a) },
+                        label = { Text("${a.filename} · ${fmtSize(a.size)}", maxLines = 1) },
+                        leadingIcon = { Icon(Icons.Outlined.AttachFile, null) },
+                        modifier = Modifier.padding(end = 8.dp),
+                    )
+                }
+            }
+        }
+
+        Row(Modifier.padding(horizontal = 4.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
+            if (isDraft && !bin) {
+                TextButton(onClick = { vm.composeDraft(m) }) {
+                    Icon(Icons.Outlined.Edit, null)
+                    Spacer(Modifier.width(6.dp))
+                    Text("Edit")
+                }
+            } else if (!bin) {
+                TextButton(onClick = { vm.composeReply(m) }) {
+                    Icon(Icons.AutoMirrored.Outlined.Reply, null)
+                    Spacer(Modifier.width(6.dp))
+                    Text("Reply")
+                }
+                TextButton(onClick = { vm.composeForward(m) }) {
+                    Icon(Icons.AutoMirrored.Outlined.Forward, null)
+                    Spacer(Modifier.width(6.dp))
+                    Text("Forward")
+                }
+            }
+            Spacer(Modifier.weight(1f))
+            if (bin) {
+                IconButton(onClick = { vm.restoreMessage(m) }) { Icon(Icons.Outlined.RestoreFromTrash, "Restore this message") }
+            }
+            IconButton(onClick = {
+                if (!bin && !isDraft) vm.deleteMessage(m, bin)
+                else if (confirmDelete) vm.deleteMessage(m, bin)
+                else confirmDelete = true
+            }) {
+                Icon(
+                    Icons.Outlined.Delete,
+                    when {
+                        confirmDelete -> "Tap again to delete forever"
+                        bin || isDraft -> "Delete forever"
+                        else -> "Move to Bin"
+                    },
+                    tint = if (confirmDelete) Danger else Muted,
+                )
+            }
+        }
+    }
+}
+
+/** Saves an attachment to Downloads, with the system's own progress notification. */
+private fun download(context: Context, api: Api, a: AttachmentInfo) {
+    val name = a.filename.replace('/', '_')
+    val request = DownloadManager.Request(Uri.parse(api.attachmentUrl(a.id)))
+        .setTitle(a.filename)
+        .setMimeType(a.contentType)
+        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
+    // Public Downloads needs a storage permission before Android 10; earlier
+    // versions keep it in the app's own folder, still opened from the notification.
+    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name)
+    } else {
+        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, name)
+    }
+    api.authorize(okhttp3.Request.Builder().url(api.attachmentUrl(a.id))).build()
+        .header("Authorization")?.let { request.addRequestHeader("Authorization", it) }
+    (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).enqueue(request)
+    Toast.makeText(context, "Downloading ${a.filename}", Toast.LENGTH_SHORT).show()
+}
diff --git a/email/app/src/main/res/drawable-hdpi/splash.png b/email/app/src/main/res/drawable-hdpi/splash.png
deleted file mode 100644
index 6e68d97..0000000
Binary files a/email/app/src/main/res/drawable-hdpi/splash.png and /dev/null differ
diff --git a/email/app/src/main/res/drawable-mdpi/splash.png b/email/app/src/main/res/drawable-mdpi/splash.png
deleted file mode 100644
index b9d3c5d..0000000
Binary files a/email/app/src/main/res/drawable-mdpi/splash.png and /dev/null differ
diff --git a/email/app/src/main/res/drawable-xhdpi/splash.png b/email/app/src/main/res/drawable-xhdpi/splash.png
deleted file mode 100644
index 06b6320..0000000
Binary files a/email/app/src/main/res/drawable-xhdpi/splash.png and /dev/null differ
diff --git a/email/app/src/main/res/drawable-xxhdpi/splash.png b/email/app/src/main/res/drawable-xxhdpi/splash.png
deleted file mode 100644
index 6cfcea9..0000000
Binary files a/email/app/src/main/res/drawable-xxhdpi/splash.png and /dev/null differ
diff --git a/email/app/src/main/res/drawable-xxxhdpi/splash.png b/email/app/src/main/res/drawable-xxxhdpi/splash.png
deleted file mode 100644
index 0b7635e..0000000
Binary files a/email/app/src/main/res/drawable-xxxhdpi/splash.png and /dev/null differ
diff --git a/email/app/src/main/res/values/strings.xml b/email/app/src/main/res/values/strings.xml
index 1e3a54b..045c1e4 100644
--- a/email/app/src/main/res/values/strings.xml
+++ b/email/app/src/main/res/values/strings.xml
@@ -1,11 +1,4 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
     <string name="app_name">Inbox</string>
-    <string name="launch_url" translatable="false">https://mail.doughmination.gay/inbox</string>
-    <string name="asset_statements" translatable="false">
-        [{
-            \"relation\": [\"delegate_permission/common.handle_all_urls\"],
-            \"target\": {\"namespace\": \"web\", \"site\": \"https://mail.doughmination.gay\"}
-        }]
-    </string>
 </resources>
diff --git a/email/app/src/main/res/values/themes.xml b/email/app/src/main/res/values/themes.xml
new file mode 100644
index 0000000..6f81fa4
--- /dev/null
+++ b/email/app/src/main/res/values/themes.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <!-- Compose draws everything; this only colours the window before it does. -->
+    <style name="Theme.Inbox" parent="android:Theme.Material.NoActionBar">
+        <item name="android:windowBackground">@color/background</item>
+        <item name="android:statusBarColor">@android:color/transparent</item>
+        <item name="android:navigationBarColor">@android:color/transparent</item>
+    </style>
+</resources>
diff --git a/email/app/src/main/res/xml/filepaths.xml b/email/app/src/main/res/xml/filepaths.xml
deleted file mode 100644
index 6f99048..0000000
--- a/email/app/src/main/res/xml/filepaths.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- res/xml/filepaths.xml
-     Where the launcher drops the splash image for Chrome to pick up. -->
-<paths>
-    <files-path
-        name="twa_splash"
-        path="twa_splash/" />
-</paths>
diff --git a/email/build.gradle.kts b/email/build.gradle.kts
index a0dd15f..70dfb63 100644
--- a/email/build.gradle.kts
+++ b/email/build.gradle.kts
@@ -1,3 +1,6 @@
 plugins {
     id("com.android.application") version "8.7.3" apply false
+    id("org.jetbrains.kotlin.android") version "2.0.21" apply false
+    id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
+    id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
 }