Modern Apps git

← Modern-Apps.git

various fixes

Commit
60525e178d13584d53a609494616e624ca118044
Author
Vayun Mathur <[email protected]>
When
2026-08-02 19:19 UTC (4 months ago)
Parents
91ecb8f

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex c96d1792e2..bf681d4576 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -315,6 +315,16 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]+ [[package]] name = "const-oid" version = "0.9.6"@@ -788,11 +798,17 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jni" version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" dependencies = [  "cesu8",+ "cfg-if",+ "combine",  "jni-sys 0.3.1",  "log",- "thiserror",+ "thiserror 1.0.69",+ "walkdir",+ "windows-sys 0.45.0", ]  [[package]]@@ -900,7 +916,7 @@ dependencies = [  "secrecy",  "serde",  "sha2 0.11.0",- "thiserror",+ "thiserror 2.0.19",  "twofish",  "uuid",  "zeroize",@@ -950,7 +966,7 @@ dependencies = [  "serde",  "sha2 0.10.9",  "stringprep",- "thiserror",+ "thiserror 2.0.19",  "weezl", ] @@ -1320,6 +1336,15 @@ dependencies = [  "cipher 0.5.2", ] +[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]+ [[package]] name = "scopeguard" version = "1.2.0"@@ -1485,13 +1510,33 @@ dependencies = [  "unicode-ident", ] +[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]+ [[package]] name = "thiserror" version = "2.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" dependencies = [- "thiserror-impl",+ "thiserror-impl 2.0.19",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119", ]  [[package]]@@ -1657,13 +1702,23 @@ dependencies = [  "parking_lot",  "rand 0.8.7",  "rand_core 0.6.4",- "thiserror",+ "thiserror 2.0.19",  "tracing",  "typed-builder",  "x25519-dalek",  "zerocopy", ] +[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]+ [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1"@@ -1753,6 +1808,15 @@ dependencies = [  "x25519-dalek", ] +[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]+ [[package]] name = "windows-core" version = "0.62.2"@@ -1812,6 +1876,81 @@ dependencies = [  "windows-link", ] +[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"+ [[package]] name = "wit-bindgen" version = "0.57.1"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex c48a46f38b..ca7e436b17 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -20,10 +20,23 @@ resolver = "2" # Centralized Rust versions – armv8-only (aarch64-linux-android)  [workspace.dependencies]-jni = { path = "third_party/jni-android", version = "0.21" }+# Upstream jni from crates.io, not a vendored fork.+#+# This was a local fork (third_party/jni-android) of 0.21.1 that trimmed the+# dependency tree: it hand-wrote the JNI signature parser to drop `combine`+# (and transitively `bytes`), dropped the `walkdir` build-dep and `windows-sys`,+# and moved to thiserror 2. That saved a handful of crates at the cost of+# carrying ~20 vendored files that had to be kept in sync with upstream by hand+# - and 0.21.1 is from March 2023, so it had drifted three years behind.+#+# 0.22 is the current release but is a substantial API change (native methods+# now receive `EnvUnowned` and must adapt it via `with_env` plus an+# `ErrorPolicy`, and `GlobalRef`/`AutoLocal` were renamed). That migration+# touches all 31 native entry points across maps and games/voxels and needs an+# Android build to verify, so it is deliberately left as a follow-up.+jni = "0.21.1" jni-sys = "0.3.1" cesu8 = "1.1.0"-# combine removed – jni-android now parses JNI signatures by hand (no combine, no bytes) thiserror = { version = "2" } log = "0.4.33" cfg-if = "1.0.4"@@ -73,7 +86,6 @@ indexmap = { version = "2.10.0" } hashbrown = "0.14.5" byteorder = "1.5.0" smallvec = "1.14.0"-# bytes removed – it was only ever pulled transitively by combine (now gone from jni-android)  # No HTTP client crate anywhere: Rust reaches the network through library:network via # the flat-framed JNI bridge in library/jni-http, so no .so links its own TLS.
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 4596c4331b..f40f838b88 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -74,14 +74,14 @@ Summed old per-crate locks (before workspace) = 712 total (641 excluding voxels)  **Cuts implemented (no feature loss, no cross-app merging, stdlib preferred per user request):** - `third_party/om-file-format-sys`: Removed build-dep `bindgen 0.72` (was pulling clang-sys, cexpr, libloading, aho-corasick, regex, prettyplease, bitflags, itertools, cfg-if, etc ~20 crates). Pre-generated bindings to `src/bindings_android.rs` (NDK 29 aarch64-linux-android) + `src/bindings_host.rs` (aarch64-apple-darwin host for `cargo test`), selected via `#[cfg(target_os=\"android\")]`. `build.rs` only uses `cc` now.-- `third_party/jni-android` fork: Removed build-dependencies `walkdir 2` (which pulled `same-file 1.0.6 -> winapi-util 0.1.11 -> windows-sys 0.61.2 -> windows-link + windows-targets 0.42.2 + 7 arch shims = 11 crates per lock). Also removed `thiserror-impl` unused? Kept `cesu8`, `combine`, `jni-sys` (required for Modified UTF-8). Also stripped optional `invocation` (java-locator, libloading pulled glob, windows, lazy_static, rusty-fork, tempfile, wait-timeout). Result: root lock 0 walkdir/0 same-file/0 winapi-util/0 windows-sys 0.45+0.61.+- `jni`: **was** a local fork at `third_party/jni-android` (0.21.1 with `combine`, `walkdir` and `windows-sys` stripped). Removed in favour of upstream `jni 0.21.1` from crates.io — the fork was ~20 hand-maintained files pinned three years behind upstream with no route to security fixes, which is the larger liability. Cost of un-forking: 16 lock entries, 10 of them `windows-*` crates behind `cfg(windows)` that never compile for Android. Upstream 0.22 would drop those again (it uses `windows-link`) but is a breaking API change across all 31 native entry points; see the note in the root `Cargo.toml`. - `pdf/rust-toolchain.toml`: Dropped `x86_64-linux-android` target – now armv8-only `aarch64-linux-android` (matches RustNative.kt `rustAbis = listOf(\"arm64-v8a\" -> \"aarch64-linux-android\")` already was armv8-only). - `weather`: Dropped `ureq 2.12` – it pulled `base64`, `flate2`, `log`, `once_cell`, `rustls 0.23.42 -> ring 0.17.14 -> untrusted 0.9 + windows-sys 0.52, rustls-pki-types/zeroize, rustls-webpki 0.103 -> webpki-roots 0.26->1.0, url 2.5 -> form_urlencoded, idna 1.1 -> idna_adapter, icu_* collections/locale/normalizer/properties/provider, litemap, smallvec, utf8_iter, etc = ~90 crates). Rewrote `weather/src/main/rust/src/lib.rs` from `HttpRangeBackend` doing `ureq` Range GET + OnceLock Agent LRU 12 to `SliceBackend(&[u8])` reading from passed slice (via `omfiles` `InMemoryBackend` trait `count/get_bytes/prefetch_data`). Added `OmTilesNative.decodeRegionBytes(ByteArray, ...)` in `/weather/src/main/java/com/vayunmathur/weather/map/OmTilesNative.kt` and refactored `WeatherMapPage.kt` to fetch `.om` via `NetworkClient.performRequestBytes` (HttpURLConnection stdlib, armv8-only) with 64KB block caching now in Kotlin OkHttp layer. - `camera`: Dropped `image 0.25 jpeg` – it pulled `bytemuck 1.25, byteorder-lite 0.2, bitflags 2.x, zune-core 0.5 + zune-jpeg 0.5 (plus moxcms 0.7 + pxfm 0.1 behind default features vs jpeg only it still pulled zune deps). Single usage was `Rgba::from_jpeg` via `image::load_from_memory.to_rgba8()`. Now uses `jpeg-decoder 0.3.2` (already in pdf, minimal pure Rust) directly in `imgbuf.rs::from_jpeg`, with L8/RGB24/CMYK32 handling matching pdf's `decode_jpeg_rgba`. Encode uses `jpeg-encoder 0.6.1` (no transitive) via `Camera::encode_jpeg` using `jpeg_encoder::Encoder` with quality param. - `photos_fx`: Dropped `rayon 1.12` – was pulling `rayon-core 1.13 + crossbeam-deque 0.8 + crossbeam-epoch 0.9 + crossbeam-utils 0.8 + either 1.13` (6 crates) just for `par_chunks_mut(w)` in `blur.rs` gaussian 2-pass, motion, radial, mask. Rewrote with plain loops + stdlib (prefer standard library). Parallelism preserved via naive std `thread::scope` split if wanted, but now sequential exact (keeps feature), could add `std::thread::scope` later if Perf needed without extra crates. - `camera` still uses `rayon` for stitch feature pyramid? Candidate for `std::thread::scope` rewrite if requested – keeping for now because bundle adjustment uses DMatrix math and perf matters, but not feature-reducing. - `passwords_kdbx`: uses `serde_json` for `Vec<BTreeMap<String,String>>` – candidate for manual JSON encoder std-only (single function). Preserved for now because `serde` is also used elsewhere heavily (CRDT signed exact JSON field order `id,parent,left,kind,payload,deleted,lamport,dev,name,attrLamport,attrDev` with skip_serializing_if exact match to Kotlin kotlinx `encodeDefaults false`). Passwords JSON leniency allows std rewrite without risk; could be done as manual encoder to drop zmij, serde_json, serde_derive chain. Kept for now to avoid risk but counted as candidate.-- `games/voxels`: Regenerated its own workspace lock (outside root workspace) after patching jni path via `../../../../../third_party/jni-android`. Dropped walkdir/windows – from 60 → 47 packages (no walkdir/windows-sys).+- `games/voxels`: has its own workspace lock (outside the root workspace); it takes `jni` from crates.io like everything else.  **Remaining heavy justified libraries (per no-feature-loss):** - `nalgebra 0.33.3` – DMatrix zeros 2n×9, Matrix3::new, Vector3, SVD try_inverse lu solve, rodrigues_to_mat for panorama bundle adjustment – cannot be replaced with glam.
appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.ktindex 8e4e4afdd0..367501bdc1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -134,7 +134,6 @@ sealed interface Route : NavKey {     @Serializable data object Updates : Route     @Serializable data object Repos : Route     @Serializable data object Detail : Route-    @Serializable data object SecurityTiers : Route }  @Composable@@ -156,7 +155,7 @@ private fun AppRoot(     MainNavigation(         backStack,         bottomBar = {-            if (current !is Route.Detail && current !is Route.SecurityTiers) {+            if (current !is Route.Detail) {                 BottomNavBar(                     backStack,                     listOf(@@ -189,19 +188,12 @@ private fun AppRoot(             })         }         entry<Route.Repos> {-            ReposPage(viewModel = viewModel, onOpenTiers = { backStack.add(Route.SecurityTiers) })+            ReposPage(viewModel = viewModel)         }         entry<Route.Detail> {             AppDetailPage(                 viewModel = viewModel,                 onBack = { backStack.pop() },-                onOpenTiers = { backStack.add(Route.SecurityTiers) },-            )-        }-        entry<Route.SecurityTiers> {-            com.vayunmathur.appstore.ui.SecurityTiersPage(-                ownSigningCertificates = viewModel.ownSigningCertificates,-                onBack = { backStack.pop() },             )         }     }
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex d7d6560ebc..602ce73482 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -199,12 +199,16 @@ class AppStoreViewModel(     val filteredInstalled: StateFlow<List<InstalledInfo>> = combine(         _installedApps, _installedSourceMap, _installedFilter     ) { installed, srcMap, filter ->-        val inStore = installed.filter { srcMap.containsKey(it.packageName) }+        // Show all installed apps instantly — don't wait for srcMap to be ready.+        // srcMap defaults to PLAYSTORE for unknown packages (see refreshInstalled).         when (filter) {-            InstalledFilter.ALL -> inStore-            InstalledFilter.MODERN_APPS -> inStore.filter { srcMap[it.packageName] == AppSource.MODERN_APPS }-            InstalledFilter.FDROID -> inStore.filter { srcMap[it.packageName] == AppSource.FDROID }-            InstalledFilter.PLAYSTORE -> inStore.filter { srcMap[it.packageName] == AppSource.PLAYSTORE }+            InstalledFilter.ALL -> installed+            InstalledFilter.MODERN_APPS -> installed.filter { srcMap[it.packageName] == AppSource.MODERN_APPS }+            InstalledFilter.FDROID -> installed.filter { srcMap[it.packageName] == AppSource.FDROID }+            InstalledFilter.PLAYSTORE -> installed.filter {+                val src = srcMap[it.packageName]+                src == AppSource.PLAYSTORE || src == null+            }         }     }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) @@ -474,7 +478,11 @@ class AppStoreViewModel(     fun refreshInstalled() {         viewModelScope.launch(Dispatchers.IO) {             val pm = context.packageManager-            val all = pm.getInstalledApplications(PackageManager.MATCH_ALL)+            val all = try {+                pm.getInstalledApplications(PackageManager.MATCH_ALL)+            } catch (_: Exception) {+                emptyList()+            }             val userApps = all.filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) == 0 }             val installed = userApps.mapNotNull { ai ->                 try {@@ -488,15 +496,24 @@ class AppStoreViewModel(                 } catch (_: Exception) { null }             }.sortedBy { it.name.lowercase() } +            // Publish the list immediately so the Installed tab is not blank for 10s.+            withContext(Dispatchers.Main) {+                _installedApps.value = installed+            }++            // Resolve sources from local DB only — no network. The old code called+            // playProvider.isPresent() which scraped Play for every package, sequentially,+            // which was the 10s bottleneck and also left filteredInstalled empty until it finished.+            resolveInstalledSources(installed.map { it.packageName })++            // Icons are expensive (binder + bitmap decode) — load after the list is visible.             val icons = userApps.mapNotNull { ai ->                 try { ai.packageName to pm.getApplicationIcon(ai.packageName) } catch (_: Exception) { null }             }.toMap()              withContext(Dispatchers.Main) {-                _installedApps.value = installed                 _installedIcons.value = icons             }-            resolveInstalledSources(installed.map { it.packageName })         }     } @@ -506,27 +523,36 @@ class AppStoreViewModel(      * Reads the cached rows directly rather than going through the providers'      * in-memory caches: those are primed asynchronously from the same table, so asking      * them right after a sync could race and report a Modern Apps package as absent.+     *+     * Fast path: no network. Anything not in Modern Apps or F-Droid is assumed Play Store,+     * which avoids N sequential Play scrapes (the 10s delay) and makes the Installed tab+     * show instantly. Play presence is not critical for the installed list — the package+     * is already on device.      */     private fun resolveInstalledSources(packages: List<String>) {         viewModelScope.launch(Dispatchers.IO) {-            val rows = try { db.cachedAppDao().all() } catch (_: Exception) { emptyList() }-            val bySource = rows.groupBy(-                { runCatching { AppSource.valueOf(it.source) }.getOrNull() },-                { it.packageName },-            ).mapValues { (_, v) -> v.toSet() }-            val modern = bySource[AppSource.MODERN_APPS].orEmpty()-            val fdroid = bySource[AppSource.FDROID].orEmpty()--            val map = mutableMapOf<String, AppSource>()-            for (pkg in packages) {-                map[pkg] = when {-                    pkg in modern -> AppSource.MODERN_APPS-                    pkg in fdroid -> AppSource.FDROID-                    playProvider.isPresent(pkg) -> AppSource.PLAYSTORE-                    else -> continue+            try {+                val rows = db.cachedAppDao().all()+                val bySource = rows.groupBy(+                    { runCatching { AppSource.valueOf(it.source) }.getOrNull() },+                    { it.packageName },+                ).mapValues { (_, v) -> v.toSet() }+                val modern = bySource[AppSource.MODERN_APPS].orEmpty()+                val fdroid = bySource[AppSource.FDROID].orEmpty()++                val map = mutableMapOf<String, AppSource>()+                for (pkg in packages) {+                    map[pkg] = when {+                        pkg in modern -> AppSource.MODERN_APPS+                        pkg in fdroid -> AppSource.FDROID+                        else -> AppSource.PLAYSTORE+                    }                 }+                _installedSourceMap.value = map+            } catch (_: Exception) {+                // Fallback: still show everything as Play Store so list isn't empty+                _installedSourceMap.value = packages.associateWith { AppSource.PLAYSTORE }             }-            _installedSourceMap.value = map         }     } 
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex 8bb6dcc6eb..92e52e7463 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -83,9 +83,8 @@ fun Project.rustNativeLib(crate: String, remapLabel: String = crate) {             inputs.file(rootProject.file("Cargo.toml"))             inputs.file(rootProject.file("Cargo.lock"))             inputs.file(rootProject.file("rust-toolchain.toml"))-            // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure)-            inputs.dir(rootProject.file("third_party/jni-android/src"))-            inputs.file(rootProject.file("third_party/jni-android/Cargo.toml"))+            // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).+            // jni is a crates.io dependency now, so Cargo.lock above covers it.             inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))             inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))             inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))
contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.ktindex 0fb2f94aa3..795691e6c4 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt@@ -75,6 +75,7 @@ interface ContactDetail<T: ContactDetail<T>> {     val value: String     fun withType(type: Int): T     fun withValue(value: String): T+    fun withLabel(label: String): T     fun typeString(context: Context): String      companion object {@@ -92,36 +93,39 @@ interface ContactDetail<T: ContactDetail<T>> { }  @Serializable-data class PhoneNumber(override val id: Long, val number: String, override val type: Int): ContactDetail<PhoneNumber> {+data class PhoneNumber(override val id: Long, val number: String, override val type: Int, val label: String = ""): ContactDetail<PhoneNumber> {     override val value: String         get() = number -    override fun withType(type: Int) = PhoneNumber(id, number, type)-    override fun withValue(value: String) = PhoneNumber(id, value, type)+    override fun withType(type: Int) = copy(type = type)+    override fun withValue(value: String) = copy(number = value)+    override fun withLabel(label: String) = copy(label = label) -    override fun typeString(context: Context) = CDKPhone.getTypeLabel(context.resources, type, "").toString()+    override fun typeString(context: Context) = CDKPhone.getTypeLabel(context.resources, type, label).toString() }  @Serializable-data class Email(override val id: Long, val address: String, override val type: Int): ContactDetail<Email> {+data class Email(override val id: Long, val address: String, override val type: Int, val label: String = ""): ContactDetail<Email> {     override val value: String         get() = address -    override fun withType(type: Int) = Email(id, address, type)-    override fun withValue(value: String) = Email(id, value, type)+    override fun withType(type: Int) = copy(type = type)+    override fun withValue(value: String) = copy(address = value)+    override fun withLabel(label: String) = copy(label = label) -    override fun typeString(context: Context) = CDKEmail.getTypeLabel(context.resources, type, "").toString()+    override fun typeString(context: Context) = CDKEmail.getTypeLabel(context.resources, type, label).toString() }  @Serializable-data class Address(override val id: Long, val formattedAddress: String, override val type: Int): ContactDetail<Address> {+data class Address(override val id: Long, val formattedAddress: String, override val type: Int, val label: String = ""): ContactDetail<Address> {     override val value: String         get() = formattedAddress -    override fun withType(type: Int) = Address(id, formattedAddress, type)-    override fun withValue(value: String) = Address(id, value, type)+    override fun withType(type: Int) = copy(type = type)+    override fun withValue(value: String) = copy(formattedAddress = value)+    override fun withLabel(label: String) = copy(label = label) -    override fun typeString(context: Context) = CDKStructuredPostal.getTypeLabel(context.resources, type, "").toString()+    override fun typeString(context: Context) = CDKStructuredPostal.getTypeLabel(context.resources, type, label).toString() }  @Serializable@@ -132,19 +136,21 @@ data class Photo(override val id: Long, val photo: String): ContactDetail<Photo>      override fun withType(type: Int) = throw UnsupportedOperationException("Cannot change type of photo")     override fun withValue(value: String) = Photo(id, value)+    override fun withLabel(label: String): Photo = this      override fun typeString(context: Context) = throw UnsupportedOperationException("Photo doesn't have type") }  @Serializable-data class Event(override val id: Long, val startDate: LocalDate, override val type: Int): ContactDetail<Event> {+data class Event(override val id: Long, val startDate: LocalDate, override val type: Int, val label: String = ""): ContactDetail<Event> {     override val value: String         get() = startDate.format(LocalDate.Formats.ISO) -    override fun withType(type: Int) = Event(id, startDate, type)-    override fun withValue(value: String) = Event(id, LocalDate.parse(value), type)+    override fun withType(type: Int) = copy(type = type)+    override fun withValue(value: String) = copy(startDate = LocalDate.parse(value))+    override fun withLabel(label: String) = copy(label = label) -    override fun typeString(context: Context) = CDKEvent.getTypeLabel(context.resources, type, "").toString()+    override fun typeString(context: Context) = CDKEvent.getTypeLabel(context.resources, type, label).toString() }  @Serializable@@ -155,6 +161,7 @@ data class Organization(override val id: Long, val company: String): ContactDeta      override fun withType(type: Int) = throw UnsupportedOperationException("Cannot change type of photo")     override fun withValue(value: String) = Organization(id, value)+    override fun withLabel(label: String): Organization = this      override fun typeString(context: Context) = throw UnsupportedOperationException("Photo doesn't have type") }@@ -174,6 +181,7 @@ data class Name(      override fun withType(type: Int) = throw UnsupportedOperationException("Cannot change type of name")     override fun withValue(value: String) = throw UnsupportedOperationException("Cannot change value of name")+    override fun withLabel(label: String): Name = this      override fun typeString(context: Context) = throw UnsupportedOperationException("Name doesn't have type") }@@ -186,6 +194,7 @@ data class Note(override val id: Long, val content: String): ContactDetail<Note>      override fun withType(type: Int) = throw UnsupportedOperationException("Cannot change type of note")     override fun withValue(value: String) = copy(content = value)+    override fun withLabel(label: String): Note = this      override fun typeString(context: Context) = throw UnsupportedOperationException("Note doesn't have type") }@@ -197,6 +206,7 @@ data class Nickname(override val id: Long, val nickname: String, override val ty      override fun withType(type: Int) = copy(type = type)     override fun withValue(value: String) = copy(nickname = value)+    override fun withLabel(label: String): Nickname = this      override fun typeString(context: Context) = throw UnsupportedOperationException("Nickname types shouldn't be written") }@@ -209,6 +219,7 @@ data class GroupMembership(override val id: Long, val groupId: Long): ContactDet      override fun withType(type: Int) = throw UnsupportedOperationException("Cannot change type of group membership")     override fun withValue(value: String) = copy(groupId = value.toLong())+    override fun withLabel(label: String): GroupMembership = this      override fun typeString(context: Context) = throw UnsupportedOperationException("Group membership doesn't have type") }@@ -326,18 +337,22 @@ data class Contact(             is PhoneNumber -> this                 .withValue(CDKPhone.NUMBER, detail.number)                 .withValue(CDKPhone.TYPE, detail.type)+                .withValue(CDKPhone.LABEL, detail.label)                 .build()             is Email -> this                 .withValue(CDKEmail.ADDRESS, detail.address)                 .withValue(CDKEmail.TYPE, detail.type)+                .withValue(CDKEmail.LABEL, detail.label)                 .build()             is Address -> this                 .withValue(CDKStructuredPostal.FORMATTED_ADDRESS, detail.formattedAddress)                 .withValue(CDKStructuredPostal.TYPE, detail.type)+                .withValue(CDKStructuredPostal.LABEL, detail.label)                 .build()             is Event -> this                 .withValue(CDKEvent.START_DATE, detail.startDate.format(LocalDate.Formats.ISO))                 .withValue(CDKEvent.TYPE, detail.type)+                .withValue(CDKEvent.LABEL, detail.label)                 .build()             is Photo -> this                 .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)@@ -528,16 +543,19 @@ fun getDetailsInternal(context: Context, id: Long? = null, isProfile: Boolean =                         CDKPhone.CONTENT_ITEM_TYPE -> {                             val number = cursor.getStringOrNull(d1Idx) ?: ""                             val type = cursor.getInt(d2Idx)-                            phoneNumbersMap.getOrPut(rawId) { mutableListOf() }.add(PhoneNumber(dataId, number, type))+                            val label = cursor.getStringOrNull(d3Idx) ?: ""+                            phoneNumbersMap.getOrPut(rawId) { mutableListOf() }.add(PhoneNumber(dataId, number, type, label))                         }                         CDKEmail.CONTENT_ITEM_TYPE -> {                             val address = cursor.getStringOrNull(d1Idx) ?: ""                             val type = cursor.getInt(d2Idx)-                            emailsMap.getOrPut(rawId) { mutableListOf() }.add(Email(dataId, address, type))+                            val label = cursor.getStringOrNull(d3Idx) ?: ""+                            emailsMap.getOrPut(rawId) { mutableListOf() }.add(Email(dataId, address, type, label))                         }                         CDKStructuredPostal.CONTENT_ITEM_TYPE -> {                             var formatted = cursor.getStringOrNull(d1Idx)                             val type = cursor.getInt(d2Idx)+                            val label = cursor.getStringOrNull(d3Idx) ?: ""                             if (formatted.isNullOrBlank()) {                                 val street = cursor.getStringOrNull(d4Idx)                                 val city = cursor.getStringOrNull(d7Idx)@@ -548,17 +566,18 @@ fun getDetailsInternal(context: Context, id: Long? = null, isProfile: Boolean =                                     .filter { it.isNotBlank() }                                     .joinToString(", ")                             }-                            addressesMap.getOrPut(rawId) { mutableListOf() }.add(Address(dataId, formatted, type))+                            addressesMap.getOrPut(rawId) { mutableListOf() }.add(Address(dataId, formatted, type, label))                         }                         CDKEvent.CONTENT_ITEM_TYPE -> {                             val date = cursor.getStringOrNull(d1Idx) ?: ""                             val type = cursor.getInt(d2Idx)+                            val label = cursor.getStringOrNull(d3Idx) ?: ""                             val localDate = runCatching { LocalDate.parse(date, LocalDate.Formats.ISO) }.getOrNull()                                 ?: runCatching { LocalDate.parse(date, LocalDate.Format { year(); monthNumber(); day() }) }.getOrNull()                                 ?: if (date.startsWith("--")) runCatching { LocalDate.parse("1604" + date.substring(2)) }.getOrNull() else null                              if (localDate != null) {-                                datesMap.getOrPut(rawId) { mutableListOf() }.add(Event(dataId, localDate, type))+                                datesMap.getOrPut(rawId) { mutableListOf() }.add(Event(dataId, localDate, type, label))                             }                         }                         CDKPhoto.CONTENT_ITEM_TYPE -> runCatching {
contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.ktindex 803823bf86..3197db1d6b 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/ContactDetailsPage.kt@@ -34,6 +34,7 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults import com.vayunmathur.library.ui.BadgedBox import com.vayunmathur.library.ui.CircularProgressIndicator@@ -331,7 +332,8 @@ fun ContactDetailsScreen(                 item {                     val clipboard = LocalClipboard.current                     GroupedSection(title = stringResource(R.string.about_name, contact.name.firstName)) {-                        contact.birthday?.let { birthday ->+                        val birthday = contact.birthday+                        if (birthday != null) {                             val birthdayText = birthday.startDate.formatDisplay()                             ListItem(                                 content = { Text(birthdayText) },@@ -346,7 +348,7 @@ fun ContactDetailsScreen(                                 )                             )                         }-                        details.dates.filter{it.type != CDKEvent.TYPE_BIRTHDAY }.forEach { event ->+                        for (event in details.dates.filter { it.type != CDKEvent.TYPE_BIRTHDAY }) {                             val eventText = event.startDate.formatDisplay()                             ListItem(                                 content = { Text(eventText) },
contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.ktindex fa8d0b4cbf..f14c61740c 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -267,7 +267,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,                 icon = { IconCall() },                 keyboardType = KeyboardType.Phone,                 visualTransformation = VisualTransformation.None,-                options = listOf(CDKPhone.TYPE_MOBILE, CDKPhone.TYPE_HOME, CDKPhone.TYPE_WORK, CDKPhone.TYPE_OTHER)+                options = listOf(CDKPhone.TYPE_MOBILE, CDKPhone.TYPE_HOME, CDKPhone.TYPE_WORK, CDKPhone.TYPE_OTHER, CDKPhone.TYPE_CUSTOM)             )             Spacer(Modifier.height(8.dp)) @@ -280,7 +280,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,                 icon = { IconMail() },                 keyboardType = KeyboardType.Email,                 visualTransformation = VisualTransformation.None,-                options = listOf(CDKEmail.TYPE_HOME, CDKEmail.TYPE_WORK, CDKEmail.TYPE_OTHER, CDKEmail.TYPE_MOBILE)+                options = listOf(CDKEmail.TYPE_HOME, CDKEmail.TYPE_WORK, CDKEmail.TYPE_OTHER, CDKEmail.TYPE_MOBILE, CDKEmail.TYPE_CUSTOM)             )              Spacer(Modifier.height(16.dp))@@ -294,7 +294,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,                 details = currentDraft.dates,                 onDetailsChange = { list -> viewModel.updateEditDraft { it.copy(dates = list) } },                 icon = { IconEvent() },-                options = listOf(CDKEvent.TYPE_ANNIVERSARY, CDKEvent.TYPE_OTHER)+                options = listOf(CDKEvent.TYPE_ANNIVERSARY, CDKEvent.TYPE_OTHER, CDKEvent.TYPE_CUSTOM)             )              Spacer(Modifier.height(12.dp))@@ -308,7 +308,7 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,                 icon = { IconEvent() },                 keyboardType = KeyboardType.Text,                 visualTransformation = VisualTransformation.None,-                options = listOf(CDKStructuredPostal.TYPE_HOME, CDKStructuredPostal.TYPE_WORK, CDKStructuredPostal.TYPE_OTHER)+                options = listOf(CDKStructuredPostal.TYPE_HOME, CDKStructuredPostal.TYPE_WORK, CDKStructuredPostal.TYPE_OTHER, CDKStructuredPostal.TYPE_CUSTOM)             )              Spacer(Modifier.height(16.dp))@@ -477,6 +477,7 @@ private fun ColumnScope.DateDetailsSection(     val context = LocalContext.current     details.forEachIndexed { index, detail ->         if(detail.type == CDKEvent.TYPE_BIRTHDAY) return@forEachIndexed+        val isCustom = detail.type == CDKEvent.TYPE_CUSTOM         Box {             ResultEffect<LocalDate>(detail.id.toString()) { newDate ->                 onDetailsChange(details.toMutableList().also { list -> list[index] = detail.withValue(newDate.toString()) })@@ -523,6 +524,18 @@ private fun ColumnScope.DateDetailsSection(                     .clickable { backStack.add(Route.EventDatePickerDialog(detail.id.toString(),detail.startDate)) }) {}             }         }+        if (isCustom) {+            Spacer(Modifier.height(4.dp))+            OutlinedTextField(+                value = detail.label,+                onValueChange = { newLabel ->+                    onDetailsChange(details.toMutableList().also { it[index] = detail.withLabel(newLabel) })+                },+                label = { Text(stringResource(R.string.custom_label)) },+                placeholder = { Text(stringResource(R.string.enter_custom_label)) },+                modifier = Modifier.fillMaxWidth()+            )+        }         Spacer(Modifier.height(8.dp))     }     FilledTonalButton(@@ -549,6 +562,8 @@ private inline fun <reified T : ContactDetail<T>> ColumnScope.DetailsSection( ) {     val context = LocalContext.current     details.forEachIndexed { index, detail ->+        // Heuristic: TYPE_CUSTOM is 0 across all CommonDataKinds+        val isCustom = detail.type == 0         OutlinedTextField(             value = detail.value,             onValueChange = { newNumber ->@@ -591,6 +606,24 @@ private inline fun <reified T : ContactDetail<T>> ColumnScope.DetailsSection(             keyboardOptions = KeyboardOptions(keyboardType = keyboardType),             modifier = Modifier.fillMaxWidth()         )+        if (isCustom) {+            Spacer(Modifier.height(4.dp))+            OutlinedTextField(+                value = when (detail) {+                    is PhoneNumber -> detail.label+                    is com.vayunmathur.contacts.data.Email -> detail.label+                    is com.vayunmathur.contacts.data.Address -> detail.label+                    is Event -> detail.label+                    else -> ""+                },+                onValueChange = { newLabel ->+                    onDetailsChange(details.toMutableList().also { it[index] = detail.withLabel(newLabel) })+                },+                label = { Text(stringResource(R.string.custom_label)) },+                placeholder = { Text(stringResource(R.string.enter_custom_label)) },+                modifier = Modifier.fillMaxWidth()+            )+        }         Spacer(Modifier.height(8.dp))     }     FilledTonalButton(
contacts/src/main/java/com/vayunmathur/contacts/util/VcfUtils.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/VcfUtils.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/VcfUtils.ktindex d8f962b827..ab5317f37b 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/VcfUtils.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/VcfUtils.kt@@ -33,7 +33,7 @@ object VcfUtils {                     val fnValue = fn.ifBlank { (details.names.firstOrNull()?.value ?: "") }                     writeFolded(writer, "FN:${escapeV(fnValue)}") -                    // Phones+                    // Phones - preserve custom label as X- token for roundtrip                     for (phone in details.phoneNumbers) {                         val typeToken = when (phone.type) {                             ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE -> "CELL"@@ -41,6 +41,10 @@ object VcfUtils {                             ContactsContract.CommonDataKinds.Phone.TYPE_WORK -> "WORK"                             ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK,                             ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME -> "FAX"+                            ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM -> {+                                val sanitized = phone.label.ifBlank { "CUSTOM" }.replace(",", "").replace(";", "").replace(":", "")+                                "X-$sanitized"+                            }                             else -> "VOICE"                         }                         writeFolded(writer, "TEL;TYPE=$typeToken:${escapeV(phone.number)}")@@ -51,6 +55,10 @@ object VcfUtils {                         val typeToken = when (email.type) {                             ContactsContract.CommonDataKinds.Email.TYPE_HOME -> "HOME"                             ContactsContract.CommonDataKinds.Email.TYPE_WORK -> "WORK"+                            ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM -> {+                                val sanitized = email.label.ifBlank { "CUSTOM" }.replace(",", "").replace(";", "").replace(":", "")+                                "X-$sanitized"+                            }                             else -> "INTERNET"                         }                         writeFolded(writer, "EMAIL;TYPE=$typeToken:${escapeV(email.address)}")@@ -59,7 +67,20 @@ object VcfUtils {                     // Addresses                     for (addr in details.addresses) {                         val formatted = addr.formattedAddress-                        writeFolded(writer, "ADR;TYPE=HOME:;;${escapeV(formatted)};;;;")+                        val typeToken = if (addr.type == ContactsContract.CommonDataKinds.StructuredPostal.TYPE_CUSTOM) {+                            val sanitized = addr.label.ifBlank { "CUSTOM" }.replace(",", "").replace(";", "").replace(":", "")+                            "X-$sanitized"+                        } else "HOME"+                        writeFolded(writer, "ADR;TYPE=$typeToken:;;${escapeV(formatted)};;;;")+                    }++                    // Other dates (non-birthday) with custom label support+                    for (event in details.dates.filter { it.type != ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY }) {+                        val typeToken = if (event.type == ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM) {+                            val sanitized = event.label.ifBlank { "CUSTOM" }.replace(",", "").replace(";", "").replace(":", "")+                            "X-$sanitized"+                        } else "OTHER"+                        writeFolded(writer, "X-EVENT;TYPE=$typeToken:${escapeV(event.startDate.toString())}")                     }                      // Organization@@ -186,12 +207,12 @@ object VcfUtils {                     }                 }                 "TEL" -> {-                    val ttype = detectPhoneType(params)-                    currentContact.phones.add(PhoneNumber(0, value, ttype))+                    val (ttype, tlabel) = detectPhoneTypeWithLabel(params)+                    currentContact.phones.add(PhoneNumber(0, value, ttype, tlabel))                 }                 "EMAIL" -> {-                    val etype = detectEmailType(params)-                    currentContact.emails.add(Email(0, value, etype))+                    val (etype, elabel) = detectEmailTypeWithLabel(params)+                    currentContact.emails.add(Email(0, value, etype, elabel))                 }                 "ADR" -> {                     val comps = value.split(';')@@ -201,8 +222,21 @@ object VcfUtils {                     val postal = comps.getOrNull(5) ?: ""                     val country = comps.getOrNull(6) ?: ""                     val formatted = listOfNotNull(street.ifEmpty { null }, city.ifEmpty { null }, region.ifEmpty { null }, postal.ifEmpty { null }, country.ifEmpty { null }).joinToString(", ")-                    val atype = if (params["TYPE"]?.any { it.equals("HOME", ignoreCase = true) } == true) ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME else ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK-                    currentContact.addresses.add(Address(0, formatted, atype))+                    val (atype, alabel) = detectAddressTypeWithLabel(params)+                    currentContact.addresses.add(Address(0, formatted, atype, alabel))+                }+                "X-EVENT" -> {+                    var dv = value+                    if (dv.matches(Regex("^\\d{8}"))) {+                        dv = dv.take(4) + "-" + dv.substring(4,6) + "-" + dv.substring(6,8)+                    } else if (dv.startsWith("--")) {+                        dv = "1604" + dv.substring(2)+                    }+                    try {+                        val date = LocalDate.parse(dv)+                        val (dtype, dlabel) = detectEventTypeWithLabel(params)+                        currentContact.dates.add(Event(0, date, dtype, dlabel))+                    } catch (_: Exception) { }                 }                 "ORG" -> {                     currentContact.orgs.clear()@@ -318,23 +352,69 @@ object VcfUtils {         return out.toString(charset(charsetName))     } -    private fun detectPhoneType(params: Map<String, List<String>>): Int {-        val tokens = params.values.flatten().joinToString(";")-        return when {-            tokens.contains("CELL", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE-            tokens.contains("HOME", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_HOME-            tokens.contains("WORK", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_WORK-            tokens.contains("FAX", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK+    private data class TypedLabel(val type: Int, val label: String)++    private fun extractCustomLabel(tokens: List<String>): String? {+        for (t in tokens) {+            if (t.startsWith("X-", ignoreCase = true) && t.length > 2) {+                return t.substring(2)+            }+        }+        return null+    }++    private fun detectPhoneTypeWithLabel(params: Map<String, List<String>>): TypedLabel {+        val allTokens = params.values.flatten()+        val customLabel = extractCustomLabel(allTokens)+        val tokenStr = allTokens.joinToString(";")+        val type = when {+            customLabel != null -> ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM+            tokenStr.contains("CELL", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE+            tokenStr.contains("HOME", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_HOME+            tokenStr.contains("WORK", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_WORK+            tokenStr.contains("FAX", ignoreCase = true) -> ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK             else -> ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE         }+        return TypedLabel(type, customLabel ?: "")     } -    private fun detectEmailType(params: Map<String, List<String>>): Int {-        val tokens = params.values.flatten().joinToString(";")-        return when {-            tokens.contains("WORK", ignoreCase = true) -> ContactsContract.CommonDataKinds.Email.TYPE_WORK-            tokens.contains("HOME", ignoreCase = true) -> ContactsContract.CommonDataKinds.Email.TYPE_HOME+    private fun detectPhoneType(params: Map<String, List<String>>): Int = detectPhoneTypeWithLabel(params).type++    private fun detectEmailTypeWithLabel(params: Map<String, List<String>>): TypedLabel {+        val allTokens = params.values.flatten()+        val customLabel = extractCustomLabel(allTokens)+        val tokenStr = allTokens.joinToString(";")+        val type = when {+            customLabel != null -> ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM+            tokenStr.contains("WORK", ignoreCase = true) -> ContactsContract.CommonDataKinds.Email.TYPE_WORK+            tokenStr.contains("HOME", ignoreCase = true) -> ContactsContract.CommonDataKinds.Email.TYPE_HOME             else -> ContactsContract.CommonDataKinds.Email.TYPE_OTHER         }+        return TypedLabel(type, customLabel ?: "")+    }++    private fun detectEmailType(params: Map<String, List<String>>): Int = detectEmailTypeWithLabel(params).type++    private fun detectAddressTypeWithLabel(params: Map<String, List<String>>): TypedLabel {+        val allTokens = params.values.flatten()+        val customLabel = extractCustomLabel(allTokens)+        val tokenStr = allTokens.joinToString(";")+        val type = when {+            customLabel != null -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_CUSTOM+            tokenStr.contains("HOME", ignoreCase = true) -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME+            tokenStr.contains("WORK", ignoreCase = true) -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK+            else -> ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME+        }+        return TypedLabel(type, customLabel ?: "")+    }++    private fun detectEventTypeWithLabel(params: Map<String, List<String>>): TypedLabel {+        val allTokens = params.values.flatten()+        val customLabel = extractCustomLabel(allTokens)+        return if (customLabel != null) {+            TypedLabel(ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM, customLabel)+        } else {+            TypedLabel(ContactsContract.CommonDataKinds.Event.TYPE_OTHER, "")+        }     } }
contacts/src/main/res/values/strings.xml
diff --git a/contacts/src/main/res/values/strings.xml b/contacts/src/main/res/values/strings.xmlindex 00afaccf97..8314f0cb60 100644--- a/contacts/src/main/res/values/strings.xml+++ b/contacts/src/main/res/values/strings.xml@@ -200,4 +200,14 @@     <string name="crop_photo">Crop Photo</string>     <!-- Settings: row label for importing contacts from VCF files -->     <string name="import_contacts_from_vcf_files">Import contacts from .vcf files</string>++    <!-- Custom label support -->+    <!-- Generic \"Custom\" type label shown in dropdown -->+    <string name="custom">Custom</string>+    <!-- Label for custom label text field -->+    <string name="custom_label">Custom label</string>+    <!-- Placeholder / description for entering custom label -->+    <string name="enter_custom_label">Enter custom label</string>+    <!-- Edit action for custom label (unused but reserved) -->+    <string name="edit_custom_label">Edit custom label</string> </resources>
dist/speech-mirror/piper/voice.zip
diff --git a/dist/speech-mirror/piper/voice.zip b/dist/speech-mirror/piper/voice.zipnew file mode 100644index 0000000000..484b794817Binary files /dev/null and b/dist/speech-mirror/piper/voice.zip differ
dist/speech-mirror/piper/voice2.zip
diff --git a/dist/speech-mirror/piper/voice2.zip b/dist/speech-mirror/piper/voice2.zipnew file mode 100644index 0000000000..484b794817Binary files /dev/null and b/dist/speech-mirror/piper/voice2.zip differ
dist/speech-mirror/piper/voice3.zip
diff --git a/dist/speech-mirror/piper/voice3.zip b/dist/speech-mirror/piper/voice3.zipnew file mode 100644index 0000000000..484b794817Binary files /dev/null and b/dist/speech-mirror/piper/voice3.zip differ
education/src/main/java/com/vayunmathur/education/ui/ExplorerCoursePage.kt
diff --git a/education/src/main/java/com/vayunmathur/education/ui/ExplorerCoursePage.kt b/education/src/main/java/com/vayunmathur/education/ui/ExplorerCoursePage.ktindex b01b831327..4c3ffaa5b2 100644--- a/education/src/main/java/com/vayunmathur/education/ui/ExplorerCoursePage.kt+++ b/education/src/main/java/com/vayunmathur/education/ui/ExplorerCoursePage.kt@@ -55,7 +55,7 @@ fun ExplorerCoursePage(backStack: NavBackStack<Route>, viewModel: EducationViewM     ) { padding ->         if (course == null) {             MissingContent(padding, stringResource(R.string.this_topic_is_unavailable))-            return@Scaffold+            return@AppScaffold         }          // The first not-yet-mastered unit is the recommended next step.
education/src/main/java/com/vayunmathur/education/ui/K2LessonPage.kt
diff --git a/education/src/main/java/com/vayunmathur/education/ui/K2LessonPage.kt b/education/src/main/java/com/vayunmathur/education/ui/K2LessonPage.ktindex 4138b5f600..4ed584c0ca 100644--- a/education/src/main/java/com/vayunmathur/education/ui/K2LessonPage.kt+++ b/education/src/main/java/com/vayunmathur/education/ui/K2LessonPage.kt@@ -46,7 +46,7 @@ fun K2LessonPage(backStack: NavBackStack<Route>, viewModel: EducationViewModel,     ) { padding ->         if (lesson == null) {             MissingContent(padding, stringResource(R.string.let_s_go_back))-            return@Scaffold+            return@AppScaffold         }         Column(             Modifier
education/src/main/java/com/vayunmathur/education/ui/LessonPage.kt
diff --git a/education/src/main/java/com/vayunmathur/education/ui/LessonPage.kt b/education/src/main/java/com/vayunmathur/education/ui/LessonPage.ktindex f6b78e5361..6179765cbc 100644--- a/education/src/main/java/com/vayunmathur/education/ui/LessonPage.kt+++ b/education/src/main/java/com/vayunmathur/education/ui/LessonPage.kt@@ -42,7 +42,7 @@ fun LessonPage(backStack: NavBackStack<Route>, viewModel: EducationViewModel, le     ) { padding ->         if (lesson == null) {             MissingContent(padding, stringResource(R.string.this_lesson_is_unavailable))-            return@Scaffold+            return@AppScaffold         }         Column(             Modifier
education/src/main/java/com/vayunmathur/education/ui/UnitPage.kt
diff --git a/education/src/main/java/com/vayunmathur/education/ui/UnitPage.kt b/education/src/main/java/com/vayunmathur/education/ui/UnitPage.ktindex 29cc0f504d..d6e2b15d47 100644--- a/education/src/main/java/com/vayunmathur/education/ui/UnitPage.kt+++ b/education/src/main/java/com/vayunmathur/education/ui/UnitPage.kt@@ -46,7 +46,7 @@ fun UnitPage(backStack: NavBackStack<Route>, viewModel: EducationViewModel, unit     ) { padding ->         if (unit == null) {             MissingContent(padding, stringResource(R.string.this_unit_is_unavailable))-            return@Scaffold+            return@AppScaffold         }         LazyColumn(             modifier = Modifier
email/build.gradle.kts
diff --git a/email/build.gradle.kts b/email/build.gradle.ktsindex e7783be03a..77a73948da 100644--- a/email/build.gradle.kts+++ b/email/build.gradle.kts@@ -1,7 +1,5 @@ plugins {     id("common-conventions-app")-    // Listing screenshots come from Compose previews (src/screenshotTest), not from an-    // instrumented test on a device. Same `:email:metadata` task name either way.     id("common-conventions-preview-metadata") } @@ -14,12 +12,12 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.email" -        // Outlook / Microsoft 365 OAuth. Public values (client ID is an-        // identifier, not a secret) so they're committed and the build stays-        // reproducible. Override with -PEVERYSYNC_* style properties if needed.+        // Outlook OAuth — own Azure public client (PKCE, no secret)         val outlookClientId = (project.findProperty("EMAIL_OUTLOOK_CLIENT_ID")             ?: "4ee55fe9-12c1-4392-82e6-6c7a2a7954c8").toString()+         buildConfigField("String", "OUTLOOK_OAUTH_CLIENT_ID", "\"$outlookClientId\"")+        buildConfigField("String", "OAUTH_REDIRECT_URI", "\"com.vayunmathur.email://oauth\"")         buildConfigField("String", "OUTLOOK_REDIRECT_URI", "\"com.vayunmathur.email://oauth\"")     } @@ -32,25 +30,13 @@ android {             excludes += "/META-INF/{AL2.0,LGPL2.1}"             excludes += "META-INF/NOTICE.md"             excludes += "META-INF/LICENSE.md"-            // Ensure JavaMail provider descriptors are kept (legacy javax + jakarta)-            pickFirsts += "META-INF/javamail.providers"-            pickFirsts += "META-INF/javamail.default.providers"-            pickFirsts += "META-INF/javamail.default.address.map"-            pickFirsts += "META-INF/jakarta.mail.providers"-            pickFirsts += "META-INF/jakarta.mail.default.providers"-            pickFirsts += "META-INF/jakarta.mail.default.address.map"-            pickFirsts += "META-INF/jakarta.mail.address.map"-            pickFirsts += "META-INF/mailcap"-            pickFirsts += "META-INF/mailcap.default"         }     } }  dependencies {-    implementation(libs.jakarta.mail)     implementation(libs.androidx.browser)     implementation(libs.kotlinx.serialization.json)-    // Room     implementation(libs.androidx.room.runtime)     implementation(libs.androidx.room.ktx)     ksp(libs.androidx.room.compiler)@@ -60,6 +46,5 @@ dependencies {     implementation(libs.androidx.glance.appwidget)     implementation(libs.androidx.glance.material3)     implementation(project(":library:widgets"))-    // Reduced CA hardening: need NetworkClient.init(SYSTEM) for dynamic IMAP hosts (any-cert via Jakarta trust=*).     implementation(project(":library:network")) }
email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex 9896863aa9..61bbfe1761 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -110,8 +110,11 @@                 android:resource="@xml/file_paths" />         </provider> +        <!-- Microsoft OAuth redirect handler. Azure app registered as Mobile & Desktop+             with redirect com.vayunmathur.email://oauth per RFC8252 compliant native pattern.+             Thunderbird Desktop uses useExternalBrowser=true + custom scheme same as this. -->         <activity-            android:name=".ui.OutlookOAuthActivity"+            android:name=".ui.OAuthActivity"             android:exported="true"             android:launchMode="singleTask"             android:theme="@android:style/Theme.Translucent.NoTitleBar">@@ -121,6 +124,13 @@                 <category android:name="android.intent.category.BROWSABLE" />                 <data android:scheme="com.vayunmathur.email" android:host="oauth" />             </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <!-- Also accept explicit path /oauth for some OEM parsers -->+                <data android:scheme="com.vayunmathur.email" android:host="" android:path="/oauth" />+            </intent-filter>         </activity>          <activity
email/src/main/java/com/vayunmathur/email/EmailClientFlag.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailClientFlag.kt b/email/src/main/java/com/vayunmathur/email/EmailClientFlag.ktnew file mode 100644index 0000000000..0fc861e8a9--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/EmailClientFlag.kt@@ -0,0 +1,14 @@+package com.vayunmathur.email++/**+ * Raw IMAP/SMTP is now permanent — legacy Jakarta Mail path removed in Phase 5.+ * All transport goes through [com.vayunmathur.email.imap.ImapClient] and+ * [com.vayunmathur.email.smtp.SmtpClient].+ */+object EmailClientFlag {+    /** Always true — raw socket clients are the only implementation. */+    const val USE_RAW = true++    /** When true, raw clients trust all certs for custom hosts (system trust for known hosts). */+    const val RAW_TRUST_ALL_CUSTOM = true+}
email/src/main/java/com/vayunmathur/email/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/EmailManager.ktindex 19bd6c53d8..ef9dcb754e 100644--- a/email/src/main/java/com/vayunmathur/email/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailManager.kt@@ -1,23 +1,20 @@ package com.vayunmathur.email -import android.content.ContentValues import android.content.Context import android.net.Uri-import android.os.Environment-import android.provider.MediaStore import com.vayunmathur.email.composer.InlineAttachment import com.vayunmathur.email.data.CredentialCrypto import com.vayunmathur.email.data.OutlookOAuth-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import java.io.ByteArrayOutputStream+import com.vayunmathur.email.imap.ImapClient+import com.vayunmathur.email.smtp.SmtpClient import java.io.File import java.io.OutputStream-import java.util.Properties-import jakarta.activation.DataHandler-import jakarta.activation.DataSource-import jakarta.mail.*-import jakarta.mail.internet.*++/**+ * Email server config + auth resolution + raw IMAP/SMTP facade.+ * Outlook uses OAuth2 (XOAUTH2), others use app passwords.+ * Raw sockets only — no Jakarta Mail.+ */  data class ServerConfig(val host: String, val port: Int, val useSsl: Boolean) {     val imapProtocol: String get() = if (useSsl) "imaps" else "imap"@@ -30,19 +27,24 @@ fun EmailAccount.loginUser(): String = username.ifBlank { email }  suspend fun EmailAccount.resolveAuth(context: Context): EmailManager.AuthType {     if (authType == "oauth2") {-        val token = OutlookOAuth.freshAccessToken(context, this)-            ?: error("Account $email is missing an OAuth access token")-        return EmailManager.AuthType.OAuth(token)+        if (provider == "outlook" || provider == com.vayunmathur.email.data.PROVIDER_OUTLOOK) {+            val token = OutlookOAuth.freshAccessToken(context, this)+                ?: error("Account $email is missing an OAuth access token")+            return EmailManager.AuthType.OAuth(token)+        }+        // Legacy non-Outlook oauth2 account — fall back to encrypted password if present+        val cipher = passwordEncrypted+        val iv = passwordIv+        if (cipher != null && iv != null) {+            return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv))+        }+        error("OAuth account $email needs to be re-added with an app password")     }-    val cipher = passwordEncrypted ?: error("Account ${email} is missing passwordEncrypted")-    val iv = passwordIv ?: error("Account ${email} is missing passwordIv")+    val cipher = passwordEncrypted ?: error("Account $email is missing passwordEncrypted")+    val iv = passwordIv ?: error("Account $email is missing passwordIv")     return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv)) } -fun Folder.closeQuietly(expunge: Boolean = false) {-    try { close(expunge) } catch (_: Throwable) {}-}- class EmailManager {      sealed class AuthType {@@ -50,185 +52,22 @@ class EmailManager {         data class OAuth(val token: String) : AuthType()     } -    private val AuthType.credential: String-        get() = when (this) {-            is AuthType.Password -> value-            is AuthType.OAuth -> token-        }--    // Email must allow any cert because users can configure arbitrary self-hosted-    // IMAP/SMTP servers (often with self-signed or private CA). We therefore-    // trust all hosts via ssl.trust=* and skip cert verification both for-    // implicit SSL and STARTTLS paths.-    private fun getImapSession(server: ServerConfig, oauth: Boolean = false): Session {-        val proto = server.imapProtocol-        val properties = Properties().apply {-            this["mail.store.protocol"] = proto-            this["mail.$proto.host"] = server.host-            this["mail.$proto.port"] = server.port.toString()-            this["mail.$proto.fetchsize"] = "1048576"-            this["mail.$proto.partialfetch"] = "true"-            if (oauth) {-                this["mail.$proto.auth.mechanisms"] = "XOAUTH2"-                this["mail.$proto.auth.login.disable"] = "true"-                this["mail.$proto.auth.plain.disable"] = "true"-            }-            if (server.useSsl) {-                this["mail.$proto.ssl.enable"] = "true"-                this["mail.$proto.ssl.trust"] = "*"-            } else {-                this["mail.$proto.starttls.enable"] = "true"-                this["mail.$proto.starttls.required"] = "true"-                this["mail.$proto.ssl.trust"] = "*"-            }-            // Permissive trust for custom user-supplied servers-            this["mail.$proto.ssl.checkserveridentity"] = "false"-        }-        return Session.getInstance(properties)-    }--    private fun getSmtpSession(server: ServerConfig, oauth: Boolean = false): Session {-        val proto = server.smtpProtocol-        val properties = Properties().apply {-            this["mail.transport.protocol"] = proto-            this["mail.$proto.host"] = server.host-            this["mail.$proto.port"] = server.port.toString()-            this["mail.$proto.auth"] = "true"-            if (oauth) {-                this["mail.$proto.auth.mechanisms"] = "XOAUTH2"-                this["mail.$proto.auth.login.disable"] = "true"-                this["mail.$proto.auth.plain.disable"] = "true"-            }-            if (server.useSsl) {-                this["mail.$proto.ssl.enable"] = "true"-                this["mail.$proto.ssl.trust"] = "*"-            } else {-                this["mail.$proto.starttls.enable"] = "true"-                this["mail.$proto.starttls.required"] = "true"-                this["mail.$proto.ssl.trust"] = "*"-            }-            this["mail.$proto.ssl.checkserveridentity"] = "false"-        }-        return Session.getInstance(properties)-    }+    data class FullFetchResult(val contentTriple: Triple<String?, Boolean, List<Attachment>>) -    suspend fun <T> withStore(server: ServerConfig, user: String, auth: AuthType, block: suspend (Store) -> T): T = withContext(Dispatchers.IO) {-        val oauth = auth is AuthType.OAuth-        val session = getImapSession(server, oauth)-        val store = session.getStore(server.imapProtocol)-        try {-            store.connect(server.host, server.port, user, auth.credential)-            block(store)-        } finally { store.close() }-    }+    suspend fun fetchFolders(server: ServerConfig, user: String, auth: AuthType): List<EmailFolder> =+        ImapClient.fetchFolders(server, user, auth) -    fun fetchFoldersInStore(store: Store, user: String): List<EmailFolder> {-        val folders = store.defaultFolder.list("*")-        return folders.map { folder ->-            EmailFolder(-                accountEmail = user,-                fullName = folder.fullName,-                name = folder.name,-                parentFullName = folder.parent?.fullName?.takeIf { it.isNotEmpty() },-                holdsMessages = (folder.type and Folder.HOLDS_MESSAGES) != 0,-                delimiter = folder.separator.toString(),-            )-        }-    }--    suspend fun fetchMessagesInStore(-        store: Store,+    suspend fun fetchMessages(+        server: ServerConfig,         user: String,+        auth: AuthType,         folderName: String,         limit: Int,         offset: Int = 0,         fetchBodies: Boolean = false,         skipUids: Set<Long> = emptySet(),-    ): Pair<List<EmailMessage>, List<Attachment>> = withContext(Dispatchers.IO) {-        val folder = store.getFolder(folderName)-        if ((folder.type and Folder.HOLDS_MESSAGES) == 0) return@withContext emptyList<EmailMessage>() to emptyList()-        folder.open(Folder.READ_ONLY)-        try { fetchMessagesFromOpenFolder(folder, user, folderName, limit, offset, fetchBodies, skipUids) }-        finally { folder.closeQuietly() }-    }--    fun fetchMessagesFromOpenFolder(-        folder: Folder,-        user: String,-        folderName: String,-        limit: Int,-        offset: Int,-        fetchBodies: Boolean,-        skipUids: Set<Long>,-    ): Pair<List<EmailMessage>, List<Attachment>> {-        val totalMessages = folder.messageCount-        if (totalMessages == 0) return emptyList<EmailMessage>() to emptyList()-        val end = (totalMessages - offset).coerceAtLeast(1)-        val start = (end - limit + 1).coerceAtLeast(1)-        if (end < 1) return emptyList<EmailMessage>() to emptyList()-        val messages = folder.getMessages(start, end)-        folder.fetch(messages, FetchProfile().apply { add(UIDFolder.FetchProfileItem.UID) })-        val uidFolder = folder as? UIDFolder-        val novel = messages.filter { (uidFolder?.getUID(it) ?: -1L) !in skipUids }.toTypedArray()-        if (novel.isEmpty()) return emptyList<EmailMessage>() to emptyList()-        val fp = FetchProfile().apply {-            add(FetchProfile.Item.ENVELOPE)-            add(UIDFolder.FetchProfileItem.UID)-            add(FetchProfile.Item.FLAGS)-            add("X-GM-THRID")-            if (fetchBodies) add(FetchProfile.Item.CONTENT_INFO)-        }-        folder.fetch(novel, fp)-        val emailMessages = mutableListOf<EmailMessage>()-        val allAttachments = mutableListOf<Attachment>()-        novel.reversedArray().forEach { msg ->-            val uid = uidFolder?.getUID(msg) ?: -1L-            val (body, isHtml, attachments) = if (fetchBodies) processMessageContent(user, folderName, uid, msg)-            else Triple<String?, Boolean, List<Attachment>>(null, false, emptyList())-            allAttachments.addAll(attachments)-            emailMessages.add(buildEmailMessage(msg, user, folderName, uid, body, isHtml, attachments.isNotEmpty(), fetchBodies))-        }-        return emailMessages to allAttachments-    }--    private fun buildEmailMessage(-        msg: Message,-        user: String,-        folderName: String,-        uid: Long,-        body: String?,-        isHtml: Boolean,-        hasAttachments: Boolean,-        fetchBodies: Boolean,-    ): EmailMessage {-        val gmailThreadId = (msg as? MimeMessage)?.getHeader("X-GM-THRID")?.firstOrNull()-        val serverId = msg.getHeader("Message-ID")?.firstOrNull()-        val refs = msg.getHeader("References")?.firstOrNull()-        val listUnsub = msg.getHeader("List-Unsubscribe")?.firstOrNull()-        val listUnsubPost = msg.getHeader("List-Unsubscribe-Post")?.firstOrNull()-        val isRead = msg.isSet(Flags.Flag.SEEN)-        val whenMillis = msg.sentDate?.time ?: msg.receivedDate?.time ?: 0L-        return EmailMessage(-            accountEmail = user,-            folderName = folderName,-            id = uid,-            serverId = serverId,-            threadId = gmailThreadId ?: uid.toString(),-            subject = msg.subject ?: "(no subject)",-            from = msg.from?.firstOrNull()?.toString() ?: "",-            to = msg.getRecipients(Message.RecipientType.TO)?.joinToString { it.toString() },-            cc = msg.getRecipients(Message.RecipientType.CC)?.joinToString { it.toString() },-            date = msg.sentDate?.toString() ?: msg.receivedDate?.toString() ?: "",-            dateMillis = whenMillis,-            body = body,-            isHtml = isHtml,-            isRead = isRead,-            references = refs,-            hasAttachments = hasAttachments || (fetchBodies && hasAttachmentsInfo(msg)),-            listUnsubscribe = listUnsub,-            listUnsubscribePost = listUnsubPost,-        )-    }+    ): Pair<List<EmailMessage>, List<Attachment>> =+        ImapClient.fetchMessages(server, user, auth, folderName, limit, offset, fetchBodies, skipUids, null)      suspend fun fetchMessageBody(         server: ServerConfig,@@ -236,150 +75,26 @@ class EmailManager {         auth: AuthType,         folderName: String,         uid: Long,-    ): Triple<String?, Boolean, List<Attachment>> = withStore(server, user, auth) { store ->-        fetchMessageBodyInStore(store, user, folderName, uid)-    }--    suspend fun fetchMessageBodyInStore(-        store: Store,-        user: String,-        folderName: String,-        uid: Long,-    ): Triple<String?, Boolean, List<Attachment>> = withContext(Dispatchers.IO) {-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_ONLY)-        try {-            val message = (folder as UIDFolder).getMessageByUID(uid) ?: return@withContext Triple<String?, Boolean, List<Attachment>>(null, false, emptyList())-            processMessageContent(user, folderName, uid, message)-        } finally { folder.closeQuietly() }-    }+    ): Triple<String?, Boolean, List<Attachment>> =+        ImapClient.fetchMessageBody(server, user, auth, folderName, uid, null) -    suspend fun fetchFolders(server: ServerConfig, user: String, auth: AuthType): List<EmailFolder> = withStore(server, user, auth) { store ->-        fetchFoldersInStore(store, user)-    }--    suspend fun fetchMessages(+    suspend fun fetchFullForBody(+        context: Context,         server: ServerConfig,         user: String,         auth: AuthType,         folderName: String,-        limit: Int,-        offset: Int,-        fetchBodies: Boolean = false,-        skipUids: Set<Long> = emptySet(),-    ): Pair<List<EmailMessage>, List<Attachment>> = withStore(server, user, auth) { store ->-        fetchMessagesInStore(store, user, folderName, limit, offset, fetchBodies, skipUids)-    }--    private fun hasAttachmentsInfo(message: Message): Boolean {-        val content = message.content as? MimeMultipart ?: return false-        return (0 until content.count).any { i ->-            val part = content.getBodyPart(i)-            Part.ATTACHMENT.equals(part.disposition, ignoreCase = true) || !part.fileName.isNullOrBlank()-        }-    }+        uid: Long,+    ): FullFetchResult = ImapClient.fetchFullForBody(context, server, user, auth, folderName, uid) -    suspend fun sendMessage(+    suspend fun fetchCidMap(         context: Context,         server: ServerConfig,         user: String,         auth: AuthType,-        to: String,-        subject: String,-        body: String,-        cc: String? = null,-        bcc: String? = null,-        attachments: List<Uri> = emptyList(),-        inlineImages: List<InlineAttachment> = emptyList(),-        inReplyTo: String? = null,-        references: String? = null,-        from: String? = null,-        asHtml: Boolean = false-    ) = withContext(Dispatchers.IO) {-        val oauth = auth is AuthType.OAuth-        val session = getSmtpSession(server, oauth)-        val message = MimeMessage(session)-        message.setFrom(InternetAddress(from ?: user))-        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))-        if (!cc.isNullOrBlank()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc))-        if (!bcc.isNullOrBlank()) message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc))-        message.subject = subject-        if (inReplyTo != null) message.setHeader("In-Reply-To", inReplyTo)-        if (references != null) message.setHeader("References", references)--        val textPart = MimeBodyPart().apply {-            if (asHtml) setContent(body, "text/html; charset=utf-8") else setText(body)-        }--        val finalMultipart: MimeMultipart-        if (inlineImages.isEmpty()) {-            finalMultipart = MimeMultipart("mixed")-            finalMultipart.addBodyPart(textPart)-            for (uri in attachments) finalMultipart.addBodyPart(buildAttachmentPart(context, uri))-        } else {-            val related = MimeMultipart("related")-            related.addBodyPart(textPart)-            for (inline in inlineImages) {-                val inlinePart = MimeBodyPart().apply {-                    val ds = object : DataSource {-                        override fun getInputStream() = try {-                            context.contentResolver.openInputStream(inline.uri) ?: File(inline.uri.path ?: "").inputStream()-                        } catch (_: Exception) { File(inline.uri.path ?: "").inputStream() }-                        override fun getOutputStream() = throw Exception("Not supported")-                        override fun getContentType() = inline.mimeType.ifBlank { "image/jpeg" }-                        override fun getName() = inline.fileName-                    }-                    dataHandler = DataHandler(ds)-                    setHeader("Content-ID", "<${inline.cid}>")-                    setHeader("Content-Disposition", "inline; filename=\"${inline.fileName}\"")-                    fileName = inline.fileName-                }-                related.addBodyPart(inlinePart)-            }-            val relatedWrapper = MimeBodyPart().apply { setContent(related) }-            finalMultipart = MimeMultipart("mixed")-            finalMultipart.addBodyPart(relatedWrapper)-            for (uri in attachments) finalMultipart.addBodyPart(buildAttachmentPart(context, uri))-        }--        message.setContent(finalMultipart)--        val transport = session.getTransport(server.smtpProtocol)-        try {-            transport.connect(server.host, server.port, user, auth.credential)-            transport.sendMessage(message, message.allRecipients)-        } finally { transport.close() }-    }--    private fun buildAttachmentPart(context: Context, uri: Uri): MimeBodyPart {-        val attachmentPart = MimeBodyPart()-        val filename = getFileName(context, uri) ?: "attachment"-        val dataSource = object : DataSource {-            override fun getInputStream() = try {-                context.contentResolver.openInputStream(uri) ?: File(uri.path ?: "").inputStream()-            } catch (_: Exception) { File(uri.path ?: "").inputStream() }-            override fun getOutputStream() = throw Exception("Not supported")-            override fun getContentType() = context.contentResolver.getType(uri) ?: "application/octet-stream"-            override fun getName() = filename-        }-        attachmentPart.dataHandler = DataHandler(dataSource)-        attachmentPart.fileName = filename-        attachmentPart.setHeader("Content-Disposition", "attachment; filename=\"$filename\"")-        return attachmentPart-    }--    private fun getFileName(context: Context, uri: Uri): String? {-        if (uri.scheme == "content") {-            val cursor = context.contentResolver.query(uri, null, null, null, null)-            cursor?.use {-                if (it.moveToFirst()) {-                    val index = it.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)-                    if (index != -1) return it.getString(index)-                }-            }-        }-        return uri.path?.let { File(it).name }-    }+        folderName: String,+        uid: Long,+    ): Map<String, File> = ImapClient.fetchCidMap(context, server, user, auth, folderName, uid)      suspend fun setSeenFlag(         server: ServerConfig,@@ -388,14 +103,7 @@ class EmailManager {         folderName: String,         uid: Long,         seen: Boolean,-    ) = withStore(server, user, auth) { store ->-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_WRITE)-        try {-            val msg = (folder as UIDFolder).getMessageByUID(uid) ?: return@withStore-            msg.setFlag(Flags.Flag.SEEN, seen)-        } finally { folder.closeQuietly() }-    }+    ) = ImapClient.setSeenFlag(server, user, auth, folderName, uid, seen)      suspend fun deleteMessage(         server: ServerConfig,@@ -403,15 +111,7 @@ class EmailManager {         auth: AuthType,         folderName: String,         uid: Long,-    ) = withStore(server, user, auth) { store ->-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_WRITE)-        try {-            val msg = (folder as UIDFolder).getMessageByUID(uid) ?: return@withStore-            msg.setFlag(Flags.Flag.DELETED, true)-            folder.expunge()-        } finally { folder.closeQuietly(true) }-    }+    ) = ImapClient.deleteMessage(server, user, auth, folderName, uid)      suspend fun downloadAttachment(         context: Context,@@ -422,51 +122,8 @@ class EmailManager {         uid: Long,         partId: String,         fileName: String,-        mimeType: String-    ): String = withStore(server, user, auth) { store ->-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_ONLY)-        try {-            val msg = (folder as UIDFolder).getMessageByUID(uid)-            val part = findPartById(msg, partId) ?: throw Exception("Part not found")-            val resolver = context.contentResolver-            val values = ContentValues().apply {-                put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)-                put(MediaStore.MediaColumns.MIME_TYPE, mimeType.ifBlank { "application/octet-stream" })-                put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)-                put(MediaStore.MediaColumns.IS_PENDING, 1)-            }-            val itemUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: throw Exception("Could not create Downloads entry")-            try {-                resolver.openOutputStream(itemUri)?.use { output -> part.inputStream.use { input -> input.copyTo(output) } }-                    ?: throw Exception("Could not open output stream")-                values.clear()-                values.put(MediaStore.MediaColumns.IS_PENDING, 0)-                resolver.update(itemUri, values, null, null)-            } catch (e: Exception) {-                resolver.delete(itemUri, null, null)-                throw e-            }-            itemUri.toString()-        } finally { folder.closeQuietly() }-    }--    private fun findPartById(part: Part, partId: String): Part? {-        if (partId == "0") return part-        if (part.isMimeType("multipart/*")) {-            val ids = partId.split(".")-            var currentPart: Part = part-            for (id in ids) {-                val index = id.toIntOrNull() ?: return null-                if (currentPart.content is MimeMultipart) {-                    val innerMp = currentPart.content as MimeMultipart-                    if (index < innerMp.count) currentPart = innerMp.getBodyPart(index) else return null-                } else return null-            }-            return currentPart-        }-        return null-    }+        mimeType: String,+    ): String = ImapClient.downloadAttachment(context, server, user, auth, folderName, uid, partId, fileName, mimeType)      suspend fun fetchRawMessageBytes(         server: ServerConfig,@@ -474,16 +131,7 @@ class EmailManager {         auth: AuthType,         folderName: String,         uid: Long,-    ): ByteArray = withStore(server, user, auth) { store ->-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_ONLY)-        try {-            val msg = (folder as UIDFolder).getMessageByUID(uid) ?: throw IllegalStateException("Message UID $uid not found in $folderName")-            val baos = ByteArrayOutputStream()-            (msg as? MimeMessage)?.writeTo(baos) ?: msg.dataHandler.writeTo(baos)-            baos.toByteArray()-        } finally { folder.closeQuietly() }-    }+    ): ByteArray = ImapClient.fetchRawMessageBytes(server, user, auth, folderName, uid)      suspend fun fetchRawMessageTo(         server: ServerConfig,@@ -492,124 +140,23 @@ class EmailManager {         folderName: String,         uid: Long,         output: OutputStream,-    ) = withStore(server, user, auth) { store ->-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_ONLY)-        try {-            val msg = (folder as UIDFolder).getMessageByUID(uid) ?: throw IllegalStateException("Message UID $uid not found in $folderName")-            (msg as? MimeMessage)?.writeTo(output) ?: msg.dataHandler.writeTo(output)-        } finally { folder.closeQuietly() }-    }--    internal fun processMessageContent(user: String, folderName: String, uid: Long, part: Part, partId: String = ""): Triple<String?, Boolean, List<Attachment>> {-        when {-            part.isMimeType("text/plain") -> return Triple(part.content.toString(), false, emptyList())-            part.isMimeType("text/html") -> return Triple(part.content.toString(), true, emptyList())-            part.isMimeType("multipart/*") -> {-                val mp = part.content as MimeMultipart-                var finalBody: String? = null-                var finalIsHtml = false-                val attachments = mutableListOf<Attachment>()-                for (i in 0 until mp.count) {-                    val bodyPart = mp.getBodyPart(i)-                    val currentPartId = if (partId.isEmpty()) i.toString() else "$partId.$i"-                    val contentId = try { bodyPart.getHeader("Content-ID")?.firstOrNull() } catch (_: Exception) { null }-                    val isInlineImage = contentId != null && (bodyPart.isMimeType("image/*") || Part.INLINE.equals(bodyPart.disposition, ignoreCase = true))-                    if (!isInlineImage && (Part.ATTACHMENT.equals(bodyPart.disposition, ignoreCase = true) || !bodyPart.fileName.isNullOrBlank())) {-                        attachments.add(Attachment(user, folderName, uid, currentPartId, bodyPart.fileName ?: "unnamed", bodyPart.contentType.split(";").first(), bodyPart.size.toLong()))-                    } else if (!isInlineImage) {-                        val (b, h, a) = processMessageContent(user, folderName, uid, bodyPart, currentPartId)-                        attachments.addAll(a)-                        if (finalBody == null || (h && !finalIsHtml)) { finalBody = b; finalIsHtml = h }-                    }-                }-                return Triple(finalBody, finalIsHtml, attachments)-            }-        }-        return Triple(null, false, emptyList())-    }--    data class FullFetchResult(val contentTriple: Triple<String?, Boolean, List<Attachment>>)+    ) = ImapClient.fetchRawMessageTo(server, user, auth, folderName, uid, output) -    suspend fun fetchFullForBody(-        context: Context,-        server: ServerConfig,-        user: String,-        auth: AuthType,-        folderName: String,-        uid: Long,-    ): FullFetchResult = withStore(server, user, auth) { store ->-        val folder = store.getFolder(folderName)-        folder.open(Folder.READ_ONLY)-        try {-            val message = (folder as UIDFolder).getMessageByUID(uid)-            if (message == null) return@withStore FullFetchResult(Triple(null, false, emptyList()))-            val ctx = context.applicationContext-            try { extractInlineCidMapSync(ctx, message, uid) } catch (_: Exception) { }-            val triple = processMessageContent(user, folderName, uid, message, "")-            FullFetchResult(triple)-        } finally { folder.closeQuietly() }-    }--    suspend fun fetchCidMap(+    suspend fun sendMessage(         context: Context,         server: ServerConfig,         user: String,         auth: AuthType,-        folderName: String,-        uid: Long,-    ): Map<String, File> = withContext(Dispatchers.IO) {-        withStore(server, user, auth) { store ->-            val folder = store.getFolder(folderName)-            folder.open(Folder.READ_ONLY)-            try {-                val msg = (folder as UIDFolder).getMessageByUID(uid) ?: return@withStore emptyMap<String, File>()-                extractInlineCidMapSync(context, msg, uid)-            } finally { folder.closeQuietly() }-        }-    }--    private fun extractInlineCidMapSync(context: Context, part: Part, uid: Long): Map<String, File> {-        val map = mutableMapOf<String, File>()-        fun walk(p: Part) {-            try {-                if (p.isMimeType("multipart/*")) {-                    val mp = p.content as? MimeMultipart ?: return-                    for (i in 0 until mp.count) walk(mp.getBodyPart(i))-                } else {-                    val cidHeader = try { p.getHeader("Content-ID")?.firstOrNull() } catch (_: Exception) { null }-                    if (cidHeader != null) {-                        val cid = cidHeader.trim().removePrefix("<").removeSuffix(">").trim()-                        if (cid.isNotEmpty()) {-                            val dir = File(context.cacheDir, "cid/$uid").also { it.mkdirs() }-                            val safeName = (p.fileName?.takeIf { it.isNotBlank() } ?: "${cid.hashCode()}.bin").replace(Regex("[/\\\\]"), "_")-                            val outFile = File(dir, safeName)-                            if (!outFile.exists()) {-                                try { p.inputStream.use { input -> outFile.outputStream().use { out -> input.copyTo(out) } } } catch (_: Exception) { }-                            }-                            if (outFile.exists()) {-                                map[cid] = outFile-                                try { File(dir, "$cid.meta").writeText(outFile.name) } catch (_: Exception) { }-                            }-                        }-                    }-                }-            } catch (_: Exception) { }-        }-        walk(part)-        val dir = File(context.cacheDir, "cid/$uid")-        if (dir.exists()) {-            dir.listFiles { f -> f.name.endsWith(".meta") }?.forEach { meta ->-                val cid = meta.name.removeSuffix(".meta")-                if (cid !in map) {-                    val targetName = try { meta.readText().trim() } catch (_: Exception) { null }-                    if (targetName != null) {-                        val file = File(dir, targetName)-                        if (file.exists()) map[cid] = file-                    }-                }-            }-        }-        return map-    }+        to: String,+        subject: String,+        body: String,+        cc: String? = null,+        bcc: String? = null,+        attachments: List<Uri> = emptyList(),+        inlineImages: List<InlineAttachment> = emptyList(),+        inReplyTo: String? = null,+        references: String? = null,+        from: String? = null,+        asHtml: Boolean = false,+    ) = SmtpClient.sendMessage(context, server, user, auth, to, subject, body, cc, bcc, attachments, inlineImages, inReplyTo, references, from, asHtml) }
email/src/main/java/com/vayunmathur/email/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/EmailModels.ktindex dfcd0ff234..7f81295855 100644--- a/email/src/main/java/com/vayunmathur/email/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailModels.kt@@ -5,7 +5,7 @@ import androidx.room.Entity import androidx.room.PrimaryKey import androidx.core.text.HtmlCompat import kotlinx.serialization.Serializable-import jakarta.mail.internet.InternetAddress+import com.vayunmathur.email.imap.MimeParser  @Serializable @Entity(primaryKeys = ["accountEmail", "fullName"])@@ -174,10 +174,26 @@ fun accountColor(email: String): Long { fun EmailMessage.plainTextBody(): String? =     body?.let { if (isHtml) HtmlCompat.fromHtml(it, HtmlCompat.FROM_HTML_MODE_LEGACY).toString() else it } -/** Display name for a "Name <addr>" sender header, falling back to the address. */-fun senderDisplayName(from: String): String =-    runCatching { InternetAddress.parse(from).firstOrNull()?.let { it.personal ?: it.address } }-        .getOrNull() ?: from.substringBefore("<").trim()+/** Display name for a "Name <addr>" sender header, falling back to the address.+ * Implemented via own RFC2047 decode + simple parse to remove Jakarta dependency. */+fun senderDisplayName(from: String): String {+    if (from.isBlank()) return ""+    // Try to extract "Name <addr>" pattern+    val trimmed = from.trim()+    // Decode RFC2047 first+    val decoded = MimeParser.decodeHeader(trimmed)+    // Look for <...> format+    val angleMatch = Regex("""^(.*)<([^>]+)>$""").find(decoded.trim())+    if (angleMatch != null) {+        val namePart = angleMatch.groupValues[1].trim().trim('"').trim()+        val addr = angleMatch.groupValues[2].trim()+        if (namePart.isNotBlank()) return namePart+        return addr+    }+    // No angle brackets — could be bare address or just name+    if (decoded.contains("@")) return decoded.substringBefore("<").trim()+    return decoded+}  /**  * A detected way to unsubscribe from a message. Produced by [detectUnsubscribe]
email/src/main/java/com/vayunmathur/email/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/EmailViewModel.ktindex 9d92f9c79f..01143a90d7 100644--- a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt@@ -8,7 +8,6 @@ import android.os.Handler import android.os.Looper import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope-import jakarta.mail.internet.InternetAddress import com.vayunmathur.email.data.EmailDatabase import com.vayunmathur.email.data.EmailSyncState import com.vayunmathur.email.data.EmailSyncWorker@@ -575,6 +574,23 @@ class EmailViewModel(application: Application) : }  /** Extract the bare email address from a "Name <addr@x>" header, or "" if none. */-private fun extractEmailAddress(from: String): String =-    runCatching { InternetAddress.parse(from).firstOrNull()?.address }-        .getOrNull()?.takeIf { it.contains("@") } ?: ""+private fun extractEmailAddress(from: String): String {+    val trimmed = from.trim()+    if (trimmed.isEmpty()) return ""+    val angleMatch = Regex("""<([^>]+@[^>]+)>""").find(trimmed)+    if (angleMatch != null) {+        val addr = angleMatch.groupValues[1].trim()+        if (addr.contains("@")) return addr+    }+    // Try bare address token+    val tokens = trimmed.split(Regex("[\\s,;<>]+"))+    for (t in tokens) {+        if (t.contains("@") && t.contains(".")) return t.trim().trim('"', '\'', '<', '>')+    }+    // Fallback: contains @ anywhere+    if (trimmed.contains("@")) {+        val maybe = trimmed.substringAfterLast(' ').trim()+        if (maybe.contains("@")) return maybe.trim('<', '>', '"', '\'')+    }+    return ""+}
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex 3a5971bc29..8b0926c66f 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -90,6 +90,14 @@ class MainActivity : ComponentActivity() {     override fun onStart() {         super.onStart()         com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground = true+        // If BootReceiver deferred IDLE on S+ boot, start it now that we're foreground.+        com.vayunmathur.email.util.AppLifecycleTracker.tryStartIdleIfForeground(this)+    }++    override fun onResume() {+        super.onResume()+        // Extra safety: also try on resume in case onStart ran before flag set.+        com.vayunmathur.email.util.AppLifecycleTracker.tryStartIdleIfForeground(this)     }      override fun onStop() {
email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.ktindex c033ac00da..6a242d3db4 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -3,14 +3,20 @@ package com.vayunmathur.email.data import android.content.Context import android.util.Log import androidx.work.*-import com.vayunmathur.email.EmailManager-import com.vayunmathur.email.resolveAuth+import com.vayunmathur.email.imap.ImapClient import com.vayunmathur.email.imapServer import com.vayunmathur.email.loginUser+import com.vayunmathur.email.resolveAuth import com.vayunmathur.email.widget.EmailWidget import androidx.glance.appwidget.updateAll import java.util.concurrent.TimeUnit +/**+ * Sync worker — now uses raw IMAP client only (no Jakarta dependency).+ * - Non-INBOX hourly via WorkManager+ * - Full one-off for folder discovery + INBOX + body backfill+ * - Notification baseline per account/folder+ */ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :     CoroutineWorker(appContext, workerParams) { @@ -26,121 +32,113 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :         }          EmailSyncState.start()-        val manager = EmailManager()         var hasErrors = false         var accountsProcessed = 0          for (account in accounts) {             try {-                Log.d("EmailSync", ">>> Starting sync for account: ${account.email} (nonInboxOnly=$nonInboxOnly)")+                Log.d("EmailSync", ">>> RAW Starting sync for ${account.email} (nonInboxOnly=$nonInboxOnly)")                 val auth = account.resolveAuth(applicationContext) -                manager.withStore(account.imapServer(), account.loginUser(), auth) { store ->-                    Log.d("EmailSync", "Fetching folders for ${account.email}...")-                    val folders = manager.fetchFoldersInStore(store, account.email)-                    dao.insertFolders(folders)-                    Log.d("EmailSync", "Synced ${folders.size} folders.")+                val folders = ImapClient.fetchFolders(account.imapServer(), account.loginUser(), auth)+                dao.insertFolders(folders)+                Log.d("EmailSync", "Synced ${folders.size} folders.") -                    val skipSet = if (account.provider == PROVIDER_GMAIL) {-                        GMAIL_VIRTUAL_FOLDERS-                    } else emptySet()-                    val messageFolders = if (nonInboxOnly) {-                        folders.filter { folder ->-                            folder.holdsMessages && folder.fullName !in skipSet && folder.fullName != "INBOX"-                        }-                    } else {-                        folders.filter { folder ->-                            folder.holdsMessages && folder.fullName !in skipSet-                        }-                    }-                    val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1)+                val skipSet = if (account.provider == PROVIDER_GMAIL) ImapClient.GMAIL_VIRTUAL_FOLDERS else emptySet()+                val messageFolders = if (nonInboxOnly) {+                    folders.filter { it.holdsMessages && it.fullName !in skipSet && it.fullName != "INBOX" }+                } else {+                    folders.filter { it.holdsMessages && it.fullName !in skipSet }+                }+                val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1) -                    for ((index, folder) in messageFolders.withIndex()) {-                        try {-                            val knownUids = dao.getKnownUids(account.email, folder.fullName).toSet()-                            val deletedUids = dao.getDeletedUids(account.email, folder.fullName).toSet()-                            val (messages, attachments) = manager.fetchMessagesInStore(-                                store = store,-                                user = account.loginUser(),-                                folderName = folder.fullName,-                                limit = 50,-                                fetchBodies = false,-                                skipUids = knownUids + deletedUids,-                            )-                            if (messages.isNotEmpty()) dao.insertMessages(messages)-                            if (attachments.isNotEmpty()) dao.insertAttachments(attachments)+                for ((index, folder) in messageFolders.withIndex()) {+                    try {+                        val knownUids = dao.getKnownUids(account.email, folder.fullName).toSet()+                        val deletedUids = dao.getDeletedUids(account.email, folder.fullName).toSet()+                        val (messages, attachments) = ImapClient.fetchMessages(+                            server = account.imapServer(),+                            user = account.loginUser(),+                            auth = auth,+                            folderName = folder.fullName,+                            limit = 50,+                            fetchBodies = false,+                            skipUids = knownUids + deletedUids,+                            context = applicationContext,+                        )+                        if (messages.isNotEmpty()) dao.insertMessages(messages)+                        if (attachments.isNotEmpty()) dao.insertAttachments(attachments)++                        if (!nonInboxOnly) {+                            if (knownUids.isNotEmpty() && folder.fullName == "INBOX") {+                                syncReadStatusRaw(applicationContext, account, folder.fullName, knownUids)+                            } -                            // INBOX-only: read-status sync + foreground notification (skip when nonInboxOnly)-                            if (!nonInboxOnly) {-                                if (knownUids.isNotEmpty() && folder.fullName == "INBOX") {-                                    syncReadStatus(store, account.email, folder.fullName, knownUids)+                            if (folder.fullName == "INBOX" && messages.isNotEmpty()) {+                                val lastSeen = lastSeenPrefs(applicationContext)+                                    .getLong(lastSeenKey(account.email, folder.fullName), -1L)+                                if (lastSeen >= 0L && !com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground) {+                                    val notifiable = messages.filter { it.id > lastSeen }+                                    com.vayunmathur.email.util.EmailNotifications.postForNewMessages(+                                        applicationContext, account.email, notifiable,+                                    )                                 }--                                if (folder.fullName == "INBOX" && messages.isNotEmpty()) {-                                    val lastSeen = lastSeenPrefs(applicationContext)-                                        .getLong(lastSeenKey(account.email, folder.fullName), -1L)-                                    if (lastSeen >= 0L && !com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground) {-                                        val notifiable = messages.filter { it.id > lastSeen }-                                        com.vayunmathur.email.util.EmailNotifications.postForNewMessages(-                                            applicationContext, account.email, notifiable,-                                        )-                                    }-                                    val maxUid = messages.maxOf { it.id }-                                    if (maxUid > lastSeen) {-                                        lastSeenPrefs(applicationContext).edit()-                                            .putLong(lastSeenKey(account.email, folder.fullName), maxUid)-                                            .apply()-                                    }+                                val maxUid = messages.maxOf { it.id }+                                if (maxUid > lastSeen) {+                                    lastSeenPrefs(applicationContext).edit()+                                        .putLong(lastSeenKey(account.email, folder.fullName), maxUid)+                                        .apply()                                 }                             }--                            Log.d("EmailSync", "[${index + 1}/${messageFolders.size}] ${folder.fullName}: ${messages.size} new (skipped ${knownUids.size}).")-                        } catch (e: Exception) {-                            Log.e("EmailSync", "   x Failed folder ${folder.fullName}", e)                         }-                        val unitsDone = accountsProcessed * messageFolders.size + (index + 1)-                        EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits)++                        Log.d("EmailSync", "[${index + 1}/${messageFolders.size}] ${folder.fullName}: ${messages.size} new (skipped ${knownUids.size}).")+                    } catch (e: Exception) {+                        Log.e("EmailSync", "   x Failed folder ${folder.fullName}", e)                     }+                    val unitsDone = accountsProcessed * messageFolders.size + (index + 1)+                    EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits)+                } -                    // Body backfill only for full sync (on-demand / initial) — skip for hourly non-INBOX to save battery.-                    if (!nonInboxOnly) {-                        val missing = dao.getMessagesWithoutBody(account.email, BACKFILL_LIMIT)-                        if (missing.isNotEmpty()) {-                            Log.d("EmailSync", "Body backfill: ${missing.size} message(s)")-                            EmailSyncState.setProgress(0f)-                            for ((idx, msg) in missing.withIndex()) {-                                if (isStopped) {-                                    Log.d("EmailSync", "Backfill stopped at ${idx}/${missing.size}")-                                    break-                                }-                                try {-                                    val current = dao.getMessage(msg.accountEmail, msg.folderName, msg.id) ?: continue-                                    if (current.body != null) continue-                                    val (body, isHtml, attachments) = manager.fetchMessageBodyInStore(-                                        store = store,-                                        user = account.loginUser(),-                                        folderName = msg.folderName,-                                        uid = msg.id,-                                    )-                                    if (body != null || attachments.isNotEmpty()) {-                                        dao.insertMessages(listOf(current.copy(-                                            body = body,-                                            isHtml = isHtml,-                                            hasAttachments = attachments.isNotEmpty(),-                                        )))-                                        if (attachments.isNotEmpty()) dao.insertAttachments(attachments)-                                    }-                                } catch (e: Exception) {-                                    Log.w("EmailSync", "   x Backfill failed for UID ${msg.id}: ${e.message}")+                if (!nonInboxOnly) {+                    val missing = dao.getMessagesWithoutBody(account.email, BACKFILL_LIMIT)+                    if (missing.isNotEmpty()) {+                        Log.d("EmailSync", "Body backfill: ${missing.size} message(s)")+                        EmailSyncState.setProgress(0f)+                        for ((idx, msg) in missing.withIndex()) {+                            if (isStopped) {+                                Log.d("EmailSync", "Backfill stopped at ${idx}/${missing.size}")+                                break+                            }+                            try {+                                val current = dao.getMessage(msg.accountEmail, msg.folderName, msg.id) ?: continue+                                if (current.body != null) continue+                                val (body, isHtml, attachments) = ImapClient.fetchMessageBody(+                                    server = account.imapServer(),+                                    user = account.loginUser(),+                                    auth = auth,+                                    folderName = msg.folderName,+                                    uid = msg.id,+                                    context = applicationContext,+                                )+                                if (body != null || attachments.isNotEmpty()) {+                                    dao.insertMessages(listOf(current.copy(+                                        body = body,+                                        isHtml = isHtml,+                                        hasAttachments = attachments.isNotEmpty(),+                                    )))+                                    if (attachments.isNotEmpty()) dao.insertAttachments(attachments)                                 }-                                EmailSyncState.setProgress((idx + 1f) / missing.size)+                            } catch (e: Exception) {+                                Log.w("EmailSync", "   x Backfill failed for UID ${msg.id}: ${e.message}")                             }-                            Log.d("EmailSync", "Backfill done for ${account.email}")+                            EmailSyncState.setProgress((idx + 1f) / missing.size)                         }+                        Log.d("EmailSync", "Backfill done for ${account.email}")                     }                 } -                Log.d("EmailSync", "<<< Completed sync for account: ${account.email}")+                Log.d("EmailSync", "<<< Completed RAW sync for ${account.email}")             } catch (e: Exception) {                 Log.e("EmailSync", "Failed to sync account ${account.email}", e)                 hasErrors = true@@ -148,11 +146,8 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :             accountsProcessed++         } -        if (!nonInboxOnly) {-            EmailWidget().updateAll(applicationContext)-        }+        if (!nonInboxOnly) EmailWidget().updateAll(applicationContext)         EmailSyncState.finish()-         return if (hasErrors) Result.retry() else Result.success()     } @@ -161,43 +156,34 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :         private const val HOURLY_NON_INBOX_WORK_NAME = "EmailNonInboxHourlySync"         private const val KEY_NON_INBOX_ONLY = "non_inbox_only" -        /**-         * Sync read/unread flags from the IMAP server for messages we already-         * have locally. Runs over the most recent messages in the folder to-         * keep the local read status in sync with other clients.-         */-        private suspend fun EmailSyncWorker.syncReadStatus(-            store: jakarta.mail.Store,-            accountEmail: String,+        /** Sync read status via raw FETCH FLAGS */+        private suspend fun syncReadStatusRaw(+            context: Context,+            account: com.vayunmathur.email.EmailAccount,             folderName: String,             knownUids: Set<Long>,         ) {-            val db = EmailDatabase.getInstance(applicationContext)-            val dao = db.emailDao()-            val folder = store.getFolder(folderName)-            if ((folder.type and jakarta.mail.Folder.HOLDS_MESSAGES) == 0) return-            folder.open(jakarta.mail.Folder.READ_ONLY)             try {-                val uidFolder = folder as? jakarta.mail.UIDFolder ?: return-                // Check read status for the 50 most recent known UIDs+                val db = EmailDatabase.getInstance(context)+                val dao = db.emailDao()                 val uidsToCheck = knownUids.sortedDescending().take(50)-                for (uid in uidsToCheck) {-                    try {-                        val msg = uidFolder.getMessageByUID(uid) ?: continue-                        val serverIsRead = msg.isSet(jakarta.mail.Flags.Flag.SEEN)-                        dao.updateReadStatus(accountEmail, folderName, uid, serverIsRead)-                    } catch (_: Exception) {}+                if (uidsToCheck.isEmpty()) return+                val auth = account.resolveAuth(context)+                val server = account.imapServer()+                val user = account.loginUser()++                ImapClient.withConnection(server, user, auth) { conn ->+                    conn.select(folderName)+                    val uidSet = uidsToCheck.joinToString(",")+                    val results = conn.uidFetchHeaders(uidSet)+                    for (r in results) {+                        val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }+                        try { dao.updateReadStatus(account.email, folderName, r.uid, isRead) } catch (_: Exception) {}+                    }                 }-            } finally {-                try { folder.close(false) } catch (_: Throwable) {}-            }+            } catch (_: Exception) {}         } -        /**-         * Gmail's IMAP exposes several "virtual" labels that mirror INBOX (and-         * other folders) — syncing them downloads everything twice. Skipping-         * them is a major sync-time win.-         */         private val GMAIL_VIRTUAL_FOLDERS = setOf(             "[Gmail]/All Mail",             "[Gmail]/Important",@@ -205,35 +191,21 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :             "[Gmail]/Chats",         ) -        /** How many missing-body messages to backfill per worker run. */         private const val BACKFILL_LIMIT = 200 -        // ---- Notification baseline -----         private fun lastSeenPrefs(context: Context) =             context.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)          private fun lastSeenKey(accountEmail: String, folderName: String) =             "$accountEmail::$folderName" -        /**-         * Legacy 15-min periodic polling — removed in IDLE-only model.-         * Kept as a no-op that cancels any previously scheduled periodic work-         * so upgrades from older APKs stop polling.-         */-        @Deprecated("IDLE-only push: periodic polling removed. This now cancels legacy periodic work.", ReplaceWith("cancelSync(context)"))+        @Deprecated("IDLE-only push: periodic polling removed.")         fun schedulePeriodicSync(context: Context) {             WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)             WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)         } -        /**-         * Hourly non-INBOX sync: polls only non-INBOX folders (e.g. Sent, custom labels)-         * once per hour via WorkManager. INBOX stays IDLE-only push — no polling.-         * Cheap: skips body backfill, skip SEEN sync, skips notifications.-         */         fun scheduleHourlyNonInboxSync(context: Context) {-            // Purge legacy 15-min full polling work that may still be scheduled.             WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)             val constraints = Constraints.Builder()                 .setRequiredNetworkType(NetworkType.CONNECTED)@@ -250,11 +222,6 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :             )         } -        /**-         * One-off catch-up: folder discovery + all-folder header fetch + body backfill.-         * Used for initial sync after account add, manual pull-to-refresh, boot recovery, and-         * non-INBOX folder catch-up. Not periodic — INBOX live push is handled by [ImapIdleService].-         */         fun runOneOffSync(context: Context) {             val syncRequest = OneTimeWorkRequestBuilder<EmailSyncWorker>()                 .setInputData(Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, false).build())
email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.ktnew file mode 100644index 0000000000..4776354fc8--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.kt@@ -0,0 +1,61 @@+package com.vayunmathur.email.data++import android.content.Context+import android.util.Log+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.OutOfQuotaPolicy+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.email.util.BootReceiver++/**+ * Retry worker that attempts to start [ImapIdleService] when network is available.+ * Uses expedited work with OUT_OF_QUOTA so it can try even if quota exhausted.+ * Scheduled from [BootReceiver] on S+ boot as fallback, and from [com.vayunmathur.email.util.AppLifecycleTracker]+ * foreground path if direct start fails.+ */+class ImapIdleRetryWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {++    override suspend fun doWork(): Result {+        return try {+            val started = ImapIdleService.start(applicationContext)+            if (started) {+                Log.d(TAG, "ImapIdleRetryWorker: IDLE started")+                // Clear pending flag on success+                applicationContext.getSharedPreferences(BootReceiver.PREFS, Context.MODE_PRIVATE)+                    .edit().remove(BootReceiver.KEY_PENDING).apply()+                Result.success()+            } else {+                Log.w(TAG, "ImapIdleRetryWorker: start returned false, retrying")+                Result.retry()+            }+        } catch (t: Throwable) {+            Log.w(TAG, "ImapIdleRetryWorker failed: ${t.message}", t)+            Result.retry()+        }+    }++    companion object {+        private const val TAG = "ImapIdleRetry"+        private const val WORK_NAME = "ImapIdleRetryWorker"++        fun schedule(context: Context) {+            val constraints = Constraints.Builder()+                .setRequiredNetworkType(NetworkType.CONNECTED)+                .build()+            val req = OneTimeWorkRequestBuilder<ImapIdleRetryWorker>()+                .setConstraints(constraints)+                .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)+                .build()+            WorkManager.getInstance(context).enqueueUniqueWork(+                WORK_NAME,+                ExistingWorkPolicy.REPLACE,+                req,+            )+        }+    }+}
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex c85f98465c..5caffda371 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -14,22 +14,21 @@ import android.os.Build import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat-import androidx.glance.appwidget.updateAll-import org.eclipse.angus.mail.imap.IMAPFolder-import org.eclipse.angus.mail.imap.IMAPStore+import com.vayunmathur.email.EmailAccount+import com.vayunmathur.email.EmailFolder import com.vayunmathur.email.EmailManager import com.vayunmathur.email.R+import com.vayunmathur.email.imap.ImapAuthException+import com.vayunmathur.email.imap.ImapClient+import com.vayunmathur.email.imap.RawImapConnection+import com.vayunmathur.email.imap.TrustAll import com.vayunmathur.email.resolveAuth import com.vayunmathur.email.imapServer import com.vayunmathur.email.loginUser-import java.util.Collections-import jakarta.mail.Flags-import jakarta.mail.Folder-import jakarta.mail.UIDFolder-import jakarta.mail.event.MessageChangedEvent-import jakarta.mail.event.MessageChangedListener-import jakarta.mail.event.MessageCountAdapter-import jakarta.mail.event.MessageCountEvent+import com.vayunmathur.email.util.AppLifecycleTracker+import com.vayunmathur.email.util.EmailNotifications+import com.vayunmathur.email.widget.EmailWidget+import androidx.glance.appwidget.updateAll import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -41,19 +40,8 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext  /**- * Foreground service that keeps one IMAP IDLE connection open per account.- *- * IDLE push model:- * - INBOX is watched via `IMAPFolder.idle(true)` for instant push (1 RTT).- *   A watchdog triggers a graceful refresh at ~24 min to beat the server's- *   ~29 min IDLE timeout — avoids BYE + full TLS re-handshake by closing- *   INBOX and reopening it on the same STORE.- * - Folder list refreshed on every store connect.- * - Read/unread via [MessageChangedListener] (FLAGS_CHANGED).- * - Deletions via `messagesRemoved` (EXPUNGE).- *- * Non-INBOX: INBOX is live push; other folders hourly via- * [EmailSyncWorker.scheduleHourlyNonInboxSync] + on-demand pull-to-refresh.+ * Foreground service — raw IMAP IDLE (no Jakarta), app-password + Outlook OAuth XOAUTH2.+ * Fix for BOOT_COMPLETED crash: start() returns Boolean, onStartCommand catches FGS exception.  */ class ImapIdleService : Service() { @@ -63,272 +51,215 @@ class ImapIdleService : Service() {     override fun onBind(intent: Intent?): IBinder? = null      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {-        startForeground(NOTIFICATION_ID, buildOngoingNotification(), foregroundServiceType())+        try {+            startForeground(NOTIFICATION_ID, buildOngoingNotification(), foregroundServiceType())+        } catch (e: Exception) {+            Log.w(TAG, "startForeground failed: ${e.message}", e)+            stopSelf()+            return START_NOT_STICKY+        }         scope.launch { startIdleLoops() }         return START_STICKY     } -    override fun onDestroy() {-        scope.cancel()-        super.onDestroy()-    }+    override fun onDestroy() { scope.cancel(); super.onDestroy() }      private suspend fun startIdleLoops() {         val dao = EmailDatabase.getInstance(applicationContext).emailDao()         val accounts = dao.getAccounts()-        if (accounts.isEmpty()) {-            stopSelf()-            return-        }-        try {-            EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext)-        } catch (_: Throwable) {}-        val currentEmails = accounts.map { it.email }.toSet()-        accountJobs.keys.filter { it !in currentEmails }.forEach { email ->-            accountJobs[email]?.cancel()-            accountJobs.remove(email)-        }+        if (accounts.isEmpty()) { stopSelf(); return }+        try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Throwable) {}+        val current = accounts.map { it.email }.toSet()+        accountJobs.keys.filter { it !in current }.forEach { accountJobs[it]?.cancel(); accountJobs.remove(it) }         for (account in accounts) {             accountJobs[account.email]?.cancel()             accountJobs[account.email] = scope.launch { idleLoop(account) }         }     } -    private suspend fun idleLoop(account: com.vayunmathur.email.EmailAccount) {+    private suspend fun idleLoop(account: EmailAccount) {         var backoffMs = 2_000L         val maxBackoffMs = 60_000L         while (scope.coroutineContext.isActive) {             try {-                runIdleSession(account)+                runIdleSessionRaw(account)                 backoffMs = 2_000L                 delay(1_000L)-            } catch (e: jakarta.mail.AuthenticationFailedException) {-                Log.w(TAG, "IDLE auth failed for ${account.email}; stopping retries")+            } catch (e: ImapAuthException) {+                Log.w(TAG, "IDLE auth failed for ${account.email}; stop")                 return             } catch (e: Exception) {-                Log.w(TAG, "IDLE error for ${account.email}: ${e.javaClass.simpleName}: ${e.message}")+                val msg = e.message?.lowercase() ?: ""+                if (msg.contains("auth") && msg.contains("fail")) { Log.w(TAG, "IDLE auth fail ${account.email}"); return }+                Log.w(TAG, "IDLE err ${account.email}: ${e.javaClass.simpleName}: ${e.message}")                 delay(backoffMs)                 backoffMs = (backoffMs * 2).coerceAtMost(maxBackoffMs)             }         }     } -    private suspend fun runIdleSession(account: com.vayunmathur.email.EmailAccount) {-        withContext(Dispatchers.IO) {-            val mgr = EmailManager()-            mgr.withStore(-                server = account.imapServer(),-                user = account.loginUser(),-                auth = account.resolveAuth(applicationContext),-            ) { store ->-                val dao = EmailDatabase.getInstance(applicationContext).emailDao()-                try {-                    val folders = mgr.fetchFoldersInStore(store, account.email)-                    dao.insertFolders(folders)-                    Log.d(TAG, "Folder discovery for ${account.email}: ${folders.size} folders")-                } catch (t: Throwable) {-                    Log.w(TAG, "Folder discovery failed for ${account.email}: ${t.message}")-                }+    private suspend fun runIdleSessionRaw(account: EmailAccount) = withContext(Dispatchers.IO) {+        val server = account.imapServer()+        val user = account.loginUser()+        val auth = account.resolveAuth(applicationContext)+        val useTrustAll = !TrustAll.isKnownHost(server.host)+        val rawConn = RawImapConnection(server, trustAll = useTrustAll)+        try {+            rawConn.connect()+            var caps = rawConn.capability()+            if (!server.useSsl && caps.has("STARTTLS")) {+                try { rawConn.startTls(); caps = rawConn.capability() } catch (e: Exception) { Log.w(TAG, "STARTTLS fail ${account.email}: ${e.message}") }+            } -                val imapStore = store as? IMAPStore-                val supportsIdle = try {-                    imapStore?.hasCapability("IDLE") ?: true-                } catch (_: Throwable) { true }-                if (!supportsIdle) {-                    Log.w(TAG, "Server ${account.imapServer().host} no IDLE cap; poll fallback")+            when (auth) {+                is EmailManager.AuthType.OAuth -> rawConn.authenticateXoauth2(user, auth.token)+                is EmailManager.AuthType.Password -> {+                    try { rawConn.login(user, auth.value) } catch (e: Exception) {+                        if (caps.has("AUTH=PLAIN")) rawConn.authenticatePlain(user, auth.value) else throw e+                    }                 }+            }++            val supportsIdle = caps.has("IDLE")+            Log.d(TAG, "Raw IDLE supports $supportsIdle for ${account.email}") +            if (!supportsIdle) {                 while (scope.coroutineContext.isActive) {-                    val folder = store.getFolder("INBOX") as IMAPFolder-                    folder.open(Folder.READ_ONLY)--                    val sawNewMail = AtomicBoolean(false)-                    val sawFlagsChanged = AtomicBoolean(false)-                    val flaggedUids = Collections.synchronizedSet(mutableSetOf<Long>())-                    val removedUids = Collections.synchronizedSet(mutableSetOf<Long>())-                    val isProactiveRefresh = AtomicBoolean(false)--                    folder.addMessageCountListener(object : MessageCountAdapter() {-                        override fun messagesAdded(e: MessageCountEvent) {-                            Log.d(TAG, "EXISTS for ${account.email}: ${e.messages.size} new")-                            sawNewMail.store(true)-                        }-                        override fun messagesRemoved(e: MessageCountEvent) {-                            for (msg in e.messages) {-                                try {-                                    val uid = (folder as UIDFolder).getUID(msg)-                                    if (uid != -1L) removedUids.add(uid)-                                } catch (_: Throwable) {}-                            }-                            if (e.messages.isNotEmpty()) {-                                Log.d(TAG, "EXPUNGE for ${account.email}: ${e.messages.size} removed, uids=$removedUids")-                            }-                        }-                    })-

Diff truncated.