Repository navigation
Fix welcome images not reloading when the URL changes mid-download - #208
Conversation
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@rymorale for review |
rymorale
left a comment
There was a problem hiding this comment.
Unfortunately I don't think this change fixes #207. I verified that against the PR head with a unit test and an instrumented test, both described below.
Root cause is in AsyncImage, not the provider
On a cold open, ConciergeChatViewModel seeds the welcome config with mock prompt image URLs (initializeWelcomeConfig). ConciergeChat's LaunchedEffect(currentTheme) then swaps in the theme's URLs right after the first composition. Because WelcomeCard renders the rows with an unkeyed forEach, the existing AsyncImages just get a new url.
rememberRemoteImage (AsyncImage.kt:125-145) uses produceState(initial, key1 = url). The state holder itself is not keyed on url, so it survives the URL change. The producer only loads when value.state == Loading. When the old load is cancelled, the caller's catch (e: Exception) catches the CancellationException and sets Error. The producer for the new URL then sees Error and never requests the new URL, so the row stays as the blank error box (AsyncImage.kt:71-81).
This PR doesn't change any of that. download.await() still throws the caller's CancellationException into that same catch. In an instrumented test using the real DefaultImageProvider with a fake Networking, swapping the URL mid-download at this PR's head gave:
requested=[https://example.com/mock.png] cachedOld=false cachedNew=false
The new URL was never requested and nothing was cached. The same stale state also keeps the old (mock) image when the old download finishes before the swap.
Suggested fix: reset the load state per URL in rememberRemoteImage, e.g. wrap it in key(url) { ... } or use remember(url) + LaunchedEffect(url). Also rethrow CancellationException from its catch block. Rethrowing in DefaultImageProvider is fine too, but the caller-side catch is the one that matters.
Other notes
- With this change, the
Unexpected error while downloading image: The coroutine scope left the compositionlog no longer appears, but the images are still blank. That log is the main signal reporters use to identify this bug, so the change makes it harder to diagnose without fixing it. - No tests were added; Codecov reports 60% patch coverage. A regression test for "URL changes while a download is in flight → new URL is requested and rendered" would catch this. The existing
AsyncImageTesttests only check that it renders without crashing.
Validation at PR head
| Check | Result |
|---|---|
ImageProviderTest (18 existing tests) |
pass |
AsyncImageTest (instrumented) |
pass |
make checkformat |
pass |
| New test: download completes after caller cancel → cached | fail |
| New test: URL swap mid-download → new URL requested | fail |
| }.also { bitmap -> | ||
| } | ||
|
|
||
| return download.await().also { bitmap -> |
There was a problem hiding this comment.
[HIGH] The cache write lives in the caller's .also { } after await(). If the caller is cancelled (the case this PR targets), await() throws the CancellationException and this block never runs, so the completed download is discarded rather than cached.
I confirmed this with a unit test: start get(url), cancel the caller after connectAsync is invoked, complete the network callback, then check getCached(url). It returns null.
To keep the "finish and cache anyway" behavior, move the generation-checked cache.put inside the async block.
| * written to the cache and served on the next request. Uses a SupervisorJob so one failed | ||
| * download does not cancel the others. | ||
| */ | ||
| private val downloadScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) |
There was a problem hiding this comment.
[MEDIUM] This scope is never cancelled. ConciergeChatViewModel.onCleared() and the identity-reset path only call imageProvider.clear(), so in-flight downloads keep running after the chat is gone, for up to the 10s connect + 30s read timeouts.
Also, without per-URL de-duplication of in-flight Deferreds, repeated get() calls for the same URL now start parallel downloads that previously would have been cancelled.
If we keep a provider-owned scope, consider cancelling it on onCleared and de-duplicating in-flight requests by URL.
| connection.close() | ||
|
|
||
| bitmap ?: throw IOException("Failed to decode image from URL: $url") | ||
| } catch (e: CancellationException) { |
There was a problem hiding this comment.
[LOW] Inside downloadScope.async, this catch is effectively unreachable, because downloadScope is never cancelled.
The CancellationException that causes the blank images is thrown from await() in the caller and caught by rememberRemoteImage's catch (e: Exception) in AsyncImage.kt, which marks the image as Error. That's where it needs to be rethrown.
On a cold open, ConciergeChatViewModel seeds the welcome config with mock prompt image URLs (initializeWelcomeConfig), and ConciergeChat's LaunchedEffect(currentTheme) swaps in the theme's real URLs right after the first composition. Because WelcomeCard renders rows with an unkeyed forEach, the existing AsyncImage composables just receive a new url. rememberRemoteImage used produceState(initial, key1 = url), but the state holder is not keyed on url, so it survives the URL change. The producer only loads when state == Loading. When the in-flight load for the old URL is cancelled, the caller's catch (e: Exception) swallowed the CancellationException and set the state to Error. The producer for the new URL then saw Error (not Loading) and never requested the new URL, leaving the row stuck as a blank error box. Fix rememberRemoteImage to reset the load state per URL and to rethrow CancellationException from the caller-side catch so a cancelled load is not misreported as Error and does not block the next URL. Also rethrow CancellationException from DefaultImageProvider.get() so cancellation is not logged as an unexpected error. Verified on an Android emulator: welcome images now render on cold open. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
bc01e66 to
5949c23
Compare
|
@rymorale when possible please review. |
| @Composable | ||
| private fun rememberRemoteImage(url: String, onError: ((Throwable) -> Unit)? = null): ImageResult { | ||
| val provider = LocalImageProvider.current | ||
| // Key the state holder on `url` so that when the URL changes (e.g. the welcome config is |
There was a problem hiding this comment.
[HIGH] This comment says the state holder is keyed on url, but the code doesn't do that. produceState(initialValue, key1 = url) keeps its state in an unkeyed remember { mutableStateOf(initialValue) }; key1 only restarts the producer (LaunchedEffect). On a URL change, the previous value is kept and the value.state == ImageLoadingState.Loading guard below skips loading the new URL whenever the old URL had already:
- succeeded: the old (mock) image stays on screen
- failed (e.g. a 404): the row stays a blank error box, which is the Welcome images cancelled when composable leaves composition (Android) #207 symptom
- been cached at first composition: the new URL is never requested
The rethrows only fix the in-flight case. Suggest actually resetting the state per URL, e.g.:
return key(url) {
produceState(...) { ... }.value
}| import androidx.compose.material3.CircularProgressIndicator | ||
| import androidx.compose.runtime.Composable | ||
| import androidx.compose.runtime.produceState | ||
| import kotlinx.coroutines.CancellationException |
There was a problem hiding this comment.
[LOW] nit: this kotlinx import is placed in the middle of the androidx.compose imports. Consider moving it so the imports stay sorted.
Address review feedback: produceState(key1 = url) restarts the producer but retains its previous state, preventing replacement images from loading after an earlier success, error, or cache hit. - Wrap the image state producer in key(url) so each URL starts with its own cached image or fresh Loading state - Preserve cancellation propagation without invoking the error callback - Fix coroutine import ordering - Add Compose UI tests for URL changes during loading, after success, after failure, and after an initial cache hit - Assert the replacement URL is requested and its image pixels render Validation: - AsyncImage UI suite: 7 tests passed - ImageProvider unit suite: 18 tests passed - Temporarily removing URL-keyed state reproduced failures in the success, error, and cache-hit tests; restoring it passed all tests - Android 17 UI tests used a temporary AndroidX test-tooling override; no repository dependency changes included
Description
On a cold open,
ConciergeChatViewModelseeds the welcome config with mock prompt image URLs (initializeWelcomeConfig), andConciergeChat'sLaunchedEffect(currentTheme)swaps in the theme's real URLs right after the first composition. BecauseWelcomeCardrenders rows with an unkeyedforEach, the existingAsyncImagecomposables just receive a newurl.rememberRemoteImageusedproduceState(initial, key1 = url), but the state holder is not keyed onurl, so it survives the URL change. The producer only loads whenstate == Loading. When the in-flight load for the old URL is cancelled, the caller'scatch (e: Exception)swallowed theCancellationExceptionand set the state toError. The producer for the new URL then sawError(notLoading) and never requested the new URL, leaving the row stuck as a blank error box.Fix:
rememberRemoteImagenow resets the load state per URL and rethrowsCancellationExceptionfrom the caller-side catch, so a cancelled load is not misreported asErrorand does not block the next URL.DefaultImageProvider.get()also rethrowsCancellationExceptionso cancellation is not logged as an unexpected error.Related Issue
Fixes #207
Motivation and Context
Welcome-screen images were intermittently blank on Android. The trigger is the welcome config being swapped in right after the first composition (mock → real URLs), which changes the
AsyncImageURL while a download is in flight. Host apps that recompose the welcome screen during load hit this reliably.How Has This Been Tested?
Note: an instrumented regression test for "URL changes mid-download → new URL requested" was authored but could not be run locally — the existing
AsyncImageTestinstrumented tests fail on the test emulator with a pre-existing Espresso/environment error (InputManager.getInstanceNoSuchMethodException) on base code as well, so instrumented tests could not be executed in this environment.Environment: Android emulator, debug build, local SDK checkout via
conciergeSdkPath.Screenshots (if appropriate):
N/A
Types of changes
Checklist: