Skip to content

Commit ae77791

Browse files
ADFA-4934: Fix findings from sixth high-effort code review of PR #1682
- ExternalFileInstallViewModel: confirmTemplateInstall() captured the live currentRequestGeneration counter instead of the generation the on-screen dialog actually belongs to. A second VIEW intent bumps that counter synchronously before its own dialog is shown, so tapping Install/Overwrite/Rename on the still-visible (but now stale) prior dialog in that window got misattributed to the newer generation - on success this incorrectly sent Finish, tearing the Activity down (and its viewModelScope) out from under the newer, still in-flight request. Fixed by tracking pendingConfirmationGeneration alongside pendingConfirmationTempFile and keying confirmTemplateInstall() off that; also guards against acting on a tempFile that's already been superseded (and deleted) entirely. - ExternalFileInstallViewModel: IgnoreTemplateInstall had the same root cause - a stale Cancel tap unconditionally sent Finish regardless of whether pendingConfirmationTempFile still matched. Now a no-op when it doesn't. - ExternalFileInstallViewModel: suggestUniqueBaseName()'s attempt-bound check ran before the collision check, so the final candidate returned when MAX_SUGGESTION_ATTEMPTS is hit was never actually checked for collision. Reordered the && operands so the bound only short-circuits after that last check has run. - ExternalFileInstallViewModel: template install failures showed a generic, non-actionable message; now includes the underlying reason (reserved name / already exists / swap failure) via a %1$s arg, matching PluginManagerViewModel's equivalent error path. - PluginManagerViewModel: _uiEffect used the default rendezvous channel, the same latent drop-before-collector-attaches bug class this PR already fixed for ExternalFileInstallViewModel's channel. Switched to Channel.BUFFERED for consistency; not user-visible today, but the channel now also serves the forwarded-.cgp path. - TemplateCollectionRepositoryImpl: extracted the renameTo()+copyTo() fallback (triplicated across the backup/swap/restore steps) into a single moveFile() helper. Not fixed (narrow races / low-value at this stage, not regressions): - installCollection() has no per-destination-name locking, so two concurrent installs to the same target name could race on the final swap. Requires two attachments sharing a name AND overlapping generations to hit; accepted as last-write-wins for now. - InstallTempFiles' hour-old sweep could delete a pending confirmation's temp file if the user leaves a dialog open that long; would need cross-ViewModel "file in use" tracking to fix properly. - installPlugin() awaits initialLoadCompleted before copying the incoming URI, when the two could run concurrently - a cold-start-only latency nicety, not a correctness issue. - dispatchTemplateInstall() does its zip-read/collision-check I/O before its own generation check - inherent to check-then-act, the I/O can't be skipped without knowing in advance it'll be superseded. Verification: full app unit test suite green, including two new regression tests for the generation-capture fix (confirming a stale dialog surfaces success without Finish-ing over a newer request; ignoring a stale dialog doesn't Finish over a newer one) and a strengthened suggestUniqueBaseName test asserting the give-up candidate was actually checked. On-device (R5CN80KZCKD): fresh install and overwrite (via the new moveFile()) both verified with a real .cgt archive - correct dialog content, clean success, no crash, no stray .tmp/.bak files left in the templates directory. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 8bfe68e commit ae77791

5 files changed

Lines changed: 156 additions & 53 deletions

File tree

‎app/src/main/java/com/itsaky/androidide/repositories/TemplateCollectionRepositoryImpl.kt‎

Lines changed: 27 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@ class TemplateCollectionRepositoryImpl : TemplateCollectionRepository {
3838
templatesDir
3939
.listFiles { file -> file.extension.equals(TEMPLATE_ARCHIVE_EXTENSION, ignoreCase = true) }
4040
?.firstOrNull { it.nameWithoutExtension.equals(baseName, ignoreCase = true) }
41+
42+
/**
43+
* Renames [src] to [dst], falling back to copy+delete - renameTo() is unreliable on-device
44+
* even for a same-directory move (confirmed during this PR). [src] is gone on success
45+
* either way; left untouched on failure.
46+
*/
47+
private fun moveFile(
48+
src: File,
49+
dst: File,
50+
): Boolean =
51+
src.renameTo(dst) ||
52+
runCatching { src.copyTo(dst, overwrite = true) }.isSuccess.also { copied -> if (copied) src.delete() }
4153
}
4254

