Dough Git

commit

Let swipes be set in Settings, and show the account's SSO picture

commit
b199ebeaf32333680471a4ee8e8e00749eb65530
author
Clove Twilight <[email protected]>
date
2026-10-31 09:15
Swiping left or right can now mark read or unread, star, move to the Bin or
do nothing, chosen in Settings and shared between the web and the app. The
account's picture comes from the SSO's picture claim (or userinfo) at each
sign-in and refresh, and shows in the drawer; Settings can switch it off for
the default initial.

diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Api.kt b/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
index 653c89b..66fc25f 100644
--- a/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
@@ -42,6 +42,8 @@ class Api(val baseUrl: String, private val tokens: TokenStore, private val onSig
     val json = Json {
         ignoreUnknownKeys = true
         encodeDefaults = true
+        // An enum value this build doesn't know (a newer swipe) takes the field's default.
+        coerceInputValues = true
     }
 
     private val jsonType = "application/json".toMediaType()
@@ -101,6 +103,7 @@ class Api(val baseUrl: String, private val tokens: TokenStore, private val onSig
     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 setPreferences(prefs: Preferences): Preferences = call("PATCH", "/api/me/preferences", prefs)
 
     suspend fun threads(folder: ListFolder, mailbox: String?, cursor: String?): Page<ThreadSummary> {
         val q = url("/api/threads").newBuilder().addQueryParameter("folder", folder.path)
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Models.kt b/app/app/src/main/java/gay/doughmination/mail/data/Models.kt
index 6c671ed..e29e01d 100644
--- a/app/app/src/main/java/gay/doughmination/mail/data/Models.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/data/Models.kt
@@ -1,5 +1,6 @@
 package gay.doughmination.mail.data
 
+import kotlinx.serialization.SerialName
 import kotlinx.serialization.Serializable
 
 // Mirrors email/src/shared/types.ts. Keep the two in step.
@@ -13,7 +14,30 @@ data class Me(
     /** Every address this user can send from. */
     val addresses: List<String>,
     val domains: List<String>,
-)
+    /** The account's picture on the SSO (https), whether or not it's in use. */
+    val picture: String? = null,
+    val usePicture: Boolean = true,
+    val swipeLeft: SwipeAction = SwipeAction.Bin,
+    val swipeRight: SwipeAction = SwipeAction.Read,
+) {
+    val preferences get() = Preferences(usePicture, swipeLeft, swipeRight)
+
+    /** The picture to show for the account, or null for the default (an initial). */
+    val shownPicture get() = picture?.takeIf { usePicture }
+}
+
+/** What swiping a row does. An unknown value (a newer server) reads as None. */
+@Serializable
+enum class SwipeAction(val label: String) {
+    @SerialName("none") None("Nothing"),
+    @SerialName("read") Read("Mark as read or unread"),
+    @SerialName("star") Star("Star or unstar"),
+    @SerialName("bin") Bin("Move to Bin"),
+}
+
+/** Settings that follow the user between the web and the app. */
+@Serializable
+data class Preferences(val usePicture: Boolean, val swipeLeft: SwipeAction, val swipeRight: SwipeAction)
 
 @Serializable
 data class Page<T>(val items: List<T>, val nextCursor: String? = null)
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/AccountPicture.kt b/app/app/src/main/java/gay/doughmination/mail/ui/AccountPicture.kt
new file mode 100644
index 0000000..120c0d3
--- /dev/null
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/AccountPicture.kt
@@ -0,0 +1,72 @@
+package gay.doughmination.mail.ui
+
+import android.graphics.BitmapFactory
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.produceState
+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.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.sp
+import gay.doughmination.mail.InboxApp
+import gay.doughmination.mail.data.Me
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.util.concurrent.ConcurrentHashMap
+
+/**
+ * The signed-in account's picture: the SSO's, when there is one and Settings
+ * says to use it, or the default, their initial on the accent colour. Also the
+ * default while the picture loads, or if it can't be loaded. Same as the web.
+ */
+@Composable
+fun AccountPicture(me: Me?, size: Dp) {
+    val url = me?.shownPicture
+    val http = (LocalContext.current.applicationContext as InboxApp).api.http
+    val picture by produceState(url?.let { loaded[it] }, url) {
+        value = url?.let { loadPicture(http, it) }
+    }
+    val shape = Modifier.size(size).clip(CircleShape)
+    picture?.let {
+        Image(it, null, shape, contentScale = ContentScale.Crop)
+        return
+    }
+    val initial = (me?.name?.ifBlank { null } ?: me?.username ?: "?").firstOrNull { it.isLetterOrDigit() }?.uppercaseChar() ?: '?'
+    Box(shape.background(Accent), contentAlignment = Alignment.Center) {
+        Text(initial.toString(), color = Color.White, fontSize = (size.value * 0.42f).sp, fontWeight = FontWeight.SemiBold)
+    }
+}
+
+/** Pictures already fetched this run, so the drawer doesn't flash its initial each time. */
+private val loaded = ConcurrentHashMap<String, ImageBitmap>()
+
+/** Fetches a picture without the session token (it's the SSO's, not ours), scaled down to avatar size. */
+private suspend fun loadPicture(http: OkHttpClient, url: String): ImageBitmap? = loaded[url] ?: withContext(Dispatchers.IO) {
+    runCatching {
+        http.newCall(Request.Builder().url(url).build()).execute().use { res ->
+            if (!res.isSuccessful) return@use null
+            val bytes = res.body?.bytes() ?: return@use null
+            val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+            BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
+            var sample = 1
+            while (minOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= 256) sample *= 2
+            BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
+                ?.asImageBitmap()
+        }
+    }.getOrNull()?.also { loaded[url] = it }
+}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt b/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
index 20c965f..49f8c99 100644
--- a/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
@@ -18,6 +18,7 @@ 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.Preferences
 import gay.doughmination.mail.data.SendRequest
 import gay.doughmination.mail.data.SignedOutException
 import gay.doughmination.mail.data.ThreadSummary
@@ -611,6 +612,19 @@ class MailViewModel(application: Application) : AndroidViewModel(application) {
         }
     }
 
+    /** Shows the change straight away, and puts it back if the server says no. */
+    fun setPreferences(prefs: Preferences) = viewModelScope.launch {
+        val before = me ?: return@launch
+        me = before.copy(usePicture = prefs.usePicture, swipeLeft = prefs.swipeLeft, swipeRight = prefs.swipeRight)
+        try {
+            val saved = api.setPreferences(prefs)
+            me = me?.copy(usePicture = saved.usePicture, swipeLeft = saved.swipeLeft, swipeRight = saved.swipeRight)
+        } catch (e: Exception) {
+            me = me?.copy(usePicture = before.usePicture, swipeLeft = before.swipeLeft, swipeRight = before.swipeRight)
+            fail(e)
+        }
+    }
+
     fun testPush() = viewModelScope.launch {
         try {
             val n = api.pushTest()
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
index 67fcea6..d96f918 100644
--- a/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
@@ -29,6 +29,11 @@ import androidx.compose.material.icons.outlined.Notifications
 import androidx.compose.material.icons.outlined.PrivacyTip
 import androidx.compose.material3.Button
 import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.ExposedDropdownMenuBox
+import androidx.compose.material3.ExposedDropdownMenuDefaults
+import androidx.compose.material3.MenuAnchorType
+import androidx.compose.material3.Switch
 import androidx.compose.material3.ExperimentalMaterial3Api
 import androidx.compose.material3.Icon
 import androidx.compose.material3.IconButton
@@ -42,6 +47,7 @@ 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.saveable.rememberSaveable
 import androidx.compose.runtime.setValue
 import androidx.compose.ui.Alignment
@@ -52,6 +58,7 @@ import androidx.compose.ui.platform.LocalContext
 import androidx.compose.ui.unit.dp
 import gay.doughmination.mail.BuildConfig
 import gay.doughmination.mail.Push
+import gay.doughmination.mail.data.SwipeAction
 
 /** Laid out like the web's settings page: one card per topic, under a small pink heading. */
 @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@@ -94,6 +101,38 @@ fun SettingsScreen(vm: MailViewModel) {
                 }
             }
 
+            Section("Profile picture") {
+                val picture = me?.picture
+                Row(verticalAlignment = Alignment.CenterVertically) {
+                    AccountPicture(me, 56.dp)
+                    Spacer(Modifier.width(16.dp))
+                    Column(Modifier.weight(1f)) {
+                        Text("Use your account's picture")
+                        Note(
+                            if (picture != null) "The one on your Doughmination account. Off shows your initial instead."
+                            else "Your Doughmination account has no picture, so your initial shows.",
+                        )
+                    }
+                    Spacer(Modifier.width(12.dp))
+                    Switch(
+                        checked = me?.shownPicture != null,
+                        onCheckedChange = { on -> me?.let { vm.setPreferences(it.preferences.copy(usePicture = on)) } },
+                        enabled = picture != null,
+                    )
+                }
+            }
+
+            Section("Swipe actions") {
+                Note(
+                    "What swiping a conversation in the list does, here and on the web. Read and unread only " +
+                        "applies to received mail, and in the Bin a swipe right always restores.",
+                )
+                me?.let {
+                    SwipePicker("Swipe right", it.swipeRight) { choice -> vm.setPreferences(it.preferences.copy(swipeRight = choice)) }
+                    SwipePicker("Swipe left", it.swipeLeft) { choice -> vm.setPreferences(it.preferences.copy(swipeLeft = choice)) }
+                }
+            }
+
             Section("Your addresses") {
                 Note("You receive and can send from each of these.")
                 for (addr in me?.addresses.orEmpty()) Text("•  $addr")
@@ -179,5 +218,27 @@ private fun Section(title: String, icon: ImageVector? = null, content: @Composab
     }
 }
 
+/** A dropdown of the swipe actions, as an outlined field. */
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+private fun SwipePicker(label: String, selected: SwipeAction, onPick: (SwipeAction) -> Unit) {
+    var open by remember { mutableStateOf(false) }
+    ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it }) {
+        OutlinedTextField(
+            value = selected.label,
+            onValueChange = {},
+            readOnly = true,
+            label = { Text(label) },
+            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) },
+            modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
+        )
+        ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
+            for (choice in SwipeAction.entries) {
+                DropdownMenuItem(text = { Text(choice.label) }, onClick = { open = false; onPick(choice) })
+            }
+        }
+    }
+}
+
 @Composable
 private fun Note(text: String) = Text(text, style = MaterialTheme.typography.bodyMedium, color = Muted)
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
index 9be58fb..cd09381 100644
--- a/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
+++ b/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
@@ -34,7 +34,6 @@ 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
@@ -94,6 +93,7 @@ import androidx.compose.ui.unit.sp
 import androidx.browser.customtabs.CustomTabsIntent
 import android.net.Uri
 import gay.doughmination.mail.data.ListFolder
