Modern Apps git

← Modern-Apps.git

photos: new photos appear in moments, enrichment trails

Commit
d5dc0a920040d26c78c74eca673163acb2f9717b
Author
Vayun Mathur <[email protected]>
When
2026-11-23 16:01 UTC (13 days ago)
Parents
fa605b9
Nothing observed MediaStore, so a just-taken photo waited
on WorkManager scheduling and a backlog EXIF pass. A
foreground ContentObserver (started/stopped with the
lifecycle, 400ms debounce, URI dedup, never widening to
a full scan) now triggers an incremental import of just
the new items: metadata first, so the row appears in the
grid immediately, with EXIF/OCR/face enrichment trailing
via ExifWorker. The watermark invariants from 0e2d54511
are preserved (triggered syncs never advance it).

Verified: tests pin one-photo import emitting in the
gallery flow before enrichment lands, observer lifecycle,
and the untouched watermark suite.

Diff

photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.ktindex 46290ba6b6..77621175c9 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/GalleryViewModel.kt@@ -472,6 +472,72 @@ class GalleryViewModel(         }     } +    /**+     * Watches MediaStore while the gallery is foregrounded (see+     * [ForegroundMediaObserver]). Started/stopped by the gallery binder on+     * ON_START/ON_STOP and stopped again in [onCleared], so the+     * registration never outlives the foreground. Tests may replace this+     * with an observer over a fake registrar.+     */+    internal var foregroundObserver: ForegroundMediaObserver = ForegroundMediaObserver(+        registrar = AndroidMediaStoreRegistrar(application.contentResolver),+        scope = viewModelScope,+        onTriggered = { uris -> importTriggeredPhotos(uris) },+    )++    /** Start the foreground MediaStore observer (idempotent). */+    fun startForegroundObserving() = foregroundObserver.start()++    /** Stop the foreground MediaStore observer (idempotent, no leak). */+    fun stopForegroundObserving() = foregroundObserver.stop()++    /**+     * Test seam: unit tests have no WorkManager initializer, so they set+     * this to record instead of doing the real metadata import. Production+     * leaves it null.+     */+    internal var foregroundImportHook: (suspend (List<Uri>) -> Unit)? = null++    /**+     * Test seam mirroring [foregroundImportHook] for the trailing+     * enrichment enqueues that follow a foreground import.+     */+    internal var trailingEnrichmentHook: (() -> Unit)? = null++    /**+     * Import just-changed [uris] on the foreground fast path: metadata+     * only ([syncTriggeredPhotos] — item-URI selection, Room upsert, no+     * full scan, no inline EXIF, no watermark write), so the new rows emit+     * from [galleryPhotos] within moments of the change. Enrichment+     * (EXIF/OCR/face/CLIP) trails in its own workers over the+     * already-visible rows.+     */+    internal suspend fun importTriggeredPhotos(uris: List<Uri>) {+        foregroundImportHook?.let { hook ->+            hook(uris)+            return+        }+        val imported = withContext(Dispatchers.IO) {+            syncTriggeredPhotos(getApplication(), resolveRepository(), uris)+        }+        if (imported) enqueueTrailingEnrichment()+    }++    private fun enqueueTrailingEnrichment() {+        trailingEnrichmentHook?.invoke() ?: run {+            val app = getApplication<Application>()+            ExifWorker.enqueue(app)+            OCRWorker.enqueue(app)+            FaceWorker.enqueue(app)+            ClipWorker.enqueue(app)+        }+    }++    override fun onCleared() {+        foregroundObserver.stop()+        super.onCleared()+    }+     /**      * Test seam mirroring [workInfosOverride] below: unit tests have no      * WorkManager initializer, so they set this to a no-op (or a recorder).
photos/src/main/java/com/vayunmathur/photos/platform/MediaStoreObserver.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/MediaStoreObserver.kt b/photos/src/main/java/com/vayunmathur/photos/platform/MediaStoreObserver.ktnew file mode 100644index 0000000000..1e4d35da37--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/MediaStoreObserver.kt@@ -0,0 +1,135 @@+package com.vayunmathur.photos.platform++import android.content.ContentResolver+import android.database.ContentObserver+import android.net.Uri+import android.os.Handler+import android.os.Looper+import android.provider.MediaStore+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * Registration seam for [ForegroundMediaObserver]: production talks to the+ * real [ContentResolver]; tests substitute a recording fake so the+ * register/unregister lifecycle can be asserted without a provider.+ */+interface MediaStoreRegistrar {+    fun register(observer: ContentObserver, uri: Uri, notifyForDescendants: Boolean)+    fun unregister(observer: ContentObserver)+}++/** [MediaStoreRegistrar] over the real [ContentResolver]. */+class AndroidMediaStoreRegistrar(+    private val resolver: ContentResolver,+) : MediaStoreRegistrar {+    override fun register(observer: ContentObserver, uri: Uri, notifyForDescendants: Boolean) {+        resolver.registerContentObserver(uri, notifyForDescendants, observer)+    }++    override fun unregister(observer: ContentObserver) {+        resolver.unregisterContentObserver(observer)+    }+}++/**+ * MediaStore content observer active only while the gallery is foregrounded.+ *+ * Before this, a just-taken photo waited for the WorkManager+ * content-triggered [SyncWorker] (OS scheduling + the unique-work queue, and+ * then that worker's inline EXIF backlog) before its row reached Room.+ * Registering a direct observer on start and unregistering it on stop makes+ * the foregrounded app react within [debounceMs] instead: changes are+ * coalesced (a burst from one camera capture fires several callbacks),+ * de-duplicated by URI, and handed to [onTriggered] as item URIs for the+ * triggered-URI incremental sync ([syncTriggeredPhotos]). Collection URIs+ * and null callbacks are dropped by that sync, never widened to a full scan.+ *+ * Lifecycle contract: [start] registers exactly the image + video+ * collections once (repeat starts are no-ops), [stop] unregisters once,+ * cancels any pending debounced import, and makes late callbacks no-ops —+ * so a stopped observer leaks neither a registration nor a pending import.+ * A later [start] re-registers cleanly.+ */+class ForegroundMediaObserver(+    private val registrar: MediaStoreRegistrar,+    private val scope: CoroutineScope,+    private val debounceMs: Long = DEFAULT_DEBOUNCE_MS,+    private val onTriggered: suspend (List<Uri>) -> Unit,+) {+    private val observer = object : ContentObserver(Handler(Looper.getMainLooper())) {+        override fun onChange(selfChange: Boolean, uri: Uri?) {+            onMediaChanged(uri)+        }++        override fun onChange(selfChange: Boolean) {+            // No URI to trigger on: ignoring it is what keeps the foreground+            // path from ever falling back to a full scan.+            onMediaChanged(null)+        }+    }++    /** True between a successful [start] and its matching [stop]. */+    var isRegistered: Boolean = false+        private set++    private val pending = linkedSetOf<Uri>()+    private var pendingJob: Job? = null++    fun start() {+        if (isRegistered) return+        OBSERVED_URIS.forEach { uri -> registrar.register(observer, uri, true) }+        isRegistered = true+    }++    fun stop() {+        if (!isRegistered) return+        isRegistered = false+        registrar.unregister(observer)+        pendingJob?.cancel()+        pendingJob = null+        synchronized(pending) { pending.clear() }+    }++    /**+     * One MediaStore change callback. Visible for tests; the production+     * entry point is the [ContentObserver] above.+     */+    fun onMediaChanged(uri: Uri?) {+        if (!isRegistered || uri == null) return+        synchronized(pending) { pending += uri }+        pendingJob?.cancel()+        pendingJob = scope.launch {+            delay(debounceMs)+            val batch = synchronized(pending) {+                pending.toList().also { pending.clear() }+            }+            if (batch.isEmpty()) return@launch+            try {+                onTriggered(batch)+            } catch (e: Exception) {+                // A failed fast import must not kill the observer: the+                // background WorkManager trigger remains as the safety net,+                // and the next change retries.+                Log.error(TAG, "Foreground media import failed for $batch", e)+            }+        }+    }++    /** Shared constants. */+    companion object {+        private const val TAG = "ForegroundMediaObserver"++        /** Coalescing window for a burst of callbacks from one capture. */+        const val DEFAULT_DEBOUNCE_MS = 400L++        /** Image + video collections watched while foregrounded. */+        val OBSERVED_URIS: List<Uri> = listOf(+            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,+            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,+        )+    }+}
photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.ktindex a95a36bcc6..c710fcee34 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/SyncWorker.kt@@ -85,7 +85,18 @@ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c             )         } -        setExifData(scanRepository, applicationContext)+        // EXIF placement (see exifRunsInline): a triggered sync's rows are+        // already upserted — visible in the gallery flow — so its EXIF pass+        // must not sit inline behind a possibly-large unscanned backlog,+        // delaying this worker's turnaround (and, under the unique-work+        // KEEP policy, the next trigger). It trails in ExifWorker instead.+        // A generation-complete sync keeps EXIF inline, ahead of the+        // watermark write below: that ordering is the watermark invariant.+        if (exifRunsInline(triggeredUris.isNotEmpty())) {+            setExifData(scanRepository, applicationContext)+        } else {+            ExifWorker.enqueue(applicationContext)+        }          // OCR and face grouping are both always on (no opt-in). Each worker is         // inert if its data/model assets are missing.@@ -194,6 +205,48 @@ class OCRWorker(context: Context, params: WorkerParameters) : CoroutineWorker(co     } } +/**+ * Trailing EXIF pass for triggered / foreground imports.+ *+ * A triggered sync upserts its rows first (visible in the gallery flow) and+ * enqueues this worker instead of running [setExifData] inline, so geo /+ * panorama enrichment lands on the already-visible rows shortly after —+ * without a large unscanned backlog delaying the new photo's worker.+ * Generation-complete syncs do NOT use this worker for their own pass:+ * they run EXIF inline ahead of the watermark write (see [exifRunsInline]).+ */+class ExifWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {++    override suspend fun doWork(): WorkResult = withContext(Dispatchers.IO) {+        setForeground(createForegroundInfo())+        val scanRepository = PhotoScanRepository.get(applicationContext)+        setExifData(scanRepository, applicationContext)+        WorkResult.success()+    }++    private fun createForegroundInfo(): ForegroundInfo = applicationContext.syncForegroundInfo(+        notificationId = 105,+        channelId = "exif_worker",+        channelName = "Photo Sync",+        title = "Reading Photo Details",+        text = "Extracting locations and photo details...",+    )++    /** Shared constants and helpers for ExifWorker. */+    companion object {+        const val WORK_NAME = "ExifWorker"++        fun enqueue(context: Context) {+            val request = OneTimeWorkRequestBuilder<ExifWorker>().build()+            WorkManager.getInstance(context).enqueueUniqueWork(+                WORK_NAME,+                ExistingWorkPolicy.KEEP,+                request,+            )+        }+    }+}+ /**  * A persisted "has this one-off job run yet" bit. An interface so the  * once-only behaviour of [syncLibrary] is testable without DataStore.@@ -252,6 +305,50 @@ private object AlreadySetFlag : OneTimeFlag { internal fun generationWatermarkAfter(triggered: Boolean, currentGeneration: Long): Long? =     if (triggered) null else currentGeneration +/**+ * Whether a sync runs its EXIF pass inline, before returning.+ *+ * Only a generation-complete (untriggered) sync does: the watermark write+ * that follows it may only advance after the EXIF pass (0e2d54511), so the+ * pass cannot trail that sync. A triggered sync's rows are upserted before+ * any EXIF work either way; running the (possibly backlog-long) pass inline+ * would only delay the worker's turnaround, so triggered syncs defer it to+ * [ExifWorker] — the rows stay visible, enrichment catches up.+ */+internal fun exifRunsInline(triggered: Boolean): Boolean = !triggered++/**+ * The item URIs in [uris] — those carrying a MediaStore id. Collection+ * URIs (and anything unparseable) are dropped: [syncPhotos] widens an+ * id-less triggered list to a null selection, i.e. a full provider scan,+ * which the foreground path must never do.+ */+internal fun triggeredItemUris(uris: List<Uri>): List<Uri> =+    uris.filter { runCatching { ContentUris.parseId(it) }.isSuccess }++/**+ * Foreground fast import of just-changed [uris]: metadata only.+ *+ * Keeps only item URIs (see [triggeredItemUris]), then runs the ordinary+ * triggered [syncPhotos] — an `_id IN (...)` selection over the provider,+ * an upsert into Room, and nothing else. No full scan, no EXIF/OCR/face+ * work inline, and no watermark write: enrichment trails via the workers+ * the caller enqueues, and the generation watermark stays owned by the+ * generation-complete background sync. Returns false (importing nothing)+ * when no URI names an item, so a collection-level callback can never+ * widen into a scan.+ */+suspend fun syncTriggeredPhotos(+    context: Context,+    repository: PhotosRepository,+    uris: List<Uri>,+): Boolean {+    val items = triggeredItemUris(uris)+    if (items.isEmpty()) return false+    syncPhotos(context, repository, items)+    return true+}+ /**  * The untriggered library sync: incremental from [lastGeneration], unless a  * full scan is owed — rows still missing their mimeType, the one-time
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 933a23dcde..8414708e54 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,14 @@ package com.vayunmathur.photos.ui  import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.platform.LocalContext+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.Route import com.vayunmathur.photos.platform.GalleryUiState@@ -44,6 +48,27 @@ fun GalleryPage(         enqueueSyncWork(context)     } +    // Foreground freshness: while this screen is started, a MediaStore+    // content observer imports just-taken photos within moments (debounced+    // item-URI sync in the ViewModel); on stop it unregisters, so no+    // observer leaks into the background. The WorkManager content trigger+    // above remains the background safety net.+    val lifecycleOwner = LocalLifecycleOwner.current+    DisposableEffect(lifecycleOwner, galleryViewModel) {+        val observer = LifecycleEventObserver { _, event ->+            when (event) {+                Lifecycle.Event.ON_START -> galleryViewModel.startForegroundObserving()+                Lifecycle.Event.ON_STOP -> galleryViewModel.stopForegroundObserving()+                else -> Unit+            }+        }+        lifecycleOwner.lifecycle.addObserver(observer)+        onDispose {+            lifecycleOwner.lifecycle.removeObserver(observer)+            galleryViewModel.stopForegroundObserving()+        }+    }+     // Trash/delete/album actions request MANAGE_MEDIA contextually inside     // rememberGalleryActions (rememberManageMediaAction); nothing to ask for     // on this browsing screen.
photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.ktindex c59456613a..0267b3c9dd 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/GalleryLoadProfileTest.kt@@ -21,10 +21,15 @@ import com.vayunmathur.photos.platform.GalleryViewModel import com.vayunmathur.photos.platform.ImageLoader import com.vayunmathur.photos.platform.PhotoScanStore import com.vayunmathur.photos.platform.PhotoStore+import com.vayunmathur.photos.platform.ForegroundMediaObserver+import com.vayunmathur.photos.platform.MediaStoreRegistrar import com.vayunmathur.photos.platform.OneTimeFlag+import com.vayunmathur.photos.platform.exifRunsInline import com.vayunmathur.photos.platform.generationWatermarkAfter import com.vayunmathur.photos.platform.syncLibrary import com.vayunmathur.photos.platform.syncPhotos+import com.vayunmathur.photos.platform.syncTriggeredPhotos+import com.vayunmathur.photos.platform.triggeredItemUris import com.vayunmathur.photos.platform.workInfosOverride import com.vayunmathur.photos.ui.groupPhotosByMonth import kotlin.test.Test@@ -251,6 +256,124 @@ class GalleryLoadProfileTest {         assertEquals(99L, generationWatermarkAfter(triggered = false, currentGeneration = 99L))     } +    @Test+    fun exifTrailsTriggeredSyncsButRunsInlineForGenerationCompleteSyncs() {+        // 0e2d54511 invariant extended: the watermark still only advances+        // after an inline EXIF pass on a generation-complete sync, but a+        // triggered sync defers EXIF to ExifWorker — its rows are already+        // upserted/visible, so the backlog cannot delay them.+        assertEquals(false, exifRunsInline(triggered = true))+        assertEquals(true, exifRunsInline(triggered = false))+    }++    @Test+    fun triggeredForegroundImportIsItemOnlyAndCollectionUriNeverWidensToFullScan() = runBlocking {+        ShadowContentResolver.registerProviderInternal(MediaStore.AUTHORITY, OneRowProvider())+        val repository = FakePhotosRepository(context)++        // Collection-level callback (no item id): importing nothing is the+        // contract — widening this to syncPhotos(null-selection) would be a+        // full provider scan on the foreground path.+        val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI+        assertEquals(emptyList(), triggeredItemUris(listOf(collection)))+        assertEquals(false, syncTriggeredPhotos(context, repository, listOf(collection)))+        assertTrue(repository.upsertedBatches.isEmpty())+        assertTrue(repository.deletedBatches.isEmpty())++        // One new item URI: exactly that row is upserted, with enrichment+        // fields still unset (EXIF trails the visible row).+        val item = android.content.ContentUris.withAppendedId(collection, 1L)+        assertEquals(listOf(item), triggeredItemUris(listOf(item, collection)))+        assertEquals(true, syncTriggeredPhotos(context, repository, listOf(item)))+        val imported = repository.upsertedBatches.single().single()+        assertEquals(1L, imported.id)+        assertEquals(false, imported.exifSet)+        assertEquals(null, imported.lat)+        Unit+    }++    private class RecordingRegistrar : MediaStoreRegistrar {+        val registeredUris = mutableListOf<Uri>()+        var unregisterCalls = 0+        override fun register(+            observer: android.database.ContentObserver,+            uri: Uri,+            notifyForDescendants: Boolean,+        ) {+            registeredUris += uri+        }++        override fun unregister(observer: android.database.ContentObserver) {+            unregisterCalls+++        }+    }++    @Test+    fun foregroundObserverRegistersOnStartUnregistersOnStopWithoutLeak() {+        val registrar = RecordingRegistrar()+        val scope = CoroutineScope(Dispatchers.Default)+        val received = mutableListOf<List<Uri>>()+        val observer = ForegroundMediaObserver(registrar, scope, debounceMs = 50L) { uris ->+            synchronized(received) { received += uris }+        }+        assertEquals(false, observer.isRegistered)++        observer.start()+        assertEquals(true, observer.isRegistered)+        assertEquals(ForegroundMediaObserver.OBSERVED_URIS, registrar.registeredUris)+        // Repeat start is a no-op: no double registration to leak.+        observer.start()+        assertEquals(2, registrar.registeredUris.size)++        // A pending debounced import is cancelled by stop, not delivered+        // after the observer is gone.+        val item = Uri.parse("content://media/external/images/media/9")+        observer.onMediaChanged(item)+        observer.stop()+        assertEquals(false, observer.isRegistered)+        assertEquals(1, registrar.unregisterCalls)+        // Repeat stop is a no-op.+        observer.stop()+        assertEquals(1, registrar.unregisterCalls)+        Thread.sleep(200)+        synchronized(received) { assertTrue(received.isEmpty(), received.toString()) }++        // Late callbacks after stop are dropped; a restart re-registers.+        observer.onMediaChanged(item)+        observer.start()+        assertEquals(true, observer.isRegistered)+        assertEquals(4, registrar.registeredUris.size)+        observer.stop()+        assertEquals(2, registrar.unregisterCalls)+        scope.cancel()+    }++    @Test+    fun foregroundObserverDebouncesAndDedupesBurstIntoOneTriggeredImport() {+        val registrar = RecordingRegistrar()+        val scope = CoroutineScope(Dispatchers.Default)+        val received = mutableListOf<List<Uri>>()+        val observer = ForegroundMediaObserver(registrar, scope, debounceMs = 50L) { uris ->+            synchronized(received) { received += uris }+        }+        observer.start()+        val a = Uri.parse("content://media/external/images/media/9")+        val b = Uri.parse("content://media/external/video/media/10")+        // One capture firing several callbacks (incl. a duplicate) coalesces.+        observer.onMediaChanged(a)+        observer.onMediaChanged(a)+        observer.onMediaChanged(b)+        observer.onMediaChanged(null)+        val batch = awaitValue {+            synchronized(received) { received.singleOrNull() }+        }+        assertEquals(listOf(a, b), batch)+        Thread.sleep(150)+        synchronized(received) { assertEquals(1, received.size) }+        observer.stop()+        scope.cancel()+    }+     /** Idles the paused main looper until [read] yields a value (bounded, real time). */     private fun <T> awaitValue(read: () -> T?): T {         val looper = org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())
photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.ktindex 033f3e9cce..b382b6d513 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/GalleryViewModelRealRepoTest.kt@@ -243,6 +243,104 @@ class GalleryViewModelRealRepoTest {         Unit     } +    private class FreshPhotoProvider : android.content.ContentProvider() {+        override fun onCreate() = true++        override fun query(+            uri: android.net.Uri, projection: Array<out String>?, selection: String?,+            selectionArgs: Array<out String>?, sortOrder: String?,+        ): android.database.Cursor = throw UnsupportedOperationException("bundle query only")++        override fun query(+            uri: android.net.Uri, projection: Array<out String>?, queryArgs: android.os.Bundle?,+            cancellationSignal: android.os.CancellationSignal?,+        ): android.database.Cursor {+            val columns = projection ?: COLUMNS+            val cursor = android.database.MatrixCursor(columns)+            if (!uri.toString().contains("/video/")) {+                val byName = COLUMNS.zip(+                    arrayOf<Any?>(+                        777L, "fresh.jpg", 1_700_000_000_000L, 1_700_000_000L, 1_700_000_000L,+                        100, 100, 0, "image/jpeg", "Camera", 0, null,+                    ),+                ).toMap()+                cursor.addRow(columns.map { byName[it] })+            }+            return cursor+        }++        override fun getType(uri: android.net.Uri): String? = null+        override fun insert(uri: android.net.Uri, values: android.content.ContentValues?): android.net.Uri? = null+        override fun delete(uri: android.net.Uri, selection: String?, selectionArgs: Array<out String>?) = 0+        override fun update(+            uri: android.net.Uri, values: android.content.ContentValues?, selection: String?,+            selectionArgs: Array<out String>?,+        ) = 0++        companion object {+            val COLUMNS = arrayOf(+                android.provider.MediaStore.MediaColumns._ID,+                android.provider.MediaStore.MediaColumns.DISPLAY_NAME,+                android.provider.MediaStore.MediaColumns.DATE_TAKEN,+                android.provider.MediaStore.MediaColumns.DATE_ADDED,+                android.provider.MediaStore.MediaColumns.DATE_MODIFIED,+                android.provider.MediaStore.MediaColumns.WIDTH,+                android.provider.MediaStore.MediaColumns.HEIGHT,+                android.provider.MediaStore.MediaColumns.IS_TRASHED,+                android.provider.MediaStore.MediaColumns.MIME_TYPE,+                android.provider.MediaStore.MediaColumns.BUCKET_DISPLAY_NAME,+                android.provider.MediaStore.MediaColumns.IS_FAVORITE,+                android.provider.MediaStore.Video.Media.DURATION,+            )+        }+    }++    @Test fun triggeredImportOfOneNewPhotoEmitsInGalleryFlowBeforeEnrichmentLands() = runBlocking {+        val provider = FreshPhotoProvider()+        provider.attachInfo(app, android.content.pm.ProviderInfo().apply {+            authority = "media"+            packageName = app.packageName+        })+        org.robolectric.shadows.ShadowContentResolver.registerProviderInternal("media", provider)++        val vm = viewModel()+        var trailingEnqueues = 0+        vm.trailingEnrichmentHook = { trailingEnqueues++ }+        val jobs = collect(vm)+        await("initial empty gallery") { !vm.galleryLoading.value && vm.galleryPhotos.value.isEmpty() }++        // Foreground fast path for one just-taken photo: metadata import+        // only. The row must emit in the gallery flow with enrichment+        // fields still unset — visibility is not gated on the EXIF pass.+        val item = android.content.ContentUris.withAppendedId(+            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 777L,+        )+        vm.importTriggeredPhotos(listOf(item))+        await("new photo visible in gallery flow") {+            vm.galleryPhotos.value.map { it.name } == listOf("fresh.jpg")+        }+        val visible = vm.galleryPhotos.value.single()+        assertEquals(777L, visible.id)+        assertFalse(visible.exifSet, "row visible before EXIF enrichment")+        assertEquals(null, visible.lat)+        assertEquals(1, trailingEnqueues)++        // A collection-level callback imports nothing and enqueues nothing:+        // it must never widen into a full scan on the foreground path.+        vm.importTriggeredPhotos(listOf(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI))+        assertEquals(1, trailingEnqueues)+        assertEquals(listOf("fresh.jpg"), vm.galleryPhotos.value.map { it.name })++        // Enrichment trails the visible row: the EXIF pass now lands its+        // fields on the same row (unreadable test URI still marks it set).+        com.vayunmathur.photos.platform.setExifData(installed.scan, app)+        await("exif enrichment landed on visible row") {+            vm.galleryPhotos.value.singleOrNull()?.exifSet == true+        }+        jobs.forEach { it.cancel() }+        Unit+    }+     @Test fun resolveAndIndexFindsSeededRow() = runBlocking {         val repo = installed.photos         repo.upsertAll(listOf(photo("indexed", 100L)))
photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.ktindex eba58ee75f..e8587d6405 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/SyncWorkersRealRepoTest.kt@@ -216,6 +216,10 @@ class SyncWorkersRealRepoTest {         assertEquals(ListenableWorker.Result.success(), clip.doWork())         val face = TestListenableWorkerBuilder<FaceWorker>(context).build()         assertEquals(ListenableWorker.Result.success(), face.doWork())+        // The trailing EXIF worker (triggered syncs defer to it) also runs+        // cleanly over an empty library.+        val exif = TestListenableWorkerBuilder<com.vayunmathur.photos.platform.ExifWorker>(context).build()+        assertEquals(ListenableWorker.Result.success(), exif.doWork())         Unit     }