4355
override suspend fun inspectCollection(candidateFile: File): Result<TemplateCollectionRepository.CollectionInfo> =
@@ -140,52 +152,33 @@ class TemplateCollectionRepositoryImpl : TemplateCollectionRepository {
140152

141153
// Back up (rather than delete) any existing destFile, so it can be put back if
142154
// the swap below fails for any reason - the existing collection is only ever
143-
// removed once the new one is confirmed successfully in its place. Same
144-
// renameTo()-then-copyTo() fallback as the swap below: renameTo() is unreliable
145-
// on-device even for a same-directory move (confirmed there during this PR).
155+
// removed once the new one is confirmed successfully in its place.
146156
val hadExisting = destFile.exists()
147157
val backupFile = File(templatesDir, "${destFile.name}.${UUID.randomUUID()}.bak")
148-
if (hadExisting) {
149-
val backedUp =
150-
destFile.renameTo(backupFile) ||
151-
runCatching { destFile.copyTo(backupFile, overwrite = true).also { destFile.delete() } }.isSuccess
152-
if (!backedUp) {
153-
stagingFile.delete()
154-
throw IllegalStateException("Failed to back up existing file before replacing: ${destFile.name}")
155-
}
158+
if (hadExisting && !moveFile(destFile, backupFile)) {
159+
stagingFile.delete()
160+
throw IllegalStateException("Failed to back up existing file before replacing: ${destFile.name}")
156161
}
157162

158163
// Both files are now on the same volume (templatesDir), so this is a cheap,
159164
// same-directory move - renameTo() failing here (as opposed to across the
160165
// temp/templates boundary candidateFile itself would have to cross) would be
161-
// unexpected, but fall back to a copy anyway.
162-
val swapSucceeded =
163-
stagingFile.renameTo(destFile) ||
164-
runCatching { stagingFile.copyTo(destFile, overwrite = true) }.isSuccess
165-
166-
if (!swapSucceeded) {
167-
if (hadExisting) {
168-
val restored =
169-
backupFile.renameTo(destFile) ||
170-
runCatching { backupFile.copyTo(destFile, overwrite = true) }.isSuccess
171-
if (!restored) {
172-
// Nothing more we can do here - surface it loudly rather than silently
173-
// leaving the user's original collection sitting under the backup's
174-
// random filename, invisible to findExistingCollision().
175-
log.error(
176-
"Failed to restore backup after a failed swap for \"{}\" - original content may still be at: {}",
177-
destFile.name,
178-
backupFile.name,
179-
)
180-
} else {
181-
backupFile.delete()
182-
}
166+
// unexpected, but moveFile() falls back to a copy anyway.
167+
if (!moveFile(stagingFile, destFile)) {
168+
if (hadExisting && !moveFile(backupFile, destFile)) {
169+
// Nothing more we can do here - surface it loudly rather than silently
170+
// leaving the user's original collection sitting under the backup's
171+
// random filename, invisible to findExistingCollision().
172+
log.error(
173+
"Failed to restore backup after a failed swap for \"{}\" - original content may still be at: {}",
174+
destFile.name,
175+
backupFile.name,
176+
)
183177
}
184178
stagingFile.delete()
185179
throw IllegalStateException("Failed to replace existing file: ${destFile.name}")
186180
}
187181

188-
stagingFile.delete()
189182
if (hadExisting && backupFile.exists() && !backupFile.delete()) {
190183
log.warn("Installed but failed to delete backup file: {}", backupFile.name)
191184
}

‎app/src/main/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModel.kt‎

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,24 @@ class ExternalFileInstallViewModel(
9393
// there's no ordering ambiguity about which file it refers to.
9494
private var pendingConfirmationTempFile: File? = null
9595

96+
// The generation pendingConfirmationTempFile actually belongs to - NOT necessarily
97+
// currentRequestGeneration, which can already have moved on to a newer, still-in-flight
98+
// request by the time the user taps a button on the dialog still on screen (its onReceived()
99+
// bumped the counter synchronously, but hasn't reached supersedePendingConfirmation() yet).
100+
// confirmTemplateInstall()/onEvent() must key off this, not the live counter, or a stale
101+
// dialog's action gets misattributed to the newer request and can tear the Activity down out
102+
// from under it.
103+
private var pendingConfirmationGeneration: Int = 0
104+
96105
private fun isCurrentGeneration(generation: Int) = generation == currentRequestGeneration
97106

98-
private suspend fun supersedePendingConfirmation(newPendingFile: File?) {
107+
private suspend fun supersedePendingConfirmation(
108+
newPendingFile: File?,
109+
newGeneration: Int,
110+
) {
99111
pendingConfirmationTempFile?.let { old -> if (old != newPendingFile) deleteQuietly(old) }
100112
pendingConfirmationTempFile = newPendingFile
113+
pendingConfirmationGeneration = newGeneration
101114
}
102115

103116
/** Call once, from `Activity.onCreate()`/`onNewIntent()`, with the VIEW intent's data [Uri]. */
@@ -164,7 +177,7 @@ class ExternalFileInstallViewModel(
164177
// Forwarded as a plain path, not a content:// Uri: both activities run in this
165178
// same process and already trust filesDir paths, so PluginManagerViewModel can
166179
// install straight from this file instead of copying it a second time.
167-
supersedePendingConfirmation(null)
180+
supersedePendingConfirmation(null, generation)
168181
_uiEffect.trySend(ExternalFileInstallUiEffect.ForwardToPluginManager(tempFile.absolutePath))
169182
} else {
170183
dispatchTemplateInstall(tempFile, baseName, generation)
@@ -200,7 +213,7 @@ class ExternalFileInstallViewModel(
200213
return
201214
}
202215

203-
supersedePendingConfirmation(tempFile)
216+
supersedePendingConfirmation(tempFile, generation)
204217
// This dialog's buttons must start enabled regardless of whether some earlier,
205218
// now-abandoned generation's install is still finishing up in the background (see
206219
// confirmTemplateInstall()'s own generation check for the other half of this).
@@ -223,10 +236,16 @@ class ExternalFileInstallViewModel(
223236
}
224237

225238
is ExternalFileInstallUiEvent.IgnoreTemplateInstall -> {
226-
if (pendingConfirmationTempFile == event.tempFile) pendingConfirmationTempFile = null
227-
viewModelScope.launch {
228-
deleteQuietly(event.tempFile)
229-
_uiEffect.trySend(ExternalFileInstallUiEffect.Finish)
239+
// If this doesn't match, the dialog this event was fired from has already been
240+
// superseded (and its tempFile already deleted by supersedePendingConfirmation) -
241+
// nothing left on screen to Finish, and Finish-ing anyway would tear down the
242+
// Activity out from under whatever newer dialog is now showing.
243+
if (pendingConfirmationTempFile == event.tempFile) {
244+
pendingConfirmationTempFile = null
245+
viewModelScope.launch {
246+
deleteQuietly(event.tempFile)
247+
_uiEffect.trySend(ExternalFileInstallUiEffect.Finish)
248+
}
230249
}
231250
}
232251
}
@@ -241,16 +260,21 @@ class ExternalFileInstallViewModel(
241260
// the second call's renameTo()/copyTo() would otherwise race the first's on the same
242261
// tempFile and surface a spurious failure toast.
243262
if (_isInstalling.value) return
263+
// If this doesn't match, the dialog this event was fired from has already been superseded
264+
// (its tempFile already deleted by supersedePendingConfirmation) - there's nothing left to
265+
// install, and proceeding anyway would mean using currentRequestGeneration as this
266+
// install's generation, misattributing it to whatever newer request bumped the counter.
267+
if (pendingConfirmationTempFile != tempFile) return
244268
_isInstalling.value = true
245-
// Captured now: if a newer onReceived() supersedes this one's dialog before this install
246-
// finishes (see dispatchTemplateInstall()), this install must neither tear down the
247-
// Activity out from under the newer dialog nor touch _isInstalling/pendingConfirmation
248-
// state that by then belongs to a completely different request.
249-
val generation = currentRequestGeneration
269+
// The generation the now-showing dialog was committed under - NOT currentRequestGeneration,
270+
// which may already have moved on to a newer, still-in-flight request (see
271+
// pendingConfirmationGeneration's kdoc). This install must neither tear down the Activity
272+
// out from under that newer request nor touch state that by then belongs to it.
273+
val generation = pendingConfirmationGeneration
250274
// From here on, tempFile's fate is owned by this install attempt, not "a dialog awaiting
251275
// an answer" - a subsequent onReceived() for a different file must not delete it out from
252276
// under an install already in flight.
253-
if (pendingConfirmationTempFile == tempFile) pendingConfirmationTempFile = null
277+
pendingConfirmationTempFile = null
254278

255279
viewModelScope.launch {
256280
templateCollectionRepository
@@ -278,7 +302,12 @@ class ExternalFileInstallViewModel(
278302
// they can retry - e.g. pick a different name after a collision, or
279303
// Overwrite instead. If a newer request has since superseded this dialog,
280304
// there's nothing left on-screen to retry against, so skip ShowError too.
281-
_uiEffect.trySend(ExternalFileInstallUiEffect.ShowError(R.string.msg_template_install_failed))
305+
_uiEffect.trySend(
306+
ExternalFileInstallUiEffect.ShowError(
307+
R.string.msg_template_install_failed,
308+
listOf(exception.message ?: exception.javaClass.simpleName),
309+
),
310+
)
282311
}
283312
}
284313
if (isCurrentGeneration(generation)) {
@@ -300,7 +329,10 @@ class ExternalFileInstallViewModel(
300329
suspend fun suggestUniqueBaseName(baseName: String): String {
301330
var candidate = baseName
302331
var suffix = 2
303-
while (suffix <= MAX_SUGGESTION_ATTEMPTS && templateCollectionRepository.findExistingCollision(candidate) != null) {
332+
// Collision must be checked before the attempt-count bound, not after: checking
333+
// `suffix <= MAX` first would let the bound short-circuit the very last candidate's
334+
// collision check, silently returning it unverified once the cap is hit.
335+
while (templateCollectionRepository.findExistingCollision(candidate) != null && suffix <= MAX_SUGGESTION_ATTEMPTS) {
304336
candidate = "$baseName ($suffix)"
305337
suffix++
306338
}
@@ -317,7 +349,7 @@ class ExternalFileInstallViewModel(
317349
// A stale (already-superseded) request never reaches here (see the isCurrentGeneration
318350
// check above), so whatever's still pending at this point genuinely belongs to an earlier,
319351
// now-being-terminated request and must be cleaned up rather than left dangling.
320-
supersedePendingConfirmation(null)
352+
supersedePendingConfirmation(null, generation)
321353
// See confirmTemplateInstall()'s onSuccess: the Screen suspends on ShowError until the
322354
// flashbar is actually shown before processing Finish, so no delay is needed here either.
323355
_uiEffect.trySend(ExternalFileInstallUiEffect.ShowError(messageResId))

‎app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,11 @@ class PluginManagerViewModel(
7575
// Public read-only state
7676
val uiState: StateFlow<PluginManagerUiState> = _uiState.asStateFlow()
7777

78-
// Channel for one-time UI effects
79-
private val _uiEffect = Channel<PluginManagerUiEffect>()
78+
// Channel for one-time UI effects. Buffered (not rendezvous): a synchronous decision path
79+
// (e.g. handlePendingInstallExtra()'s effect right after onCreate()/onNewIntent()) can
80+
// otherwise complete before the Activity's collector actually attaches, silently dropping the
81+
// effect - see ExternalFileInstallViewModel's identical reasoning for its own uiEffect.
82+
private val _uiEffect = Channel<PluginManagerUiEffect>(capacity = Channel.BUFFERED)
8083
val uiEffect = _uiEffect.receiveAsFlow()
8184

8285
// Current operation tracking

‎app/src/test/java/com/itsaky/androidide/viewmodels/ExternalFileInstallViewModelTest.kt‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import com.itsaky.androidide.ui.models.ExternalFileInstallUiEffect
1111
import com.itsaky.androidide.ui.models.ExternalFileInstallUiEvent
1212
import com.itsaky.androidide.viewmodel.MainDispatcherRule
1313
import io.mockk.coEvery
14+
import io.mockk.coVerify
1415
import io.mockk.every
1516
import io.mockk.mockk
1617
import io.mockk.verify
@@ -197,6 +198,77 @@ class ExternalFileInstallViewModelTest {
197198
assertThat(viewModel.isInstalling.value).isFalse()
198199
}
199200

201+
@Test
202+
fun `confirming a stale dialog uses its own generation, not a newer request's`() =
203+
runTest {
204+
// Regression test: confirmTemplateInstall() must key off the generation the on-screen
205+
// dialog was actually committed under (pendingConfirmationGeneration), not the live
206+
// currentRequestGeneration counter, which a second onReceived() can already have bumped
207+
// before its own dialog is shown.
208+
stubTemplatesFeatureAvailable(true)
209+
val info = TemplateCollectionRepository.CollectionInfo(templateNames = listOf("Empty Activity"))
210+
coEvery { templateCollectionRepository.inspectCollection(any()) } returns Result.success(info)
211+
coEvery { templateCollectionRepository.findExistingCollision("first") } returns null
212+
coEvery { templateCollectionRepository.installCollection(any(), any(), any()) } returns Result.success(Unit)
213+
214+
val secondGate = CompletableDeferred<Unit>()
215+
coEvery { templateCollectionRepository.findExistingCollision("second") } coAnswers {
216+
secondGate.await()
217+
null
218+
}
219+
220+
viewModel.onReceived(sourceUriFor("first.cgt"))
221+
val firstEffect = viewModel.uiEffect.first() as ExternalFileInstallUiEffect.ShowTemplateInstallConfirmation
222+
val firstTempFile = firstEffect.tempFile
223+
224+
// A second VIEW intent arrives (e.g. via onNewIntent) while file A's dialog is still
225+
// the one on screen - this bumps currentRequestGeneration synchronously, well before
226+
// file B's own async pipeline (gated on secondGate) can commit its own dialog.
227+
viewModel.onReceived(sourceUriFor("second.cgt"))
228+
229+
// The user taps Install on the still-visible (but now globally-stale) dialog for A.
230+
viewModel.onEvent(
231+
ExternalFileInstallUiEvent.ConfirmTemplateInstall(firstTempFile, firstEffect.suggestedBaseName, overwrite = false),
232+
)
233+
234+
// File A's install genuinely succeeds - but must not Finish the Activity, since file
235+
// B's request (a newer generation) is still in flight and hasn't shown its own dialog.
236+
assertThat(viewModel.uiEffect.first()).isInstanceOf(ExternalFileInstallUiEffect.ShowSuccess::class.java)
237+
238+
secondGate.complete(Unit)
239+
assertThat(viewModel.uiEffect.first()).isInstanceOf(ExternalFileInstallUiEffect.ShowTemplateInstallConfirmation::class.java)
240+
}
241+
242+
@Test
243+
fun `ignoring a stale dialog does not finish the activity out from under a newer one`() =
244+
runTest {
245+
stubTemplatesFeatureAvailable(true)
246+
val info = TemplateCollectionRepository.CollectionInfo(templateNames = listOf("Empty Activity"))
247+
coEvery { templateCollectionRepository.inspectCollection(any()) } returns Result.success(info)
248+
coEvery { templateCollectionRepository.findExistingCollision(any()) } returns null
249+
coEvery { templateCollectionRepository.installCollection(any(), any(), any()) } returns Result.success(Unit)
250+
251+
viewModel.onReceived(sourceUriFor("first.cgt"))
252+
val firstEffect = viewModel.uiEffect.first() as ExternalFileInstallUiEffect.ShowTemplateInstallConfirmation
253+
val firstTempFile = firstEffect.tempFile
254+
255+
viewModel.onReceived(sourceUriFor("second.cgt"))
256+
val secondEffect = viewModel.uiEffect.first() as ExternalFileInstallUiEffect.ShowTemplateInstallConfirmation
257+
258+
// A stale Ignore/Cancel tap for file A's now-replaced dialog must be a no-op - in
259+
// particular it must not Finish the Activity out from under file B's current dialog.
260+
viewModel.onEvent(ExternalFileInstallUiEvent.IgnoreTemplateInstall(firstTempFile))
261+
262+
viewModel.onEvent(
263+
ExternalFileInstallUiEvent.ConfirmTemplateInstall(
264+
secondEffect.tempFile,
265+
secondEffect.suggestedBaseName,
266+
overwrite = false,
267+
),
268+
)
269+
assertThat(viewModel.uiEffect.first()).isInstanceOf(ExternalFileInstallUiEffect.ShowSuccess::class.java)
270+
}
271+
200272
@Test
201273
fun `invalid cgt shows invalid-file error`() =
202274
runTest {
@@ -263,6 +335,9 @@ class ExternalFileInstallViewModelTest {
263335
val suggested = viewModel.suggestUniqueBaseName("foo")
264336

265337
assertThat(suggested).isEqualTo("foo (50)")
338+
// The give-up candidate itself must actually have been checked for collision - not
339+
// returned unverified because the attempt-count bound short-circuited before it.
340+
coVerify(exactly = 1) { templateCollectionRepository.findExistingCollision("foo (50)") }
266341
}
267342

268343
private fun stubPluginManagerAvailable(available: Boolean) {

‎resources/src/main/res/values/strings.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1102,7 +1102,7 @@
11021102
<string name="hint_new_template_collection_name">New collection name</string>
11031103
<string name="msg_template_installed">"%1$s" installed successfully</string>
11041104
<string name="msg_template_invalid_file">Invalid or corrupted template collection file.</string>
1105-
<string name="msg_template_install_failed">Failed to install template collection.</string>
1105+
<string name="msg_template_install_failed">Failed to install template collection: %1$s</string>
11061106

11071107
<string name="msg_template_warnings">\n\nProject creation finished with warnings/errors. Open IDE Logs for details.</string>
11081108

0 commit comments

Comments
 (0)