+import gay.doughmination.mail.data.SwipeAction
 import gay.doughmination.mail.data.ThreadSummary
 import kotlinx.coroutines.launch
 
@@ -229,70 +229,81 @@ private fun Centered(modifier: Modifier = Modifier.fillMaxSize(), content: @Comp
     ) { content() }
 }
 
+/** One way to swipe a row: what it shows underneath, and what it does. */
+private class Swipe(val label: String, val icon: ImageVector, val color: Color, val dismiss: Boolean, val run: () -> Unit)
+
+/** What a swipe set up in Settings does to this row; null where it can't apply. Same as the web. */
+private fun swipeFor(choice: SwipeAction, vm: MailViewModel, t: ThreadSummary): Swipe? = when (choice) {
+    // Only received mail has a read state.
+    SwipeAction.Read -> if (vm.folder != ListFolder.Inbox && vm.folder != ListFolder.Starred) null else Swipe(
+        if (t.unread > 0) "Read" else "Unread",
+        if (t.unread > 0) Icons.Outlined.MarkEmailRead else Icons.Outlined.MarkEmailUnread,
+        Accent,
+        dismiss = false,
+    ) { vm.toggleRead(t) }
+    SwipeAction.Star -> Swipe(
+        if (t.starred) "Unstar" else "Star",
+        if (t.starred) Icons.Outlined.StarOutline else Icons.Filled.Star,
+        Accent,
+        // Unstarring takes it out of Starred.
+        dismiss = vm.folder == ListFolder.Starred && t.starred,
+    ) { vm.toggleStar(t.id, !t.starred) }
+    SwipeAction.Bin -> Swipe("Bin", Icons.Outlined.Delete, Danger, dismiss = true) { vm.moveToBin(t.id) }
+    SwipeAction.None -> null
+}
+
 /**
- * Swipe right to toggle read (or restore, in the Bin); swipe left to bin it.
- * Same as the web app.
+ * Swipes do what Settings says (toggle read and bin it, unless changed). In
+ * the Bin, swiping right restores and left does nothing. 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 right = if (inBin) Swipe("Restore", Icons.Outlined.RestoreFromTrash, Accent, dismiss = true) { vm.restore(t.id) }
+    else swipeFor(vm.me?.swipeRight ?: SwipeAction.Read, vm, t)
+    val left = if (inBin) null else swipeFor(vm.me?.swipeLeft ?: SwipeAction.Bin, vm, t)
     val view = LocalView.current
-    // Material can ask more than once for one swipe; a toggle must only run once.
+    // Material can ask more than once for one swipe; an action 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
-            }
+            val swipe = when (value) {
+                SwipeToDismissBoxValue.StartToEnd -> right
+                SwipeToDismissBoxValue.EndToStart -> left
+                SwipeToDismissBoxValue.Settled -> return@rememberSwipeToDismissBoxState true
+            } ?: return@rememberSwipeToDismissBoxState false
+            view.performHapticFeedback(swipeHaptic)
+            swipe.run()
+            // Not dismissed: the row springs back, showing its new state.
+            swipe.dismiss
         },
         positionalThreshold = { it * 0.35f },
     )
 
     SwipeToDismissBox(
         state = state,
-        enableDismissFromStartToEnd = inBin || canToggleRead,
-        enableDismissFromEndToStart = !inBin,
+        enableDismissFromStartToEnd = right != null,
+        enableDismissFromEndToStart = left != null,
         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)
+            val swipe = when (direction) {
+                SwipeToDismissBoxValue.StartToEnd -> right
+                SwipeToDismissBoxValue.EndToStart -> left
+                SwipeToDismissBoxValue.Settled -> null
             }
             Row(
-                Modifier.fillMaxSize().background(color).padding(horizontal = 24.dp),
+                Modifier.fillMaxSize().background(swipe?.color ?: Color.Transparent).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)
+                if (swipe != null) {
+                    Icon(swipe.icon, null, tint = Color.White)
                     Spacer(Modifier.width(8.dp))
-                    Text(label, color = Color.White, fontWeight = FontWeight.SemiBold)
+                    Text(swipe.label, color = Color.White, fontWeight = FontWeight.SemiBold)
                 }
             }
         },
@@ -486,7 +497,7 @@ private fun Drawer(vm: MailViewModel, close: () -> Unit) {
     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)
+                AccountPicture(me, 40.dp)
                 Spacer(Modifier.width(12.dp))
                 Column {
                     Text(me?.name ?: me?.username ?: "Inbox", style = MaterialTheme.typography.titleMedium)
diff --git a/email/migrations/0008_profile_and_swipes.sql b/email/migrations/0008_profile_and_swipes.sql
new file mode 100644
index 0000000..9c7a15d
--- /dev/null
+++ b/email/migrations/0008_profile_and_swipes.sql
@@ -0,0 +1,11 @@
+-- The picture the SSO has for the account (its `picture` claim), refreshed on
+-- every sign-in. use_picture is the user's choice in Settings: 1 shows it,
+-- 0 shows the default (their initial) instead.
+ALTER TABLE users ADD COLUMN picture TEXT;
+ALTER TABLE users ADD COLUMN use_picture INTEGER NOT NULL DEFAULT 1;
+
+-- What swiping a row in the list does, set in Settings. One of none, read
+-- (toggle read), star (toggle starred) or bin. The defaults are what swiping
+-- always did before.
+ALTER TABLE users ADD COLUMN swipe_left TEXT NOT NULL DEFAULT 'bin';
+ALTER TABLE users ADD COLUMN swipe_right TEXT NOT NULL DEFAULT 'read';
diff --git a/email/src/shared/types.ts b/email/src/shared/types.ts
index 4dca5dd..8963bee 100644
--- a/email/src/shared/types.ts
+++ b/email/src/shared/types.ts
@@ -8,10 +8,24 @@ export type Folder = "inbox" | "sent" | "drafts";
  */
 export type ListFolder = Folder | "bin" | "starred";
 
