Modern Apps git

← Modern-Apps.git

photos: ask for media management at first edit, not at startup

Commit
c48f36a75e5958a13b4a8c6dc29ae3d09d510cce
Author
Vayun Mathur <[email protected]>
When
2026-11-21 12:31 UTC (15 days ago)
Parents
ae62ec4
The startup gate blocked the whole app until MANAGE_MEDIA
was granted, though only trash/delete/move actions need it.
The gate now requires just media reads. A rememberManageMedia
action wraps those actions: granted runs immediately,
otherwise it explains via the system settings flow and runs
the held action once on grant; still-denied drops the action
untouched with a messenger explanation. Browsing never cares.

Includes a one-line @OptIn(ExperimentalTestApi) that un-breaks
PhotosSlice3PagesTest compilation at HEAD (uses
waitUntilExactlyOneExists without it) - flagged by the agent
as a separate drive-by.
Verified: photos 802 tests pass incl. 5 new gate tests.

Diff

photos/src/main/java/com/vayunmathur/photos/MainActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt b/photos/src/main/java/com/vayunmathur/photos/MainActivity.ktindex c1eeec6445..63821db75e 100644--- a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt+++ b/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt@@ -130,10 +130,15 @@ class MainActivity : MaFragmentActivity() {                     arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)                 )             }+        // MANAGE_MEDIA is deliberately NOT a startup requirement: browsing+        // only needs the runtime media reads below. It is requested+        // contextually at the first trash/delete/move action instead (see+        // rememberManageMediaAction), so first use is not blocked on an+        // edit-only grant.         AppPermissionsGate(             spec = AppPermissionsSpec(                 title = getString(R.string.grant_image_video_permissions),-                requirements = listOf(runtime, PermissionRequirement.ManageMedia)+                requirements = listOf(runtime)             )         ) {             Navigation(galleryViewModel, photoMapViewModel, secureFolderViewModel, viewUri)
photos/src/main/java/com/vayunmathur/photos/platform/AlbumMediaStore.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/AlbumMediaStore.kt b/photos/src/main/java/com/vayunmathur/photos/platform/AlbumMediaStore.ktindex 10b6af0387..8d8972abdb 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/AlbumMediaStore.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/AlbumMediaStore.kt@@ -19,8 +19,11 @@ import com.vayunmathur.photos.data.Photo  *  * Callers must hold write access to the items first — most library photos are not  * owned by this app, so the binder runs [MediaStore.createWriteRequest] over- * [urisOf] before invoking [applyMove]. The app requires MANAGE_MEDIA, so that- * grant is silent, like the existing trash/delete flows.+ * [urisOf] before invoking [applyMove]. The UI ensures MANAGE_MEDIA+ * contextually before that (rememberManageMediaAction, deferred from app+ * start), so the direct [resolver.update][android.content.ContentResolver.update]+ * calls below apply silently; without the grant they throw+ * [SecurityException] and the item is logged and skipped.  */ object AlbumMediaStore {     private const val TAG = "AlbumMediaStore"
photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailPage.ktindex 2b89f27306..098d799617 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumDetailPage.kt@@ -13,7 +13,10 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.R import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.platform.AlbumMediaStore@@ -45,6 +48,15 @@ fun AlbumDetailPage(     // the album ceases to exist and there is nothing left to show.     var pendingPop by remember { mutableStateOf(false) } +    val messenger = rememberMessenger()+    val manageMediaDeniedMessage = stringResource(R.string.manage_media_required)+    // Album moves edit shared media: MANAGE_MEDIA is asked for here, at the+    // action, not at app start. A refusal clears the pending pop and explains.+    val ensureManageMedia = rememberManageMediaAction {+        pendingPop = false+        messenger.show(manageMediaDeniedMessage)+    }+     val mediaResultLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.StartIntentSenderForResult()     ) { result ->@@ -61,9 +73,11 @@ fun AlbumDetailPage(      fun launchMove(photos: List<Photo>, target: String?) {         if (photos.isEmpty()) return-        galleryViewModel.requestAlbumMove(photos, target)-        val pendingIntent = MediaStore.createWriteRequest(context.contentResolver, AlbumMediaStore.urisOf(photos))-        mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+        ensureManageMedia {+            galleryViewModel.requestAlbumMove(photos, target)+            val pendingIntent = MediaStore.createWriteRequest(context.contentResolver, AlbumMediaStore.urisOf(photos))+            mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+        }     }      AlbumDetailScreen(
photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.ktindex 0b42531b5a..e5523c76b9 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt@@ -1,10 +1,5 @@ package com.vayunmathur.photos.ui -import android.content.Intent-import android.provider.MediaStore-import android.provider.Settings-import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -12,7 +7,6 @@ import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext-import androidx.core.net.toUri import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.Route import com.vayunmathur.photos.platform.GalleryUiState@@ -50,23 +44,9 @@ fun GalleryPage(         enqueueSyncWork(context)     } -    // Helper to request MANAGE_MEDIA permission-    val manageMediaLauncher = rememberLauncherForActivityResult(-        ActivityResultContracts.StartActivityForResult()-    ) { _ ->-        // User returned from Settings - permission may or may not be granted-        // The next delete attempt will check again-    }--    fun requestManageMediaPermission() {-        if (!MediaStore.canManageMedia(context)) {-            val intent = Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA).apply {-                data = "package:${context.packageName}".toUri()-            }-            manageMediaLauncher.launch(intent)-        }-    }-+    // Trash/delete/album actions request MANAGE_MEDIA contextually inside+    // rememberGalleryActions (rememberManageMediaAction); nothing to ask for+    // on this browsing screen.     val actions = rememberGalleryActions(galleryViewModel, secureFolderViewModel, photos, selectedIds)      GalleryScreen(
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex a3399652aa..8b45cd4c4f 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -26,15 +26,18 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource import androidx.core.net.toUri import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ZoomState+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.PhotoSource+import com.vayunmathur.photos.R import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.platform.pushPhoto@@ -84,9 +87,11 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie     val faceBoxes by galleryViewModel.faceBoxesByPhoto.collectAsState()      // In-viewer delete: move the current photo to the system trash via the same-    // MediaStore IntentSender flow the grid uses. MANAGE_MEDIA (enforced at app-    // start) means no per-item confirmation popup. On success we hide it locally-    // (the pager falls through to the next photo) and trash it in the DB.+    // MediaStore IntentSender flow the grid uses. MANAGE_MEDIA is requested+    // contextually here (it is no longer an app-start requirement), so the+    // trash applies without a per-item confirmation popup once granted; a+    // refusal explains and leaves the photo in place. On success we hide it+    // locally (the pager falls through to the next photo) and trash it in the DB.     //     // Declared before the delete launcher: its result callback resets the chrome     // so the photo the pager falls through to keeps its info card.@@ -107,12 +112,19 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie         }         pendingDelete = null     }+    val messenger = rememberMessenger()+    val manageMediaDeniedMessage = stringResource(R.string.manage_media_required)+    val ensureManageMedia = rememberManageMediaAction {+        messenger.show(manageMediaDeniedMessage)+    }     val onDeletePhoto: (Photo) -> Unit = { p ->-        pendingDelete = p-        val pendingIntent = MediaStore.createTrashRequest(-            context.contentResolver, listOf(p.uri.toUri()), true-        )-        deleteLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+        ensureManageMedia {+            pendingDelete = p+            val pendingIntent = MediaStore.createTrashRequest(+                context.contentResolver, listOf(p.uri.toUri()), true+            )+            deleteLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+        }     }      // Resolve the page to open by id, falling back to the incoming view-intent
photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt b/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.ktindex 12c307bd46..6fb1195e79 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt@@ -11,9 +11,12 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource import androidx.core.net.toUri import androidx.fragment.app.FragmentActivity import com.vayunmathur.library.log.Log+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.photos.R import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.platform.GalleryActions import com.vayunmathur.photos.platform.GalleryViewModel@@ -36,6 +39,13 @@ fun rememberGalleryActions(     selectedIds: Set<Long>, ): GalleryActions {     val context = LocalContext.current+    val messenger = rememberMessenger()+    val manageMediaDeniedMessage = stringResource(R.string.manage_media_required)+    // MANAGE_MEDIA is deferred from app start: the first trash/delete/move+    // asks for it here, and a refusal just explains and drops the action.+    val ensureManageMedia = rememberManageMediaAction {+        messenger.show(manageMediaDeniedMessage)+    }      val mediaResultLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->         if (result.resultCode == Activity.RESULT_OK) {@@ -62,11 +72,11 @@ fun rememberGalleryActions(     val currentPhotos by rememberUpdatedState(photos)     val currentSelectedIds by rememberUpdatedState(selectedIds) -    return remember(galleryViewModel, secureFolderViewModel, context, toggleFavorite) {+    return remember(galleryViewModel, secureFolderViewModel, context, toggleFavorite, ensureManageMedia) {         // The ViewModel is the actions implementation; the two MediaStore operations are         // the exception, because they need the launchers created above.         object : GalleryActions by galleryViewModel {-            override fun moveSelectionToSecureFolder() {+            override fun moveSelectionToSecureFolder() = ensureManageMedia {                 val activity = context as FragmentActivity                 val selectedPhotos = currentPhotos.filter { it.id in currentSelectedIds } @@ -77,14 +87,15 @@ fun rememberGalleryActions(                             photos = selectedPhotos,                             sourceRepository = com.vayunmathur.photos.data.PhotosRepository.get(context.applicationContext),                         ) { urisToDelete ->-                            // Use MediaStore operations to delete files-                            // MANAGE_MEDIA permission is required to run the app (checked in PermissionsWrapper)+                            // Delete the originals now the copies are in the+                            // vault. The ensureManageMedia wrapper above has+                            // already secured MANAGE_MEDIA, so this applies+                            // without a per-item popup.                             try {                                 val pendingIntent = MediaStore.createDeleteRequest(                                     context.contentResolver,                                     urisToDelete                                 )-                                // With MANAGE_MEDIA permission granted, this will delete without popup                                 mediaResultLauncher.launch(                                     IntentSenderRequest.Builder(pendingIntent.intentSender).build()                                 )@@ -105,7 +116,7 @@ fun rememberGalleryActions(                 )             } -            override fun trashSelection() {+            override fun trashSelection() = ensureManageMedia {                 val uris = currentPhotos.filter { it.id in currentSelectedIds }.map { it.uri.toUri() }                 val pendingIntent = MediaStore.createTrashRequest(context.contentResolver, uris, true)                 mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())@@ -115,11 +126,11 @@ fun rememberGalleryActions(                 toggleFavorite(currentPhotos.filter { it.id in currentSelectedIds })             } -            override fun addSelectionToAlbum(name: String) {+            override fun addSelectionToAlbum(name: String) = ensureManageMedia gate@{                 val album = com.vayunmathur.photos.platform.AlbumMediaStore.sanitizeAlbumName(name)-                if (album.isBlank()) return+                if (album.isBlank()) return@gate                 val selected = currentPhotos.filter { it.id in currentSelectedIds }-                if (selected.isEmpty()) return+                if (selected.isEmpty()) return@gate                 galleryViewModel.requestAlbumMove(selected, album)                 val pendingIntent = MediaStore.createWriteRequest(                     context.contentResolver,
photos/src/main/java/com/vayunmathur/photos/ui/RememberManageMediaAction.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/RememberManageMediaAction.kt b/photos/src/main/java/com/vayunmathur/photos/ui/RememberManageMediaAction.ktnew file mode 100644index 0000000000..09a5f68a2e--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/RememberManageMediaAction.kt@@ -0,0 +1,88 @@+package com.vayunmathur.photos.ui++import android.content.ActivityNotFoundException+import android.content.Intent+import android.provider.Settings+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.platform.LocalContext+import androidx.core.net.toUri+import com.vayunmathur.library.ui.SpecialAccess++/**+ * Wraps an action that edits shared media (trash, delete, album move) so+ * MANAGE_MEDIA is requested contextually instead of at app start.+ *+ * Returns a function to call in place of the action: when media management+ * is already granted the action runs immediately; otherwise the action is+ * held while the system "Allow media management" settings page opens (the+ * same intent the gallery's old helper built). That page returns no reliable+ * result code, so on return the grant is re-checked: granted runs the held+ * action, still denied drops it and reports through [onDenied], where the+ * caller explains why the action could not proceed. Browsing never passes+ * through here, so denying the grant costs nothing until an edit is tried.+ */+@Composable+fun rememberManageMediaAction(onDenied: () -> Unit): (action: () -> Unit) -> Unit {+    val context = LocalContext.current+    val currentOnDenied by rememberUpdatedState(onDenied)+    val gate = remember { ManageMediaGate() }+    val launcher = rememberLauncherForActivityResult(+        ActivityResultContracts.StartActivityForResult()+    ) {+        gate.onRequestReturned()+    }+    SideEffect {+        gate.isGranted = { SpecialAccess.hasManageMedia(context) }+        gate.launchRequest = {+            try {+                launcher.launch(+                    Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA).apply {+                        data = "package:${context.packageName}".toUri()+                    }+                )+            } catch (_: ActivityNotFoundException) {+                // No settings page can ask: treat as a denied return.+                gate.onRequestReturned()+            }+        }+        gate.onDenied = { currentOnDenied() }+    }+    return remember(gate) { { action -> gate.run(action) } }+}++/**+ * The grant/pending state machine behind [rememberManageMediaAction],+ * separated from Compose so the defer-and-recheck behaviour is unit-testable+ * (the [FavoriteRequestDriver] pattern).+ */+internal class ManageMediaGate(+    var isGranted: () -> Boolean = { false },+    var launchRequest: () -> Unit = {},+    var onDenied: () -> Unit = {},+) {+    private var pending: (() -> Unit)? = null++    /** Run [action] now if granted; otherwise hold it and ask for the grant. */+    fun run(action: () -> Unit) {+        if (isGranted()) {+            pending = null+            action()+        } else {+            pending = action+            launchRequest()+        }+    }++    /** The settings trip ended: run the held action if granted, else deny it. */+    fun onRequestReturned() {+        val action = pending ?: return+        pending = null+        if (isGranted()) action() else onDenied()+    }+}
photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.ktindex fe5867c2a5..00199448ee 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt@@ -41,6 +41,7 @@ import androidx.compose.ui.unit.dp import androidx.core.net.toUri import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconUnarchive+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.ui.LocalColumnCount import com.vayunmathur.photos.Route@@ -78,6 +79,14 @@ fun TrashPage(backStack: NavBackStack<Route>, galleryViewModel: GalleryViewModel         }     } +    val messenger = rememberMessenger()+    val manageMediaDeniedMessage = stringResource(R.string.manage_media_required)+    // Restore and permanent delete edit shared media: MANAGE_MEDIA is asked+    // for at the tap, not at app start; a refusal explains and changes nothing.+    val ensureManageMedia = rememberManageMediaAction {+        messenger.show(manageMediaDeniedMessage)+    }+     // Grouping is O(N) with a timezone conversion per photo, so it runs on     // Dispatchers.Default. The seed is computed once so the grid isn't blank on the     // first frame; produceState's initialValue is eagerly evaluated, hence the@@ -103,25 +112,31 @@ fun TrashPage(backStack: NavBackStack<Route>, galleryViewModel: GalleryViewModel         actions = {             if (isSelectionMode) {                 IconButton(onClick = {-                    val uris = trashedPhotos.filter { it.id in selectedIds }.map { it.uri.toUri() }-                    val pendingIntent = MediaStore.createTrashRequest(context.contentResolver, uris, false)-                    trashLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                    ensureManageMedia {+                        val uris = trashedPhotos.filter { it.id in selectedIds }.map { it.uri.toUri() }+                        val pendingIntent = MediaStore.createTrashRequest(context.contentResolver, uris, false)+                        trashLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                    }                 }) {                     IconUnarchive() // Restore icon                 }                 IconButton(onClick = {-                    val uris = trashedPhotos.filter { it.id in selectedIds }.map { it.uri.toUri() }-                    val pendingIntent = MediaStore.createDeleteRequest(context.contentResolver, uris)-                    trashLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                    ensureManageMedia {+                        val uris = trashedPhotos.filter { it.id in selectedIds }.map { it.uri.toUri() }+                        val pendingIntent = MediaStore.createDeleteRequest(context.contentResolver, uris)+                        trashLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                    }                 }) {                     IconDelete() // Permanent delete icon                 }             } else {                 if (trashedPhotos.isNotEmpty()) {                     IconButton(onClick = {-                        val uris = trashedPhotos.map { it.uri.toUri() }-                        val pendingIntent = MediaStore.createDeleteRequest(context.contentResolver, uris)-                        trashLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                        ensureManageMedia {+                            val uris = trashedPhotos.map { it.uri.toUri() }+                            val pendingIntent = MediaStore.createDeleteRequest(context.contentResolver, uris)+                            trashLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                        }                     }) {                         IconDelete()                     }
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex a606ebae37..22c10bda8e 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -9,9 +9,8 @@     <!-- Permission prompt button to grant READ_MEDIA_IMAGES/VIDEO. Verb phrase -->     <string name="grant_image_video_permissions">Grant Image/Video Permissions</string>     <!-- Button to request storage permission. Shown on Android versions below 13. Verb phrase -->-    <!-- Title when Media Management permission required to delete/move -->-    <!-- Explanatory body when canManageMedia false, tells user to grant Allow media management in Settings -->-    <!-- Button to open system Settings from permission blocker screen. Verb phrase -->+    <!-- Message when a trash/delete/move action cannot proceed because media management is not granted. Sentence -->+    <string name="manage_media_required">Allow media management to delete, move or restore photos</string>     <!-- Navigation label: Gallery tab. Noun -->     <string name="label_gallery">Gallery</string>     <!-- Navigation label: Map tab. Noun -->
photos/src/test/java/com/vayunmathur/photos/ui/ManageMediaGateTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/ManageMediaGateTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/ManageMediaGateTest.ktnew file mode 100644index 0000000000..ce5b2eb15e--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/ManageMediaGateTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.photos.ui++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * [ManageMediaGate]: MANAGE_MEDIA is deferred from app start, so a+ * trash/delete/move action runs immediately when granted, is held (and the+ * settings ask launched) when not, then runs on a granted return or is+ * dropped with a denial notice on a refused one.+ */+class ManageMediaGateTest {+    private class Probe {+        var granted = false+        var launches = 0+        var denials = 0+        val ran = mutableListOf<String>()+    }++    private fun gate(probe: Probe) = ManageMediaGate(+        isGranted = { probe.granted },+        launchRequest = { probe.launches++ },+        onDenied = { probe.denials++ },+    )++    @Test+    fun grantedRunsImmediatelyWithoutAsking() {+        val probe = Probe().apply { granted = true }+        gate(probe).run { probe.ran += "trash" }+        assertEquals(listOf("trash"), probe.ran)+        assertEquals(0, probe.launches)+        assertEquals(0, probe.denials)+    }++    @Test+    fun ungrantedDefersThenRunsOnceWhenGrantLands() {+        val probe = Probe()+        val gate = gate(probe)+        gate.run { probe.ran += "move" }+        assertEquals(emptyList(), probe.ran)+        assertEquals(1, probe.launches)+        probe.granted = true+        gate.onRequestReturned()+        assertEquals(listOf("move"), probe.ran)+        assertEquals(0, probe.denials)+        // The held action is consumed: a second resume must not replay it.+        gate.onRequestReturned()+        assertEquals(listOf("move"), probe.ran)+    }++    @Test+    fun ungrantedStillDeniedDropsActionAndExplains() {+        val probe = Probe()+        val gate = gate(probe)+        gate.run { probe.ran += "delete" }+        gate.onRequestReturned()+        assertEquals(emptyList(), probe.ran)+        assertEquals(1, probe.denials)+        // Nothing remains pending after a denial.+        probe.granted = true+        gate.onRequestReturned()+        assertEquals(emptyList(), probe.ran)+        assertEquals(1, probe.denials)+    }++    @Test+    fun returnWithNothingPendingIsNoOp() {+        val probe = Probe().apply { granted = true }+        gate(probe).onRequestReturned()+        assertEquals(0, probe.denials)+        assertEquals(emptyList(), probe.ran)+    }++    @Test+    fun latestActionReplacesOneStillWaiting() {+        val probe = Probe()+        val gate = gate(probe)+        gate.run { probe.ran += "stale" }+        gate.run { probe.ran += "fresh" }+        probe.granted = true+        gate.onRequestReturned()+        assertEquals(listOf("fresh"), probe.ran)+    }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.ktindex 3ebf972907..7d4b4e3a84 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt@@ -255,6 +255,7 @@ class PhotosSlice3PagesTest {      // ---- PhotoPage re-deriving its list from the view-model by sourceKey ---- +    @OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)     @Test     fun photoPagePagerOpensOnOverridePhoto() {         val gallery = galleryVm()