From 81df219f0cdf44362891e6a79f0cb7e2e4167b2d Mon Sep 17 00:00:00 2001 From: yaturner Date: Wed, 16 Sep 2026 10:33:15 -0700 Subject: [PATCH 01/10] ADFA-5446: Confirm template uninstall/replace instead of failing silently Uninstalling a template refused to run when a same-named file already sat in Downloads, with no way to proceed - the user's only options were delete the Downloads file themselves or give up. Add an "Uninstall template?" confirmation (mirroring the existing Delete confirmation) and, on a Downloads name collision, a "Replace file in Downloads?" prompt that lets the user overwrite it instead of hitting a dead end. TemplateRepository.uninstallTemplate gains an `overwrite` parameter; a collision without it now returns TemplateReplaceConflictException instead of a generic IllegalStateException, so the ViewModel can route it to the new confirmation dialog rather than a plain error toast. Co-Authored-By: Claude Sonnet 5 --- .../repositories/TemplateRepository.kt | 18 +++- .../repositories/TemplateRepositoryImpl.kt | 21 +++- .../templates/TemplateManagerDialogs.kt | 39 ++++++++ .../templates/TemplateManagerScreen.kt | 46 +++++++++ .../ui/models/TemplateManagerUiState.kt | 9 ++ .../viewmodels/TemplateManagerViewModel.kt | 38 ++++++-- .../TemplateRepositoryImplTest.kt | 22 ++++- .../TemplateManagerViewModelTest.kt | 95 +++++++++++++++++++ resources/src/main/res/values/strings.xml | 4 + 9 files changed, 276 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt index ee497b0106..9966e238a2 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.repositories import com.itsaky.androidide.templates.manager.models.CgtFileItem +import java.io.IOException /** * Repository interface for template (`.cgt`) file operations. @@ -20,9 +21,22 @@ interface TemplateRepository { /** Moves [item]'s file from Downloads into the templates directory and reloads templates. */ suspend fun installTemplate(item: CgtFileItem): Result - /** Restores a copy of [item]'s file to Downloads, removes it from the templates directory, and reloads templates. */ - suspend fun uninstallTemplate(item: CgtFileItem): Result + /** + * Restores a copy of [item]'s file to Downloads, removes it from the templates directory, and + * reloads templates. Fails with [TemplateReplaceConflictException] if a file of the same name + * already exists in Downloads, unless [overwrite] is true. + */ + suspend fun uninstallTemplate( + item: CgtFileItem, + overwrite: Boolean = false, + ): Result /** Deletes a not-installed [item]'s file from Downloads. */ suspend fun deleteDownloadFile(item: CgtFileItem): Result } + +/** Thrown by [TemplateRepository.uninstallTemplate] when restoring to Downloads would silently + * overwrite an existing file there and the caller didn't opt into replacing it. */ +class TemplateReplaceConflictException( + val fileName: String, +) : IOException("A file named '$fileName' already exists in Downloads") diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index 21662008d1..a313b45d23 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -137,7 +137,10 @@ class TemplateRepositoryImpl( } } - override suspend fun uninstallTemplate(item: CgtFileItem): Result = + override suspend fun uninstallTemplate( + item: CgtFileItem, + overwrite: Boolean, + ): Result = withContext(Dispatchers.IO) { try { check(item.installed) { "'${item.name}' is not installed" } @@ -146,10 +149,20 @@ class TemplateRepositoryImpl( // Restore a copy to Downloads BEFORE removing it from the store: if the restore // throws, the store copy below is never touched, so the user's only copy survives. val restored = File(downloadDir, item.file.name) - check(!restored.exists()) { "A download named '${restored.name}' already exists in $downloadDir" } - item.file.copyTo(restored, overwrite = false) + val hadExistingDownload = restored.exists() + if (hadExistingDownload && !overwrite) { + return@withContext Result.failure(TemplateReplaceConflictException(restored.name)) + } + item.file.copyTo(restored, overwrite = overwrite) if (!item.file.delete()) { - restored.delete() + // Only roll back a copy this call created itself. When `overwrite` replaced a + // pre-existing Downloads file, that original content is already gone - deleting + // `restored` here would destroy the new copy too and leave the user with nothing, + // whereas the still-installed source (its delete just failed) means leaving the + // new copy in place costs nothing and loses no data. + if (!hadExistingDownload) { + restored.delete() + } throw IOException("Failed to delete source file after copying: ${item.file.absolutePath}") } ITemplateProvider.getInstance(reload = true) diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt index dcdb2f54e3..2ca82f190a 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt @@ -44,6 +44,45 @@ fun DeleteTemplateConfirmationDialog( ) } +@Composable +fun UninstallTemplateConfirmationDialog( + item: CgtFileItem, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.title_uninstall_template)) }, + text = { Text(stringResource(R.string.msg_uninstall_template_confirm, item.displayName)) }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_uninstall_template)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } + }, + ) +} + +/** Shown when uninstalling [item] would silently overwrite an existing Downloads file of the same name. */ +@Composable +fun ReplaceTemplateInDownloadsDialog( + item: CgtFileItem, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.title_replace_template)) }, + text = { Text(stringResource(R.string.msg_replace_template_confirm, item.displayName)) }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(R.string.replace)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } + }, + ) +} + /** File-level details for a single-template .cgt (multi-template files use [TemplateListDialog]). */ @Composable fun TemplateFileDetailsDialog( diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt index 4e6da44a51..cd9bd56903 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt @@ -67,6 +67,16 @@ private sealed interface TemplateManagerDialogState : Parcelable { val path: String, ) : TemplateManagerDialogState + @Parcelize + data class UninstallConfirm( + val path: String, + ) : TemplateManagerDialogState + + @Parcelize + data class ReplaceConfirm( + val path: String, + ) : TemplateManagerDialogState + @Parcelize data class FileDetails( val path: String, @@ -153,6 +163,14 @@ fun TemplateManagerScreen( dialogState = TemplateManagerDialogState.DeleteConfirm(effect.item.file.absolutePath) } + is TemplateManagerUiEffect.ShowUninstallConfirmation -> { + dialogState = TemplateManagerDialogState.UninstallConfirm(effect.item.file.absolutePath) + } + + is TemplateManagerUiEffect.ShowReplaceConfirmation -> { + dialogState = TemplateManagerDialogState.ReplaceConfirm(effect.item.file.absolutePath) + } + is TemplateManagerUiEffect.ShowTemplateDetails -> { dialogState = TemplateManagerDialogState.FileDetails(effect.item.file.absolutePath) } @@ -215,6 +233,34 @@ fun TemplateManagerScreen( } } + is TemplateManagerDialogState.UninstallConfirm -> { + val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } + if (item != null) { + UninstallTemplateConfirmationDialog( + item = item, + onConfirm = { + viewModel.confirmUninstallTemplate(item) + dialogState = TemplateManagerDialogState.None + }, + onDismiss = { dialogState = TemplateManagerDialogState.None }, + ) + } + } + + is TemplateManagerDialogState.ReplaceConfirm -> { + val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } + if (item != null) { + ReplaceTemplateInDownloadsDialog( + item = item, + onConfirm = { + viewModel.confirmUninstallTemplate(item, overwrite = true) + dialogState = TemplateManagerDialogState.None + }, + onDismiss = { dialogState = TemplateManagerDialogState.None }, + ) + } + } + is TemplateManagerDialogState.FileDetails -> { val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } if (item != null) { diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt index b47f16115e..10a1fd6165 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt @@ -50,6 +50,15 @@ sealed class TemplateManagerUiEffect { val item: CgtFileItem, ) : TemplateManagerUiEffect() + data class ShowUninstallConfirmation( + val item: CgtFileItem, + ) : TemplateManagerUiEffect() + + /** A Downloads file with the same name already exists; ask before [uninstallTemplate][com.itsaky.androidide.repositories.TemplateRepository.uninstallTemplate] overwrites it. */ + data class ShowReplaceConfirmation( + val item: CgtFileItem, + ) : TemplateManagerUiEffect() + data class ShowTemplateDetails( val item: CgtFileItem, ) : TemplateManagerUiEffect() diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt index 13df7bca84..bb60d1e76f 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.viewmodels import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.itsaky.androidide.repositories.TemplateReplaceConflictException import com.itsaky.androidide.repositories.TemplateRepository import com.itsaky.androidide.resources.R import com.itsaky.androidide.templates.manager.models.CgtFileItem @@ -42,7 +43,7 @@ class TemplateManagerViewModel( when (event) { is TemplateManagerUiEvent.LoadTemplates -> loadTemplates() is TemplateManagerUiEvent.InstallTemplate -> installTemplate(event.item) - is TemplateManagerUiEvent.UninstallTemplate -> uninstallTemplate(event.item) + is TemplateManagerUiEvent.UninstallTemplate -> showUninstallConfirmation(event.item) is TemplateManagerUiEvent.DeleteDownloadFile -> showDeleteConfirmation(event.item) is TemplateManagerUiEvent.ShowTemplateDetails -> showTemplateDetails(event.item) is TemplateManagerUiEvent.ShowTemplateList -> showTemplateList(event.item) @@ -101,11 +102,26 @@ class TemplateManagerViewModel( } } - private fun uninstallTemplate(item: CgtFileItem) { + private fun showUninstallConfirmation(item: CgtFileItem) { + viewModelScope.launch { + _uiEffect.send(TemplateManagerUiEffect.ShowUninstallConfirmation(item)) + } + } + + /** + * Uninstalls [item] (called after [TemplateManagerUiEffect.ShowUninstallConfirmation] is + * confirmed). A [TemplateReplaceConflictException] means a same-named file already sits in + * Downloads; [ShowReplaceConfirmation][TemplateManagerUiEffect.ShowReplaceConfirmation] asks + * whether to replace it, and a confirmed replace re-enters this with [overwrite] set. + */ + fun confirmUninstallTemplate( + item: CgtFileItem, + overwrite: Boolean = false, + ) { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } templateRepository - .uninstallTemplate(item) + .uninstallTemplate(item, overwrite) .onSuccess { Log.d(TAG, "Template uninstalled successfully: ${item.name}") _uiEffect.send(TemplateManagerUiEffect.ShowSuccess(R.string.msg_template_uninstalled)) @@ -113,12 +129,16 @@ class TemplateManagerViewModel( }.onFailure { exception -> Log.e(TAG, "Failed to uninstall template: ${item.name}", exception) _uiState.update { it.copy(isLoading = false) } - _uiEffect.send( - TemplateManagerUiEffect.ShowError( - R.string.msg_template_uninstall_failed, - listOf(exception.message ?: ""), - ), - ) + if (exception is TemplateReplaceConflictException) { + _uiEffect.send(TemplateManagerUiEffect.ShowReplaceConfirmation(item)) + } else { + _uiEffect.send( + TemplateManagerUiEffect.ShowError( + R.string.msg_template_uninstall_failed, + listOf(exception.message ?: ""), + ), + ) + } } } } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index c1c0048630..b4b0a1d514 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -98,7 +98,7 @@ class TemplateRepositoryImplTest { } @Test - fun uninstallTemplate_nameCollision_failsWithoutTouchingEitherCopy() = + fun uninstallTemplate_nameCollision_failsWithReplaceConflict_withoutTouchingEitherCopy() = runTest { val source = File(templatesDir, "dup.cgt").apply { writeText("installed") } val existingDownload = File(downloadDir, "dup.cgt").apply { writeText("already in downloads") } @@ -106,6 +106,7 @@ class TemplateRepositoryImplTest { val result = repository.uninstallTemplate(item(source, installed = true)) assertThat(result.isFailure).isTrue() + assertThat(result.exceptionOrNull()).isInstanceOf(TemplateReplaceConflictException::class.java) assertThat(source.exists()).isTrue() assertThat(source.readText()).isEqualTo("installed") assertThat(existingDownload.readText()).isEqualTo("already in downloads") @@ -127,6 +128,25 @@ class TemplateRepositoryImplTest { assertThat(restored.exists()).isFalse() } + @Test + fun uninstallTemplate_overwriteTrue_deleteFails_leavesTheReplacementCopyInDownloads() = + runTest { + val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } + val restored = File(downloadDir, "uninstall.cgt").apply { writeText("stale") } + + check(templatesDir.setWritable(false)) { "test setup: could not make templatesDir read-only" } + + val result = repository.uninstallTemplate(item(source, installed = true), overwrite = true) + + assertThat(result.isFailure).isTrue() + assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) + // The source is still installed (its delete failed) - the pre-existing Downloads + // content was already overwritten and can't be recovered either way, so the new copy + // is left in place rather than deleted for nothing. + assertThat(source.exists()).isTrue() + assertThat(restored.readText()).isEqualTo("installed") + } + @Test fun deleteDownloadFile_succeeds_whenNotInstalled() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt index d84bb62bc5..5c66369dfc 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.viewmodels import android.util.Log import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.repositories.TemplateReplaceConflictException import com.itsaky.androidide.repositories.TemplateRepository import com.itsaky.androidide.templates.manager.models.CgtFileItem import com.itsaky.androidide.templates.manager.models.TemplateMetadata @@ -44,6 +45,15 @@ class TemplateManagerViewModelTest { provenance = TemplateProvenance.USER, ) + private val installedItem = + CgtFileItem( + file = File("/tmp/uninstall.cgt"), + name = "uninstall.cgt", + templates = listOf(TemplateMetadata("T", "d", "1.0")), + installed = true, + provenance = TemplateProvenance.USER, + ) + @Before fun stubAndroidLog() { // TemplateManagerViewModel calls android.util.Log.d/Log.e directly; under plain JVM @@ -113,4 +123,89 @@ class TemplateManagerViewModelTest { coVerify(exactly = 1) { repository.listTemplateFiles() } assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowError).isTrue() } + + @Test + fun uninstallTemplate_event_asksForConfirmation_withoutCallingRepository() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.onEvent(TemplateManagerUiEvent.UninstallTemplate(installedItem)) + advanceUntilIdle() + + coVerify(exactly = 0) { repository.uninstallTemplate(any(), any()) } + val effect = viewModel.uiEffect.first() + assertThat(effect).isInstanceOf(TemplateManagerUiEffect.ShowUninstallConfirmation::class.java) + assertThat((effect as TemplateManagerUiEffect.ShowUninstallConfirmation).item).isEqualTo(installedItem) + } + + @Test + fun confirmUninstallTemplate_onSuccess_reloadsAndSendsShowSuccessEffect() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.uninstallTemplate(installedItem, false) } returns Result.success(Unit) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.confirmUninstallTemplate(installedItem) + advanceUntilIdle() + + coVerify(exactly = 2) { repository.listTemplateFiles() } + assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowSuccess).isTrue() + } + + @Test + fun confirmUninstallTemplate_onReplaceConflict_sendsShowReplaceConfirmation_notShowError() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.uninstallTemplate(installedItem, false) } returns + Result.failure(TemplateReplaceConflictException(installedItem.name)) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.confirmUninstallTemplate(installedItem) + advanceUntilIdle() + + // A conflict isn't a reload-worthy outcome and must not be reported as a generic error. + coVerify(exactly = 1) { repository.listTemplateFiles() } + val effect = viewModel.uiEffect.first() + assertThat(effect).isInstanceOf(TemplateManagerUiEffect.ShowReplaceConfirmation::class.java) + assertThat((effect as TemplateManagerUiEffect.ShowReplaceConfirmation).item).isEqualTo(installedItem) + } + + @Test + fun confirmUninstallTemplate_withOverwrite_passesOverwriteThrough_onReplaceConfirm() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.uninstallTemplate(installedItem, true) } returns Result.success(Unit) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.confirmUninstallTemplate(installedItem, overwrite = true) + advanceUntilIdle() + + coVerify(exactly = 1) { repository.uninstallTemplate(installedItem, true) } + assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowSuccess).isTrue() + } + + @Test + fun confirmUninstallTemplate_onOtherFailure_sendsShowErrorEffect_withoutReloading() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.uninstallTemplate(installedItem, false) } returns Result.failure(java.io.IOException("boom")) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.confirmUninstallTemplate(installedItem) + advanceUntilIdle() + + coVerify(exactly = 1) { repository.listTemplateFiles() } + assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowError).isTrue() + } } diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 9426a6f6ca..69274af381 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1430,6 +1430,10 @@ Templates in %1$s Delete template? This permanently deletes \'%1$s\' from Downloads. + Uninstall template? + This moves \'%1$s\' back to Downloads. + Replace file in Downloads? + A file named \'%1$s\' already exists in Downloads. Replace it? File Status Location From e2e08881f169eb51d2a0265dfa0c7710a9d9f413 Mon Sep 17 00:00:00 2001 From: yaturner Date: Wed, 16 Sep 2026 14:34:02 -0700 Subject: [PATCH 02/10] ADFA-5446: Restore collision logging and clarify the overwrite-delete-fails message The replace-conflict path returns early via return@withContext, so it never reached the catch blocks' logger.error call the old IllegalStateException path used to hit - a repeated replace conflict left no log trace. Log it directly where it's decided instead. Also: when overwrite=true and the subsequent source delete fails, the old Downloads content has already been irrecoverably replaced, but the thrown message was identical to the non-overwrite rollback case ("failed to delete source file"), which reads as if nothing happened. The message now says the template exists in both places, since that's what's actually true and rolling back would only destroy the new copy too for nothing. Co-Authored-By: Claude Sonnet 5 --- .../repositories/TemplateRepositoryImpl.kt | 12 +++++++++++- .../repositories/TemplateRepositoryImplTest.kt | 4 ++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index a313b45d23..75fbe7e69a 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -151,6 +151,12 @@ class TemplateRepositoryImpl( val restored = File(downloadDir, item.file.name) val hadExistingDownload = restored.exists() if (hadExistingDownload && !overwrite) { + // Not thrown, so it skips the catch blocks below - log it here instead, or a + // repeated replace-conflict leaves no trace for support to find. + logger.warn( + "Uninstall of '{}' would overwrite an existing Downloads file; asking for confirmation", + item.name, + ) return@withContext Result.failure(TemplateReplaceConflictException(restored.name)) } item.file.copyTo(restored, overwrite = overwrite) @@ -162,8 +168,12 @@ class TemplateRepositoryImpl( // new copy in place costs nothing and loses no data. if (!hadExistingDownload) { restored.delete() + throw IOException("Failed to delete source file after copying: ${item.file.absolutePath}") } - throw IOException("Failed to delete source file after copying: ${item.file.absolutePath}") + throw IOException( + "Replaced '${restored.name}' in Downloads, but failed to delete the installed copy at " + + "${item.file.absolutePath} - the template now exists in both places", + ) } ITemplateProvider.getInstance(reload = true) Result.success(Unit) diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index b4b0a1d514..6d0c810a6c 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -145,6 +145,10 @@ class TemplateRepositoryImplTest { // is left in place rather than deleted for nothing. assertThat(source.exists()).isTrue() assertThat(restored.readText()).isEqualTo("installed") + // The message must say the file now exists in both places, not the plain "failed to + // delete" wording the non-overwrite rollback case uses - a user reading that after an + // overwrite would wrongly assume their prior Downloads content is still intact. + assertThat(result.exceptionOrNull()?.message).contains("now exists in both places") } @Test From 6588402c5020d2edd2406aed7e05bf3a3832f2d6 Mon Sep 17 00:00:00 2001 From: yaturner Date: Thu, 17 Sep 2026 06:09:46 -0700 Subject: [PATCH 03/10] ADFA-5446: Add KDoc to the uninstall-confirmation public declarations CodeRabbit review nitpicks: TemplateRepositoryImpl.uninstallTemplate's rollback-on-delete-failure contract, ShowUninstallConfirmation, and UninstallTemplateConfirmationDialog were undocumented public declarations. Added brief KDoc to each. Not changed: CodeRabbit's suggestion that the test file's single-arg uninstallTemplate calls need an explicit `overwrite = false` because "the override does not inherit the interface default" is incorrect - Kotlin overrides inherit the base declaration's default parameter value at every call site regardless of the reference's static type, and those exact calls already compile and pass. Co-Authored-By: Claude Sonnet 5 --- .../itsaky/androidide/repositories/TemplateRepositoryImpl.kt | 5 +++++ .../ui/compose/templates/TemplateManagerDialogs.kt | 1 + .../itsaky/androidide/ui/models/TemplateManagerUiState.kt | 1 + 3 files changed, 7 insertions(+) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index 75fbe7e69a..cb2301eae2 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -137,6 +137,11 @@ class TemplateRepositoryImpl( } } + /** + * On a post-copy delete failure: rolls back (deletes the Downloads copy this call created) when + * `overwrite` was false, but leaves the Downloads copy in place when `overwrite` was true, since + * the pre-existing content there was already replaced and can't be recovered either way. + */ override suspend fun uninstallTemplate( item: CgtFileItem, overwrite: Boolean, diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt index 2ca82f190a..07266a1585 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt @@ -44,6 +44,7 @@ fun DeleteTemplateConfirmationDialog( ) } +/** Confirm before uninstalling [item], since it moves the file back to Downloads. */ @Composable fun UninstallTemplateConfirmationDialog( item: CgtFileItem, diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt index 10a1fd6165..ae236fb5bb 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt @@ -50,6 +50,7 @@ sealed class TemplateManagerUiEffect { val item: CgtFileItem, ) : TemplateManagerUiEffect() + /** Ask before uninstalling [item], mirroring [ShowDeleteConfirmation]'s pattern for a Downloads file. */ data class ShowUninstallConfirmation( val item: CgtFileItem, ) : TemplateManagerUiEffect() From 362b6ca3ac26cb7d965a1d9633512fe5a3bccbaf Mon Sep 17 00:00:00 2001 From: yaturner Date: Thu, 15 Oct 2026 07:13:31 -0700 Subject: [PATCH 04/10] ADFA-5446: Keep the Downloads file safe when an uninstall replace fails Address review findings on #2045: - copyTo(overwrite = true) deletes the target before copying, so a copy that failed partway destroyed the user's Downloads file. Copy into a hidden .part file and rename it into place; a failed copy now leaves the existing file intact and no truncated file behind. - The Replace dialog showed the extension-less display name, which names no real file. It now shows the conflicting file's exact name on disk, carried from TemplateReplaceConflictException. - The conflict check was case-sensitive while the list filter is not, so a Downloads twin differing only in case was hidden and silently duplicated. Match it case-insensitively and replace that file in place. Co-Authored-By: Claude Opus 5.5 --- .../repositories/TemplateRepository.kt | 2 +- .../repositories/TemplateRepositoryImpl.kt | 33 ++++++++++-- .../templates/TemplateManagerDialogs.kt | 9 ++-- .../templates/TemplateManagerScreen.kt | 5 +- .../ui/models/TemplateManagerUiState.kt | 6 ++- .../viewmodels/TemplateManagerViewModel.kt | 2 +- .../TemplateRepositoryImplTest.kt | 51 +++++++++++++++++++ .../TemplateManagerViewModelTest.kt | 4 +- 8 files changed, 100 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt index 9966e238a2..6d7ae7da21 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt @@ -24,7 +24,7 @@ interface TemplateRepository { /** * Restores a copy of [item]'s file to Downloads, removes it from the templates directory, and * reloads templates. Fails with [TemplateReplaceConflictException] if a file of the same name - * already exists in Downloads, unless [overwrite] is true. + * (ignoring case) already exists in Downloads, unless [overwrite] is true. */ suspend fun uninstallTemplate( item: CgtFileItem, diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index cb2301eae2..2d7e206abd 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -153,8 +153,14 @@ class TemplateRepositoryImpl( // Restore a copy to Downloads BEFORE removing it from the store: if the restore // throws, the store copy below is never touched, so the user's only copy survives. - val restored = File(downloadDir, item.file.name) - val hadExistingDownload = restored.exists() + // The existing-file lookup ignores case, like scanTemplates: a twin differing only in + // case is hidden from the list, so it must still raise the Replace prompt. + val existingDownload = + downloadDir.listFiles()?.firstOrNull { file -> + file.isFile && file.name.equals(item.file.name, ignoreCase = true) + } + val restored = existingDownload ?: File(downloadDir, item.file.name) + val hadExistingDownload = existingDownload != null if (hadExistingDownload && !overwrite) { // Not thrown, so it skips the catch blocks below - log it here instead, or a // repeated replace-conflict leaves no trace for support to find. @@ -164,7 +170,7 @@ class TemplateRepositoryImpl( ) return@withContext Result.failure(TemplateReplaceConflictException(restored.name)) } - item.file.copyTo(restored, overwrite = overwrite) + copyThroughTempFile(item.file, restored) if (!item.file.delete()) { // Only roll back a copy this call created itself. When `overwrite` replaced a // pre-existing Downloads file, that original content is already gone - deleting @@ -193,6 +199,27 @@ class TemplateRepositoryImpl( } } + /** + * Copies [source] to [target] via a temp file renamed into place, so a copy that fails partway + * (storage full, I/O error) leaves an existing [target] intact and no truncated file behind. + * `copyTo(overwrite = true)` deletes the target before copying, which would lose it. + */ + private fun copyThroughTempFile( + source: File, + target: File, + ) { + // Not a .cgt name, so a leftover is never listed as a template. + val temp = File(target.parentFile, ".${target.name}.part") + try { + source.copyTo(temp, overwrite = true) + if (!temp.renameTo(target)) { + throw IOException("Failed to move ${temp.absolutePath} into place as ${target.absolutePath}") + } + } finally { + temp.delete() + } + } + override suspend fun deleteDownloadFile(item: CgtFileItem): Result = withContext(Dispatchers.IO) { try { diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt index 07266a1585..97c5938574 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt @@ -64,17 +64,20 @@ fun UninstallTemplateConfirmationDialog( ) } -/** Shown when uninstalling [item] would silently overwrite an existing Downloads file of the same name. */ +/** + * Shown when an uninstall would overwrite [fileName] in Downloads. [fileName] is the exact name on + * disk, extension included, so the user can find the file they are about to replace. + */ @Composable fun ReplaceTemplateInDownloadsDialog( - item: CgtFileItem, + fileName: String, onConfirm: () -> Unit, onDismiss: () -> Unit, ) { AlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.title_replace_template)) }, - text = { Text(stringResource(R.string.msg_replace_template_confirm, item.displayName)) }, + text = { Text(stringResource(R.string.msg_replace_template_confirm, fileName)) }, confirmButton = { TextButton(onClick = onConfirm) { Text(stringResource(R.string.replace)) } }, diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt index cd9bd56903..9678a2973e 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt @@ -75,6 +75,7 @@ private sealed interface TemplateManagerDialogState : Parcelable { @Parcelize data class ReplaceConfirm( val path: String, + val fileName: String, ) : TemplateManagerDialogState @Parcelize @@ -168,7 +169,7 @@ fun TemplateManagerScreen( } is TemplateManagerUiEffect.ShowReplaceConfirmation -> { - dialogState = TemplateManagerDialogState.ReplaceConfirm(effect.item.file.absolutePath) + dialogState = TemplateManagerDialogState.ReplaceConfirm(effect.item.file.absolutePath, effect.fileName) } is TemplateManagerUiEffect.ShowTemplateDetails -> { @@ -251,7 +252,7 @@ fun TemplateManagerScreen( val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } if (item != null) { ReplaceTemplateInDownloadsDialog( - item = item, + fileName = dialog.fileName, onConfirm = { viewModel.confirmUninstallTemplate(item, overwrite = true) dialogState = TemplateManagerDialogState.None diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt index ae236fb5bb..75f17f00c2 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt @@ -55,9 +55,13 @@ sealed class TemplateManagerUiEffect { val item: CgtFileItem, ) : TemplateManagerUiEffect() - /** A Downloads file with the same name already exists; ask before [uninstallTemplate][com.itsaky.androidide.repositories.TemplateRepository.uninstallTemplate] overwrites it. */ + /** + * A Downloads file with the same name already exists; ask before [uninstallTemplate][com.itsaky.androidide.repositories.TemplateRepository.uninstallTemplate] overwrites it. + * [fileName] is that file's exact name on disk, which can differ from [item]'s in case. + */ data class ShowReplaceConfirmation( val item: CgtFileItem, + val fileName: String, ) : TemplateManagerUiEffect() data class ShowTemplateDetails( diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt index bb60d1e76f..c9ed767c75 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt @@ -130,7 +130,7 @@ class TemplateManagerViewModel( Log.e(TAG, "Failed to uninstall template: ${item.name}", exception) _uiState.update { it.copy(isLoading = false) } if (exception is TemplateReplaceConflictException) { - _uiEffect.send(TemplateManagerUiEffect.ShowReplaceConfirmation(item)) + _uiEffect.send(TemplateManagerUiEffect.ShowReplaceConfirmation(item, exception.fileName)) } else { _uiEffect.send( TemplateManagerUiEffect.ShowError( diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index 6d0c810a6c..46461ef577 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -151,6 +151,57 @@ class TemplateRepositoryImplTest { assertThat(result.exceptionOrNull()?.message).contains("now exists in both places") } + @Test + fun uninstallTemplate_overwriteTrue_copyFails_keepsTheExistingDownloadIntact() = + runTest { + val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } + val existingDownload = File(downloadDir, "uninstall.cgt").apply { writeText("user's file") } + + // An unreadable source makes the copy itself fail. copyTo(overwrite = true) deletes + // the target before it opens the source, so this used to destroy the Downloads file. + check(source.setReadable(false)) { "test setup: could not make the source unreadable" } + + val result = repository.uninstallTemplate(item(source, installed = true), overwrite = true) + + assertThat(result.isFailure).isTrue() + assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) + assertThat(existingDownload.readText()).isEqualTo("user's file") + assertThat(source.exists()).isTrue() + // No partial or temp file left behind in Downloads. + assertThat(downloadDir.list()).asList().containsExactly("uninstall.cgt") + } + + @Test + fun uninstallTemplate_caseOnlyNameCollision_failsWithReplaceConflictNamingTheExistingFile() = + runTest { + val source = File(templatesDir, "dup.cgt").apply { writeText("installed") } + val existingDownload = File(downloadDir, "Dup.CGT").apply { writeText("already in downloads") } + + val result = repository.uninstallTemplate(item(source, installed = true)) + + assertThat(result.exceptionOrNull()).isInstanceOf(TemplateReplaceConflictException::class.java) + // The dialog shows this name, so it must be the file actually on disk. + assertThat((result.exceptionOrNull() as TemplateReplaceConflictException).fileName).isEqualTo("Dup.CGT") + assertThat(source.readText()).isEqualTo("installed") + assertThat(existingDownload.readText()).isEqualTo("already in downloads") + assertThat(downloadDir.list()).asList().containsExactly("Dup.CGT") + } + + @Test + fun uninstallTemplate_overwriteTrue_caseOnlyNameCollision_replacesTheExistingFile_notAddsATwin() = + runTest { + val source = File(templatesDir, "dup.cgt").apply { writeText("installed") } + val existingDownload = File(downloadDir, "Dup.CGT").apply { writeText("stale") } + + // A read-only templatesDir stops the call after the copy, before it reaches + // ITemplateProvider (not wired up here - see the class KDoc). + check(templatesDir.setWritable(false)) { "test setup: could not make templatesDir read-only" } + repository.uninstallTemplate(item(source, installed = true), overwrite = true) + + assertThat(existingDownload.readText()).isEqualTo("installed") + assertThat(downloadDir.list()).asList().containsExactly("Dup.CGT") + } + @Test fun deleteDownloadFile_succeeds_whenNotInstalled() = runTest { diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt index 5c66369dfc..2b218127c6 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt @@ -162,7 +162,7 @@ class TemplateManagerViewModelTest { runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) coEvery { repository.uninstallTemplate(installedItem, false) } returns - Result.failure(TemplateReplaceConflictException(installedItem.name)) + Result.failure(TemplateReplaceConflictException("Existing.CGT")) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() @@ -175,6 +175,8 @@ class TemplateManagerViewModelTest { val effect = viewModel.uiEffect.first() assertThat(effect).isInstanceOf(TemplateManagerUiEffect.ShowReplaceConfirmation::class.java) assertThat((effect as TemplateManagerUiEffect.ShowReplaceConfirmation).item).isEqualTo(installedItem) + // The dialog names the file on disk, not the item's extension-less display name. + assertThat(effect.fileName).isEqualTo("Existing.CGT") } @Test From 9843039698cc928711a76c889d5fd0257dee44e9 Mon Sep 17 00:00:00 2001 From: jimturner-adfa Date: Fri, 16 Oct 2026 11:48:58 -0700 Subject: [PATCH 05/10] ADFA-5446: Replace the Downloads file with Files.move, not renameTo File.renameTo leaves replacing an existing target unspecified, and a confirmed Replace always has one. Files.move with REPLACE_EXISTING makes the replacement part of the documented contract (API 26+; minSdk is 28). Co-Authored-By: Claude Opus 5.5 --- .../androidide/repositories/TemplateRepositoryImpl.kt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index 8abdc71bf0..aadb2c773f 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -12,6 +12,8 @@ import org.json.JSONException import org.slf4j.LoggerFactory import java.io.File import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardCopyOption /** * Implementation of [TemplateRepository]. @@ -219,9 +221,9 @@ class TemplateRepositoryImpl( val temp = File(target.parentFile, ".${target.name}.part") try { source.copyTo(temp, overwrite = true) - if (!temp.renameTo(target)) { - throw IOException("Failed to move ${temp.absolutePath} into place as ${target.absolutePath}") - } + // Files.move, not File.renameTo: renameTo leaves replacing an existing target + // unspecified, and a confirmed Replace always has one. + Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) } finally { temp.delete() } From c8f9bac2919c8d3ad7cdb0e93f3d28bd77779d8c Mon Sep 17 00:00:00 2001 From: jimturner-adfa Date: Fri, 16 Oct 2026 12:36:39 -0700 Subject: [PATCH 06/10] ADFA-5446: Only replace a Downloads file when overwrite was confirmed copyThroughTempFile used Files.move(..., REPLACE_EXISTING) unconditionally, so a file that appeared at the target path without the caller's prior existence check seeing it (a race, or the check itself failing to list the directory) was silently overwritten - exactly the bug class this PR exists to fix, just reached a different way. copyThroughTempFile now takes replaceExisting, true only when the uninstallTemplate caller already found and confirmed the collision. In the unconfirmed case, Files.move without REPLACE_EXISTING throws FileAlreadyExistsException if something is there after all; that's now converted to the same TemplateReplaceConflictException the normal pre-check already raises, so the ViewModel's existing Replace-confirmation handling covers it without any new UI path. Regression test: uninstallTemplate_existingFileInvisibleToTheLookup_ stillFailsWithReplaceConflict_insteadOfOverwriting makes downloadDir unreadable so the pre-move listFiles() lookup misses an existing file there. Against the old code this reaches success and then ITemplateProvider.getInstance(reload = true), which isn't wired up on the unit test classpath (see the class's own KDoc on why a happy-path test isn't included) - so the old code silently treats this as success. It fails with TemplateReplaceConflictException now. Verified: :app:compileV8DebugKotlin, Spotless, and TemplateRepositoryImplTest (19/19) pass. Co-Authored-By: Claude Sonnet 5 --- .../repositories/TemplateRepositoryImpl.kt | 21 ++++++++++++++++-- .../TemplateRepositoryImplTest.kt | 22 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index aadb2c773f..c342e539e3 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -12,6 +12,7 @@ import org.json.JSONException import org.slf4j.LoggerFactory import java.io.File import java.io.IOException +import java.nio.file.FileAlreadyExistsException import java.nio.file.Files import java.nio.file.StandardCopyOption @@ -179,7 +180,9 @@ class TemplateRepositoryImpl( ) return@withContext Result.failure(TemplateReplaceConflictException(restored.name)) } - copyThroughTempFile(item.file, restored) + // hadExistingDownload is only true here because the !overwrite case above already + // returned - replacement is confirmed exactly when a pre-existing file was found. + copyThroughTempFile(item.file, restored, replaceExisting = hadExistingDownload) if (!item.file.delete()) { // Only roll back a copy this call created itself. When `overwrite` replaced a // pre-existing Downloads file, that original content is already gone - deleting @@ -212,10 +215,16 @@ class TemplateRepositoryImpl( * Copies [source] to [target] via a temp file renamed into place, so a copy that fails partway * (storage full, I/O error) leaves an existing [target] intact and no truncated file behind. * `copyTo(overwrite = true)` deletes the target before copying, which would lose it. + * + * [replaceExisting] must be true only when the caller already confirmed overwriting [target]; + * when false, a [target] that exists anyway (e.g. created after the caller's own check, between + * that check and this call) fails with [TemplateReplaceConflictException] instead of being + * silently replaced. */ private fun copyThroughTempFile( source: File, target: File, + replaceExisting: Boolean, ) { // Not a .cgt name, so a leftover is never listed as a template. val temp = File(target.parentFile, ".${target.name}.part") @@ -223,7 +232,15 @@ class TemplateRepositoryImpl( source.copyTo(temp, overwrite = true) // Files.move, not File.renameTo: renameTo leaves replacing an existing target // unspecified, and a confirmed Replace always has one. - Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) + try { + if (replaceExisting) { + Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) + } else { + Files.move(temp.toPath(), target.toPath()) + } + } catch (e: FileAlreadyExistsException) { + throw TemplateReplaceConflictException(target.name) + } } finally { temp.delete() } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index 11b414ff11..513197877a 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -52,6 +52,7 @@ class TemplateRepositoryImplTest { // Undo any permission changes a test made, or TemporaryFolder can't clean up after itself. templatesDir.setWritable(true) downloadDir.setWritable(true) + downloadDir.setReadable(true) } private fun item( @@ -203,6 +204,27 @@ class TemplateRepositoryImplTest { assertThat(downloadDir.list()).asList().containsExactly("Dup.CGT") } + @Test + fun uninstallTemplate_existingFileInvisibleToTheLookup_stillFailsWithReplaceConflict_insteadOfOverwriting() = + runTest { + val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } + val existingDownload = File(downloadDir, "uninstall.cgt").apply { writeText("already in downloads") } + + // downloadDir.listFiles() returns null without read permission, so the pre-move + // existence check misses existingDownload even though it's still there - this is the + // race window a lookup-then-move approach has in general (the file could just as well + // have appeared between the check and the move). Without a confirmed `overwrite`, + // Files.move must still refuse to replace it rather than silently overwriting. + check(downloadDir.setReadable(false)) { "test setup: could not make downloadDir unreadable" } + + val result = repository.uninstallTemplate(item(source, installed = true)) + + assertThat(result.exceptionOrNull()).isInstanceOf(TemplateReplaceConflictException::class.java) + assertThat(source.exists()).isTrue() + downloadDir.setReadable(true) + assertThat(existingDownload.readText()).isEqualTo("already in downloads") + } + @Test fun deleteDownloadFile_succeeds_whenNotInstalled() = runTest { From bbd08978ad3851aab31fb61893a758c4a5e8bd39 Mon Sep 17 00:00:00 2001 From: jimturner-adfa Date: Tue, 3 Nov 2026 12:14:39 -0800 Subject: [PATCH 07/10] ADFA-5446: Drop restore: install copies, uninstall deletes Per review: remove the idea of restoring an uninstalled template to Downloads, which is what made uninstall fail whenever a same-named file was already there. This replaces the overwrite/Replace-in-Downloads flow with the design from #2049 (Hal's option 1), applied onto current stage: - installTemplate copies the .cgt and leaves the Downloads original; uninstallTemplate deletes the installed copy, whatever its provenance. - Install opens an "Install Template Collection" dialog with the Plugins tab's "Delete installation file after install" checkbox. - Removed: the overwrite parameter, TemplateReplaceConflictException, ShowReplaceConfirmation, ReplaceTemplateInDownloadsDialog and its strings. A user reinstalls from the original .cgt, which the list shows again once the installed copy is gone, or by reinstalling the plugin that provided it. Co-Authored-By: Claude Opus 5.5 --- .../repositories/TemplateRepository.kt | 22 +-- .../repositories/TemplateRepositoryImpl.kt | 101 +--------- .../templates/TemplateManagerDialogs.kt | 72 +++---- .../templates/TemplateManagerScreen.kt | 50 ++--- .../ui/models/TemplateManagerUiState.kt | 14 +- .../viewmodels/TemplateManagerViewModel.kt | 61 +++--- .../TemplateRepositoryImplTest.kt | 175 +++++------------- .../TemplateManagerViewModelTest.kt | 109 +++++------ resources/src/main/res/values/strings.xml | 4 - 9 files changed, 193 insertions(+), 415 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt index 6d7ae7da21..0ef1e085de 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepository.kt @@ -1,7 +1,6 @@ package com.itsaky.androidide.repositories import com.itsaky.androidide.templates.manager.models.CgtFileItem -import java.io.IOException /** * Repository interface for template (`.cgt`) file operations. @@ -18,25 +17,18 @@ interface TemplateRepository { */ suspend fun listTemplateFiles(): Result> - /** Moves [item]'s file from Downloads into the templates directory and reloads templates. */ + /** + * Copies [item]'s file from Downloads into the templates directory and reloads templates. The + * Downloads original is left in place; removing it is the caller's choice ([deleteDownloadFile]). + */ suspend fun installTemplate(item: CgtFileItem): Result /** - * Restores a copy of [item]'s file to Downloads, removes it from the templates directory, and - * reloads templates. Fails with [TemplateReplaceConflictException] if a file of the same name - * (ignoring case) already exists in Downloads, unless [overwrite] is true. + * Deletes [item] from the templates directory and reloads templates. There is no restore: the + * user re-installs from the original `.cgt`, or re-installs the plugin that provided it. */ - suspend fun uninstallTemplate( - item: CgtFileItem, - overwrite: Boolean = false, - ): Result + suspend fun uninstallTemplate(item: CgtFileItem): Result /** Deletes a not-installed [item]'s file from Downloads. */ suspend fun deleteDownloadFile(item: CgtFileItem): Result } - -/** Thrown by [TemplateRepository.uninstallTemplate] when restoring to Downloads would silently - * overwrite an existing file there and the caller didn't opt into replacing it. */ -class TemplateReplaceConflictException( - val fileName: String, -) : IOException("A file named '$fileName' already exists in Downloads") diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index 4adaaaa565..f98dcc1a7c 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -12,9 +12,6 @@ import org.json.JSONException import org.slf4j.LoggerFactory import java.io.File import java.io.IOException -import java.nio.file.FileAlreadyExistsException -import java.nio.file.Files -import java.nio.file.StandardCopyOption /** * Implementation of [TemplateRepository]. @@ -50,11 +47,11 @@ class TemplateRepositoryImpl( } /** - * One card per archive, not per file on disk. The same `.cgt` name can exist in both - * directories at once - a copy dropped into Downloads by hand, or the picker-install path, - * which copies rather than moves. Both rows would then render identically apart from the - * status line, and the Downloads twin is a dead end: [installTemplate] refuses to overwrite, - * so its Install can only ever fail. The installed copy wins. + * One card per archive, not per file on disk. The same `.cgt` name normally exists in both + * directories at once, since [installTemplate] copies and leaves the Downloads original + * behind. The Downloads twin is a dead end while the installed copy exists ([installTemplate] + * refuses to overwrite), so the installed copy wins; after [uninstallTemplate] the twin is + * listed again, which is how the user re-installs. * * Names are compared case-insensitively, matching the stricter of the two install paths * (`TemplateCollectionRepository.findExistingCollision`), so any row still listed as @@ -124,10 +121,6 @@ class TemplateRepositoryImpl( val dest = File(templatesDir, item.file.name) check(!dest.exists()) { "A template named '${dest.name}' already exists in $templatesDir" } item.file.copyTo(dest, overwrite = false) - if (!item.file.delete()) { - dest.delete() - throw IOException("Failed to delete source file after copying: ${item.file.absolutePath}") - } ITemplateProvider.getInstance(reload = true) Result.success(Unit) } catch (e: CancellationException) { @@ -141,58 +134,15 @@ class TemplateRepositoryImpl( } } - /** - * On a post-copy delete failure: rolls back (deletes the Downloads copy this call created) when - * `overwrite` was false, but leaves the Downloads copy in place when `overwrite` was true, since - * the pre-existing content there was already replaced and can't be recovered either way. - */ - override suspend fun uninstallTemplate( - item: CgtFileItem, - overwrite: Boolean, - ): Result = + override suspend fun uninstallTemplate(item: CgtFileItem): Result = withContext(Dispatchers.IO) { try { check(item.installed) { "'${item.name}' is not installed" } - // Guarded here as well as hidden by scanTemplates: once moved out, core.cgt is never + // Guarded here as well as hidden by scanTemplates: once deleted, core.cgt is never // listed again, so there would be no in-app way to put it back. check(!isCoreArchive(item.name)) { "Cannot uninstall the bundled template" } - - // Restore a copy to Downloads BEFORE removing it from the store: if the restore - // throws, the store copy below is never touched, so the user's only copy survives. - // The existing-file lookup ignores case, like scanTemplates: a twin differing only in - // case is hidden from the list, so it must still raise the Replace prompt. - val existingDownload = - downloadDir.listFiles()?.firstOrNull { file -> - file.isFile && file.name.equals(item.file.name, ignoreCase = true) - } - val restored = existingDownload ?: File(downloadDir, item.file.name) - val hadExistingDownload = existingDownload != null - if (hadExistingDownload && !overwrite) { - // Not thrown, so it skips the catch blocks below - log it here instead, or a - // repeated replace-conflict leaves no trace for support to find. - logger.warn( - "Uninstall of '{}' would overwrite an existing Downloads file; asking for confirmation", - item.name, - ) - return@withContext Result.failure(TemplateReplaceConflictException(restored.name)) - } - // hadExistingDownload is only true here because the !overwrite case above already - // returned - replacement is confirmed exactly when a pre-existing file was found. - copyThroughTempFile(item.file, restored, replaceExisting = hadExistingDownload) if (!item.file.delete()) { - // Only roll back a copy this call created itself. When `overwrite` replaced a - // pre-existing Downloads file, that original content is already gone - deleting - // `restored` here would destroy the new copy too and leave the user with nothing, - // whereas the still-installed source (its delete just failed) means leaving the - // new copy in place costs nothing and loses no data. - if (!hadExistingDownload) { - restored.delete() - throw IOException("Failed to delete source file after copying: ${item.file.absolutePath}") - } - throw IOException( - "Replaced '${restored.name}' in Downloads, but failed to delete the installed copy at " + - "${item.file.absolutePath} - the template now exists in both places", - ) + throw IOException("Failed to delete ${item.file.absolutePath}") } ITemplateProvider.getInstance(reload = true) Result.success(Unit) @@ -207,41 +157,6 @@ class TemplateRepositoryImpl( } } - /** - * Copies [source] to [target] via a temp file renamed into place, so a copy that fails partway - * (storage full, I/O error) leaves an existing [target] intact and no truncated file behind. - * `copyTo(overwrite = true)` deletes the target before copying, which would lose it. - * - * [replaceExisting] must be true only when the caller already confirmed overwriting [target]; - * when false, a [target] that exists anyway (e.g. created after the caller's own check, between - * that check and this call) fails with [TemplateReplaceConflictException] instead of being - * silently replaced. - */ - private fun copyThroughTempFile( - source: File, - target: File, - replaceExisting: Boolean, - ) { - // Not a .cgt name, so a leftover is never listed as a template. - val temp = File(target.parentFile, ".${target.name}.part") - try { - source.copyTo(temp, overwrite = true) - // Files.move, not File.renameTo: renameTo leaves replacing an existing target - // unspecified, and a confirmed Replace always has one. - try { - if (replaceExisting) { - Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) - } else { - Files.move(temp.toPath(), target.toPath()) - } - } catch (e: FileAlreadyExistsException) { - throw TemplateReplaceConflictException(target.name) - } - } finally { - temp.delete() - } - } - override suspend fun deleteDownloadFile(item: CgtFileItem): Result = withContext(Dispatchers.IO) { try { diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt index 5df29cb97b..4b3f591c3d 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.ui.compose.templates import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn @@ -11,10 +12,16 @@ import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card +import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @@ -26,38 +33,41 @@ import com.itsaky.androidide.templates.manager.models.effectiveDisplayName import com.itsaky.androidide.templates.manager.models.primaryTemplate import com.itsaky.androidide.templates.manager.models.versionLabel +/** Same "delete after install" choice as the Plugins tab's install dialog. */ @Composable -fun DeleteTemplateConfirmationDialog( +fun InstallTemplateConfirmationDialog( item: CgtFileItem, - onConfirm: () -> Unit, + onConfirm: (deleteSourceAfterInstall: Boolean) -> Unit, onDismiss: () -> Unit, ) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(stringResource(R.string.title_delete_template)) }, - text = { Text(stringResource(R.string.msg_delete_template_confirm, item.displayName)) }, - confirmButton = { - TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_delete_template)) } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } - }, - ) -} + var deleteSource by rememberSaveable { mutableStateOf(false) } -/** Confirm before uninstalling [item], since it moves the file back to Downloads. */ -@Composable -fun UninstallTemplateConfirmationDialog( - item: CgtFileItem, - onConfirm: () -> Unit, - onDismiss: () -> Unit, -) { AlertDialog( onDismissRequest = onDismiss, - title = { Text(stringResource(R.string.title_uninstall_template)) }, - text = { Text(stringResource(R.string.msg_uninstall_template_confirm, item.displayName)) }, + title = { Text(stringResource(R.string.title_install_template_collection)) }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState())) { + Text( + stringResource( + R.string.msg_template_install_confirm, + item.displayName, + item.templates.joinToString(", ") { it.name }, + ), + ) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(top = 8.dp), + ) { + Checkbox(checked = deleteSource, onCheckedChange = { deleteSource = it }) + Text( + stringResource(R.string.checkbox_delete_source_after_install), + modifier = Modifier.weight(1f), + ) + } + } + }, confirmButton = { - TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_uninstall_template)) } + TextButton(onClick = { onConfirm(deleteSource) }) { Text(stringResource(R.string.btn_install)) } }, dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } @@ -65,22 +75,18 @@ fun UninstallTemplateConfirmationDialog( ) } -/** - * Shown when an uninstall would overwrite [fileName] in Downloads. [fileName] is the exact name on - * disk, extension included, so the user can find the file they are about to replace. - */ @Composable -fun ReplaceTemplateInDownloadsDialog( - fileName: String, +fun DeleteTemplateConfirmationDialog( + item: CgtFileItem, onConfirm: () -> Unit, onDismiss: () -> Unit, ) { AlertDialog( onDismissRequest = onDismiss, - title = { Text(stringResource(R.string.title_replace_template)) }, - text = { Text(stringResource(R.string.msg_replace_template_confirm, fileName)) }, + title = { Text(stringResource(R.string.title_delete_template)) }, + text = { Text(stringResource(R.string.msg_delete_template_confirm, item.displayName)) }, confirmButton = { - TextButton(onClick = onConfirm) { Text(stringResource(R.string.replace)) } + TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_delete_template)) } }, dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt index 75ab8f984e..139720c416 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt @@ -63,19 +63,13 @@ private sealed interface TemplateManagerDialogState : Parcelable { data object None : TemplateManagerDialogState @Parcelize - data class DeleteConfirm( - val path: String, - ) : TemplateManagerDialogState - - @Parcelize - data class UninstallConfirm( + data class InstallConfirm( val path: String, ) : TemplateManagerDialogState @Parcelize - data class ReplaceConfirm( + data class DeleteConfirm( val path: String, - val fileName: String, ) : TemplateManagerDialogState @Parcelize @@ -161,16 +155,12 @@ fun TemplateManagerScreen( ) } - is TemplateManagerUiEffect.ShowDeleteConfirmation -> { - dialogState = TemplateManagerDialogState.DeleteConfirm(effect.item.file.absolutePath) + is TemplateManagerUiEffect.ShowInstallConfirmation -> { + dialogState = TemplateManagerDialogState.InstallConfirm(effect.item.file.absolutePath) } - is TemplateManagerUiEffect.ShowUninstallConfirmation -> { - dialogState = TemplateManagerDialogState.UninstallConfirm(effect.item.file.absolutePath) - } - - is TemplateManagerUiEffect.ShowReplaceConfirmation -> { - dialogState = TemplateManagerDialogState.ReplaceConfirm(effect.item.file.absolutePath, effect.fileName) + is TemplateManagerUiEffect.ShowDeleteConfirmation -> { + dialogState = TemplateManagerDialogState.DeleteConfirm(effect.item.file.absolutePath) } is TemplateManagerUiEffect.ShowTemplateDetails -> { @@ -221,13 +211,13 @@ fun TemplateManagerScreen( when (val dialog = dialogState) { is TemplateManagerDialogState.None -> {} - is TemplateManagerDialogState.DeleteConfirm -> { + is TemplateManagerDialogState.InstallConfirm -> { val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } if (item != null) { - DeleteTemplateConfirmationDialog( + InstallTemplateConfirmationDialog( item = item, - onConfirm = { - viewModel.confirmDeleteDownloadFile(item) + onConfirm = { deleteSource -> + viewModel.confirmInstallTemplate(item, deleteSource) dialogState = TemplateManagerDialogState.None }, onDismiss = { dialogState = TemplateManagerDialogState.None }, @@ -235,27 +225,13 @@ fun TemplateManagerScreen( } } - is TemplateManagerDialogState.UninstallConfirm -> { + is TemplateManagerDialogState.DeleteConfirm -> { val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } if (item != null) { - UninstallTemplateConfirmationDialog( + DeleteTemplateConfirmationDialog( item = item, onConfirm = { - viewModel.confirmUninstallTemplate(item) - dialogState = TemplateManagerDialogState.None - }, - onDismiss = { dialogState = TemplateManagerDialogState.None }, - ) - } - } - - is TemplateManagerDialogState.ReplaceConfirm -> { - val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } - if (item != null) { - ReplaceTemplateInDownloadsDialog( - fileName = dialog.fileName, - onConfirm = { - viewModel.confirmUninstallTemplate(item, overwrite = true) + viewModel.confirmDeleteDownloadFile(item) dialogState = TemplateManagerDialogState.None }, onDismiss = { dialogState = TemplateManagerDialogState.None }, diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt index 437b488c46..7d8824aae4 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt @@ -46,22 +46,12 @@ sealed class TemplateManagerUiEffect { val formatArgs: List = emptyList(), ) : TemplateManagerUiEffect() - data class ShowDeleteConfirmation( + data class ShowInstallConfirmation( val item: CgtFileItem, ) : TemplateManagerUiEffect() - /** Ask before uninstalling [item], mirroring [ShowDeleteConfirmation]'s pattern for a Downloads file. */ - data class ShowUninstallConfirmation( - val item: CgtFileItem, - ) : TemplateManagerUiEffect() - - /** - * A Downloads file with the same name already exists; ask before [uninstallTemplate][com.itsaky.androidide.repositories.TemplateRepository.uninstallTemplate] overwrites it. - * [fileName] is that file's exact name on disk, which can differ from [item]'s in case. - */ - data class ShowReplaceConfirmation( + data class ShowDeleteConfirmation( val item: CgtFileItem, - val fileName: String, ) : TemplateManagerUiEffect() data class ShowTemplateDetails( diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt index c9ed767c75..4569ebe143 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt @@ -3,7 +3,6 @@ package com.itsaky.androidide.viewmodels import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope -import com.itsaky.androidide.repositories.TemplateReplaceConflictException import com.itsaky.androidide.repositories.TemplateRepository import com.itsaky.androidide.resources.R import com.itsaky.androidide.templates.manager.models.CgtFileItem @@ -42,8 +41,8 @@ class TemplateManagerViewModel( fun onEvent(event: TemplateManagerUiEvent) { when (event) { is TemplateManagerUiEvent.LoadTemplates -> loadTemplates() - is TemplateManagerUiEvent.InstallTemplate -> installTemplate(event.item) - is TemplateManagerUiEvent.UninstallTemplate -> showUninstallConfirmation(event.item) + is TemplateManagerUiEvent.InstallTemplate -> showInstallConfirmation(event.item) + is TemplateManagerUiEvent.UninstallTemplate -> uninstallTemplate(event.item) is TemplateManagerUiEvent.DeleteDownloadFile -> showDeleteConfirmation(event.item) is TemplateManagerUiEvent.ShowTemplateDetails -> showTemplateDetails(event.item) is TemplateManagerUiEvent.ShowTemplateList -> showTemplateList(event.item) @@ -72,7 +71,21 @@ class TemplateManagerViewModel( } } - private fun installTemplate(item: CgtFileItem) { + private fun showInstallConfirmation(item: CgtFileItem) { + viewModelScope.launch { + _uiEffect.send(TemplateManagerUiEffect.ShowInstallConfirmation(item)) + } + } + + /** + * Installs a Downloads template (called after confirmation). Install copies, so the Downloads + * original is kept unless [deleteSourceAfterInstall] - the same choice the Plugins tab offers. + * A failed delete is reported but doesn't undo the install, matching the Plugins tab. + */ + fun confirmInstallTemplate( + item: CgtFileItem, + deleteSourceAfterInstall: Boolean, + ) { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } templateRepository @@ -85,6 +98,11 @@ class TemplateManagerViewModel( listOf(item.displayName), ), ) + if (deleteSourceAfterInstall) { + templateRepository.deleteDownloadFile(item).onFailure { + _uiEffect.send(TemplateManagerUiEffect.ShowError(R.string.msg_source_delete_failed)) + } + } // loadTemplates() clears isLoading once the post-install rescan completes, so the // indicator stays up continuously across both phases instead of flickering off // between them. @@ -102,26 +120,11 @@ class TemplateManagerViewModel( } } - private fun showUninstallConfirmation(item: CgtFileItem) { - viewModelScope.launch { - _uiEffect.send(TemplateManagerUiEffect.ShowUninstallConfirmation(item)) - } - } - - /** - * Uninstalls [item] (called after [TemplateManagerUiEffect.ShowUninstallConfirmation] is - * confirmed). A [TemplateReplaceConflictException] means a same-named file already sits in - * Downloads; [ShowReplaceConfirmation][TemplateManagerUiEffect.ShowReplaceConfirmation] asks - * whether to replace it, and a confirmed replace re-enters this with [overwrite] set. - */ - fun confirmUninstallTemplate( - item: CgtFileItem, - overwrite: Boolean = false, - ) { + private fun uninstallTemplate(item: CgtFileItem) { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } templateRepository - .uninstallTemplate(item, overwrite) + .uninstallTemplate(item) .onSuccess { Log.d(TAG, "Template uninstalled successfully: ${item.name}") _uiEffect.send(TemplateManagerUiEffect.ShowSuccess(R.string.msg_template_uninstalled)) @@ -129,16 +132,12 @@ class TemplateManagerViewModel( }.onFailure { exception -> Log.e(TAG, "Failed to uninstall template: ${item.name}", exception) _uiState.update { it.copy(isLoading = false) } - if (exception is TemplateReplaceConflictException) { - _uiEffect.send(TemplateManagerUiEffect.ShowReplaceConfirmation(item, exception.fileName)) - } else { - _uiEffect.send( - TemplateManagerUiEffect.ShowError( - R.string.msg_template_uninstall_failed, - listOf(exception.message ?: ""), - ), - ) - } + _uiEffect.send( + TemplateManagerUiEffect.ShowError( + R.string.msg_template_uninstall_failed, + listOf(exception.message ?: ""), + ), + ) } } } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index 30191c706d..885ae3c9ce 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -1,9 +1,14 @@ package com.itsaky.androidide.repositories import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.templates.ITemplateProvider import com.itsaky.androidide.templates.manager.models.CgtFileItem import com.itsaky.androidide.templates.manager.models.TemplateMetadata import com.itsaky.androidide.templates.manager.models.TemplateProvenance +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject import kotlinx.coroutines.test.runTest import org.adfa.constants.TEMPLATE_CORE_ARCHIVE import org.junit.After @@ -19,13 +24,9 @@ import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream /** - * Pins the two riskiest branches in [TemplateRepositoryImpl.installTemplate]/ - * [TemplateRepositoryImpl.uninstallTemplate]: a name collision must fail without touching either - * copy, and a failed delete after a successful copy must roll back to leave exactly one copy - * behind. Both are reachable without [com.itsaky.androidide.templates.ITemplateProvider], which is - * only touched on the success path (`ITemplateProvider.getInstance(reload = true)`, a - * ServiceLoader-backed singleton not wired up on the unit test classpath) - so a happy-path - * install/uninstall test is intentionally not included here. + * Install copies (the Downloads original stays), uninstall deletes (nothing is restored), and + * neither touches the other directory. [ITemplateProvider.getInstance] - a ServiceLoader-backed + * singleton not wired up on the unit test classpath - is stubbed so the success paths run. * * Runs under Robolectric rather than plain JUnit4 because the `listTemplateFiles` cases build * real `.cgt` archives, and parsing one reaches `org.json.JSONObject` - a "not mocked" stub @@ -45,184 +46,98 @@ class TemplateRepositoryImplTest { templatesDir = tempFolder.newFolder("templates") downloadDir = tempFolder.newFolder("downloads") repository = TemplateRepositoryImpl(templatesDir, downloadDir) + mockkObject(ITemplateProvider.Companion) + every { ITemplateProvider.getInstance(any()) } returns mockk(relaxed = true) } @After fun tearDown() { + unmockkObject(ITemplateProvider.Companion) // Undo any permission changes a test made, or TemporaryFolder can't clean up after itself. templatesDir.setWritable(true) downloadDir.setWritable(true) - downloadDir.setReadable(true) } private fun item( file: File, installed: Boolean, + provenance: TemplateProvenance = TemplateProvenance.USER, ) = CgtFileItem( file = file, name = file.name, templates = listOf(TemplateMetadata("T", "d", "1.0")), installed = installed, - provenance = TemplateProvenance.USER, + provenance = provenance, ) @Test - fun installTemplate_nameCollision_failsWithoutTouchingEitherCopy() = + fun installTemplate_copiesIntoTheStore_andLeavesTheDownloadsOriginal() = runTest { - val source = File(downloadDir, "dup.cgt").apply { writeText("source") } - val existingDest = File(templatesDir, "dup.cgt").apply { writeText("already installed") } + val source = File(downloadDir, "install.cgt").apply { writeText("source") } val result = repository.installTemplate(item(source, installed = false)) - assertThat(result.isFailure).isTrue() - assertThat(source.exists()).isTrue() + assertThat(result.isSuccess).isTrue() + assertThat(File(templatesDir, "install.cgt").readText()).isEqualTo("source") assertThat(source.readText()).isEqualTo("source") - assertThat(existingDest.readText()).isEqualTo("already installed") } @Test - fun installTemplate_deleteFails_rollsBackAndLeavesExactlyOneCopy() = + fun installTemplate_nameCollision_failsWithoutTouchingEitherCopy() = runTest { - val source = File(downloadDir, "install.cgt").apply { writeText("source") } - val dest = File(templatesDir, "install.cgt") - - // File.delete() needs write permission on the *parent directory*, not the file - // itself - this is what makes item.file.delete() fail after copyTo() already - // succeeded (dest is in the unaffected templatesDir). - check(downloadDir.setWritable(false)) { "test setup: could not make downloadDir read-only" } + val source = File(downloadDir, "dup.cgt").apply { writeText("source") } + val existingDest = File(templatesDir, "dup.cgt").apply { writeText("already installed") } val result = repository.installTemplate(item(source, installed = false)) assertThat(result.isFailure).isTrue() - assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) assertThat(source.exists()).isTrue() - assertThat(dest.exists()).isFalse() + assertThat(source.readText()).isEqualTo("source") + assertThat(existingDest.readText()).isEqualTo("already installed") } @Test - fun uninstallTemplate_nameCollision_failsWithReplaceConflict_withoutTouchingEitherCopy() = + fun uninstallTemplate_deletesTheInstalledCopy_withoutWritingToDownloads() = runTest { - val source = File(templatesDir, "dup.cgt").apply { writeText("installed") } - val existingDownload = File(downloadDir, "dup.cgt").apply { writeText("already in downloads") } + // Both provenances behave the same (ADFA-5444): nothing is restored for either. + for (provenance in TemplateProvenance.entries) { + val installed = File(templatesDir, "uninstall_$provenance.cgt").apply { writeText("installed") } - val result = repository.uninstallTemplate(item(source, installed = true)) + val result = repository.uninstallTemplate(item(installed, installed = true, provenance = provenance)) - assertThat(result.isFailure).isTrue() - assertThat(result.exceptionOrNull()).isInstanceOf(TemplateReplaceConflictException::class.java) - assertThat(source.exists()).isTrue() - assertThat(source.readText()).isEqualTo("installed") - assertThat(existingDownload.readText()).isEqualTo("already in downloads") + assertThat(result.isSuccess).isTrue() + assertThat(installed.exists()).isFalse() + } + assertThat(downloadDir.list()).isEmpty() } @Test - fun uninstallTemplate_deleteFails_rollsBackAndLeavesExactlyOneCopy() = + fun uninstallTemplate_succeeds_whenTheDownloadsOriginalIsStillThere() = runTest { - val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } - val restored = File(downloadDir, "uninstall.cgt") + // The normal state after a copy-install - the old restore path failed here on its + // "already exists in Downloads" check, which is what made uninstall look broken. + val installed = File(templatesDir, "dup.cgt").apply { writeText("installed") } + val original = File(downloadDir, "dup.cgt").apply { writeText("original") } - check(templatesDir.setWritable(false)) { "test setup: could not make templatesDir read-only" } - - val result = repository.uninstallTemplate(item(source, installed = true)) + val result = repository.uninstallTemplate(item(installed, installed = true)) - assertThat(result.isFailure).isTrue() - assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) - assertThat(source.exists()).isTrue() - assertThat(restored.exists()).isFalse() + assertThat(result.isSuccess).isTrue() + assertThat(installed.exists()).isFalse() + assertThat(original.readText()).isEqualTo("original") } @Test - fun uninstallTemplate_overwriteTrue_deleteFails_leavesTheReplacementCopyInDownloads() = + fun uninstallTemplate_deleteFails_reportsIOException_andKeepsTheInstalledCopy() = runTest { - val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } - val restored = File(downloadDir, "uninstall.cgt").apply { writeText("stale") } + val installed = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } + // File.delete() needs write permission on the *parent directory*, not the file itself. check(templatesDir.setWritable(false)) { "test setup: could not make templatesDir read-only" } - val result = repository.uninstallTemplate(item(source, installed = true), overwrite = true) - - assertThat(result.isFailure).isTrue() - assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) - // The source is still installed (its delete failed) - the pre-existing Downloads - // content was already overwritten and can't be recovered either way, so the new copy - // is left in place rather than deleted for nothing. - assertThat(source.exists()).isTrue() - assertThat(restored.readText()).isEqualTo("installed") - // The message must say the file now exists in both places, not the plain "failed to - // delete" wording the non-overwrite rollback case uses - a user reading that after an - // overwrite would wrongly assume their prior Downloads content is still intact. - assertThat(result.exceptionOrNull()?.message).contains("now exists in both places") - } - - @Test - fun uninstallTemplate_overwriteTrue_copyFails_keepsTheExistingDownloadIntact() = - runTest { - val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } - val existingDownload = File(downloadDir, "uninstall.cgt").apply { writeText("user's file") } - - // An unreadable source makes the copy itself fail. copyTo(overwrite = true) deletes - // the target before it opens the source, so this used to destroy the Downloads file. - check(source.setReadable(false)) { "test setup: could not make the source unreadable" } - - val result = repository.uninstallTemplate(item(source, installed = true), overwrite = true) + val result = repository.uninstallTemplate(item(installed, installed = true)) - assertThat(result.isFailure).isTrue() assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) - assertThat(existingDownload.readText()).isEqualTo("user's file") - assertThat(source.exists()).isTrue() - // No partial or temp file left behind in Downloads. - assertThat(downloadDir.list()).asList().containsExactly("uninstall.cgt") - } - - @Test - fun uninstallTemplate_caseOnlyNameCollision_failsWithReplaceConflictNamingTheExistingFile() = - runTest { - val source = File(templatesDir, "dup.cgt").apply { writeText("installed") } - val existingDownload = File(downloadDir, "Dup.CGT").apply { writeText("already in downloads") } - - val result = repository.uninstallTemplate(item(source, installed = true)) - - assertThat(result.exceptionOrNull()).isInstanceOf(TemplateReplaceConflictException::class.java) - // The dialog shows this name, so it must be the file actually on disk. - assertThat((result.exceptionOrNull() as TemplateReplaceConflictException).fileName).isEqualTo("Dup.CGT") - assertThat(source.readText()).isEqualTo("installed") - assertThat(existingDownload.readText()).isEqualTo("already in downloads") - assertThat(downloadDir.list()).asList().containsExactly("Dup.CGT") - } - - @Test - fun uninstallTemplate_overwriteTrue_caseOnlyNameCollision_replacesTheExistingFile_notAddsATwin() = - runTest { - val source = File(templatesDir, "dup.cgt").apply { writeText("installed") } - val existingDownload = File(downloadDir, "Dup.CGT").apply { writeText("stale") } - - // A read-only templatesDir stops the call after the copy, before it reaches - // ITemplateProvider (not wired up here - see the class KDoc). - check(templatesDir.setWritable(false)) { "test setup: could not make templatesDir read-only" } - repository.uninstallTemplate(item(source, installed = true), overwrite = true) - - assertThat(existingDownload.readText()).isEqualTo("installed") - assertThat(downloadDir.list()).asList().containsExactly("Dup.CGT") - } - - @Test - fun uninstallTemplate_existingFileInvisibleToTheLookup_stillFailsWithReplaceConflict_insteadOfOverwriting() = - runTest { - val source = File(templatesDir, "uninstall.cgt").apply { writeText("installed") } - val existingDownload = File(downloadDir, "uninstall.cgt").apply { writeText("already in downloads") } - - // downloadDir.listFiles() returns null without read permission, so the pre-move - // existence check misses existingDownload even though it's still there - this is the - // race window a lookup-then-move approach has in general (the file could just as well - // have appeared between the check and the move). Without a confirmed `overwrite`, - // Files.move must still refuse to replace it rather than silently overwriting. - check(downloadDir.setReadable(false)) { "test setup: could not make downloadDir unreadable" } - - val result = repository.uninstallTemplate(item(source, installed = true)) - - assertThat(result.exceptionOrNull()).isInstanceOf(TemplateReplaceConflictException::class.java) - assertThat(source.exists()).isTrue() - downloadDir.setReadable(true) - assertThat(existingDownload.readText()).isEqualTo("already in downloads") + assertThat(installed.exists()).isTrue() } @Test diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt index 2b218127c6..07d9783a30 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt @@ -2,8 +2,8 @@ package com.itsaky.androidide.viewmodels import android.util.Log import com.google.common.truth.Truth.assertThat -import com.itsaky.androidide.repositories.TemplateReplaceConflictException import com.itsaky.androidide.repositories.TemplateRepository +import com.itsaky.androidide.resources.R import com.itsaky.androidide.templates.manager.models.CgtFileItem import com.itsaky.androidide.templates.manager.models.TemplateMetadata import com.itsaky.androidide.templates.manager.models.TemplateProvenance @@ -12,12 +12,15 @@ import com.itsaky.androidide.ui.models.TemplateManagerUiEvent import com.itsaky.androidide.viewmodel.MainDispatcherRule import io.mockk.coEvery import io.mockk.coVerify +import io.mockk.coVerifyOrder import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkStatic import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest import org.junit.After @@ -45,15 +48,6 @@ class TemplateManagerViewModelTest { provenance = TemplateProvenance.USER, ) - private val installedItem = - CgtFileItem( - file = File("/tmp/uninstall.cgt"), - name = "uninstall.cgt", - templates = listOf(TemplateMetadata("T", "d", "1.0")), - installed = true, - provenance = TemplateProvenance.USER, - ) - @Before fun stubAndroidLog() { // TemplateManagerViewModel calls android.util.Log.d/Log.e directly; under plain JVM @@ -80,20 +74,10 @@ class TemplateManagerViewModelTest { assertThat(viewModel.uiState.value.items).containsExactly(item) } - /** - * Also pins why `_uiEffect` is a `Channel(Channel.BUFFERED)` rather than the rendezvous - * default: `onEvent` -> `installTemplate` sends this effect, and only afterward (the - * `advanceUntilIdle()` below) does anything collect `uiEffect` via `.first()` - mirroring - * production, where the screen's `LaunchedEffect` collector attaches on first composition, - * strictly after the ViewModel (and its `init { loadTemplates() }`) is constructed. A - * rendezvous channel would drop this send with nothing collecting yet; `first()` returning - * it here proves it was buffered instead. - */ @Test - fun installTemplate_onSuccess_reloadsAndSendsShowSuccessEffect() = + fun installTemplateEvent_onlyAsksForConfirmation() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) - coEvery { repository.installTemplate(item) } returns Result.success(Unit) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() @@ -101,112 +85,117 @@ class TemplateManagerViewModelTest { viewModel.onEvent(TemplateManagerUiEvent.InstallTemplate(item)) advanceUntilIdle() - coVerify(exactly = 1) { repository.installTemplate(item) } - // listTemplateFiles is called once by init{} and again by the post-install reload. - coVerify(exactly = 2) { repository.listTemplateFiles() } - assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowSuccess).isTrue() + assertThat(viewModel.uiEffect.first()).isEqualTo(TemplateManagerUiEffect.ShowInstallConfirmation(item)) + coVerify(exactly = 0) { repository.installTemplate(any()) } } @Test - fun installTemplate_onFailure_sendsShowErrorEffect_withoutReloading() = + fun confirmInstallTemplate_withoutDelete_keepsTheDownloadsOriginal() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) - coEvery { repository.installTemplate(item) } returns Result.failure(java.io.IOException("boom")) + coEvery { repository.installTemplate(item) } returns Result.success(Unit) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() - viewModel.onEvent(TemplateManagerUiEvent.InstallTemplate(item)) + viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = false) advanceUntilIdle() - // Only the init{} load - a failed install must not trigger a reload. - coVerify(exactly = 1) { repository.listTemplateFiles() } - assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowError).isTrue() + coVerify(exactly = 0) { repository.deleteDownloadFile(any()) } } @Test - fun uninstallTemplate_event_asksForConfirmation_withoutCallingRepository() = + fun confirmInstallTemplate_withDelete_deletesTheDownloadsOriginalAfterInstalling() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.installTemplate(item) } returns Result.success(Unit) + coEvery { repository.deleteDownloadFile(item) } returns Result.success(Unit) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() - viewModel.onEvent(TemplateManagerUiEvent.UninstallTemplate(installedItem)) + viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = true) advanceUntilIdle() - coVerify(exactly = 0) { repository.uninstallTemplate(any(), any()) } - val effect = viewModel.uiEffect.first() - assertThat(effect).isInstanceOf(TemplateManagerUiEffect.ShowUninstallConfirmation::class.java) - assertThat((effect as TemplateManagerUiEffect.ShowUninstallConfirmation).item).isEqualTo(installedItem) + coVerifyOrder { + repository.installTemplate(item) + repository.deleteDownloadFile(item) + } } @Test - fun confirmUninstallTemplate_onSuccess_reloadsAndSendsShowSuccessEffect() = + fun confirmInstallTemplate_deleteFails_stillReportsTheInstall_thenTheDeleteError() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) - coEvery { repository.uninstallTemplate(installedItem, false) } returns Result.success(Unit) + coEvery { repository.installTemplate(item) } returns Result.success(Unit) + coEvery { repository.deleteDownloadFile(item) } returns Result.failure(java.io.IOException("ro")) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() - viewModel.confirmUninstallTemplate(installedItem) + viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = true) advanceUntilIdle() - coVerify(exactly = 2) { repository.listTemplateFiles() } - assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowSuccess).isTrue() + val effects = viewModel.uiEffect.take(2).toList() + assertThat(effects[0]).isInstanceOf(TemplateManagerUiEffect.ShowSuccess::class.java) + assertThat(effects[1]).isEqualTo(TemplateManagerUiEffect.ShowError(R.string.msg_source_delete_failed)) } @Test - fun confirmUninstallTemplate_onReplaceConflict_sendsShowReplaceConfirmation_notShowError() = + fun confirmInstallTemplate_installFails_neverDeletesTheDownloadsOriginal() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) - coEvery { repository.uninstallTemplate(installedItem, false) } returns - Result.failure(TemplateReplaceConflictException("Existing.CGT")) + coEvery { repository.installTemplate(item) } returns Result.failure(java.io.IOException("boom")) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() - viewModel.confirmUninstallTemplate(installedItem) + viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = true) advanceUntilIdle() - // A conflict isn't a reload-worthy outcome and must not be reported as a generic error. - coVerify(exactly = 1) { repository.listTemplateFiles() } - val effect = viewModel.uiEffect.first() - assertThat(effect).isInstanceOf(TemplateManagerUiEffect.ShowReplaceConfirmation::class.java) - assertThat((effect as TemplateManagerUiEffect.ShowReplaceConfirmation).item).isEqualTo(installedItem) - // The dialog names the file on disk, not the item's extension-less display name. - assertThat(effect.fileName).isEqualTo("Existing.CGT") + coVerify(exactly = 0) { repository.deleteDownloadFile(any()) } } + /** + * Also pins why `_uiEffect` is a `Channel(Channel.BUFFERED)` rather than the rendezvous + * default: `confirmInstallTemplate` sends this effect, and only afterward (the + * `advanceUntilIdle()` below) does anything collect `uiEffect` via `.first()` - mirroring + * production, where the screen's `LaunchedEffect` collector attaches on first composition, + * strictly after the ViewModel (and its `init { loadTemplates() }`) is constructed. A + * rendezvous channel would drop this send with nothing collecting yet; `first()` returning + * it here proves it was buffered instead. + */ @Test - fun confirmUninstallTemplate_withOverwrite_passesOverwriteThrough_onReplaceConfirm() = + fun installTemplate_onSuccess_reloadsAndSendsShowSuccessEffect() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) - coEvery { repository.uninstallTemplate(installedItem, true) } returns Result.success(Unit) + coEvery { repository.installTemplate(item) } returns Result.success(Unit) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() - viewModel.confirmUninstallTemplate(installedItem, overwrite = true) + viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = false) advanceUntilIdle() - coVerify(exactly = 1) { repository.uninstallTemplate(installedItem, true) } + coVerify(exactly = 1) { repository.installTemplate(item) } + // listTemplateFiles is called once by init{} and again by the post-install reload. + coVerify(exactly = 2) { repository.listTemplateFiles() } assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowSuccess).isTrue() } @Test - fun confirmUninstallTemplate_onOtherFailure_sendsShowErrorEffect_withoutReloading() = + fun installTemplate_onFailure_sendsShowErrorEffect_withoutReloading() = runTest { coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) - coEvery { repository.uninstallTemplate(installedItem, false) } returns Result.failure(java.io.IOException("boom")) + coEvery { repository.installTemplate(item) } returns Result.failure(java.io.IOException("boom")) val viewModel = TemplateManagerViewModel(repository) advanceUntilIdle() - viewModel.confirmUninstallTemplate(installedItem) + viewModel.confirmInstallTemplate(item, deleteSourceAfterInstall = false) advanceUntilIdle() + // Only the init{} load - a failed install must not trigger a reload. coVerify(exactly = 1) { repository.listTemplateFiles() } assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowError).isTrue() } diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index f663d25b70..676ef36758 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1570,10 +1570,6 @@ Templates in %1$s Delete template? This permanently deletes \'%1$s\' from Downloads. - Uninstall template? - This moves \'%1$s\' back to Downloads. - Replace file in Downloads? - A file named \'%1$s\' already exists in Downloads. Replace it? File Status Location From 9a4b516900ced570c52e01bb0d21322eccfc7859 Mon Sep 17 00:00:00 2001 From: jimturner-adfa Date: Tue, 3 Nov 2026 12:14:51 -0800 Subject: [PATCH 08/10] ADFA-5446: Confirm before uninstalling a template Keeps this PR's confirm-before-uninstall step, which the Plugins tab also has, now that nothing is restored: Uninstall opens a dialog and confirmUninstallTemplate does the work, like confirmDeleteDownloadFile. The message says the template is removed and how to get it back (reinstall the .cgt or the plugin), instead of "moves it back to Downloads". The Uninstall and Delete messages now scroll. AlertDialog's text slot does not, so a long file name at 2x font scale was clipped (CodeRabbit). The Install dialog already scrolled. The uninstall-event test fails with the ask-first step reverted. Co-Authored-By: Claude Opus 5.5 --- .../templates/TemplateManagerDialogs.kt | 33 +++++++++++- .../templates/TemplateManagerScreen.kt | 23 ++++++++ .../ui/models/TemplateManagerUiState.kt | 4 ++ .../viewmodels/TemplateManagerViewModel.kt | 11 +++- .../TemplateManagerViewModelTest.kt | 54 +++++++++++++++++++ resources/src/main/res/values/strings.xml | 2 + 6 files changed, 124 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt index 4b3f591c3d..661bf7112e 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerDialogs.kt @@ -75,6 +75,32 @@ fun InstallTemplateConfirmationDialog( ) } +/** Same confirm-before-uninstall step as the Plugins tab. Nothing is restored to Downloads. */ +@Composable +fun UninstallTemplateConfirmationDialog( + item: CgtFileItem, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.title_uninstall_template)) }, + // AlertDialog's text slot does not scroll; a long file name at 2x font scale would clip. + text = { + Text( + stringResource(R.string.msg_uninstall_template_confirm, item.displayName), + modifier = Modifier.verticalScroll(rememberScrollState()), + ) + }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_uninstall_template)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(android.R.string.cancel)) } + }, + ) +} + @Composable fun DeleteTemplateConfirmationDialog( item: CgtFileItem, @@ -84,7 +110,12 @@ fun DeleteTemplateConfirmationDialog( AlertDialog( onDismissRequest = onDismiss, title = { Text(stringResource(R.string.title_delete_template)) }, - text = { Text(stringResource(R.string.msg_delete_template_confirm, item.displayName)) }, + text = { + Text( + stringResource(R.string.msg_delete_template_confirm, item.displayName), + modifier = Modifier.verticalScroll(rememberScrollState()), + ) + }, confirmButton = { TextButton(onClick = onConfirm) { Text(stringResource(R.string.action_delete_template)) } }, diff --git a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt index 139720c416..135314207b 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/compose/templates/TemplateManagerScreen.kt @@ -67,6 +67,11 @@ private sealed interface TemplateManagerDialogState : Parcelable { val path: String, ) : TemplateManagerDialogState + @Parcelize + data class UninstallConfirm( + val path: String, + ) : TemplateManagerDialogState + @Parcelize data class DeleteConfirm( val path: String, @@ -159,6 +164,10 @@ fun TemplateManagerScreen( dialogState = TemplateManagerDialogState.InstallConfirm(effect.item.file.absolutePath) } + is TemplateManagerUiEffect.ShowUninstallConfirmation -> { + dialogState = TemplateManagerDialogState.UninstallConfirm(effect.item.file.absolutePath) + } + is TemplateManagerUiEffect.ShowDeleteConfirmation -> { dialogState = TemplateManagerDialogState.DeleteConfirm(effect.item.file.absolutePath) } @@ -225,6 +234,20 @@ fun TemplateManagerScreen( } } + is TemplateManagerDialogState.UninstallConfirm -> { + val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } + if (item != null) { + UninstallTemplateConfirmationDialog( + item = item, + onConfirm = { + viewModel.confirmUninstallTemplate(item) + dialogState = TemplateManagerDialogState.None + }, + onDismiss = { dialogState = TemplateManagerDialogState.None }, + ) + } + } + is TemplateManagerDialogState.DeleteConfirm -> { val item = uiState.items.firstOrNull { it.file.absolutePath == dialog.path } if (item != null) { diff --git a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt index 7d8824aae4..d8d8ec9dbe 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/models/TemplateManagerUiState.kt @@ -50,6 +50,10 @@ sealed class TemplateManagerUiEffect { val item: CgtFileItem, ) : TemplateManagerUiEffect() + data class ShowUninstallConfirmation( + val item: CgtFileItem, + ) : TemplateManagerUiEffect() + data class ShowDeleteConfirmation( val item: CgtFileItem, ) : TemplateManagerUiEffect() diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt index 4569ebe143..999c6332ce 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModel.kt @@ -42,7 +42,7 @@ class TemplateManagerViewModel( when (event) { is TemplateManagerUiEvent.LoadTemplates -> loadTemplates() is TemplateManagerUiEvent.InstallTemplate -> showInstallConfirmation(event.item) - is TemplateManagerUiEvent.UninstallTemplate -> uninstallTemplate(event.item) + is TemplateManagerUiEvent.UninstallTemplate -> showUninstallConfirmation(event.item) is TemplateManagerUiEvent.DeleteDownloadFile -> showDeleteConfirmation(event.item) is TemplateManagerUiEvent.ShowTemplateDetails -> showTemplateDetails(event.item) is TemplateManagerUiEvent.ShowTemplateList -> showTemplateList(event.item) @@ -120,7 +120,14 @@ class TemplateManagerViewModel( } } - private fun uninstallTemplate(item: CgtFileItem) { + private fun showUninstallConfirmation(item: CgtFileItem) { + viewModelScope.launch { + _uiEffect.send(TemplateManagerUiEffect.ShowUninstallConfirmation(item)) + } + } + + /** Uninstalls [item] (called after [TemplateManagerUiEffect.ShowUninstallConfirmation] is confirmed). */ + fun confirmUninstallTemplate(item: CgtFileItem) { viewModelScope.launch { _uiState.update { it.copy(isLoading = true) } templateRepository diff --git a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt index 07d9783a30..bdb90510b6 100644 --- a/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt +++ b/app/src/test/java/com/itsaky/androidide/viewmodels/TemplateManagerViewModelTest.kt @@ -48,6 +48,8 @@ class TemplateManagerViewModelTest { provenance = TemplateProvenance.USER, ) + private val installedItem = item.copy(file = File("/tmp/templates/install.cgt"), installed = true) + @Before fun stubAndroidLog() { // TemplateManagerViewModel calls android.util.Log.d/Log.e directly; under plain JVM @@ -199,4 +201,56 @@ class TemplateManagerViewModelTest { coVerify(exactly = 1) { repository.listTemplateFiles() } assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowError).isTrue() } + + @Test + fun uninstallTemplateEvent_onlyAsksForConfirmation() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + // Stubbed so a regression that uninstalls straight away sends ShowSuccess and fails the + // assertion below, rather than throwing inside the coroutine and hanging first(). + coEvery { repository.uninstallTemplate(installedItem) } returns Result.success(Unit) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.onEvent(TemplateManagerUiEvent.UninstallTemplate(installedItem)) + advanceUntilIdle() + + assertThat(viewModel.uiEffect.first()).isEqualTo(TemplateManagerUiEffect.ShowUninstallConfirmation(installedItem)) + coVerify(exactly = 0) { repository.uninstallTemplate(any()) } + } + + @Test + fun confirmUninstallTemplate_onSuccess_reloadsAndSendsShowSuccessEffect() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.uninstallTemplate(installedItem) } returns Result.success(Unit) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.confirmUninstallTemplate(installedItem) + advanceUntilIdle() + + coVerify(exactly = 1) { repository.uninstallTemplate(installedItem) } + // listTemplateFiles is called once by init{} and again by the post-uninstall reload. + coVerify(exactly = 2) { repository.listTemplateFiles() } + assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowSuccess).isTrue() + } + + @Test + fun confirmUninstallTemplate_onFailure_sendsShowErrorEffect_withoutReloading() = + runTest { + coEvery { repository.listTemplateFiles() } returns Result.success(emptyList()) + coEvery { repository.uninstallTemplate(installedItem) } returns Result.failure(java.io.IOException("boom")) + + val viewModel = TemplateManagerViewModel(repository) + advanceUntilIdle() + + viewModel.confirmUninstallTemplate(installedItem) + advanceUntilIdle() + + coVerify(exactly = 1) { repository.listTemplateFiles() } + assertThat(viewModel.uiEffect.first() is TemplateManagerUiEffect.ShowError).isTrue() + } } diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 676ef36758..43fb5c2fb6 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1570,6 +1570,8 @@ Templates in %1$s Delete template? This permanently deletes \'%1$s\' from Downloads. + Uninstall template? + This removes \'%1$s\' from your templates. To use it again, reinstall it from its .cgt file, or reinstall the plugin that added it. File Status Location From 68d874881e44bbf21b15d85d26e7c191f636668e Mon Sep 17 00:00:00 2001 From: jimturner-adfa Date: Tue, 3 Nov 2026 12:29:39 -0800 Subject: [PATCH 09/10] ADFA-5446: Remove a partial copy when installing a template fails installTemplate copies straight to the final path in templatesDir. A copy that failed partway (storage full, say) left a truncated .cgt that never parses, so it was unlisted and could not be uninstalled, and every retry then failed with "already exists". Delete it on IOException, but not on FileAlreadyExistsException: that file belongs to another writer (CodeRabbit). The new test fails without the fix on the "no partial file" assertion. Co-Authored-By: Claude Opus 5.5 --- .../repositories/TemplateRepositoryImpl.kt | 12 +++++++++++- .../repositories/TemplateRepositoryImplTest.kt | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index f98dcc1a7c..caf5e7f464 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -120,7 +120,17 @@ class TemplateRepositoryImpl( check(!item.installed) { "'${item.name}' is already installed" } val dest = File(templatesDir, item.file.name) check(!dest.exists()) { "A template named '${dest.name}' already exists in $templatesDir" } - item.file.copyTo(dest, overwrite = false) + try { + item.file.copyTo(dest, overwrite = false) + } catch (e: FileAlreadyExistsException) { + // Another writer created dest after the check above; it isn't ours to delete. + throw e + } catch (e: IOException) { + // A copy that failed partway (e.g. storage full) leaves a truncated archive that + // never lists, so it can't be uninstalled, and that blocks every retry. + dest.delete() + throw e + } ITemplateProvider.getInstance(reload = true) Result.success(Unit) } catch (e: CancellationException) { diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index 885ae3c9ce..a9402ee219 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -12,6 +12,7 @@ import io.mockk.unmockkObject import kotlinx.coroutines.test.runTest import org.adfa.constants.TEMPLATE_CORE_ARCHIVE import org.junit.After +import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Rule import org.junit.Test @@ -82,6 +83,21 @@ class TemplateRepositoryImplTest { assertThat(source.readText()).isEqualTo("source") } + @Test + fun installTemplate_copyFailsPartway_leavesNoPartialFileInTheStore() = + runTest { + // /proc/self/mem opens but fails its first read with EIO, so copyTo has already + // created the destination when it throws - the "storage filled up mid-copy" case. + val failingSource = File("/proc/self/mem") + assumeTrue("needs Linux /proc", failingSource.exists()) + + val result = repository.installTemplate(item(failingSource, installed = false)) + + assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) + // A truncated archive would be unlisted (it doesn't parse) and block every retry. + assertThat(File(templatesDir, failingSource.name).exists()).isFalse() + } + @Test fun installTemplate_nameCollision_failsWithoutTouchingEitherCopy() = runTest { From 0f1196d7b4912e7b7d3b6507c20354cf533911e8 Mon Sep 17 00:00:00 2001 From: yaturner Date: Sat, 7 Nov 2026 05:15:51 -0800 Subject: [PATCH 10/10] ADFA-5446: Delete only an install destination this install created A failed copy deleted dest even when the failure came before the copy created it. If another writer created dest after the exists() check and the source then failed to open, the cleanup removed that writer's file. Open the source first and create dest with CREATE_NEW (O_EXCL), so the cleanup after a partial copy can only remove a file this call made. The new test fails on the old code: the racing writer's file is deleted. Co-Authored-By: Claude Opus 5.5 --- .../repositories/TemplateRepositoryImpl.kt | 36 +++++++++++++------ .../TemplateRepositoryImplTest.kt | 28 +++++++++++++++ 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt index caf5e7f464..9d44ea3881 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/TemplateRepositoryImpl.kt @@ -11,7 +11,10 @@ import org.adfa.constants.TEMPLATE_CORE_ARCHIVE import org.json.JSONException import org.slf4j.LoggerFactory import java.io.File +import java.io.FileInputStream import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardOpenOption /** * Implementation of [TemplateRepository]. @@ -120,17 +123,7 @@ class TemplateRepositoryImpl( check(!item.installed) { "'${item.name}' is already installed" } val dest = File(templatesDir, item.file.name) check(!dest.exists()) { "A template named '${dest.name}' already exists in $templatesDir" } - try { - item.file.copyTo(dest, overwrite = false) - } catch (e: FileAlreadyExistsException) { - // Another writer created dest after the check above; it isn't ours to delete. - throw e - } catch (e: IOException) { - // A copy that failed partway (e.g. storage full) leaves a truncated archive that - // never lists, so it can't be uninstalled, and that blocks every retry. - dest.delete() - throw e - } + copyIntoNewFile(item.file, dest) ITemplateProvider.getInstance(reload = true) Result.success(Unit) } catch (e: CancellationException) { @@ -144,6 +137,27 @@ class TemplateRepositoryImpl( } } + /** + * Copies [source] to [dest], which must not exist yet. A copy that fails partway (e.g. storage + * full) is deleted: a truncated archive never lists, so it can't be uninstalled, and it blocks + * every retry. Only a [dest] this call created is deleted: the source is opened first, and + * CREATE_NEW creates [dest] atomically, failing if another writer got there first. + */ + private fun copyIntoNewFile( + source: File, + dest: File, + ) { + FileInputStream(source).use { input -> + val output = Files.newOutputStream(dest.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) + try { + output.use { input.copyTo(it) } + } catch (e: IOException) { + dest.delete() + throw e + } + } + } + override suspend fun uninstallTemplate(item: CgtFileItem): Result = withContext(Dispatchers.IO) { try { diff --git a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt index a9402ee219..6741005a29 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/TemplateRepositoryImplTest.kt @@ -112,6 +112,34 @@ class TemplateRepositoryImplTest { assertThat(existingDest.readText()).isEqualTo("already installed") } + @Test + fun installTemplate_destCreatedAfterTheCheck_isNotDeletedWhenTheSourceFailsToOpen() = + runTest { + val dest = File(templatesDir, "race.cgt") + // Another writer creates dest after installTemplate's exists() check, the moment the + // install first touches the source, and the source then fails to open. + val source = + object : File(downloadDir, "race.cgt") { + private var raced = false + + private fun race() { + if (!raced) { + raced = true + dest.writeText("another writer") + } + } + + override fun exists(): Boolean = super.exists().also { race() } + + override fun getPath(): String = super.getPath().also { race() } + } + + val result = repository.installTemplate(item(source, installed = false)) + + assertThat(result.exceptionOrNull()).isInstanceOf(IOException::class.java) + assertThat(dest.readText()).isEqualTo("another writer") + } + @Test fun uninstallTemplate_deletesTheInstalledCopy_withoutWritingToDownloads() = runTest {