-export interface Me {
+/** What swiping a row does: toggle read, toggle starred, move to the Bin, or nothing. */
+export const SWIPE_ACTIONS = ["none", "read", "star", "bin"] as const;
+export type SwipeAction = (typeof SWIPE_ACTIONS)[number];
+
+/** Settings that follow the user between the web and the app. */
+export interface Preferences {
+  /** Show `picture` as the account's picture; otherwise the default (an initial). */
+  usePicture: boolean;
+  swipeLeft: SwipeAction;
+  swipeRight: SwipeAction;
+}
+
+export interface Me extends Preferences {
   username: string;
   /** Display name put on outgoing mail; null sends from the bare address. */
   name: string | null;
+  /** The account's picture on the SSO (https), whether or not it's in use. */
+  picture: string | null;
   isAdmin: boolean;
   /** Every address this user can send from, across all enabled domains. */
   addresses: string[];
diff --git a/email/src/web/components/AccountPicture.svelte b/email/src/web/components/AccountPicture.svelte
new file mode 100644
index 0000000..45f1959
--- /dev/null
+++ b/email/src/web/components/AccountPicture.svelte
@@ -0,0 +1,47 @@
+<!-- mailbox/src/web/components/AccountPicture.svelte
+     Copyright (c) 2026 Clove Nytrix Doughmination Twilight
+     Licensed under the DASL-1.0 Licence.
+     See LICENCE.md in the project root for full licence information. -->
+<script lang="ts">
+  import { session } from "../lib/state.svelte";
+
+  /**
+   * The signed-in account's picture: the SSO's, when there is one and Settings
+   * says to use it, or the default, their initial on the accent colour. Also
+   * falls back to the default if the SSO's picture fails to load.
+   */
+  let { size = 40 }: { size?: number } = $props();
+
+  let broken = $state(false);
+  const me = $derived(session.me);
+  const picture = $derived(me?.usePicture && me.picture && !broken ? me.picture : null);
+  const initial = $derived((me?.name || me?.username || "?").match(/\p{L}|\p{N}/u)?.[0]?.toUpperCase() ?? "?");
+
+  // A new picture gets a fresh try.
+  $effect(() => {
+    void me?.picture;
+    broken = false;
+  });
+</script>
+
+{#if picture}
+  <img class="pfp" src={picture} alt="" width={size} height={size} referrerpolicy="no-referrer" onerror={() => (broken = true)} />
+{:else}
+  <span class="pfp initial" style:width="{size}px" style:height="{size}px" style:font-size="{size * 0.42}px" aria-hidden="true">{initial}</span>
+{/if}
+
+<style>
+  .pfp {
+    flex-shrink: 0;
+    border-radius: 50%;
+    object-fit: cover;
+  }
+
+  .initial {
+    display: grid;
+    place-items: center;
+    background: var(--accent);
+    color: #fff;
+    font-weight: 600;
+  }
+</style>
diff --git a/email/src/web/components/Sidebar.svelte b/email/src/web/components/Sidebar.svelte
index bc1bfd8..302099a 100644
--- a/email/src/web/components/Sidebar.svelte
+++ b/email/src/web/components/Sidebar.svelte
@@ -9,7 +9,6 @@
   import Globe from "../lib/icons/Globe.svelte";
   import InboxIcon from "../lib/icons/Inbox.svelte";
   import LogOut from "../lib/icons/LogOut.svelte";
-  import Mail from "../lib/icons/Mail.svelte";
   import Mobile from "../lib/icons/Mobile.svelte";
   import Send from "../lib/icons/Send.svelte";
   import SettingsIcon from "../lib/icons/Settings.svelte";
@@ -21,6 +20,7 @@
   import { api } from "../lib/api";
   import { router } from "../lib/router.svelte";
   import { composeNew, session } from "../lib/state.svelte";
+  import AccountPicture from "./AccountPicture.svelte";
 
   /** Phones: whether the drawer is out. Ignored on wider screens. */
   let { open = false, onclose = () => {} }: { open?: boolean; onclose?: () => void } = $props();
@@ -69,7 +69,7 @@
      settings. On wide screens it's the sidebar, with a compose button. -->
 <nav class="sidebar" class:open>
   <div class="who">
-    <Mail size={24} />
+    <AccountPicture size={40} />
     <div>
       <p class="name">{session.me?.name || session.me?.username || "Inbox"}</p>
       {#if session.me?.addresses[0]}<p class="address">{session.me.addresses[0]}</p>{/if}
@@ -151,7 +151,6 @@
     align-items: center;
     gap: 0.75rem;
     padding: 0.75rem 1rem;
-    color: var(--accent);
   }
 
   .who p {
diff --git a/email/src/web/components/ThreadList.svelte b/email/src/web/components/ThreadList.svelte
index cba048e..49c21bc 100644
--- a/email/src/web/components/ThreadList.svelte
+++ b/email/src/web/components/ThreadList.svelte
@@ -14,7 +14,7 @@
   import Trash2 from "../lib/icons/Trash2.svelte";
   import { flip } from "svelte/animate";
   import { fly, slide } from "svelte/transition";
-  import type { ListFolder, ThreadSummary } from "../../shared/types";
+  import type { ListFolder, SwipeAction as SwipeChoice, ThreadSummary } from "../../shared/types";
   import { api } from "../lib/api";
   import { displayName, fmtTime } from "../lib/format";
   import { router } from "../lib/router.svelte";
@@ -185,25 +185,47 @@
         run: () => restore(thread),
       };
     }
-    if (folder !== "inbox" && folder !== "starred") return undefined;
-    return {
-      label: thread.unread ? "Read" : "Unread",
-      icon: thread.unread ? MarkRead : MarkUnread,
-      tone: "accent",
-      dismiss: false,
-      run: () => toggleRead(thread),
-    };
+    return swipe(session.me?.swipeRight ?? "read", thread);
   }
 
   function swipeLeft(thread: ThreadSummary): SwipeAction | undefined {
     if (folder === "bin") return undefined;
-    return {
-      label: "Bin",
-      icon: Trash2,
-      tone: "danger",
-      dismiss: true,
-      run: () => moveToBin(thread),
-    };
+    return swipe(session.me?.swipeLeft ?? "bin", thread);
+  }
+
+  /** What a swipe set up in Settings does to this row; nothing where it can't apply. */
+  function swipe(choice: SwipeChoice, thread: ThreadSummary): SwipeAction | undefined {
+    switch (choice) {
+      case "read":
+        // Only received mail has a read state.
+        if (folder !== "inbox" && folder !== "starred") return undefined;
+        return {
+          label: thread.unread ? "Read" : "Unread",
+          icon: thread.unread ? MarkRead : MarkUnread,
+          tone: "accent",
+          dismiss: false,
+          run: () => toggleRead(thread),
+        };
+      case "star":
+        return {
+          label: thread.starred ? "Unstar" : "Star",
+          icon: thread.starred ? StarOff : Star,
+          tone: "accent",
+          // Unstarring takes it out of Starred.
+          dismiss: folder === "starred" && thread.starred,
+          run: () => toggleStar(thread),
+        };
+      case "bin":
+        return {
+          label: "Bin",
+          icon: Trash2,
+          tone: "danger",
+          dismiss: true,
+          run: () => moveToBin(thread),
+        };
+      case "none":
+        return undefined;
+    }
   }
 
   function menuItems(thread: ThreadSummary): MenuItem[] {
diff --git a/email/src/web/lib/api.ts b/email/src/web/lib/api.ts
index 21ecffe..5984929 100644
--- a/email/src/web/lib/api.ts
+++ b/email/src/web/lib/api.ts
@@ -7,6 +7,7 @@ import type {
   Me,
   Message,
   Page,
+  Preferences,
   Thread,
   ThreadSummary,
   UserInfo,
@@ -55,6 +56,8 @@ const server = {
   me: () => get<Me>("/api/me"),
   logout: () => post<{ endSession: string | null }>("/auth/logout"),
   setName: (name: string) => patch<{ name: string | null }>("/api/me", { name }),
+  /** Saves the preferences given; returns them all. */
+  setPreferences: (prefs: Partial<Preferences>) => patch<Preferences>("/api/me/preferences", prefs),
 
   threads(folder: ListFolder, mailbox: string | null, cursor?: string | null) {
     const q = new URLSearchParams({ folder });
diff --git a/email/src/web/lib/demo.ts b/email/src/web/lib/demo.ts
index 85a8094..213b7f6 100644
--- a/email/src/web/lib/demo.ts
+++ b/email/src/web/lib/demo.ts
@@ -16,6 +16,7 @@ import type {
   Me,
   Message,
   Page,
+  Preferences,
   Thread,
   ThreadSummary,
   UserInfo,
@@ -144,6 +145,8 @@ export function createDemoApi(): Api {
     { username: "ari", name: "Ari Lane", isAdmin: false, createdAt: Date.now() - 60 * DAY, lastLoginAt: Date.now() - 2 * DAY },
   ];
   const myName = () => users.find((u) => u.username === ME)!.name;
+  // The mascot stands in for an SSO picture.
+  const prefs: Preferences = { usePicture: true, swipeLeft: "bin", swipeRight: "read" };
 
   /** Blob or data: URLs for attachment bytes, by attachment id. */
   const files = new Map<string, string>();
@@ -470,7 +473,14 @@ export function createDemoApi(): Api {
         addresses: addressesOf(ME),
         domains: domains.filter((d) => d.enabled).map((d) => d.name),
         pushPublicKey: null,
+        picture: "/icon.svg",
+        ...prefs,
       })),
+    setPreferences: (changes) =>
+      later(() => {
+        Object.assign(prefs, changes);
+        return { ...prefs };
+      }),
     // Reloading the page starts the demo over.
     logout: () => later(() => ({ endSession: "/demo" as string | null })),
     setName: (name) =>
diff --git a/email/src/web/lib/icons/Star.svelte b/email/src/web/lib/icons/Star.svelte
index b3e24a7..30e2933 100644
--- a/email/src/web/lib/icons/Star.svelte
+++ b/email/src/web/lib/icons/Star.svelte
@@ -5,8 +5,9 @@
 <script lang="ts">
   import Icon from "./Icon.svelte";
 
-  // Filled when `fill` is set (starred), an outline otherwise, as in the app.
-  let { fill = "none", ...props }: { size?: number; class?: string; fill?: string; [key: string]: unknown } = $props();
+  // Filled unless `fill` is "none", as in the app: the list and thread pass it
+  // to show whether a thread is starred; menus and swipes show it filled.
+  let { fill = "currentColor", ...props }: { size?: number; class?: string; fill?: string; [key: string]: unknown } = $props();
 </script>
 
 <!-- Material "star" and "star_outline" -->
diff --git a/email/src/web/pages/Settings.svelte b/email/src/web/pages/Settings.svelte
index 2dcec8b..b03c823 100644
--- a/email/src/web/pages/Settings.svelte
+++ b/email/src/web/pages/Settings.svelte
@@ -10,8 +10,33 @@
   import { api } from "../lib/api";
   import { router } from "../lib/router.svelte";
   import { session } from "../lib/state.svelte";
+  import AccountPicture from "../components/AccountPicture.svelte";
+  import type { Preferences, SwipeAction } from "../../shared/types";
 
   let name = $state(session.me?.name ?? "");
+  let prefsStatus = $state("");
+
+  const swipeLabels: Record<SwipeAction, string> = {
+    none: "Nothing",
+    read: "Mark as read or unread",
+    star: "Star or unstar",
+    bin: "Move to Bin",
+  };
+
+  /** Shows the change straight away, and puts it back if the server says no. */
+  async function savePreferences(changes: Partial<Preferences>) {
+    const me = session.me;
+    if (!me) return;
+    const before: Preferences = { usePicture: me.usePicture, swipeLeft: me.swipeLeft, swipeRight: me.swipeRight };
+    Object.assign(me, changes);
+    prefsStatus = "";
+    try {
+      Object.assign(me, await api.setPreferences(changes));
+    } catch (err) {
+      Object.assign(me, before);
+      prefsStatus = (err as Error).message;
+    }
+  }
   let nameStatus = $state("");
   let subscription = $state<PushSubscription | null>(null);
   let status = $state("");
@@ -80,6 +105,49 @@
     {#if nameStatus}<p class="muted">{nameStatus}</p>{/if}
   </section>
 
+  <section>
+    <h2>Profile picture</h2>
+    <label class="pfp">
+      <AccountPicture size={56} />
+      <span class="grow">
+        <span>Use your account's picture</span>
+        <span class="muted small">
+          {session.me?.picture
+            ? "The one on your Doughmination account. Off shows your initial instead."
+            : "Your Doughmination account has no picture, so your initial shows."}
+        </span>
+      </span>
+      <input
+        type="checkbox"
+        role="switch"
+        class="switch"
+        checked={!!session.me?.usePicture && !!session.me?.picture}
+        disabled={!session.me?.picture}
+        onchange={(e) => savePreferences({ usePicture: e.currentTarget.checked })}
+      />
+    </label>
+  </section>
+
+  <section>
+    <h2>Swipe actions</h2>
+    <p class="muted">What swiping a conversation in the list does, here and in the app. Read and unread only applies to received mail, and in the Bin a swipe right always restores.</p>
+    <div class="swipes">
+      <label class="field">
+        Swipe right
+        <select value={session.me?.swipeRight} onchange={(e) => savePreferences({ swipeRight: e.currentTarget.value as SwipeAction })}>
+          {#each Object.entries(swipeLabels) as [value, label] (value)}<option {value}>{label}</option>{/each}
+        </select>
+      </label>
+      <label class="field">
+        Swipe left
+        <select value={session.me?.swipeLeft} onchange={(e) => savePreferences({ swipeLeft: e.currentTarget.value as SwipeAction })}>
+          {#each Object.entries(swipeLabels) as [value, label] (value)}<option {value}>{label}</option>{/each}
+        </select>
+      </label>
+    </div>
+    {#if prefsStatus}<p class="error">{prefsStatus}</p>{/if}
+  </section>
+
   <section>
     <h2>Your addresses</h2>
     <p class="muted">You receive and can send from each of these.</p>
@@ -176,6 +244,85 @@
     overflow-wrap: anywhere;
   }
 
+  .pfp {
+    display: flex;
+    align-items: center;
+    gap: 1rem;
+    cursor: pointer;
+  }
+
+  .grow {
+    display: flex;
+    flex: 1;
+    flex-direction: column;
+    min-width: 0;
+  }
+
+  .small {
+    font-size: 0.85rem;
+  }
+
+  .swipes {
+    display: grid;
+    grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
+    gap: 0.75rem;
+  }
+
+  .swipes option {
+    background: var(--surface-high);
+  }
+
+  /* Material's switch. */
+  .switch {
+    position: relative;
+    flex-shrink: 0;
+    width: 52px;
+    height: 32px;
+    margin: 0;
+    border: 2px solid var(--outline);
+    border-radius: 999px;
+    background: var(--surface-high);
+    appearance: none;
+    cursor: pointer;
+    transition:
+      background 0.15s ease,
+      border-color 0.15s ease;
+  }
+
+  .switch::before {
+    content: "";
+    position: absolute;
+    top: 50%;
+    left: 6px;
+    width: 16px;
+    height: 16px;
+    border-radius: 50%;
+    background: var(--outline);
+    transform: translateY(-50%);
+    transition:
+      left 0.15s ease,
+      width 0.15s ease,
+      height 0.15s ease,
+      background 0.15s ease;
+  }
+
+  .switch:checked {
+    border-color: var(--accent);
+    background: var(--accent);
+  }
+
+  .switch:checked::before {
+    left: 22px;
+    width: 24px;
+    height: 24px;
+    background: #fff;
+  }
+
+  .switch:disabled {
+    opacity: 0.38;
+    cursor: default;
+  }
+
   .link {
     display: inline-flex;
     align-items: center;
diff --git a/email/src/worker/routes/mail.ts b/email/src/worker/routes/mail.ts
index a0c70a0..2bd8287 100644
--- a/email/src/worker/routes/mail.ts
+++ b/email/src/worker/routes/mail.ts
@@ -1,11 +1,11 @@
 import { Hono } from "hono";
 import { zValidator } from "@hono/zod-validator";
 import { z } from "zod";
-import type { ComposeInput, Me } from "../../shared/types";
+import { SWIPE_ACTIONS, type ComposeInput, type Me } from "../../shared/types";
 import { isAddress } from "../lib/address";
 import type { AppEnv } from "../middleware";
 import { MAX_UPLOAD_BYTES, getAttachment, saveUpload } from "../services/attachments";
-import { addressesFor, displayName, enabledDomains, setDisplayName } from "../services/directory";
+import { addressesFor, enabledDomains, profile, setDisplayName, setPreferences } from "../services/directory";
 import {
   deleteMessage,
   deleteThread,
@@ -59,14 +59,27 @@ function composeError(err: unknown): string {
 export const mail = new Hono<AppEnv>()
   .get("/me", async (c) => {
     const { username, isAdmin } = c.get("user");
-    const [name, addresses, domains] = await Promise.all([
-      displayName(c.env, username),
+    const [prof, addresses, domains] = await Promise.all([
+      profile(c.env, username),
       addressesFor(c.env, username),
       enabledDomains(c.env),
     ]);
-    return c.json<Me>({ username, name: name || null, isAdmin, addresses, domains, pushPublicKey: pushPublicKey(c.env) });
+    return c.json<Me>({ username, ...prof, isAdmin, addresses, domains, pushPublicKey: pushPublicKey(c.env) });
   })
 
+  .patch(
+    "/me/preferences",
+    zValidator(
+      "json",
+      z.object({
+        usePicture: z.boolean().optional(),
+        swipeLeft: z.enum(SWIPE_ACTIONS).optional(),
+        swipeRight: z.enum(SWIPE_ACTIONS).optional(),
+      }),
+    ),
+    async (c) => c.json(await setPreferences(c.env, c.get("user").username, c.req.valid("json"))),
+  )
+
   // An empty name is kept as "" rather than NULL, so the SSO's doesn't come back on the next sign-in.
   .patch("/me", zValidator("json", z.object({ name: z.string().trim().max(100) })), async (c) => {
     const { name } = c.req.valid("json");
diff --git a/email/src/worker/services/directory.ts b/email/src/worker/services/directory.ts
index c87ae47..1ff1c1d 100644
--- a/email/src/worker/services/directory.ts
+++ b/email/src/worker/services/directory.ts
@@ -1,6 +1,7 @@
 import { bareAddress } from "../lib/address";
 import { chunks } from "../lib/chunk";
 import { addressesOf, buildDirectory, route, type AliasRow, type Directory, type DomainRow } from "../lib/routing";
+import { SWIPE_ACTIONS, type Preferences, type SwipeAction } from "../../shared/types";
 import type { TokenSet } from "./oidc";
 
 // Read per request rather than cached per isolate: an admin's change has to
@@ -102,6 +103,58 @@ export async function setDisplayName(env: Env, username: string, name: string |
   await env.DB.prepare("UPDATE users SET display_name = ? WHERE username = ?").bind(name, username).run();
 }
 
+interface ProfileRow {
+  display_name: string | null;
+  picture: string | null;
+  use_picture: number;
+  swipe_left: string;
+  swipe_right: string;
+}
+
+const asSwipe = (v: string): SwipeAction =>
+  (SWIPE_ACTIONS as readonly string[]).includes(v) ? (v as SwipeAction) : "none";
+
+/** The user's name, SSO picture and preferences, for /api/me. */
+export async function profile(
+  env: Env,
+  username: string,
+): Promise<{ name: string | null; picture: string | null } & Preferences> {
+  const row = await env.DB.prepare(
+    "SELECT display_name, picture, use_picture, swipe_left, swipe_right FROM users WHERE username = ?",
+  )
+    .bind(username)
+    .first<ProfileRow>();
+  return {
+    name: row?.display_name || null,
+    picture: row?.picture ?? null,
+    usePicture: (row?.use_picture ?? 1) === 1,
+    swipeLeft: asSwipe(row?.swipe_left ?? "bin"),
+    swipeRight: asSwipe(row?.swipe_right ?? "read"),
+  };
+}
+
+/** Saves whichever preferences are given and returns them all. */
+export async function setPreferences(env: Env, username: string, prefs: Partial<Preferences>): Promise<Preferences> {
+  await env.DB.prepare(
+    "UPDATE users SET use_picture = COALESCE(?, use_picture), swipe_left = COALESCE(?, swipe_left), " +
+      "swipe_right = COALESCE(?, swipe_right) WHERE username = ?",
+  )
+    .bind(
+      prefs.usePicture === undefined ? null : prefs.usePicture ? 1 : 0,
+      prefs.swipeLeft ?? null,
+      prefs.swipeRight ?? null,
+      username,
+    )
+    .run();
+  const { usePicture, swipeLeft, swipeRight } = await profile(env, username);
+  return { usePicture, swipeLeft, swipeRight };
+}
+
+/** A refreshed ID token's picture, for whoever owns the SSO account. */
+export async function setPicture(env: Env, sub: string, picture: string | null): Promise<void> {
+  await env.DB.prepare("UPDATE users SET picture = ? WHERE sub = ?").bind(picture, sub).run();
+}
+
 /**
  * Records a sign-in and returns the username it signs in as.
  *
@@ -125,10 +178,10 @@ export async function recordLogin(env: Env, tokens: TokenSet): Promise<string> {
     .first<{ username: string }>();
   if (known) {
     await env.DB.prepare(
-      "UPDATE users SET last_login_at = ?, is_admin = MAX(is_admin, ?), display_name = COALESCE(display_name, ?) " +
-        "WHERE sub = ?",
+      "UPDATE users SET last_login_at = ?, is_admin = MAX(is_admin, ?), display_name = COALESCE(display_name, ?), " +
+        "picture = ? WHERE sub = ?",
     )
-      .bind(ts, admins.has(known.username.toLowerCase()) ? 1 : 0, tokens.name ?? null, tokens.sub)
+      .bind(ts, admins.has(known.username.toLowerCase()) ? 1 : 0, tokens.name ?? null, tokens.picture ?? null, tokens.sub)
       .run();
     return known.username;
   }
@@ -137,11 +190,11 @@ export async function recordLogin(env: Env, tokens: TokenSet): Promise<string> {
   if (RESERVED.has(username)) throw new ReservedUsername(`${username} is reserved`);
   // One statement, so two sign-ins racing for a name can't both get it.
   const res = await env.DB.prepare(
-    "INSERT INTO users (username, sub, is_admin, display_name, created_at, last_login_at) " +
-      "SELECT ?1, ?2, ?3 AND NOT EXISTS (SELECT 1 FROM users WHERE is_admin = 1), ?4, ?5, ?5 WHERE true " +
+    "INSERT INTO users (username, sub, is_admin, display_name, picture, created_at, last_login_at) " +
+      "SELECT ?1, ?2, ?3 AND NOT EXISTS (SELECT 1 FROM users WHERE is_admin = 1), ?4, ?6, ?5, ?5 WHERE true " +
       "ON CONFLICT DO NOTHING",
   )
-    .bind(username, tokens.sub, admins.has(username) ? 1 : 0, tokens.name ?? null, ts)
+    .bind(username, tokens.sub, admins.has(username) ? 1 : 0, tokens.name ?? null, ts, tokens.picture ?? null)
     .run();
   if (res.meta.changes === 0) {
     throw new AccountConflict(`username ${username} already belongs to a different SSO account`);
diff --git a/email/src/worker/services/oidc.ts b/email/src/worker/services/oidc.ts
index e2531df..2de1200 100644
--- a/email/src/worker/services/oidc.ts
+++ b/email/src/worker/services/oidc.ts
@@ -32,6 +32,7 @@ interface Discovery {
   jwks_uri: string;
   end_session_endpoint?: string;
   revocation_endpoint?: string;
+  userinfo_endpoint?: string;
 }
 
 // Cached per isolate; the issuer never changes without a deploy.
@@ -85,6 +86,29 @@ function pickName(claims: Record<string, unknown>): string | null {
   return name ? name.slice(0, 100) : null;
 }
 
+/** The account's picture, if the SSO gives one. Only https, so it can load anywhere. */
+function pickPicture(claims: Record<string, unknown>): string | null {
+  const raw = typeof claims.picture === "string" ? claims.picture.trim() : "";
+  if (!raw || raw.length > 2000) return null;
+  try {
+    return new URL(raw).protocol === "https:" ? raw : null;
+  } catch {
+    return null;
+  }
+}
+
+/** Some SSOs only put `picture` in userinfo, not the ID token. */
+async function userinfoPicture(cfg: OidcConfig, accessToken: string | undefined): Promise<string | null> {
+  const d = await getDiscovery(cfg);
+  if (!d.userinfo_endpoint || !accessToken) return null;
+  try {
+    const res = await fetch(d.userinfo_endpoint, { headers: { Authorization: `Bearer ${accessToken}` } });
+    return res.ok ? pickPicture((await res.json()) as Record<string, unknown>) : null;
+  } catch {
+    return null;
+  }
+}
+
 function pickUsername(claims: Record<string, unknown>): string {
   const email = typeof claims.email === "string" ? claims.email.split("@")[0] : "";
   const raw =
@@ -153,6 +177,8 @@ export interface TokenSet {
   username: string;
   /** From the ID token; absent when the SSO doesn't share one. */
   name?: string | null;
+  /** From the ID token or userinfo; null when the SSO has none. */
+  picture?: string | null;
   sub: string;
   refreshToken: string | null;
   idToken: string;
@@ -163,7 +189,7 @@ export class GrantRejected extends Error {}
 async function tokenRequest(
   cfg: OidcConfig,
   params: Record<string, string>,
-): Promise<{ id_token?: string; refresh_token?: string }> {
+): Promise<{ id_token?: string; refresh_token?: string; access_token?: string }> {
   const d = await getDiscovery(cfg);
   const res = await fetch(d.token_endpoint, {
     method: "POST",
@@ -187,7 +213,7 @@ async function tokenRequest(
     if (error === "invalid_grant") throw new GrantRejected(text);
     throw new Error(`token request failed (${res.status}): ${text}`);
   }
-  return (await res.json()) as { id_token?: string; refresh_token?: string };
+  return (await res.json()) as { id_token?: string; refresh_token?: string; access_token?: string };
 }
 
 async function verifyIdToken(cfg: OidcConfig, idToken: string): Promise<JWTPayload> {
@@ -218,6 +244,7 @@ export async function completeLogin(env: Env, code: string, pending: Pending): P
   return {
     username,
     name: pickName(payload as Record<string, unknown>),
+    picture: pickPicture(payload as Record<string, unknown>) ?? (await userinfoPicture(cfg, tokens.access_token)),
     sub: String(payload.sub || ""),
     refreshToken: tokens.refresh_token ?? null,
     idToken: tokens.id_token,
@@ -232,11 +259,14 @@ export async function completeLogin(env: Env, code: string, pending: Pending): P
 export async function refreshSession(
   env: Env,
   refreshToken: string,
-): Promise<{ sub: string; refreshToken: string | null; idToken: string | null }> {
+): Promise<{ sub: string; refreshToken: string | null; idToken: string | null; picture?: string | null }> {
   const cfg = config(env);
   const tokens = await tokenRequest(cfg, { grant_type: "refresh_token", refresh_token: refreshToken });
   const payload = tokens.id_token ? await verifyIdToken(cfg, tokens.id_token) : null;
+  // Only when the new ID token says: one without the claim isn't news that it's gone.
+  const claims = payload as Record<string, unknown> | null;
   return {
+    ...(claims && "picture" in claims ? { picture: pickPicture(claims) } : {}),
     sub: payload ? String(payload.sub || "") : "",
     refreshToken: tokens.refresh_token ?? null,
     idToken: tokens.id_token ?? null,
diff --git a/email/src/worker/services/sessions.ts b/email/src/worker/services/sessions.ts
index f444230..b47f36d 100644
--- a/email/src/worker/services/sessions.ts
+++ b/email/src/worker/services/sessions.ts
@@ -1,3 +1,4 @@
+import { setPicture } from "./directory";
 import { GrantRejected, refreshSession, type Pending, type TokenSet } from "./oidc";
 
 // Sessions live in D1 so they can be ended from the server side, and each one
@@ -117,6 +118,8 @@ async function revalidate(env: Env, token: string, session: Session): Promise<Se
         await deleteSession(env, token);
         return null;
       }
+      // The account's picture may have changed on the SSO since sign-in.
+      if (fresh.picture !== undefined) await setPicture(env, session.sub, fresh.picture);
       const at = now();
       const updated: Session = {
         ...session,
diff --git a/email/test/profile.test.ts b/email/test/profile.test.ts
new file mode 100644
index 0000000..c3025a7
--- /dev/null
+++ b/email/test/profile.test.ts
@@ -0,0 +1,57 @@
+import { env, exports } from "cloudflare:workers";
+import { describe, expect, it } from "vitest";
+import type { Me } from "../src/shared/types";
+import { recordLogin } from "../src/worker/services/directory";
+import { sessionKey } from "../src/worker/services/sessions";
+
+const ORIGIN = "https://mail.test";
+
+async function session(username: string, sub: string): Promise<string> {
+  const token = crypto.randomUUID();
+  const ts = Math.floor(Date.now() / 1000);
+  const data = { username, sub, refreshToken: null, idToken: null, createdAt: ts, verifiedAt: ts, checkedAt: ts };
+  await env.DB.prepare("INSERT INTO sessions (token, data, expires_at) VALUES (?, ?, ?)")
+    .bind(await sessionKey(token), JSON.stringify(data), ts + 3600)
+    .run();
+  return token;
+}
+
+const call = (token: string, path: string, init: RequestInit = {}) =>
+  exports.default.fetch(
+    new Request(`${ORIGIN}${path}`, {
+      ...init,
+      headers: { cookie: `session=${token}`, origin: ORIGIN, "content-type": "application/json" },
+    }),
+  );
+
+describe("the SSO picture and preferences", () => {
+  it("keeps the picture from each sign-in, and starts with the old swipes", async () => {
+    await recordLogin(env, { username: "pat", sub: "sub-pat", picture: "https://sso.test/a.png", refreshToken: null, idToken: "x" });
+    const token = await session("pat", "sub-pat");
+    let me = (await (await call(token, "/api/me")).json()) as Me;
+    expect(me).toMatchObject({ picture: "https://sso.test/a.png", usePicture: true, swipeLeft: "bin", swipeRight: "read" });
+
+    // A later sign-in with no picture clears it.
+    await recordLogin(env, { username: "pat", sub: "sub-pat", picture: null, refreshToken: null, idToken: "x" });
+    me = (await (await call(token, "/api/me")).json()) as Me;
+    expect(me.picture).toBeNull();
+  });
+
+  it("saves only the preferences given", async () => {
+    await recordLogin(env, { username: "lee", sub: "sub-lee", refreshToken: null, idToken: "x" });
+    const token = await session("lee", "sub-lee");
+    const res = await call(token, "/api/me/preferences", { method: "PATCH", body: JSON.stringify({ swipeLeft: "star" }) });
+    expect(await res.json()).toEqual({ usePicture: true, swipeLeft: "star", swipeRight: "read" });
+
+    await call(token, "/api/me/preferences", { method: "PATCH", body: JSON.stringify({ usePicture: false, swipeRight: "none" }) });
+    const me = (await (await call(token, "/api/me")).json()) as Me;
+    expect(me).toMatchObject({ usePicture: false, swipeLeft: "star", swipeRight: "none" });
+  });
+
+  it("refuses a swipe it doesn't know", async () => {
+    await recordLogin(env, { username: "kai", sub: "sub-kai", refreshToken: null, idToken: "x" });
+    const token = await session("kai", "sub-kai");
+    const res = await call(token, "/api/me/preferences", { method: "PATCH", body: JSON.stringify({ swipeLeft: "archive" }) });
+    expect(res.status).toBe(400);
+  });
+});